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