xref: /freebsd/contrib/llvm-project/clang/lib/AST/ExprCXX.cpp (revision 1323ec571215a77ddd21294f0871979d5ad6b992)
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.hasValue();
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.hasValue();
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 
994 CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(EmptyShell Empty,
995                                                unsigned NumArgs)
996     : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty, NumArgs) {}
997 
998 CXXTemporaryObjectExpr *CXXTemporaryObjectExpr::Create(
999     const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
1000     TypeSourceInfo *TSI, ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,
1001     bool HadMultipleCandidates, bool ListInitialization,
1002     bool StdInitListInitialization, bool ZeroInitialization) {
1003   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());
1004   void *Mem =
1005       Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,
1006                    alignof(CXXTemporaryObjectExpr));
1007   return new (Mem) CXXTemporaryObjectExpr(
1008       Cons, Ty, TSI, Args, ParenOrBraceRange, HadMultipleCandidates,
1009       ListInitialization, StdInitListInitialization, ZeroInitialization);
1010 }
1011 
1012 CXXTemporaryObjectExpr *
1013 CXXTemporaryObjectExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs) {
1014   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);
1015   void *Mem =
1016       Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,
1017                    alignof(CXXTemporaryObjectExpr));
1018   return new (Mem) CXXTemporaryObjectExpr(EmptyShell(), NumArgs);
1019 }
1020 
1021 SourceLocation CXXTemporaryObjectExpr::getBeginLoc() const {
1022   return getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1023 }
1024 
1025 SourceLocation CXXTemporaryObjectExpr::getEndLoc() const {
1026   SourceLocation Loc = getParenOrBraceRange().getEnd();
1027   if (Loc.isInvalid() && getNumArgs())
1028     Loc = getArg(getNumArgs() - 1)->getEndLoc();
1029   return Loc;
1030 }
1031 
1032 CXXConstructExpr *CXXConstructExpr::Create(
1033     const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1034     CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1035     bool HadMultipleCandidates, bool ListInitialization,
1036     bool StdInitListInitialization, bool ZeroInitialization,
1037     ConstructionKind ConstructKind, SourceRange ParenOrBraceRange) {
1038   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());
1039   void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,
1040                            alignof(CXXConstructExpr));
1041   return new (Mem) CXXConstructExpr(
1042       CXXConstructExprClass, Ty, Loc, Ctor, Elidable, Args,
1043       HadMultipleCandidates, ListInitialization, StdInitListInitialization,
1044       ZeroInitialization, ConstructKind, ParenOrBraceRange);
1045 }
1046 
1047 CXXConstructExpr *CXXConstructExpr::CreateEmpty(const ASTContext &Ctx,
1048                                                 unsigned NumArgs) {
1049   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);
1050   void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,
1051                            alignof(CXXConstructExpr));
1052   return new (Mem)
1053       CXXConstructExpr(CXXConstructExprClass, EmptyShell(), NumArgs);
1054 }
1055 
1056 CXXConstructExpr::CXXConstructExpr(
1057     StmtClass SC, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor,
1058     bool Elidable, ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1059     bool ListInitialization, bool StdInitListInitialization,
1060     bool ZeroInitialization, ConstructionKind ConstructKind,
1061     SourceRange ParenOrBraceRange)
1062     : Expr(SC, Ty, VK_PRValue, OK_Ordinary), Constructor(Ctor),
1063       ParenOrBraceRange(ParenOrBraceRange), NumArgs(Args.size()) {
1064   CXXConstructExprBits.Elidable = Elidable;
1065   CXXConstructExprBits.HadMultipleCandidates = HadMultipleCandidates;
1066   CXXConstructExprBits.ListInitialization = ListInitialization;
1067   CXXConstructExprBits.StdInitListInitialization = StdInitListInitialization;
1068   CXXConstructExprBits.ZeroInitialization = ZeroInitialization;
1069   CXXConstructExprBits.ConstructionKind = ConstructKind;
1070   CXXConstructExprBits.Loc = Loc;
1071 
1072   Stmt **TrailingArgs = getTrailingArgs();
1073   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
1074     assert(Args[I] && "NULL argument in CXXConstructExpr!");
1075     TrailingArgs[I] = Args[I];
1076   }
1077 
1078   setDependence(computeDependence(this));
1079 }
1080 
1081 CXXConstructExpr::CXXConstructExpr(StmtClass SC, EmptyShell Empty,
1082                                    unsigned NumArgs)
1083     : Expr(SC, Empty), NumArgs(NumArgs) {}
1084 
1085 LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit,
1086                              LambdaCaptureKind Kind, VarDecl *Var,
1087                              SourceLocation EllipsisLoc)
1088     : DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc) {
1089   unsigned Bits = 0;
1090   if (Implicit)
1091     Bits |= Capture_Implicit;
1092 
1093   switch (Kind) {
1094   case LCK_StarThis:
1095     Bits |= Capture_ByCopy;
1096     LLVM_FALLTHROUGH;
1097   case LCK_This:
1098     assert(!Var && "'this' capture cannot have a variable!");
1099     Bits |= Capture_This;
1100     break;
1101 
1102   case LCK_ByCopy:
1103     Bits |= Capture_ByCopy;
1104     LLVM_FALLTHROUGH;
1105   case LCK_ByRef:
1106     assert(Var && "capture must have a variable!");
1107     break;
1108   case LCK_VLAType:
1109     assert(!Var && "VLA type capture cannot have a variable!");
1110     break;
1111   }
1112   DeclAndBits.setInt(Bits);
1113 }
1114 
1115 LambdaCaptureKind LambdaCapture::getCaptureKind() const {
1116   if (capturesVLAType())
1117     return LCK_VLAType;
1118   bool CapByCopy = DeclAndBits.getInt() & Capture_ByCopy;
1119   if (capturesThis())
1120     return CapByCopy ? LCK_StarThis : LCK_This;
1121   return CapByCopy ? LCK_ByCopy : LCK_ByRef;
1122 }
1123 
1124 LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange,
1125                        LambdaCaptureDefault CaptureDefault,
1126                        SourceLocation CaptureDefaultLoc, bool ExplicitParams,
1127                        bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1128                        SourceLocation ClosingBrace,
1129                        bool ContainsUnexpandedParameterPack)
1130     : Expr(LambdaExprClass, T, VK_PRValue, OK_Ordinary),
1131       IntroducerRange(IntroducerRange), CaptureDefaultLoc(CaptureDefaultLoc),
1132       ClosingBrace(ClosingBrace) {
1133   LambdaExprBits.NumCaptures = CaptureInits.size();
1134   LambdaExprBits.CaptureDefault = CaptureDefault;
1135   LambdaExprBits.ExplicitParams = ExplicitParams;
1136   LambdaExprBits.ExplicitResultType = ExplicitResultType;
1137 
1138   CXXRecordDecl *Class = getLambdaClass();
1139   (void)Class;
1140   assert(capture_size() == Class->capture_size() && "Wrong number of captures");
1141   assert(getCaptureDefault() == Class->getLambdaCaptureDefault());
1142 
1143   // Copy initialization expressions for the non-static data members.
1144   Stmt **Stored = getStoredStmts();
1145   for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
1146     *Stored++ = CaptureInits[I];
1147 
1148   // Copy the body of the lambda.
1149   *Stored++ = getCallOperator()->getBody();
1150 
1151   setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
1152 }
1153 
1154 LambdaExpr::LambdaExpr(EmptyShell Empty, unsigned NumCaptures)
1155     : Expr(LambdaExprClass, Empty) {
1156   LambdaExprBits.NumCaptures = NumCaptures;
1157 
1158   // Initially don't initialize the body of the LambdaExpr. The body will
1159   // be lazily deserialized when needed.
1160   getStoredStmts()[NumCaptures] = nullptr; // Not one past the end.
1161 }
1162 
1163 LambdaExpr *LambdaExpr::Create(const ASTContext &Context, CXXRecordDecl *Class,
1164                                SourceRange IntroducerRange,
1165                                LambdaCaptureDefault CaptureDefault,
1166                                SourceLocation CaptureDefaultLoc,
1167                                bool ExplicitParams, bool ExplicitResultType,
1168                                ArrayRef<Expr *> CaptureInits,
1169                                SourceLocation ClosingBrace,
1170                                bool ContainsUnexpandedParameterPack) {
1171   // Determine the type of the expression (i.e., the type of the
1172   // function object we're creating).
1173   QualType T = Context.getTypeDeclType(Class);
1174 
1175   unsigned Size = totalSizeToAlloc<Stmt *>(CaptureInits.size() + 1);
1176   void *Mem = Context.Allocate(Size);
1177   return new (Mem)
1178       LambdaExpr(T, IntroducerRange, CaptureDefault, CaptureDefaultLoc,
1179                  ExplicitParams, ExplicitResultType, CaptureInits, ClosingBrace,
1180                  ContainsUnexpandedParameterPack);
1181 }
1182 
1183 LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,
1184                                            unsigned NumCaptures) {
1185   unsigned Size = totalSizeToAlloc<Stmt *>(NumCaptures + 1);
1186   void *Mem = C.Allocate(Size);
1187   return new (Mem) LambdaExpr(EmptyShell(), NumCaptures);
1188 }
1189 
1190 void LambdaExpr::initBodyIfNeeded() const {
1191   if (!getStoredStmts()[capture_size()]) {
1192     auto *This = const_cast<LambdaExpr *>(this);
1193     This->getStoredStmts()[capture_size()] = getCallOperator()->getBody();
1194   }
1195 }
1196 
1197 Stmt *LambdaExpr::getBody() const {
1198   initBodyIfNeeded();
1199   return getStoredStmts()[capture_size()];
1200 }
1201 
1202 const CompoundStmt *LambdaExpr::getCompoundStmtBody() const {
1203   Stmt *Body = getBody();
1204   if (const auto *CoroBody = dyn_cast<CoroutineBodyStmt>(Body))
1205     return cast<CompoundStmt>(CoroBody->getBody());
1206   return cast<CompoundStmt>(Body);
1207 }
1208 
1209 bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {
1210   return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&
1211           (getCallOperator() == C->getCapturedVar()->getDeclContext()));
1212 }
1213 
1214 LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
1215   return getLambdaClass()->getLambdaData().Captures;
1216 }
1217 
1218 LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
1219   return capture_begin() + capture_size();
1220 }
1221 
1222 LambdaExpr::capture_range LambdaExpr::captures() const {
1223   return capture_range(capture_begin(), capture_end());
1224 }
1225 
1226 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
1227   return capture_begin();
1228 }
1229 
1230 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
1231   struct CXXRecordDecl::LambdaDefinitionData &Data
1232     = getLambdaClass()->getLambdaData();
1233   return Data.Captures + Data.NumExplicitCaptures;
1234 }
1235 
1236 LambdaExpr::capture_range LambdaExpr::explicit_captures() const {
1237   return capture_range(explicit_capture_begin(), explicit_capture_end());
1238 }
1239 
1240 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
1241   return explicit_capture_end();
1242 }
1243 
1244 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
1245   return capture_end();
1246 }
1247 
1248 LambdaExpr::capture_range LambdaExpr::implicit_captures() const {
1249   return capture_range(implicit_capture_begin(), implicit_capture_end());
1250 }
1251 
1252 CXXRecordDecl *LambdaExpr::getLambdaClass() const {
1253   return getType()->getAsCXXRecordDecl();
1254 }
1255 
1256 CXXMethodDecl *LambdaExpr::getCallOperator() const {
1257   CXXRecordDecl *Record = getLambdaClass();
1258   return Record->getLambdaCallOperator();
1259 }
1260 
1261 FunctionTemplateDecl *LambdaExpr::getDependentCallOperator() const {
1262   CXXRecordDecl *Record = getLambdaClass();
1263   return Record->getDependentLambdaCallOperator();
1264 }
1265 
1266 TemplateParameterList *LambdaExpr::getTemplateParameterList() const {
1267   CXXRecordDecl *Record = getLambdaClass();
1268   return Record->getGenericLambdaTemplateParameterList();
1269 }
1270 
1271 ArrayRef<NamedDecl *> LambdaExpr::getExplicitTemplateParameters() const {
1272   const CXXRecordDecl *Record = getLambdaClass();
1273   return Record->getLambdaExplicitTemplateParameters();
1274 }
1275 
1276 Expr *LambdaExpr::getTrailingRequiresClause() const {
1277   return getCallOperator()->getTrailingRequiresClause();
1278 }
1279 
1280 bool LambdaExpr::isMutable() const { return !getCallOperator()->isConst(); }
1281 
1282 LambdaExpr::child_range LambdaExpr::children() {
1283   initBodyIfNeeded();
1284   return child_range(getStoredStmts(), getStoredStmts() + capture_size() + 1);
1285 }
1286 
1287 LambdaExpr::const_child_range LambdaExpr::children() const {
1288   initBodyIfNeeded();
1289   return const_child_range(getStoredStmts(),
1290                            getStoredStmts() + capture_size() + 1);
1291 }
1292 
1293 ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
1294                                    bool CleanupsHaveSideEffects,
1295                                    ArrayRef<CleanupObject> objects)
1296     : FullExpr(ExprWithCleanupsClass, subexpr) {
1297   ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects;
1298   ExprWithCleanupsBits.NumObjects = objects.size();
1299   for (unsigned i = 0, e = objects.size(); i != e; ++i)
1300     getTrailingObjects<CleanupObject>()[i] = objects[i];
1301 }
1302 
1303 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,
1304                                            bool CleanupsHaveSideEffects,
1305                                            ArrayRef<CleanupObject> objects) {
1306   void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(objects.size()),
1307                             alignof(ExprWithCleanups));
1308   return new (buffer)
1309       ExprWithCleanups(subexpr, CleanupsHaveSideEffects, objects);
1310 }
1311 
1312 ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
1313     : FullExpr(ExprWithCleanupsClass, empty) {
1314   ExprWithCleanupsBits.NumObjects = numObjects;
1315 }
1316 
1317 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,
1318                                            EmptyShell empty,
1319                                            unsigned numObjects) {
1320   void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(numObjects),
1321                             alignof(ExprWithCleanups));
1322   return new (buffer) ExprWithCleanups(empty, numObjects);
1323 }
1324 
1325 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(QualType T,
1326                                                        TypeSourceInfo *TSI,
1327                                                        SourceLocation LParenLoc,
1328                                                        ArrayRef<Expr *> Args,
1329                                                        SourceLocation RParenLoc)
1330     : Expr(CXXUnresolvedConstructExprClass, T,
1331            (TSI->getType()->isLValueReferenceType()   ? VK_LValue
1332             : TSI->getType()->isRValueReferenceType() ? VK_XValue
1333                                                       : VK_PRValue),
1334            OK_Ordinary),
1335       TSI(TSI), LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
1336   CXXUnresolvedConstructExprBits.NumArgs = Args.size();
1337   auto **StoredArgs = getTrailingObjects<Expr *>();
1338   for (unsigned I = 0; I != Args.size(); ++I)
1339     StoredArgs[I] = Args[I];
1340   setDependence(computeDependence(this));
1341 }
1342 
1343 CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create(
1344     const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc,
1345     ArrayRef<Expr *> Args, SourceLocation RParenLoc) {
1346   void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(Args.size()));
1347   return new (Mem)
1348       CXXUnresolvedConstructExpr(T, TSI, LParenLoc, Args, RParenLoc);
1349 }
1350 
1351 CXXUnresolvedConstructExpr *
1352 CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context,
1353                                         unsigned NumArgs) {
1354   void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(NumArgs));
1355   return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs);
1356 }
1357 
1358 SourceLocation CXXUnresolvedConstructExpr::getBeginLoc() const {
1359   return TSI->getTypeLoc().getBeginLoc();
1360 }
1361 
1362 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1363     const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1364     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1365     SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1366     DeclarationNameInfo MemberNameInfo,
1367     const TemplateArgumentListInfo *TemplateArgs)
1368     : Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue,
1369            OK_Ordinary),
1370       Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc),
1371       MemberNameInfo(MemberNameInfo) {
1372   CXXDependentScopeMemberExprBits.IsArrow = IsArrow;
1373   CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1374       (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1375   CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1376       FirstQualifierFoundInScope != nullptr;
1377   CXXDependentScopeMemberExprBits.OperatorLoc = OperatorLoc;
1378 
1379   if (TemplateArgs) {
1380     auto Deps = TemplateArgumentDependence::None;
1381     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1382         TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
1383         Deps);
1384   } else if (TemplateKWLoc.isValid()) {
1385     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1386         TemplateKWLoc);
1387   }
1388 
1389   if (hasFirstQualifierFoundInScope())
1390     *getTrailingObjects<NamedDecl *>() = FirstQualifierFoundInScope;
1391   setDependence(computeDependence(this));
1392 }
1393 
1394 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1395     EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
1396     bool HasFirstQualifierFoundInScope)
1397     : Expr(CXXDependentScopeMemberExprClass, Empty) {
1398   CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1399       HasTemplateKWAndArgsInfo;
1400   CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1401       HasFirstQualifierFoundInScope;
1402 }
1403 
1404 CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create(
1405     const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1406     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1407     SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1408     DeclarationNameInfo MemberNameInfo,
1409     const TemplateArgumentListInfo *TemplateArgs) {
1410   bool HasTemplateKWAndArgsInfo =
1411       (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1412   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1413   bool HasFirstQualifierFoundInScope = FirstQualifierFoundInScope != nullptr;
1414 
1415   unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1416                                    TemplateArgumentLoc, NamedDecl *>(
1417       HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1418 
1419   void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1420   return new (Mem) CXXDependentScopeMemberExpr(
1421       Ctx, Base, BaseType, IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1422       FirstQualifierFoundInScope, MemberNameInfo, TemplateArgs);
1423 }
1424 
1425 CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty(
1426     const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
1427     unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) {
1428   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1429 
1430   unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1431                                    TemplateArgumentLoc, NamedDecl *>(
1432       HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1433 
1434   void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1435   return new (Mem) CXXDependentScopeMemberExpr(
1436       EmptyShell(), HasTemplateKWAndArgsInfo, HasFirstQualifierFoundInScope);
1437 }
1438 
1439 static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1440                                             UnresolvedSetIterator end) {
1441   do {
1442     NamedDecl *decl = *begin;
1443     if (isa<UnresolvedUsingValueDecl>(decl))
1444       return false;
1445 
1446     // Unresolved member expressions should only contain methods and
1447     // method templates.
1448     if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())
1449             ->isStatic())
1450       return false;
1451   } while (++begin != end);
1452 
1453   return true;
1454 }
1455 
1456 UnresolvedMemberExpr::UnresolvedMemberExpr(
1457     const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1458     QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1459     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1460     const DeclarationNameInfo &MemberNameInfo,
1461     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1462     UnresolvedSetIterator End)
1463     : OverloadExpr(
1464           UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc,
1465           MemberNameInfo, TemplateArgs, Begin, End,
1466           // Dependent
1467           ((Base && Base->isTypeDependent()) || BaseType->isDependentType()),
1468           ((Base && Base->isInstantiationDependent()) ||
1469            BaseType->isInstantiationDependentType()),
1470           // Contains unexpanded parameter pack
1471           ((Base && Base->containsUnexpandedParameterPack()) ||
1472            BaseType->containsUnexpandedParameterPack())),
1473       Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1474   UnresolvedMemberExprBits.IsArrow = IsArrow;
1475   UnresolvedMemberExprBits.HasUnresolvedUsing = HasUnresolvedUsing;
1476 
1477   // Check whether all of the members are non-static member functions,
1478   // and if so, mark give this bound-member type instead of overload type.
1479   if (hasOnlyNonStaticMemberFunctions(Begin, End))
1480     setType(Context.BoundMemberTy);
1481 }
1482 
1483 UnresolvedMemberExpr::UnresolvedMemberExpr(EmptyShell Empty,
1484                                            unsigned NumResults,
1485                                            bool HasTemplateKWAndArgsInfo)
1486     : OverloadExpr(UnresolvedMemberExprClass, Empty, NumResults,
1487                    HasTemplateKWAndArgsInfo) {}
1488 
1489 bool UnresolvedMemberExpr::isImplicitAccess() const {
1490   if (!Base)
1491     return true;
1492 
1493   return cast<Expr>(Base)->isImplicitCXXThis();
1494 }
1495 
1496 UnresolvedMemberExpr *UnresolvedMemberExpr::Create(
1497     const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1498     QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1499     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1500     const DeclarationNameInfo &MemberNameInfo,
1501     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1502     UnresolvedSetIterator End) {
1503   unsigned NumResults = End - Begin;
1504   bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1505   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1506   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1507                                    TemplateArgumentLoc>(
1508       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1509   void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1510   return new (Mem) UnresolvedMemberExpr(
1511       Context, HasUnresolvedUsing, Base, BaseType, IsArrow, OperatorLoc,
1512       QualifierLoc, TemplateKWLoc, MemberNameInfo, TemplateArgs, Begin, End);
1513 }
1514 
1515 UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty(
1516     const ASTContext &Context, unsigned NumResults,
1517     bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {
1518   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1519   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1520                                    TemplateArgumentLoc>(
1521       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1522   void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1523   return new (Mem)
1524       UnresolvedMemberExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);
1525 }
1526 
1527 CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() {
1528   // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1529 
1530   // If there was a nested name specifier, it names the naming class.
1531   // It can't be dependent: after all, we were actually able to do the
1532   // lookup.
1533   CXXRecordDecl *Record = nullptr;
1534   auto *NNS = getQualifier();
1535   if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {
1536     const Type *T = getQualifier()->getAsType();
1537     assert(T && "qualifier in member expression does not name type");
1538     Record = T->getAsCXXRecordDecl();
1539     assert(Record && "qualifier in member expression does not name record");
1540   }
1541   // Otherwise the naming class must have been the base class.
1542   else {
1543     QualType BaseType = getBaseType().getNonReferenceType();
1544     if (isArrow())
1545       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1546 
1547     Record = BaseType->getAsCXXRecordDecl();
1548     assert(Record && "base of member expression does not name record");
1549   }
1550 
1551   return Record;
1552 }
1553 
1554 SizeOfPackExpr *
1555 SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc,
1556                        NamedDecl *Pack, SourceLocation PackLoc,
1557                        SourceLocation RParenLoc,
1558                        Optional<unsigned> Length,
1559                        ArrayRef<TemplateArgument> PartialArgs) {
1560   void *Storage =
1561       Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size()));
1562   return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,
1563                                       PackLoc, RParenLoc, Length, PartialArgs);
1564 }
1565 
1566 SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,
1567                                                    unsigned NumPartialArgs) {
1568   void *Storage =
1569       Context.Allocate(totalSizeToAlloc<TemplateArgument>(NumPartialArgs));
1570   return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);
1571 }
1572 
1573 QualType SubstNonTypeTemplateParmExpr::getParameterType(
1574     const ASTContext &Context) const {
1575   // Note that, for a class type NTTP, we will have an lvalue of type 'const
1576   // T', so we can't just compute this from the type and value category.
1577   if (isReferenceParameter())
1578     return Context.getLValueReferenceType(getType());
1579   return getType().getUnqualifiedType();
1580 }
1581 
1582 SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr(
1583     QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param,
1584     SourceLocation NameLoc, const TemplateArgument &ArgPack)
1585     : Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary),
1586       Param(Param), Arguments(ArgPack.pack_begin()),
1587       NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) {
1588   setDependence(ExprDependence::TypeValueInstantiation |
1589                 ExprDependence::UnexpandedPack);
1590 }
1591 
1592 TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1593   return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
1594 }
1595 
1596 FunctionParmPackExpr::FunctionParmPackExpr(QualType T, VarDecl *ParamPack,
1597                                            SourceLocation NameLoc,
1598                                            unsigned NumParams,
1599                                            VarDecl *const *Params)
1600     : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary),
1601       ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
1602   if (Params)
1603     std::uninitialized_copy(Params, Params + NumParams,
1604                             getTrailingObjects<VarDecl *>());
1605   setDependence(ExprDependence::TypeValueInstantiation |
1606                 ExprDependence::UnexpandedPack);
1607 }
1608 
1609 FunctionParmPackExpr *
1610 FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,
1611                              VarDecl *ParamPack, SourceLocation NameLoc,
1612                              ArrayRef<VarDecl *> Params) {
1613   return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(Params.size())))
1614       FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
1615 }
1616 
1617 FunctionParmPackExpr *
1618 FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,
1619                                   unsigned NumParams) {
1620   return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(NumParams)))
1621       FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);
1622 }
1623 
1624 MaterializeTemporaryExpr::MaterializeTemporaryExpr(
1625     QualType T, Expr *Temporary, bool BoundToLvalueReference,
1626     LifetimeExtendedTemporaryDecl *MTD)
1627     : Expr(MaterializeTemporaryExprClass, T,
1628            BoundToLvalueReference ? VK_LValue : VK_XValue, OK_Ordinary) {
1629   if (MTD) {
1630     State = MTD;
1631     MTD->ExprWithTemporary = Temporary;
1632     return;
1633   }
1634   State = Temporary;
1635   setDependence(computeDependence(this));
1636 }
1637 
1638 void MaterializeTemporaryExpr::setExtendingDecl(ValueDecl *ExtendedBy,
1639                                                 unsigned ManglingNumber) {
1640   // We only need extra state if we have to remember more than just the Stmt.
1641   if (!ExtendedBy)
1642     return;
1643 
1644   // We may need to allocate extra storage for the mangling number and the
1645   // extended-by ValueDecl.
1646   if (!State.is<LifetimeExtendedTemporaryDecl *>())
1647     State = LifetimeExtendedTemporaryDecl::Create(
1648         cast<Expr>(State.get<Stmt *>()), ExtendedBy, ManglingNumber);
1649 
1650   auto ES = State.get<LifetimeExtendedTemporaryDecl *>();
1651   ES->ExtendingDecl = ExtendedBy;
1652   ES->ManglingNumber = ManglingNumber;
1653 }
1654 
1655 bool MaterializeTemporaryExpr::isUsableInConstantExpressions(
1656     const ASTContext &Context) const {
1657   // C++20 [expr.const]p4:
1658   //   An object or reference is usable in constant expressions if it is [...]
1659   //   a temporary object of non-volatile const-qualified literal type
1660   //   whose lifetime is extended to that of a variable that is usable
1661   //   in constant expressions
1662   auto *VD = dyn_cast_or_null<VarDecl>(getExtendingDecl());
1663   return VD && getType().isConstant(Context) &&
1664          !getType().isVolatileQualified() &&
1665          getType()->isLiteralType(Context) &&
1666          VD->isUsableInConstantExpressions(Context);
1667 }
1668 
1669 TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1670                              ArrayRef<TypeSourceInfo *> Args,
1671                              SourceLocation RParenLoc, bool Value)
1672     : Expr(TypeTraitExprClass, T, VK_PRValue, OK_Ordinary), Loc(Loc),
1673       RParenLoc(RParenLoc) {
1674   assert(Kind <= TT_Last && "invalid enum value!");
1675   TypeTraitExprBits.Kind = Kind;
1676   assert(static_cast<unsigned>(Kind) == TypeTraitExprBits.Kind &&
1677          "TypeTraitExprBits.Kind overflow!");
1678   TypeTraitExprBits.Value = Value;
1679   TypeTraitExprBits.NumArgs = Args.size();
1680   assert(Args.size() == TypeTraitExprBits.NumArgs &&
1681          "TypeTraitExprBits.NumArgs overflow!");
1682 
1683   auto **ToArgs = getTrailingObjects<TypeSourceInfo *>();
1684   for (unsigned I = 0, N = Args.size(); I != N; ++I)
1685     ToArgs[I] = Args[I];
1686 
1687   setDependence(computeDependence(this));
1688 }
1689 
1690 TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,
1691                                      SourceLocation Loc,
1692                                      TypeTrait Kind,
1693                                      ArrayRef<TypeSourceInfo *> Args,
1694                                      SourceLocation RParenLoc,
1695                                      bool Value) {
1696   void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(Args.size()));
1697   return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1698 }
1699 
1700 TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,
1701                                                  unsigned NumArgs) {
1702   void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(NumArgs));
1703   return new (Mem) TypeTraitExpr(EmptyShell());
1704 }
1705 
1706 CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config,
1707                                        ArrayRef<Expr *> Args, QualType Ty,
1708                                        ExprValueKind VK, SourceLocation RP,
1709                                        FPOptionsOverride FPFeatures,
1710                                        unsigned MinNumArgs)
1711     : CallExpr(CUDAKernelCallExprClass, Fn, /*PreArgs=*/Config, Args, Ty, VK,
1712                RP, FPFeatures, MinNumArgs, NotADL) {}
1713 
1714 CUDAKernelCallExpr::CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures,
1715                                        EmptyShell Empty)
1716     : CallExpr(CUDAKernelCallExprClass, /*NumPreArgs=*/END_PREARG, NumArgs,
1717                HasFPFeatures, Empty) {}
1718 
1719 CUDAKernelCallExpr *
1720 CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config,
1721                            ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1722                            SourceLocation RP, FPOptionsOverride FPFeatures,
1723                            unsigned MinNumArgs) {
1724   // Allocate storage for the trailing objects of CallExpr.
1725   unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1726   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1727       /*NumPreArgs=*/END_PREARG, NumArgs, FPFeatures.requiresTrailingStorage());
1728   void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1729                            alignof(CUDAKernelCallExpr));
1730   return new (Mem)
1731       CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, FPFeatures, MinNumArgs);
1732 }
1733 
1734 CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx,
1735                                                     unsigned NumArgs,
1736                                                     bool HasFPFeatures,
1737                                                     EmptyShell Empty) {
1738   // Allocate storage for the trailing objects of CallExpr.
1739   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1740       /*NumPreArgs=*/END_PREARG, NumArgs, HasFPFeatures);
1741   void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1742                            alignof(CUDAKernelCallExpr));
1743   return new (Mem) CUDAKernelCallExpr(NumArgs, HasFPFeatures, Empty);
1744 }
1745