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