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