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