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,
1091                        ArrayRef<LambdaCapture> Captures, bool ExplicitParams,
1092                        bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1093                        SourceLocation ClosingBrace,
1094                        bool ContainsUnexpandedParameterPack)
1095     : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary),
1096       IntroducerRange(IntroducerRange), CaptureDefaultLoc(CaptureDefaultLoc),
1097       NumCaptures(Captures.size()), CaptureDefault(CaptureDefault),
1098       ExplicitParams(ExplicitParams), ExplicitResultType(ExplicitResultType),
1099       ClosingBrace(ClosingBrace) {
1100   assert(CaptureInits.size() == Captures.size() && "Wrong number of arguments");
1101   CXXRecordDecl *Class = getLambdaClass();
1102   CXXRecordDecl::LambdaDefinitionData &Data = Class->getLambdaData();
1103 
1104   // FIXME: Propagate "has unexpanded parameter pack" bit.
1105 
1106   // Copy captures.
1107   const ASTContext &Context = Class->getASTContext();
1108   Data.NumCaptures = NumCaptures;
1109   Data.NumExplicitCaptures = 0;
1110   Data.Captures =
1111       (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) * NumCaptures);
1112   LambdaCapture *ToCapture = Data.Captures;
1113   for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
1114     if (Captures[I].isExplicit())
1115       ++Data.NumExplicitCaptures;
1116 
1117     *ToCapture++ = Captures[I];
1118   }
1119 
1120   // Copy initialization expressions for the non-static data members.
1121   Stmt **Stored = getStoredStmts();
1122   for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
1123     *Stored++ = CaptureInits[I];
1124 
1125   // Copy the body of the lambda.
1126   *Stored++ = getCallOperator()->getBody();
1127 
1128   setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
1129 }
1130 
1131 LambdaExpr *LambdaExpr::Create(
1132     const ASTContext &Context, CXXRecordDecl *Class,
1133     SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault,
1134     SourceLocation CaptureDefaultLoc, ArrayRef<LambdaCapture> Captures,
1135     bool ExplicitParams, bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1136     SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack) {
1137   // Determine the type of the expression (i.e., the type of the
1138   // function object we're creating).
1139   QualType T = Context.getTypeDeclType(Class);
1140 
1141   unsigned Size = totalSizeToAlloc<Stmt *>(Captures.size() + 1);
1142   void *Mem = Context.Allocate(Size);
1143   return new (Mem)
1144       LambdaExpr(T, IntroducerRange, CaptureDefault, CaptureDefaultLoc,
1145                  Captures, ExplicitParams, ExplicitResultType, CaptureInits,
1146                  ClosingBrace, ContainsUnexpandedParameterPack);
1147 }
1148 
1149 LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,
1150                                            unsigned NumCaptures) {
1151   unsigned Size = totalSizeToAlloc<Stmt *>(NumCaptures + 1);
1152   void *Mem = C.Allocate(Size);
1153   return new (Mem) LambdaExpr(EmptyShell(), NumCaptures);
1154 }
1155 
1156 bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {
1157   return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&
1158           (getCallOperator() == C->getCapturedVar()->getDeclContext()));
1159 }
1160 
1161 LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
1162   return getLambdaClass()->getLambdaData().Captures;
1163 }
1164 
1165 LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
1166   return capture_begin() + NumCaptures;
1167 }
1168 
1169 LambdaExpr::capture_range LambdaExpr::captures() const {
1170   return capture_range(capture_begin(), capture_end());
1171 }
1172 
1173 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
1174   return capture_begin();
1175 }
1176 
1177 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
1178   struct CXXRecordDecl::LambdaDefinitionData &Data
1179     = getLambdaClass()->getLambdaData();
1180   return Data.Captures + Data.NumExplicitCaptures;
1181 }
1182 
1183 LambdaExpr::capture_range LambdaExpr::explicit_captures() const {
1184   return capture_range(explicit_capture_begin(), explicit_capture_end());
1185 }
1186 
1187 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
1188   return explicit_capture_end();
1189 }
1190 
1191 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
1192   return capture_end();
1193 }
1194 
1195 LambdaExpr::capture_range LambdaExpr::implicit_captures() const {
1196   return capture_range(implicit_capture_begin(), implicit_capture_end());
1197 }
1198 
1199 CXXRecordDecl *LambdaExpr::getLambdaClass() const {
1200   return getType()->getAsCXXRecordDecl();
1201 }
1202 
1203 CXXMethodDecl *LambdaExpr::getCallOperator() const {
1204   CXXRecordDecl *Record = getLambdaClass();
1205   return Record->getLambdaCallOperator();
1206 }
1207 
1208 FunctionTemplateDecl *LambdaExpr::getDependentCallOperator() const {
1209   CXXRecordDecl *Record = getLambdaClass();
1210   return Record->getDependentLambdaCallOperator();
1211 }
1212 
1213 TemplateParameterList *LambdaExpr::getTemplateParameterList() const {
1214   CXXRecordDecl *Record = getLambdaClass();
1215   return Record->getGenericLambdaTemplateParameterList();
1216 }
1217 
1218 ArrayRef<NamedDecl *> LambdaExpr::getExplicitTemplateParameters() const {
1219   const CXXRecordDecl *Record = getLambdaClass();
1220   return Record->getLambdaExplicitTemplateParameters();
1221 }
1222 
1223 CompoundStmt *LambdaExpr::getBody() const {
1224   // FIXME: this mutation in getBody is bogus. It should be
1225   // initialized in ASTStmtReader::VisitLambdaExpr, but for reasons I
1226   // don't understand, that doesn't work.
1227   if (!getStoredStmts()[NumCaptures])
1228     *const_cast<Stmt **>(&getStoredStmts()[NumCaptures]) =
1229         getCallOperator()->getBody();
1230 
1231   return static_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
1232 }
1233 
1234 bool LambdaExpr::isMutable() const {
1235   return !getCallOperator()->isConst();
1236 }
1237 
1238 ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
1239                                    bool CleanupsHaveSideEffects,
1240                                    ArrayRef<CleanupObject> objects)
1241     : FullExpr(ExprWithCleanupsClass, subexpr) {
1242   ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects;
1243   ExprWithCleanupsBits.NumObjects = objects.size();
1244   for (unsigned i = 0, e = objects.size(); i != e; ++i)
1245     getTrailingObjects<CleanupObject>()[i] = objects[i];
1246 }
1247 
1248 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,
1249                                            bool CleanupsHaveSideEffects,
1250                                            ArrayRef<CleanupObject> objects) {
1251   void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(objects.size()),
1252                             alignof(ExprWithCleanups));
1253   return new (buffer)
1254       ExprWithCleanups(subexpr, CleanupsHaveSideEffects, objects);
1255 }
1256 
1257 ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
1258     : FullExpr(ExprWithCleanupsClass, empty) {
1259   ExprWithCleanupsBits.NumObjects = numObjects;
1260 }
1261 
1262 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,
1263                                            EmptyShell empty,
1264                                            unsigned numObjects) {
1265   void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(numObjects),
1266                             alignof(ExprWithCleanups));
1267   return new (buffer) ExprWithCleanups(empty, numObjects);
1268 }
1269 
1270 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *TSI,
1271                                                        SourceLocation LParenLoc,
1272                                                        ArrayRef<Expr *> Args,
1273                                                        SourceLocation RParenLoc)
1274     : Expr(CXXUnresolvedConstructExprClass,
1275            TSI->getType().getNonReferenceType(),
1276            (TSI->getType()->isLValueReferenceType()
1277                 ? VK_LValue
1278                 : TSI->getType()->isRValueReferenceType() ? VK_XValue
1279                                                           : VK_RValue),
1280            OK_Ordinary),
1281       TSI(TSI), LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
1282   CXXUnresolvedConstructExprBits.NumArgs = Args.size();
1283   auto **StoredArgs = getTrailingObjects<Expr *>();
1284   for (unsigned I = 0; I != Args.size(); ++I)
1285     StoredArgs[I] = Args[I];
1286   setDependence(computeDependence(this));
1287 }
1288 
1289 CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create(
1290     const ASTContext &Context, TypeSourceInfo *TSI, SourceLocation LParenLoc,
1291     ArrayRef<Expr *> Args, SourceLocation RParenLoc) {
1292   void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(Args.size()));
1293   return new (Mem) CXXUnresolvedConstructExpr(TSI, LParenLoc, Args, RParenLoc);
1294 }
1295 
1296 CXXUnresolvedConstructExpr *
1297 CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context,
1298                                         unsigned NumArgs) {
1299   void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(NumArgs));
1300   return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs);
1301 }
1302 
1303 SourceLocation CXXUnresolvedConstructExpr::getBeginLoc() const {
1304   return TSI->getTypeLoc().getBeginLoc();
1305 }
1306 
1307 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1308     const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1309     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1310     SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1311     DeclarationNameInfo MemberNameInfo,
1312     const TemplateArgumentListInfo *TemplateArgs)
1313     : Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue,
1314            OK_Ordinary),
1315       Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc),
1316       MemberNameInfo(MemberNameInfo) {
1317   CXXDependentScopeMemberExprBits.IsArrow = IsArrow;
1318   CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1319       (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1320   CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1321       FirstQualifierFoundInScope != nullptr;
1322   CXXDependentScopeMemberExprBits.OperatorLoc = OperatorLoc;
1323 
1324   if (TemplateArgs) {
1325     auto Deps = TemplateArgumentDependence::None;
1326     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1327         TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
1328         Deps);
1329   } else if (TemplateKWLoc.isValid()) {
1330     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1331         TemplateKWLoc);
1332   }
1333 
1334   if (hasFirstQualifierFoundInScope())
1335     *getTrailingObjects<NamedDecl *>() = FirstQualifierFoundInScope;
1336   setDependence(computeDependence(this));
1337 }
1338 
1339 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1340     EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
1341     bool HasFirstQualifierFoundInScope)
1342     : Expr(CXXDependentScopeMemberExprClass, Empty) {
1343   CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1344       HasTemplateKWAndArgsInfo;
1345   CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1346       HasFirstQualifierFoundInScope;
1347 }
1348 
1349 CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create(
1350     const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1351     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1352     SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1353     DeclarationNameInfo MemberNameInfo,
1354     const TemplateArgumentListInfo *TemplateArgs) {
1355   bool HasTemplateKWAndArgsInfo =
1356       (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1357   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1358   bool HasFirstQualifierFoundInScope = FirstQualifierFoundInScope != nullptr;
1359 
1360   unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1361                                    TemplateArgumentLoc, NamedDecl *>(
1362       HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1363 
1364   void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1365   return new (Mem) CXXDependentScopeMemberExpr(
1366       Ctx, Base, BaseType, IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1367       FirstQualifierFoundInScope, MemberNameInfo, TemplateArgs);
1368 }
1369 
1370 CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty(
1371     const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
1372     unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) {
1373   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1374 
1375   unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1376                                    TemplateArgumentLoc, NamedDecl *>(
1377       HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1378 
1379   void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1380   return new (Mem) CXXDependentScopeMemberExpr(
1381       EmptyShell(), HasTemplateKWAndArgsInfo, HasFirstQualifierFoundInScope);
1382 }
1383 
1384 static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1385                                             UnresolvedSetIterator end) {
1386   do {
1387     NamedDecl *decl = *begin;
1388     if (isa<UnresolvedUsingValueDecl>(decl))
1389       return false;
1390 
1391     // Unresolved member expressions should only contain methods and
1392     // method templates.
1393     if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())
1394             ->isStatic())
1395       return false;
1396   } while (++begin != end);
1397 
1398   return true;
1399 }
1400 
1401 UnresolvedMemberExpr::UnresolvedMemberExpr(
1402     const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1403     QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1404     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1405     const DeclarationNameInfo &MemberNameInfo,
1406     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1407     UnresolvedSetIterator End)
1408     : OverloadExpr(
1409           UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc,
1410           MemberNameInfo, TemplateArgs, Begin, End,
1411           // Dependent
1412           ((Base && Base->isTypeDependent()) || BaseType->isDependentType()),
1413           ((Base && Base->isInstantiationDependent()) ||
1414            BaseType->isInstantiationDependentType()),
1415           // Contains unexpanded parameter pack
1416           ((Base && Base->containsUnexpandedParameterPack()) ||
1417            BaseType->containsUnexpandedParameterPack())),
1418       Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1419   UnresolvedMemberExprBits.IsArrow = IsArrow;
1420   UnresolvedMemberExprBits.HasUnresolvedUsing = HasUnresolvedUsing;
1421 
1422   // Check whether all of the members are non-static member functions,
1423   // and if so, mark give this bound-member type instead of overload type.
1424   if (hasOnlyNonStaticMemberFunctions(Begin, End))
1425     setType(Context.BoundMemberTy);
1426 }
1427 
1428 UnresolvedMemberExpr::UnresolvedMemberExpr(EmptyShell Empty,
1429                                            unsigned NumResults,
1430                                            bool HasTemplateKWAndArgsInfo)
1431     : OverloadExpr(UnresolvedMemberExprClass, Empty, NumResults,
1432                    HasTemplateKWAndArgsInfo) {}
1433 
1434 bool UnresolvedMemberExpr::isImplicitAccess() const {
1435   if (!Base)
1436     return true;
1437 
1438   return cast<Expr>(Base)->isImplicitCXXThis();
1439 }
1440 
1441 UnresolvedMemberExpr *UnresolvedMemberExpr::Create(
1442     const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1443     QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1444     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1445     const DeclarationNameInfo &MemberNameInfo,
1446     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1447     UnresolvedSetIterator End) {
1448   unsigned NumResults = End - Begin;
1449   bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1450   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1451   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1452                                    TemplateArgumentLoc>(
1453       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1454   void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1455   return new (Mem) UnresolvedMemberExpr(
1456       Context, HasUnresolvedUsing, Base, BaseType, IsArrow, OperatorLoc,
1457       QualifierLoc, TemplateKWLoc, MemberNameInfo, TemplateArgs, Begin, End);
1458 }
1459 
1460 UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty(
1461     const ASTContext &Context, unsigned NumResults,
1462     bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {
1463   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1464   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1465                                    TemplateArgumentLoc>(
1466       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1467   void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1468   return new (Mem)
1469       UnresolvedMemberExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);
1470 }
1471 
1472 CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() {
1473   // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1474 
1475   // If there was a nested name specifier, it names the naming class.
1476   // It can't be dependent: after all, we were actually able to do the
1477   // lookup.
1478   CXXRecordDecl *Record = nullptr;
1479   auto *NNS = getQualifier();
1480   if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {
1481     const Type *T = getQualifier()->getAsType();
1482     assert(T && "qualifier in member expression does not name type");
1483     Record = T->getAsCXXRecordDecl();
1484     assert(Record && "qualifier in member expression does not name record");
1485   }
1486   // Otherwise the naming class must have been the base class.
1487   else {
1488     QualType BaseType = getBaseType().getNonReferenceType();
1489     if (isArrow())
1490       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1491 
1492     Record = BaseType->getAsCXXRecordDecl();
1493     assert(Record && "base of member expression does not name record");
1494   }
1495 
1496   return Record;
1497 }
1498 
1499 SizeOfPackExpr *
1500 SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc,
1501                        NamedDecl *Pack, SourceLocation PackLoc,
1502                        SourceLocation RParenLoc,
1503                        Optional<unsigned> Length,
1504                        ArrayRef<TemplateArgument> PartialArgs) {
1505   void *Storage =
1506       Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size()));
1507   return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,
1508                                       PackLoc, RParenLoc, Length, PartialArgs);
1509 }
1510 
1511 SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,
1512                                                    unsigned NumPartialArgs) {
1513   void *Storage =
1514       Context.Allocate(totalSizeToAlloc<TemplateArgument>(NumPartialArgs));
1515   return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);
1516 }
1517 
1518 SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr(
1519     QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param,
1520     SourceLocation NameLoc, const TemplateArgument &ArgPack)
1521     : Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary),
1522       Param(Param), Arguments(ArgPack.pack_begin()),
1523       NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) {
1524   setDependence(ExprDependence::TypeValueInstantiation |
1525                 ExprDependence::UnexpandedPack);
1526 }
1527 
1528 TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1529   return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
1530 }
1531 
1532 FunctionParmPackExpr::FunctionParmPackExpr(QualType T, VarDecl *ParamPack,
1533                                            SourceLocation NameLoc,
1534                                            unsigned NumParams,
1535                                            VarDecl *const *Params)
1536     : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary),
1537       ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
1538   if (Params)
1539     std::uninitialized_copy(Params, Params + NumParams,
1540                             getTrailingObjects<VarDecl *>());
1541   setDependence(ExprDependence::TypeValueInstantiation |
1542                 ExprDependence::UnexpandedPack);
1543 }
1544 
1545 FunctionParmPackExpr *
1546 FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,
1547                              VarDecl *ParamPack, SourceLocation NameLoc,
1548                              ArrayRef<VarDecl *> Params) {
1549   return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(Params.size())))
1550       FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
1551 }
1552 
1553 FunctionParmPackExpr *
1554 FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,
1555                                   unsigned NumParams) {
1556   return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(NumParams)))
1557       FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);
1558 }
1559 
1560 MaterializeTemporaryExpr::MaterializeTemporaryExpr(
1561     QualType T, Expr *Temporary, bool BoundToLvalueReference,
1562     LifetimeExtendedTemporaryDecl *MTD)
1563     : Expr(MaterializeTemporaryExprClass, T,
1564            BoundToLvalueReference ? VK_LValue : VK_XValue, OK_Ordinary) {
1565   if (MTD) {
1566     State = MTD;
1567     MTD->ExprWithTemporary = Temporary;
1568     return;
1569   }
1570   State = Temporary;
1571   setDependence(computeDependence(this));
1572 }
1573 
1574 void MaterializeTemporaryExpr::setExtendingDecl(ValueDecl *ExtendedBy,
1575                                                 unsigned ManglingNumber) {
1576   // We only need extra state if we have to remember more than just the Stmt.
1577   if (!ExtendedBy)
1578     return;
1579 
1580   // We may need to allocate extra storage for the mangling number and the
1581   // extended-by ValueDecl.
1582   if (!State.is<LifetimeExtendedTemporaryDecl *>())
1583     State = LifetimeExtendedTemporaryDecl::Create(
1584         cast<Expr>(State.get<Stmt *>()), ExtendedBy, ManglingNumber);
1585 
1586   auto ES = State.get<LifetimeExtendedTemporaryDecl *>();
1587   ES->ExtendingDecl = ExtendedBy;
1588   ES->ManglingNumber = ManglingNumber;
1589 }
1590 
1591 TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1592                              ArrayRef<TypeSourceInfo *> Args,
1593                              SourceLocation RParenLoc, bool Value)
1594     : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary), Loc(Loc),
1595       RParenLoc(RParenLoc) {
1596   TypeTraitExprBits.Kind = Kind;
1597   TypeTraitExprBits.Value = Value;
1598   TypeTraitExprBits.NumArgs = Args.size();
1599 
1600   auto **ToArgs = getTrailingObjects<TypeSourceInfo *>();
1601   for (unsigned I = 0, N = Args.size(); I != N; ++I)
1602     ToArgs[I] = Args[I];
1603 
1604   setDependence(computeDependence(this));
1605 }
1606 
1607 TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,
1608                                      SourceLocation Loc,
1609                                      TypeTrait Kind,
1610                                      ArrayRef<TypeSourceInfo *> Args,
1611                                      SourceLocation RParenLoc,
1612                                      bool Value) {
1613   void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(Args.size()));
1614   return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1615 }
1616 
1617 TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,
1618                                                  unsigned NumArgs) {
1619   void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(NumArgs));
1620   return new (Mem) TypeTraitExpr(EmptyShell());
1621 }
1622 
1623 CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config,
1624                                        ArrayRef<Expr *> Args, QualType Ty,
1625                                        ExprValueKind VK, SourceLocation RP,
1626                                        unsigned MinNumArgs)
1627     : CallExpr(CUDAKernelCallExprClass, Fn, /*PreArgs=*/Config, Args, Ty, VK,
1628                RP, MinNumArgs, NotADL) {}
1629 
1630 CUDAKernelCallExpr::CUDAKernelCallExpr(unsigned NumArgs, EmptyShell Empty)
1631     : CallExpr(CUDAKernelCallExprClass, /*NumPreArgs=*/END_PREARG, NumArgs,
1632                Empty) {}
1633 
1634 CUDAKernelCallExpr *
1635 CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config,
1636                            ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1637                            SourceLocation RP, unsigned MinNumArgs) {
1638   // Allocate storage for the trailing objects of CallExpr.
1639   unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1640   unsigned SizeOfTrailingObjects =
1641       CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/END_PREARG, NumArgs);
1642   void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1643                            alignof(CUDAKernelCallExpr));
1644   return new (Mem) CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, MinNumArgs);
1645 }
1646 
1647 CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx,
1648                                                     unsigned NumArgs,
1649                                                     EmptyShell Empty) {
1650   // Allocate storage for the trailing objects of CallExpr.
1651   unsigned SizeOfTrailingObjects =
1652       CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/END_PREARG, NumArgs);
1653   void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1654                            alignof(CUDAKernelCallExpr));
1655   return new (Mem) CUDAKernelCallExpr(NumArgs, Empty);
1656 }
1657