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