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