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