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