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