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