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