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