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