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