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