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