]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/ExprCXX.cpp
Update ELF Tool Chain to upstream rev 3400
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / ExprCXX.cpp
1 //===--- ExprCXX.cpp - (C++) Expression AST Node Implementation -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the subclesses of Expr class declared in ExprCXX.h
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/IdentifierTable.h"
21 using namespace clang;
22
23
24 //===----------------------------------------------------------------------===//
25 //  Child Iterators for iterating over subexpressions/substatements
26 //===----------------------------------------------------------------------===//
27
28 bool CXXTypeidExpr::isPotentiallyEvaluated() const {
29   if (isTypeOperand())
30     return false;
31
32   // C++11 [expr.typeid]p3:
33   //   When typeid is applied to an expression other than a glvalue of
34   //   polymorphic class type, [...] the expression is an unevaluated operand.
35   const Expr *E = getExprOperand();
36   if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl())
37     if (RD->isPolymorphic() && E->isGLValue())
38       return true;
39
40   return false;
41 }
42
43 QualType CXXTypeidExpr::getTypeOperand(ASTContext &Context) const {
44   assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
45   Qualifiers Quals;
46   return Context.getUnqualifiedArrayType(
47       Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);
48 }
49
50 QualType CXXUuidofExpr::getTypeOperand(ASTContext &Context) const {
51   assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
52   Qualifiers Quals;
53   return Context.getUnqualifiedArrayType(
54       Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);
55 }
56
57 // static
58 const UuidAttr *CXXUuidofExpr::GetUuidAttrOfType(QualType QT,
59                                                  bool *RDHasMultipleGUIDsPtr) {
60   // Optionally remove one level of pointer, reference or array indirection.
61   const Type *Ty = QT.getTypePtr();
62   if (QT->isPointerType() || QT->isReferenceType())
63     Ty = QT->getPointeeType().getTypePtr();
64   else if (QT->isArrayType())
65     Ty = Ty->getBaseElementTypeUnsafe();
66
67   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
68   if (!RD)
69     return nullptr;
70
71   if (const UuidAttr *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>())
72     return Uuid;
73
74   // __uuidof can grab UUIDs from template arguments.
75   if (const ClassTemplateSpecializationDecl *CTSD =
76           dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
77     const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
78     const UuidAttr *UuidForRD = nullptr;
79
80     for (const TemplateArgument &TA : TAL.asArray()) {
81       bool SeenMultipleGUIDs = false;
82
83       const UuidAttr *UuidForTA = nullptr;
84       if (TA.getKind() == TemplateArgument::Type)
85         UuidForTA = GetUuidAttrOfType(TA.getAsType(), &SeenMultipleGUIDs);
86       else if (TA.getKind() == TemplateArgument::Declaration)
87         UuidForTA =
88             GetUuidAttrOfType(TA.getAsDecl()->getType(), &SeenMultipleGUIDs);
89
90       // If the template argument has a UUID, there are three cases:
91       //  - This is the first UUID seen for this RecordDecl.
92       //  - This is a different UUID than previously seen for this RecordDecl.
93       //  - This is the same UUID than previously seen for this RecordDecl.
94       if (UuidForTA) {
95         if (!UuidForRD)
96           UuidForRD = UuidForTA;
97         else if (UuidForRD != UuidForTA)
98           SeenMultipleGUIDs = true;
99       }
100
101       // Seeing multiple UUIDs means that we couldn't find a UUID
102       if (SeenMultipleGUIDs) {
103         if (RDHasMultipleGUIDsPtr)
104           *RDHasMultipleGUIDsPtr = true;
105         return nullptr;
106       }
107     }
108
109     return UuidForRD;
110   }
111
112   return nullptr;
113 }
114
115 StringRef CXXUuidofExpr::getUuidAsStringRef(ASTContext &Context) const {
116   StringRef Uuid;
117   if (isTypeOperand())
118     Uuid = CXXUuidofExpr::GetUuidAttrOfType(getTypeOperand(Context))->getGuid();
119   else {
120     // Special case: __uuidof(0) means an all-zero GUID.
121     Expr *Op = getExprOperand();
122     if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
123       Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
124     else
125       Uuid = "00000000-0000-0000-0000-000000000000";
126   }
127   return Uuid;
128 }
129
130 // CXXScalarValueInitExpr
131 SourceLocation CXXScalarValueInitExpr::getLocStart() const {
132   return TypeInfo ? TypeInfo->getTypeLoc().getBeginLoc() : RParenLoc;
133 }
134
135 // CXXNewExpr
136 CXXNewExpr::CXXNewExpr(const ASTContext &C, bool globalNew,
137                        FunctionDecl *operatorNew, FunctionDecl *operatorDelete,
138                        bool usualArrayDeleteWantsSize,
139                        ArrayRef<Expr*> placementArgs,
140                        SourceRange typeIdParens, Expr *arraySize,
141                        InitializationStyle initializationStyle,
142                        Expr *initializer, QualType ty,
143                        TypeSourceInfo *allocatedTypeInfo,
144                        SourceRange Range, SourceRange directInitRange)
145   : Expr(CXXNewExprClass, ty, VK_RValue, OK_Ordinary,
146          ty->isDependentType(), ty->isDependentType(),
147          ty->isInstantiationDependentType(),
148          ty->containsUnexpandedParameterPack()),
149     SubExprs(nullptr), OperatorNew(operatorNew), OperatorDelete(operatorDelete),
150     AllocatedTypeInfo(allocatedTypeInfo), TypeIdParens(typeIdParens),
151     Range(Range), DirectInitRange(directInitRange),
152     GlobalNew(globalNew), UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) {
153   assert((initializer != nullptr || initializationStyle == NoInit) &&
154          "Only NoInit can have no initializer.");
155   StoredInitializationStyle = initializer ? initializationStyle + 1 : 0;
156   AllocateArgsArray(C, arraySize != nullptr, placementArgs.size(),
157                     initializer != nullptr);
158   unsigned i = 0;
159   if (Array) {
160     if (arraySize->isInstantiationDependent())
161       ExprBits.InstantiationDependent = true;
162     
163     if (arraySize->containsUnexpandedParameterPack())
164       ExprBits.ContainsUnexpandedParameterPack = true;
165
166     SubExprs[i++] = arraySize;
167   }
168
169   if (initializer) {
170     if (initializer->isInstantiationDependent())
171       ExprBits.InstantiationDependent = true;
172
173     if (initializer->containsUnexpandedParameterPack())
174       ExprBits.ContainsUnexpandedParameterPack = true;
175
176     SubExprs[i++] = initializer;
177   }
178
179   for (unsigned j = 0; j != placementArgs.size(); ++j) {
180     if (placementArgs[j]->isInstantiationDependent())
181       ExprBits.InstantiationDependent = true;
182     if (placementArgs[j]->containsUnexpandedParameterPack())
183       ExprBits.ContainsUnexpandedParameterPack = true;
184
185     SubExprs[i++] = placementArgs[j];
186   }
187
188   switch (getInitializationStyle()) {
189   case CallInit:
190     this->Range.setEnd(DirectInitRange.getEnd()); break;
191   case ListInit:
192     this->Range.setEnd(getInitializer()->getSourceRange().getEnd()); break;
193   default:
194     if (TypeIdParens.isValid())
195       this->Range.setEnd(TypeIdParens.getEnd());
196     break;
197   }
198 }
199
200 void CXXNewExpr::AllocateArgsArray(const ASTContext &C, bool isArray,
201                                    unsigned numPlaceArgs, bool hasInitializer){
202   assert(SubExprs == nullptr && "SubExprs already allocated");
203   Array = isArray;
204   NumPlacementArgs = numPlaceArgs;
205
206   unsigned TotalSize = Array + hasInitializer + NumPlacementArgs;
207   SubExprs = new (C) Stmt*[TotalSize];
208 }
209
210 bool CXXNewExpr::shouldNullCheckAllocation(const ASTContext &Ctx) const {
211   return getOperatorNew()->getType()->castAs<FunctionProtoType>()->isNothrow(
212              Ctx) &&
213          !getOperatorNew()->isReservedGlobalPlacementOperator();
214 }
215
216 // CXXDeleteExpr
217 QualType CXXDeleteExpr::getDestroyedType() const {
218   const Expr *Arg = getArgument();
219   // The type-to-delete may not be a pointer if it's a dependent type.
220   const QualType ArgType = Arg->getType();
221
222   if (ArgType->isDependentType() && !ArgType->isPointerType())
223     return QualType();
224
225   return ArgType->getAs<PointerType>()->getPointeeType();
226 }
227
228 // CXXPseudoDestructorExpr
229 PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)
230  : Type(Info) 
231 {
232   Location = Info->getTypeLoc().getLocalSourceRange().getBegin();
233 }
234
235 CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(const ASTContext &Context,
236                 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
237                 NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, 
238                 SourceLocation ColonColonLoc, SourceLocation TildeLoc, 
239                 PseudoDestructorTypeStorage DestroyedType)
240   : Expr(CXXPseudoDestructorExprClass,
241          Context.BoundMemberTy,
242          VK_RValue, OK_Ordinary,
243          /*isTypeDependent=*/(Base->isTypeDependent() ||
244            (DestroyedType.getTypeSourceInfo() &&
245             DestroyedType.getTypeSourceInfo()->getType()->isDependentType())),
246          /*isValueDependent=*/Base->isValueDependent(),
247          (Base->isInstantiationDependent() ||
248           (QualifierLoc &&
249            QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) ||
250           (ScopeType &&
251            ScopeType->getType()->isInstantiationDependentType()) ||
252           (DestroyedType.getTypeSourceInfo() &&
253            DestroyedType.getTypeSourceInfo()->getType()
254                                              ->isInstantiationDependentType())),
255          // ContainsUnexpandedParameterPack
256          (Base->containsUnexpandedParameterPack() ||
257           (QualifierLoc && 
258            QualifierLoc.getNestedNameSpecifier()
259                                         ->containsUnexpandedParameterPack()) ||
260           (ScopeType && 
261            ScopeType->getType()->containsUnexpandedParameterPack()) ||
262           (DestroyedType.getTypeSourceInfo() &&
263            DestroyedType.getTypeSourceInfo()->getType()
264                                    ->containsUnexpandedParameterPack()))),
265     Base(static_cast<Stmt *>(Base)), IsArrow(isArrow),
266     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
267     ScopeType(ScopeType), ColonColonLoc(ColonColonLoc), TildeLoc(TildeLoc),
268     DestroyedType(DestroyedType) { }
269
270 QualType CXXPseudoDestructorExpr::getDestroyedType() const {
271   if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
272     return TInfo->getType();
273   
274   return QualType();
275 }
276
277 SourceLocation CXXPseudoDestructorExpr::getLocEnd() const {
278   SourceLocation End = DestroyedType.getLocation();
279   if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
280     End = TInfo->getTypeLoc().getLocalSourceRange().getEnd();
281   return End;
282 }
283
284 // UnresolvedLookupExpr
285 UnresolvedLookupExpr *
286 UnresolvedLookupExpr::Create(const ASTContext &C,
287                              CXXRecordDecl *NamingClass,
288                              NestedNameSpecifierLoc QualifierLoc,
289                              SourceLocation TemplateKWLoc,
290                              const DeclarationNameInfo &NameInfo,
291                              bool ADL,
292                              const TemplateArgumentListInfo *Args,
293                              UnresolvedSetIterator Begin,
294                              UnresolvedSetIterator End)
295 {
296   assert(Args || TemplateKWLoc.isValid());
297   unsigned num_args = Args ? Args->size() : 0;
298   void *Mem = C.Allocate(sizeof(UnresolvedLookupExpr) +
299                          ASTTemplateKWAndArgsInfo::sizeFor(num_args));
300   return new (Mem) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
301                                         TemplateKWLoc, NameInfo,
302                                         ADL, /*Overload*/ true, Args,
303                                         Begin, End);
304 }
305
306 UnresolvedLookupExpr *
307 UnresolvedLookupExpr::CreateEmpty(const ASTContext &C,
308                                   bool HasTemplateKWAndArgsInfo,
309                                   unsigned NumTemplateArgs) {
310   std::size_t size = sizeof(UnresolvedLookupExpr);
311   if (HasTemplateKWAndArgsInfo)
312     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
313
314   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedLookupExpr>());
315   UnresolvedLookupExpr *E = new (Mem) UnresolvedLookupExpr(EmptyShell());
316   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
317   return E;
318 }
319
320 OverloadExpr::OverloadExpr(StmtClass K, const ASTContext &C,
321                            NestedNameSpecifierLoc QualifierLoc,
322                            SourceLocation TemplateKWLoc,
323                            const DeclarationNameInfo &NameInfo,
324                            const TemplateArgumentListInfo *TemplateArgs,
325                            UnresolvedSetIterator Begin, 
326                            UnresolvedSetIterator End,
327                            bool KnownDependent,
328                            bool KnownInstantiationDependent,
329                            bool KnownContainsUnexpandedParameterPack)
330   : Expr(K, C.OverloadTy, VK_LValue, OK_Ordinary, KnownDependent, 
331          KnownDependent,
332          (KnownInstantiationDependent ||
333           NameInfo.isInstantiationDependent() ||
334           (QualifierLoc &&
335            QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())),
336          (KnownContainsUnexpandedParameterPack ||
337           NameInfo.containsUnexpandedParameterPack() ||
338           (QualifierLoc && 
339            QualifierLoc.getNestedNameSpecifier()
340                                       ->containsUnexpandedParameterPack()))),
341     NameInfo(NameInfo), QualifierLoc(QualifierLoc),
342     Results(nullptr), NumResults(End - Begin),
343     HasTemplateKWAndArgsInfo(TemplateArgs != nullptr ||
344                              TemplateKWLoc.isValid()) {
345   NumResults = End - Begin;
346   if (NumResults) {
347     // Determine whether this expression is type-dependent.
348     for (UnresolvedSetImpl::const_iterator I = Begin; I != End; ++I) {
349       if ((*I)->getDeclContext()->isDependentContext() ||
350           isa<UnresolvedUsingValueDecl>(*I)) {
351         ExprBits.TypeDependent = true;
352         ExprBits.ValueDependent = true;
353         ExprBits.InstantiationDependent = true;
354       }
355     }
356
357     Results = static_cast<DeclAccessPair *>(
358                                 C.Allocate(sizeof(DeclAccessPair) * NumResults, 
359                                            llvm::alignOf<DeclAccessPair>()));
360     memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));
361   }
362
363   // If we have explicit template arguments, check for dependent
364   // template arguments and whether they contain any unexpanded pack
365   // expansions.
366   if (TemplateArgs) {
367     bool Dependent = false;
368     bool InstantiationDependent = false;
369     bool ContainsUnexpandedParameterPack = false;
370     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
371                                                Dependent,
372                                                InstantiationDependent,
373                                                ContainsUnexpandedParameterPack);
374
375     if (Dependent) {
376       ExprBits.TypeDependent = true;
377       ExprBits.ValueDependent = true;
378     }
379     if (InstantiationDependent)
380       ExprBits.InstantiationDependent = true;
381     if (ContainsUnexpandedParameterPack)
382       ExprBits.ContainsUnexpandedParameterPack = true;
383   } else if (TemplateKWLoc.isValid()) {
384     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
385   }
386
387   if (isTypeDependent())
388     setType(C.DependentTy);
389 }
390
391 void OverloadExpr::initializeResults(const ASTContext &C,
392                                      UnresolvedSetIterator Begin,
393                                      UnresolvedSetIterator End) {
394   assert(!Results && "Results already initialized!");
395   NumResults = End - Begin;
396   if (NumResults) {
397      Results = static_cast<DeclAccessPair *>(
398                                C.Allocate(sizeof(DeclAccessPair) * NumResults,
399  
400                                           llvm::alignOf<DeclAccessPair>()));
401      memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));
402   }
403 }
404
405 CXXRecordDecl *OverloadExpr::getNamingClass() const {
406   if (isa<UnresolvedLookupExpr>(this))
407     return cast<UnresolvedLookupExpr>(this)->getNamingClass();
408   else
409     return cast<UnresolvedMemberExpr>(this)->getNamingClass();
410 }
411
412 // DependentScopeDeclRefExpr
413 DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(QualType T,
414                             NestedNameSpecifierLoc QualifierLoc,
415                             SourceLocation TemplateKWLoc,
416                             const DeclarationNameInfo &NameInfo,
417                             const TemplateArgumentListInfo *Args)
418   : Expr(DependentScopeDeclRefExprClass, T, VK_LValue, OK_Ordinary,
419          true, true,
420          (NameInfo.isInstantiationDependent() ||
421           (QualifierLoc && 
422            QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())),
423          (NameInfo.containsUnexpandedParameterPack() ||
424           (QualifierLoc && 
425            QualifierLoc.getNestedNameSpecifier()
426                             ->containsUnexpandedParameterPack()))),
427     QualifierLoc(QualifierLoc), NameInfo(NameInfo), 
428     HasTemplateKWAndArgsInfo(Args != nullptr || TemplateKWLoc.isValid())
429 {
430   if (Args) {
431     bool Dependent = true;
432     bool InstantiationDependent = true;
433     bool ContainsUnexpandedParameterPack
434       = ExprBits.ContainsUnexpandedParameterPack;
435     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *Args,
436                                                Dependent,
437                                                InstantiationDependent,
438                                                ContainsUnexpandedParameterPack);
439     ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
440   } else if (TemplateKWLoc.isValid()) {
441     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
442   }
443 }
444
445 DependentScopeDeclRefExpr *
446 DependentScopeDeclRefExpr::Create(const ASTContext &C,
447                                   NestedNameSpecifierLoc QualifierLoc,
448                                   SourceLocation TemplateKWLoc,
449                                   const DeclarationNameInfo &NameInfo,
450                                   const TemplateArgumentListInfo *Args) {
451   assert(QualifierLoc && "should be created for dependent qualifiers");
452   std::size_t size = sizeof(DependentScopeDeclRefExpr);
453   if (Args)
454     size += ASTTemplateKWAndArgsInfo::sizeFor(Args->size());
455   else if (TemplateKWLoc.isValid())
456     size += ASTTemplateKWAndArgsInfo::sizeFor(0);
457   void *Mem = C.Allocate(size);
458   return new (Mem) DependentScopeDeclRefExpr(C.DependentTy, QualifierLoc,
459                                              TemplateKWLoc, NameInfo, Args);
460 }
461
462 DependentScopeDeclRefExpr *
463 DependentScopeDeclRefExpr::CreateEmpty(const ASTContext &C,
464                                        bool HasTemplateKWAndArgsInfo,
465                                        unsigned NumTemplateArgs) {
466   std::size_t size = sizeof(DependentScopeDeclRefExpr);
467   if (HasTemplateKWAndArgsInfo)
468     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
469   void *Mem = C.Allocate(size);
470   DependentScopeDeclRefExpr *E
471     = new (Mem) DependentScopeDeclRefExpr(QualType(), NestedNameSpecifierLoc(),
472                                           SourceLocation(),
473                                           DeclarationNameInfo(), nullptr);
474   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
475   return E;
476 }
477
478 SourceLocation CXXConstructExpr::getLocStart() const {
479   if (isa<CXXTemporaryObjectExpr>(this))
480     return cast<CXXTemporaryObjectExpr>(this)->getLocStart();
481   return Loc;
482 }
483
484 SourceLocation CXXConstructExpr::getLocEnd() const {
485   if (isa<CXXTemporaryObjectExpr>(this))
486     return cast<CXXTemporaryObjectExpr>(this)->getLocEnd();
487
488   if (ParenOrBraceRange.isValid())
489     return ParenOrBraceRange.getEnd();
490
491   SourceLocation End = Loc;
492   for (unsigned I = getNumArgs(); I > 0; --I) {
493     const Expr *Arg = getArg(I-1);
494     if (!Arg->isDefaultArgument()) {
495       SourceLocation NewEnd = Arg->getLocEnd();
496       if (NewEnd.isValid()) {
497         End = NewEnd;
498         break;
499       }
500     }
501   }
502
503   return End;
504 }
505
506 SourceRange CXXOperatorCallExpr::getSourceRangeImpl() const {
507   OverloadedOperatorKind Kind = getOperator();
508   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
509     if (getNumArgs() == 1)
510       // Prefix operator
511       return SourceRange(getOperatorLoc(), getArg(0)->getLocEnd());
512     else
513       // Postfix operator
514       return SourceRange(getArg(0)->getLocStart(), getOperatorLoc());
515   } else if (Kind == OO_Arrow) {
516     return getArg(0)->getSourceRange();
517   } else if (Kind == OO_Call) {
518     return SourceRange(getArg(0)->getLocStart(), getRParenLoc());
519   } else if (Kind == OO_Subscript) {
520     return SourceRange(getArg(0)->getLocStart(), getRParenLoc());
521   } else if (getNumArgs() == 1) {
522     return SourceRange(getOperatorLoc(), getArg(0)->getLocEnd());
523   } else if (getNumArgs() == 2) {
524     return SourceRange(getArg(0)->getLocStart(), getArg(1)->getLocEnd());
525   } else {
526     return getOperatorLoc();
527   }
528 }
529
530 Expr *CXXMemberCallExpr::getImplicitObjectArgument() const {
531   const Expr *Callee = getCallee()->IgnoreParens();
532   if (const MemberExpr *MemExpr = dyn_cast<MemberExpr>(Callee))
533     return MemExpr->getBase();
534   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Callee))
535     if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)
536       return BO->getLHS();
537
538   // FIXME: Will eventually need to cope with member pointers.
539   return nullptr;
540 }
541
542 CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const {
543   if (const MemberExpr *MemExpr = 
544       dyn_cast<MemberExpr>(getCallee()->IgnoreParens()))
545     return cast<CXXMethodDecl>(MemExpr->getMemberDecl());
546
547   // FIXME: Will eventually need to cope with member pointers.
548   return nullptr;
549 }
550
551
552 CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const {
553   Expr* ThisArg = getImplicitObjectArgument();
554   if (!ThisArg)
555     return nullptr;
556
557   if (ThisArg->getType()->isAnyPointerType())
558     return ThisArg->getType()->getPointeeType()->getAsCXXRecordDecl();
559
560   return ThisArg->getType()->getAsCXXRecordDecl();
561 }
562
563
564 //===----------------------------------------------------------------------===//
565 //  Named casts
566 //===----------------------------------------------------------------------===//
567
568 /// getCastName - Get the name of the C++ cast being used, e.g.,
569 /// "static_cast", "dynamic_cast", "reinterpret_cast", or
570 /// "const_cast". The returned pointer must not be freed.
571 const char *CXXNamedCastExpr::getCastName() const {
572   switch (getStmtClass()) {
573   case CXXStaticCastExprClass:      return "static_cast";
574   case CXXDynamicCastExprClass:     return "dynamic_cast";
575   case CXXReinterpretCastExprClass: return "reinterpret_cast";
576   case CXXConstCastExprClass:       return "const_cast";
577   default:                          return "<invalid cast>";
578   }
579 }
580
581 CXXStaticCastExpr *CXXStaticCastExpr::Create(const ASTContext &C, QualType T,
582                                              ExprValueKind VK,
583                                              CastKind K, Expr *Op,
584                                              const CXXCastPath *BasePath,
585                                              TypeSourceInfo *WrittenTy,
586                                              SourceLocation L, 
587                                              SourceLocation RParenLoc,
588                                              SourceRange AngleBrackets) {
589   unsigned PathSize = (BasePath ? BasePath->size() : 0);
590   void *Buffer = C.Allocate(sizeof(CXXStaticCastExpr)
591                             + PathSize * sizeof(CXXBaseSpecifier*));
592   CXXStaticCastExpr *E =
593     new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
594                                    RParenLoc, AngleBrackets);
595   if (PathSize) E->setCastPath(*BasePath);
596   return E;
597 }
598
599 CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C,
600                                                   unsigned PathSize) {
601   void *Buffer =
602     C.Allocate(sizeof(CXXStaticCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
603   return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize);
604 }
605
606 CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T,
607                                                ExprValueKind VK,
608                                                CastKind K, Expr *Op,
609                                                const CXXCastPath *BasePath,
610                                                TypeSourceInfo *WrittenTy,
611                                                SourceLocation L, 
612                                                SourceLocation RParenLoc,
613                                                SourceRange AngleBrackets) {
614   unsigned PathSize = (BasePath ? BasePath->size() : 0);
615   void *Buffer = C.Allocate(sizeof(CXXDynamicCastExpr)
616                             + PathSize * sizeof(CXXBaseSpecifier*));
617   CXXDynamicCastExpr *E =
618     new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
619                                     RParenLoc, AngleBrackets);
620   if (PathSize) E->setCastPath(*BasePath);
621   return E;
622 }
623
624 CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C,
625                                                     unsigned PathSize) {
626   void *Buffer =
627     C.Allocate(sizeof(CXXDynamicCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
628   return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize);
629 }
630
631 /// isAlwaysNull - Return whether the result of the dynamic_cast is proven
632 /// to always be null. For example:
633 ///
634 /// struct A { };
635 /// struct B final : A { };
636 /// struct C { };
637 ///
638 /// C *f(B* b) { return dynamic_cast<C*>(b); }
639 bool CXXDynamicCastExpr::isAlwaysNull() const
640 {
641   QualType SrcType = getSubExpr()->getType();
642   QualType DestType = getType();
643
644   if (const PointerType *SrcPTy = SrcType->getAs<PointerType>()) {
645     SrcType = SrcPTy->getPointeeType();
646     DestType = DestType->castAs<PointerType>()->getPointeeType();
647   }
648
649   if (DestType->isVoidType())
650     return false;
651
652   const CXXRecordDecl *SrcRD = 
653     cast<CXXRecordDecl>(SrcType->castAs<RecordType>()->getDecl());
654
655   if (!SrcRD->hasAttr<FinalAttr>())
656     return false;
657
658   const CXXRecordDecl *DestRD = 
659     cast<CXXRecordDecl>(DestType->castAs<RecordType>()->getDecl());
660
661   return !DestRD->isDerivedFrom(SrcRD);
662 }
663
664 CXXReinterpretCastExpr *
665 CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T,
666                                ExprValueKind VK, CastKind K, Expr *Op,
667                                const CXXCastPath *BasePath,
668                                TypeSourceInfo *WrittenTy, SourceLocation L, 
669                                SourceLocation RParenLoc,
670                                SourceRange AngleBrackets) {
671   unsigned PathSize = (BasePath ? BasePath->size() : 0);
672   void *Buffer =
673     C.Allocate(sizeof(CXXReinterpretCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
674   CXXReinterpretCastExpr *E =
675     new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
676                                         RParenLoc, AngleBrackets);
677   if (PathSize) E->setCastPath(*BasePath);
678   return E;
679 }
680
681 CXXReinterpretCastExpr *
682 CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {
683   void *Buffer = C.Allocate(sizeof(CXXReinterpretCastExpr)
684                             + PathSize * sizeof(CXXBaseSpecifier*));
685   return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize);
686 }
687
688 CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T,
689                                            ExprValueKind VK, Expr *Op,
690                                            TypeSourceInfo *WrittenTy,
691                                            SourceLocation L, 
692                                            SourceLocation RParenLoc,
693                                            SourceRange AngleBrackets) {
694   return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets);
695 }
696
697 CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) {
698   return new (C) CXXConstCastExpr(EmptyShell());
699 }
700
701 CXXFunctionalCastExpr *
702 CXXFunctionalCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,
703                               TypeSourceInfo *Written, CastKind K, Expr *Op,
704                               const CXXCastPath *BasePath,
705                               SourceLocation L, SourceLocation R) {
706   unsigned PathSize = (BasePath ? BasePath->size() : 0);
707   void *Buffer = C.Allocate(sizeof(CXXFunctionalCastExpr)
708                             + PathSize * sizeof(CXXBaseSpecifier*));
709   CXXFunctionalCastExpr *E =
710     new (Buffer) CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, L, R);
711   if (PathSize) E->setCastPath(*BasePath);
712   return E;
713 }
714
715 CXXFunctionalCastExpr *
716 CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {
717   void *Buffer = C.Allocate(sizeof(CXXFunctionalCastExpr)
718                             + PathSize * sizeof(CXXBaseSpecifier*));
719   return new (Buffer) CXXFunctionalCastExpr(EmptyShell(), PathSize);
720 }
721
722 SourceLocation CXXFunctionalCastExpr::getLocStart() const {
723   return getTypeInfoAsWritten()->getTypeLoc().getLocStart();
724 }
725
726 SourceLocation CXXFunctionalCastExpr::getLocEnd() const {
727   return RParenLoc.isValid() ? RParenLoc : getSubExpr()->getLocEnd();
728 }
729
730 UserDefinedLiteral::LiteralOperatorKind
731 UserDefinedLiteral::getLiteralOperatorKind() const {
732   if (getNumArgs() == 0)
733     return LOK_Template;
734   if (getNumArgs() == 2)
735     return LOK_String;
736
737   assert(getNumArgs() == 1 && "unexpected #args in literal operator call");
738   QualType ParamTy =
739     cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();
740   if (ParamTy->isPointerType())
741     return LOK_Raw;
742   if (ParamTy->isAnyCharacterType())
743     return LOK_Character;
744   if (ParamTy->isIntegerType())
745     return LOK_Integer;
746   if (ParamTy->isFloatingType())
747     return LOK_Floating;
748
749   llvm_unreachable("unknown kind of literal operator");
750 }
751
752 Expr *UserDefinedLiteral::getCookedLiteral() {
753 #ifndef NDEBUG
754   LiteralOperatorKind LOK = getLiteralOperatorKind();
755   assert(LOK != LOK_Template && LOK != LOK_Raw && "not a cooked literal");
756 #endif
757   return getArg(0);
758 }
759
760 const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {
761   return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();
762 }
763
764 CXXDefaultArgExpr *
765 CXXDefaultArgExpr::Create(const ASTContext &C, SourceLocation Loc, 
766                           ParmVarDecl *Param, Expr *SubExpr) {
767   void *Mem = C.Allocate(sizeof(CXXDefaultArgExpr) + sizeof(Stmt *));
768   return new (Mem) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param, 
769                                      SubExpr);
770 }
771
772 CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &C, SourceLocation Loc,
773                                        FieldDecl *Field, QualType T)
774     : Expr(CXXDefaultInitExprClass, T.getNonLValueExprType(C),
775            T->isLValueReferenceType() ? VK_LValue : T->isRValueReferenceType()
776                                                         ? VK_XValue
777                                                         : VK_RValue,
778            /*FIXME*/ OK_Ordinary, false, false, false, false),
779       Field(Field), Loc(Loc) {
780   assert(Field->hasInClassInitializer());
781 }
782
783 CXXTemporary *CXXTemporary::Create(const ASTContext &C,
784                                    const CXXDestructorDecl *Destructor) {
785   return new (C) CXXTemporary(Destructor);
786 }
787
788 CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C,
789                                                    CXXTemporary *Temp,
790                                                    Expr* SubExpr) {
791   assert((SubExpr->getType()->isRecordType() ||
792           SubExpr->getType()->isArrayType()) &&
793          "Expression bound to a temporary must have record or array type!");
794
795   return new (C) CXXBindTemporaryExpr(Temp, SubExpr);
796 }
797
798 CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(const ASTContext &C,
799                                                CXXConstructorDecl *Cons,
800                                                TypeSourceInfo *Type,
801                                                ArrayRef<Expr*> Args,
802                                                SourceRange ParenOrBraceRange,
803                                                bool HadMultipleCandidates,
804                                                bool ListInitialization,
805                                                bool StdInitListInitialization,
806                                                bool ZeroInitialization)
807   : CXXConstructExpr(C, CXXTemporaryObjectExprClass, 
808                      Type->getType().getNonReferenceType(), 
809                      Type->getTypeLoc().getBeginLoc(),
810                      Cons, false, Args,
811                      HadMultipleCandidates,
812                      ListInitialization,
813                      StdInitListInitialization,
814                      ZeroInitialization,
815                      CXXConstructExpr::CK_Complete, ParenOrBraceRange),
816     Type(Type) {
817 }
818
819 SourceLocation CXXTemporaryObjectExpr::getLocStart() const {
820   return Type->getTypeLoc().getBeginLoc();
821 }
822
823 SourceLocation CXXTemporaryObjectExpr::getLocEnd() const {
824   SourceLocation Loc = getParenOrBraceRange().getEnd();
825   if (Loc.isInvalid() && getNumArgs())
826     Loc = getArg(getNumArgs()-1)->getLocEnd();
827   return Loc;
828 }
829
830 CXXConstructExpr *CXXConstructExpr::Create(const ASTContext &C, QualType T,
831                                            SourceLocation Loc,
832                                            CXXConstructorDecl *D, bool Elidable,
833                                            ArrayRef<Expr*> Args,
834                                            bool HadMultipleCandidates,
835                                            bool ListInitialization,
836                                            bool StdInitListInitialization,
837                                            bool ZeroInitialization,
838                                            ConstructionKind ConstructKind,
839                                            SourceRange ParenOrBraceRange) {
840   return new (C) CXXConstructExpr(C, CXXConstructExprClass, T, Loc, D, 
841                                   Elidable, Args,
842                                   HadMultipleCandidates, ListInitialization,
843                                   StdInitListInitialization,
844                                   ZeroInitialization, ConstructKind,
845                                   ParenOrBraceRange);
846 }
847
848 CXXConstructExpr::CXXConstructExpr(const ASTContext &C, StmtClass SC,
849                                    QualType T, SourceLocation Loc,
850                                    CXXConstructorDecl *D, bool elidable,
851                                    ArrayRef<Expr*> args,
852                                    bool HadMultipleCandidates,
853                                    bool ListInitialization,
854                                    bool StdInitListInitialization,
855                                    bool ZeroInitialization,
856                                    ConstructionKind ConstructKind,
857                                    SourceRange ParenOrBraceRange)
858   : Expr(SC, T, VK_RValue, OK_Ordinary,
859          T->isDependentType(), T->isDependentType(),
860          T->isInstantiationDependentType(),
861          T->containsUnexpandedParameterPack()),
862     Constructor(D), Loc(Loc), ParenOrBraceRange(ParenOrBraceRange),
863     NumArgs(args.size()),
864     Elidable(elidable), HadMultipleCandidates(HadMultipleCandidates),
865     ListInitialization(ListInitialization),
866     StdInitListInitialization(StdInitListInitialization),
867     ZeroInitialization(ZeroInitialization),
868     ConstructKind(ConstructKind), Args(nullptr)
869 {
870   if (NumArgs) {
871     Args = new (C) Stmt*[args.size()];
872     
873     for (unsigned i = 0; i != args.size(); ++i) {
874       assert(args[i] && "NULL argument in CXXConstructExpr");
875
876       if (args[i]->isValueDependent())
877         ExprBits.ValueDependent = true;
878       if (args[i]->isInstantiationDependent())
879         ExprBits.InstantiationDependent = true;
880       if (args[i]->containsUnexpandedParameterPack())
881         ExprBits.ContainsUnexpandedParameterPack = true;
882   
883       Args[i] = args[i];
884     }
885   }
886 }
887
888 LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit,
889                              LambdaCaptureKind Kind, VarDecl *Var,
890                              SourceLocation EllipsisLoc)
891   : DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc)
892 {
893   unsigned Bits = 0;
894   if (Implicit)
895     Bits |= Capture_Implicit;
896   
897   switch (Kind) {
898   case LCK_This:
899     assert(!Var && "'this' capture cannot have a variable!");
900     break;
901
902   case LCK_ByCopy:
903     Bits |= Capture_ByCopy;
904     // Fall through 
905   case LCK_ByRef:
906     assert(Var && "capture must have a variable!");
907     break;
908   case LCK_VLAType:
909     assert(!Var && "VLA type capture cannot have a variable!");
910     Bits |= Capture_ByCopy;
911     break;
912   }
913   DeclAndBits.setInt(Bits);
914 }
915
916 LambdaCaptureKind LambdaCapture::getCaptureKind() const {
917   Decl *D = DeclAndBits.getPointer();
918   bool CapByCopy = DeclAndBits.getInt() & Capture_ByCopy;
919   if (!D)
920     return CapByCopy ? LCK_VLAType : LCK_This;
921
922   return CapByCopy ? LCK_ByCopy : LCK_ByRef;
923 }
924
925 LambdaExpr::LambdaExpr(QualType T,
926                        SourceRange IntroducerRange,
927                        LambdaCaptureDefault CaptureDefault,
928                        SourceLocation CaptureDefaultLoc,
929                        ArrayRef<Capture> Captures,
930                        bool ExplicitParams,
931                        bool ExplicitResultType,
932                        ArrayRef<Expr *> CaptureInits,
933                        ArrayRef<VarDecl *> ArrayIndexVars,
934                        ArrayRef<unsigned> ArrayIndexStarts,
935                        SourceLocation ClosingBrace,
936                        bool ContainsUnexpandedParameterPack)
937   : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary,
938          T->isDependentType(), T->isDependentType(), T->isDependentType(),
939          ContainsUnexpandedParameterPack),
940     IntroducerRange(IntroducerRange),
941     CaptureDefaultLoc(CaptureDefaultLoc),
942     NumCaptures(Captures.size()),
943     CaptureDefault(CaptureDefault),
944     ExplicitParams(ExplicitParams),
945     ExplicitResultType(ExplicitResultType),
946     ClosingBrace(ClosingBrace)
947 {
948   assert(CaptureInits.size() == Captures.size() && "Wrong number of arguments");
949   CXXRecordDecl *Class = getLambdaClass();
950   CXXRecordDecl::LambdaDefinitionData &Data = Class->getLambdaData();
951   
952   // FIXME: Propagate "has unexpanded parameter pack" bit.
953   
954   // Copy captures.
955   const ASTContext &Context = Class->getASTContext();
956   Data.NumCaptures = NumCaptures;
957   Data.NumExplicitCaptures = 0;
958   Data.Captures = (Capture *)Context.Allocate(sizeof(Capture) * NumCaptures);
959   Capture *ToCapture = Data.Captures;
960   for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
961     if (Captures[I].isExplicit())
962       ++Data.NumExplicitCaptures;
963     
964     *ToCapture++ = Captures[I];
965   }
966  
967   // Copy initialization expressions for the non-static data members.
968   Stmt **Stored = getStoredStmts();
969   for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
970     *Stored++ = CaptureInits[I];
971   
972   // Copy the body of the lambda.
973   *Stored++ = getCallOperator()->getBody();
974
975   // Copy the array index variables, if any.
976   HasArrayIndexVars = !ArrayIndexVars.empty();
977   if (HasArrayIndexVars) {
978     assert(ArrayIndexStarts.size() == NumCaptures);
979     memcpy(getArrayIndexVars(), ArrayIndexVars.data(),
980            sizeof(VarDecl *) * ArrayIndexVars.size());
981     memcpy(getArrayIndexStarts(), ArrayIndexStarts.data(), 
982            sizeof(unsigned) * Captures.size());
983     getArrayIndexStarts()[Captures.size()] = ArrayIndexVars.size();
984   }
985 }
986
987 LambdaExpr *LambdaExpr::Create(const ASTContext &Context,
988                                CXXRecordDecl *Class,
989                                SourceRange IntroducerRange,
990                                LambdaCaptureDefault CaptureDefault,
991                                SourceLocation CaptureDefaultLoc,
992                                ArrayRef<Capture> Captures,
993                                bool ExplicitParams,
994                                bool ExplicitResultType,
995                                ArrayRef<Expr *> CaptureInits,
996                                ArrayRef<VarDecl *> ArrayIndexVars,
997                                ArrayRef<unsigned> ArrayIndexStarts,
998                                SourceLocation ClosingBrace,
999                                bool ContainsUnexpandedParameterPack) {
1000   // Determine the type of the expression (i.e., the type of the
1001   // function object we're creating).
1002   QualType T = Context.getTypeDeclType(Class);
1003
1004   unsigned Size = sizeof(LambdaExpr) + sizeof(Stmt *) * (Captures.size() + 1);
1005   if (!ArrayIndexVars.empty()) {
1006     Size += sizeof(unsigned) * (Captures.size() + 1);
1007     // Realign for following VarDecl array.
1008     Size = llvm::RoundUpToAlignment(Size, llvm::alignOf<VarDecl*>());
1009     Size += sizeof(VarDecl *) * ArrayIndexVars.size();
1010   }
1011   void *Mem = Context.Allocate(Size);
1012   return new (Mem) LambdaExpr(T, IntroducerRange,
1013                               CaptureDefault, CaptureDefaultLoc, Captures,
1014                               ExplicitParams, ExplicitResultType,
1015                               CaptureInits, ArrayIndexVars, ArrayIndexStarts,
1016                               ClosingBrace, ContainsUnexpandedParameterPack);
1017 }
1018
1019 LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,
1020                                            unsigned NumCaptures,
1021                                            unsigned NumArrayIndexVars) {
1022   unsigned Size = sizeof(LambdaExpr) + sizeof(Stmt *) * (NumCaptures + 1);
1023   if (NumArrayIndexVars)
1024     Size += sizeof(VarDecl) * NumArrayIndexVars
1025           + sizeof(unsigned) * (NumCaptures + 1);
1026   void *Mem = C.Allocate(Size);
1027   return new (Mem) LambdaExpr(EmptyShell(), NumCaptures, NumArrayIndexVars > 0);
1028 }
1029
1030 bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {
1031   return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&
1032           (getCallOperator() == C->getCapturedVar()->getDeclContext()));
1033 }
1034
1035 LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
1036   return getLambdaClass()->getLambdaData().Captures;
1037 }
1038
1039 LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
1040   return capture_begin() + NumCaptures;
1041 }
1042
1043 LambdaExpr::capture_range LambdaExpr::captures() const {
1044   return capture_range(capture_begin(), capture_end());
1045 }
1046
1047 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
1048   return capture_begin();
1049 }
1050
1051 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
1052   struct CXXRecordDecl::LambdaDefinitionData &Data
1053     = getLambdaClass()->getLambdaData();
1054   return Data.Captures + Data.NumExplicitCaptures;
1055 }
1056
1057 LambdaExpr::capture_range LambdaExpr::explicit_captures() const {
1058   return capture_range(explicit_capture_begin(), explicit_capture_end());
1059 }
1060
1061 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
1062   return explicit_capture_end();
1063 }
1064
1065 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
1066   return capture_end();
1067 }
1068
1069 LambdaExpr::capture_range LambdaExpr::implicit_captures() const {
1070   return capture_range(implicit_capture_begin(), implicit_capture_end());
1071 }
1072
1073 ArrayRef<VarDecl *> 
1074 LambdaExpr::getCaptureInitIndexVars(capture_init_iterator Iter) const {
1075   assert(HasArrayIndexVars && "No array index-var data?");
1076   
1077   unsigned Index = Iter - capture_init_begin();
1078   assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
1079          "Capture index out-of-range");
1080   VarDecl **IndexVars = getArrayIndexVars();
1081   unsigned *IndexStarts = getArrayIndexStarts();
1082   return llvm::makeArrayRef(IndexVars + IndexStarts[Index],
1083                             IndexVars + IndexStarts[Index + 1]);
1084 }
1085
1086 CXXRecordDecl *LambdaExpr::getLambdaClass() const {
1087   return getType()->getAsCXXRecordDecl();
1088 }
1089
1090 CXXMethodDecl *LambdaExpr::getCallOperator() const {
1091   CXXRecordDecl *Record = getLambdaClass();
1092   return Record->getLambdaCallOperator();  
1093 }
1094
1095 TemplateParameterList *LambdaExpr::getTemplateParameterList() const {
1096   CXXRecordDecl *Record = getLambdaClass();
1097   return Record->getGenericLambdaTemplateParameterList();
1098
1099 }
1100
1101 CompoundStmt *LambdaExpr::getBody() const {
1102   if (!getStoredStmts()[NumCaptures])
1103     getStoredStmts()[NumCaptures] = getCallOperator()->getBody();
1104     
1105   return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
1106 }
1107
1108 bool LambdaExpr::isMutable() const {
1109   return !getCallOperator()->isConst();
1110 }
1111
1112 ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
1113                                    ArrayRef<CleanupObject> objects)
1114   : Expr(ExprWithCleanupsClass, subexpr->getType(),
1115          subexpr->getValueKind(), subexpr->getObjectKind(),
1116          subexpr->isTypeDependent(), subexpr->isValueDependent(),
1117          subexpr->isInstantiationDependent(),
1118          subexpr->containsUnexpandedParameterPack()),
1119     SubExpr(subexpr) {
1120   ExprWithCleanupsBits.NumObjects = objects.size();
1121   for (unsigned i = 0, e = objects.size(); i != e; ++i)
1122     getObjectsBuffer()[i] = objects[i];
1123 }
1124
1125 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,
1126                                            ArrayRef<CleanupObject> objects) {
1127   size_t size = sizeof(ExprWithCleanups)
1128               + objects.size() * sizeof(CleanupObject);
1129   void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
1130   return new (buffer) ExprWithCleanups(subexpr, objects);
1131 }
1132
1133 ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
1134   : Expr(ExprWithCleanupsClass, empty) {
1135   ExprWithCleanupsBits.NumObjects = numObjects;
1136 }
1137
1138 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,
1139                                            EmptyShell empty,
1140                                            unsigned numObjects) {
1141   size_t size = sizeof(ExprWithCleanups) + numObjects * sizeof(CleanupObject);
1142   void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
1143   return new (buffer) ExprWithCleanups(empty, numObjects);
1144 }
1145
1146 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
1147                                                  SourceLocation LParenLoc,
1148                                                  ArrayRef<Expr*> Args,
1149                                                  SourceLocation RParenLoc)
1150   : Expr(CXXUnresolvedConstructExprClass, 
1151          Type->getType().getNonReferenceType(),
1152          (Type->getType()->isLValueReferenceType() ? VK_LValue
1153           :Type->getType()->isRValueReferenceType()? VK_XValue
1154           :VK_RValue),
1155          OK_Ordinary,
1156          Type->getType()->isDependentType(), true, true,
1157          Type->getType()->containsUnexpandedParameterPack()),
1158     Type(Type),
1159     LParenLoc(LParenLoc),
1160     RParenLoc(RParenLoc),
1161     NumArgs(Args.size()) {
1162   Stmt **StoredArgs = reinterpret_cast<Stmt **>(this + 1);
1163   for (unsigned I = 0; I != Args.size(); ++I) {
1164     if (Args[I]->containsUnexpandedParameterPack())
1165       ExprBits.ContainsUnexpandedParameterPack = true;
1166
1167     StoredArgs[I] = Args[I];
1168   }
1169 }
1170
1171 CXXUnresolvedConstructExpr *
1172 CXXUnresolvedConstructExpr::Create(const ASTContext &C,
1173                                    TypeSourceInfo *Type,
1174                                    SourceLocation LParenLoc,
1175                                    ArrayRef<Expr*> Args,
1176                                    SourceLocation RParenLoc) {
1177   void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
1178                          sizeof(Expr *) * Args.size());
1179   return new (Mem) CXXUnresolvedConstructExpr(Type, LParenLoc, Args, RParenLoc);
1180 }
1181
1182 CXXUnresolvedConstructExpr *
1183 CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &C, unsigned NumArgs) {
1184   Stmt::EmptyShell Empty;
1185   void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
1186                          sizeof(Expr *) * NumArgs);
1187   return new (Mem) CXXUnresolvedConstructExpr(Empty, NumArgs);
1188 }
1189
1190 SourceLocation CXXUnresolvedConstructExpr::getLocStart() const {
1191   return Type->getTypeLoc().getBeginLoc();
1192 }
1193
1194 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(const ASTContext &C,
1195                                                  Expr *Base, QualType BaseType,
1196                                                  bool IsArrow,
1197                                                  SourceLocation OperatorLoc,
1198                                           NestedNameSpecifierLoc QualifierLoc,
1199                                           SourceLocation TemplateKWLoc,
1200                                           NamedDecl *FirstQualifierFoundInScope,
1201                                           DeclarationNameInfo MemberNameInfo,
1202                                    const TemplateArgumentListInfo *TemplateArgs)
1203   : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
1204          VK_LValue, OK_Ordinary, true, true, true,
1205          ((Base && Base->containsUnexpandedParameterPack()) ||
1206           (QualifierLoc && 
1207            QualifierLoc.getNestedNameSpecifier()
1208                                        ->containsUnexpandedParameterPack()) ||
1209           MemberNameInfo.containsUnexpandedParameterPack())),
1210     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
1211     HasTemplateKWAndArgsInfo(TemplateArgs != nullptr ||
1212                              TemplateKWLoc.isValid()),
1213     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc), 
1214     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
1215     MemberNameInfo(MemberNameInfo) {
1216   if (TemplateArgs) {
1217     bool Dependent = true;
1218     bool InstantiationDependent = true;
1219     bool ContainsUnexpandedParameterPack = false;
1220     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
1221                                                Dependent,
1222                                                InstantiationDependent,
1223                                                ContainsUnexpandedParameterPack);
1224     if (ContainsUnexpandedParameterPack)
1225       ExprBits.ContainsUnexpandedParameterPack = true;
1226   } else if (TemplateKWLoc.isValid()) {
1227     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1228   }
1229 }
1230
1231 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(const ASTContext &C,
1232                           Expr *Base, QualType BaseType,
1233                           bool IsArrow,
1234                           SourceLocation OperatorLoc,
1235                           NestedNameSpecifierLoc QualifierLoc,
1236                           NamedDecl *FirstQualifierFoundInScope,
1237                           DeclarationNameInfo MemberNameInfo)
1238   : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
1239          VK_LValue, OK_Ordinary, true, true, true,
1240          ((Base && Base->containsUnexpandedParameterPack()) ||
1241           (QualifierLoc && 
1242            QualifierLoc.getNestedNameSpecifier()->
1243                                          containsUnexpandedParameterPack()) ||
1244           MemberNameInfo.containsUnexpandedParameterPack())),
1245     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
1246     HasTemplateKWAndArgsInfo(false),
1247     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
1248     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
1249     MemberNameInfo(MemberNameInfo) { }
1250
1251 CXXDependentScopeMemberExpr *
1252 CXXDependentScopeMemberExpr::Create(const ASTContext &C,
1253                                 Expr *Base, QualType BaseType, bool IsArrow,
1254                                 SourceLocation OperatorLoc,
1255                                 NestedNameSpecifierLoc QualifierLoc,
1256                                 SourceLocation TemplateKWLoc,
1257                                 NamedDecl *FirstQualifierFoundInScope,
1258                                 DeclarationNameInfo MemberNameInfo,
1259                                 const TemplateArgumentListInfo *TemplateArgs) {
1260   if (!TemplateArgs && !TemplateKWLoc.isValid())
1261     return new (C) CXXDependentScopeMemberExpr(C, Base, BaseType,
1262                                                IsArrow, OperatorLoc,
1263                                                QualifierLoc,
1264                                                FirstQualifierFoundInScope,
1265                                                MemberNameInfo);
1266
1267   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1268   std::size_t size = sizeof(CXXDependentScopeMemberExpr)
1269     + ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1270
1271   void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
1272   return new (Mem) CXXDependentScopeMemberExpr(C, Base, BaseType,
1273                                                IsArrow, OperatorLoc,
1274                                                QualifierLoc,
1275                                                TemplateKWLoc,
1276                                                FirstQualifierFoundInScope,
1277                                                MemberNameInfo, TemplateArgs);
1278 }
1279
1280 CXXDependentScopeMemberExpr *
1281 CXXDependentScopeMemberExpr::CreateEmpty(const ASTContext &C,
1282                                          bool HasTemplateKWAndArgsInfo,
1283                                          unsigned NumTemplateArgs) {
1284   if (!HasTemplateKWAndArgsInfo)
1285     return new (C) CXXDependentScopeMemberExpr(C, nullptr, QualType(),
1286                                                0, SourceLocation(),
1287                                                NestedNameSpecifierLoc(),
1288                                                nullptr, DeclarationNameInfo());
1289
1290   std::size_t size = sizeof(CXXDependentScopeMemberExpr) +
1291                      ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1292   void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
1293   CXXDependentScopeMemberExpr *E
1294     =  new (Mem) CXXDependentScopeMemberExpr(C, nullptr, QualType(),
1295                                              0, SourceLocation(),
1296                                              NestedNameSpecifierLoc(),
1297                                              SourceLocation(), nullptr,
1298                                              DeclarationNameInfo(), nullptr);
1299   E->HasTemplateKWAndArgsInfo = true;
1300   return E;
1301 }
1302
1303 bool CXXDependentScopeMemberExpr::isImplicitAccess() const {
1304   if (!Base)
1305     return true;
1306   
1307   return cast<Expr>(Base)->isImplicitCXXThis();
1308 }
1309
1310 static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1311                                             UnresolvedSetIterator end) {
1312   do {
1313     NamedDecl *decl = *begin;
1314     if (isa<UnresolvedUsingValueDecl>(decl))
1315       return false;
1316
1317     // Unresolved member expressions should only contain methods and
1318     // method templates.
1319     if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())
1320             ->isStatic())
1321       return false;
1322   } while (++begin != end);
1323
1324   return true;
1325 }
1326
1327 UnresolvedMemberExpr::UnresolvedMemberExpr(const ASTContext &C,
1328                                            bool HasUnresolvedUsing,
1329                                            Expr *Base, QualType BaseType,
1330                                            bool IsArrow,
1331                                            SourceLocation OperatorLoc,
1332                                            NestedNameSpecifierLoc QualifierLoc,
1333                                            SourceLocation TemplateKWLoc,
1334                                    const DeclarationNameInfo &MemberNameInfo,
1335                                    const TemplateArgumentListInfo *TemplateArgs,
1336                                            UnresolvedSetIterator Begin, 
1337                                            UnresolvedSetIterator End)
1338   : OverloadExpr(UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc,
1339                  MemberNameInfo, TemplateArgs, Begin, End,
1340                  // Dependent
1341                  ((Base && Base->isTypeDependent()) ||
1342                   BaseType->isDependentType()),
1343                  ((Base && Base->isInstantiationDependent()) ||
1344                    BaseType->isInstantiationDependentType()),
1345                  // Contains unexpanded parameter pack
1346                  ((Base && Base->containsUnexpandedParameterPack()) ||
1347                   BaseType->containsUnexpandedParameterPack())),
1348     IsArrow(IsArrow), HasUnresolvedUsing(HasUnresolvedUsing),
1349     Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1350
1351   // Check whether all of the members are non-static member functions,
1352   // and if so, mark give this bound-member type instead of overload type.
1353   if (hasOnlyNonStaticMemberFunctions(Begin, End))
1354     setType(C.BoundMemberTy);
1355 }
1356
1357 bool UnresolvedMemberExpr::isImplicitAccess() const {
1358   if (!Base)
1359     return true;
1360   
1361   return cast<Expr>(Base)->isImplicitCXXThis();
1362 }
1363
1364 UnresolvedMemberExpr *
1365 UnresolvedMemberExpr::Create(const ASTContext &C, bool HasUnresolvedUsing,
1366                              Expr *Base, QualType BaseType, bool IsArrow,
1367                              SourceLocation OperatorLoc,
1368                              NestedNameSpecifierLoc QualifierLoc,
1369                              SourceLocation TemplateKWLoc,
1370                              const DeclarationNameInfo &MemberNameInfo,
1371                              const TemplateArgumentListInfo *TemplateArgs,
1372                              UnresolvedSetIterator Begin, 
1373                              UnresolvedSetIterator End) {
1374   std::size_t size = sizeof(UnresolvedMemberExpr);
1375   if (TemplateArgs)
1376     size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
1377   else if (TemplateKWLoc.isValid())
1378     size += ASTTemplateKWAndArgsInfo::sizeFor(0);
1379
1380   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
1381   return new (Mem) UnresolvedMemberExpr(C, 
1382                              HasUnresolvedUsing, Base, BaseType,
1383                              IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1384                              MemberNameInfo, TemplateArgs, Begin, End);
1385 }
1386
1387 UnresolvedMemberExpr *
1388 UnresolvedMemberExpr::CreateEmpty(const ASTContext &C,
1389                                   bool HasTemplateKWAndArgsInfo,
1390                                   unsigned NumTemplateArgs) {
1391   std::size_t size = sizeof(UnresolvedMemberExpr);
1392   if (HasTemplateKWAndArgsInfo)
1393     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1394
1395   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
1396   UnresolvedMemberExpr *E = new (Mem) UnresolvedMemberExpr(EmptyShell());
1397   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
1398   return E;
1399 }
1400
1401 CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() const {
1402   // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1403
1404   // If there was a nested name specifier, it names the naming class.
1405   // It can't be dependent: after all, we were actually able to do the
1406   // lookup.
1407   CXXRecordDecl *Record = nullptr;
1408   auto *NNS = getQualifier();
1409   if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {
1410     const Type *T = getQualifier()->getAsType();
1411     assert(T && "qualifier in member expression does not name type");
1412     Record = T->getAsCXXRecordDecl();
1413     assert(Record && "qualifier in member expression does not name record");
1414   }
1415   // Otherwise the naming class must have been the base class.
1416   else {
1417     QualType BaseType = getBaseType().getNonReferenceType();
1418     if (isArrow()) {
1419       const PointerType *PT = BaseType->getAs<PointerType>();
1420       assert(PT && "base of arrow member access is not pointer");
1421       BaseType = PT->getPointeeType();
1422     }
1423     
1424     Record = BaseType->getAsCXXRecordDecl();
1425     assert(Record && "base of member expression does not name record");
1426   }
1427   
1428   return Record;
1429 }
1430
1431 SubstNonTypeTemplateParmPackExpr::
1432 SubstNonTypeTemplateParmPackExpr(QualType T, 
1433                                  NonTypeTemplateParmDecl *Param,
1434                                  SourceLocation NameLoc,
1435                                  const TemplateArgument &ArgPack)
1436   : Expr(SubstNonTypeTemplateParmPackExprClass, T, VK_RValue, OK_Ordinary, 
1437          true, true, true, true),
1438     Param(Param), Arguments(ArgPack.pack_begin()), 
1439     NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) { }
1440
1441 TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1442   return TemplateArgument(Arguments, NumArguments);
1443 }
1444
1445 FunctionParmPackExpr::FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
1446                                            SourceLocation NameLoc,
1447                                            unsigned NumParams,
1448                                            Decl * const *Params)
1449   : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary,
1450          true, true, true, true),
1451     ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
1452   if (Params)
1453     std::uninitialized_copy(Params, Params + NumParams,
1454                             reinterpret_cast<Decl**>(this+1));
1455 }
1456
1457 FunctionParmPackExpr *
1458 FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,
1459                              ParmVarDecl *ParamPack, SourceLocation NameLoc,
1460                              ArrayRef<Decl *> Params) {
1461   return new (Context.Allocate(sizeof(FunctionParmPackExpr) +
1462                                sizeof(ParmVarDecl*) * Params.size()))
1463     FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
1464 }
1465
1466 FunctionParmPackExpr *
1467 FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,
1468                                   unsigned NumParams) {
1469   return new (Context.Allocate(sizeof(FunctionParmPackExpr) +
1470                                sizeof(ParmVarDecl*) * NumParams))
1471     FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);
1472 }
1473
1474 void MaterializeTemporaryExpr::setExtendingDecl(const ValueDecl *ExtendedBy,
1475                                                 unsigned ManglingNumber) {
1476   // We only need extra state if we have to remember more than just the Stmt.
1477   if (!ExtendedBy)
1478     return;
1479
1480   // We may need to allocate extra storage for the mangling number and the
1481   // extended-by ValueDecl.
1482   if (!State.is<ExtraState *>()) {
1483     auto ES = new (ExtendedBy->getASTContext()) ExtraState;
1484     ES->Temporary = State.get<Stmt *>();
1485     State = ES;
1486   }
1487
1488   auto ES = State.get<ExtraState *>();
1489   ES->ExtendingDecl = ExtendedBy;
1490   ES->ManglingNumber = ManglingNumber;
1491 }
1492
1493 TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1494                              ArrayRef<TypeSourceInfo *> Args,
1495                              SourceLocation RParenLoc,
1496                              bool Value)
1497   : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary,
1498          /*TypeDependent=*/false,
1499          /*ValueDependent=*/false,
1500          /*InstantiationDependent=*/false,
1501          /*ContainsUnexpandedParameterPack=*/false),
1502     Loc(Loc), RParenLoc(RParenLoc)
1503 {
1504   TypeTraitExprBits.Kind = Kind;
1505   TypeTraitExprBits.Value = Value;
1506   TypeTraitExprBits.NumArgs = Args.size();
1507
1508   TypeSourceInfo **ToArgs = getTypeSourceInfos();
1509   
1510   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
1511     if (Args[I]->getType()->isDependentType())
1512       setValueDependent(true);
1513     if (Args[I]->getType()->isInstantiationDependentType())
1514       setInstantiationDependent(true);
1515     if (Args[I]->getType()->containsUnexpandedParameterPack())
1516       setContainsUnexpandedParameterPack(true);
1517     
1518     ToArgs[I] = Args[I];
1519   }
1520 }
1521
1522 TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,
1523                                      SourceLocation Loc, 
1524                                      TypeTrait Kind,
1525                                      ArrayRef<TypeSourceInfo *> Args,
1526                                      SourceLocation RParenLoc,
1527                                      bool Value) {
1528   unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * Args.size();
1529   void *Mem = C.Allocate(Size);
1530   return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1531 }
1532
1533 TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,
1534                                                  unsigned NumArgs) {
1535   unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * NumArgs;
1536   void *Mem = C.Allocate(Size);
1537   return new (Mem) TypeTraitExpr(EmptyShell());
1538 }
1539
1540 void ArrayTypeTraitExpr::anchor() { }