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