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