ExprCXX.cpp revision 9fcce65e7e1307b5b8da9be13e4092d6bb94dc1d
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"
19using namespace clang;
20
21
22//===----------------------------------------------------------------------===//
23//  Child Iterators for iterating over subexpressions/substatements
24//===----------------------------------------------------------------------===//
25
26QualType CXXTypeidExpr::getTypeOperand() const {
27  assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
28  return Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType()
29                                                        .getUnqualifiedType();
30}
31
32QualType 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
39SourceRange CXXScalarValueInitExpr::getSourceRange() const {
40  SourceLocation Start = RParenLoc;
41  if (TypeInfo)
42    Start = TypeInfo->getTypeLoc().getBeginLoc();
43  return SourceRange(Start, RParenLoc);
44}
45
46// CXXNewExpr
47CXXNewExpr::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
99void 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
109bool CXXNewExpr::shouldNullCheckAllocation(ASTContext &Ctx) const {
110  return getOperatorNew()->getType()->
111    castAs<FunctionProtoType>()->isNothrow(Ctx);
112}
113
114SourceLocation 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
127QualType 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
146PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)
147 : Type(Info)
148{
149  Location = Info->getTypeLoc().getLocalSourceRange().getBegin();
150}
151
152CXXPseudoDestructorExpr::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
188QualType CXXPseudoDestructorExpr::getDestroyedType() const {
189  if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
190    return TInfo->getType();
191
192  return QualType();
193}
194
195SourceRange 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
203UnresolvedLookupExpr *
204UnresolvedLookupExpr::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
224UnresolvedLookupExpr *
225UnresolvedLookupExpr::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
238OverloadExpr::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
309void 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
324CXXRecordDecl *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
332DependentScopeDeclRefExpr::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
364DependentScopeDeclRefExpr *
365DependentScopeDeclRefExpr::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
380DependentScopeDeclRefExpr *
381DependentScopeDeclRefExpr::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
396SourceRange 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
418SourceRange 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
445Expr *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
454CXXMethodDecl *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
464CXXRecordDecl *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.
483const 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
493CXXStaticCastExpr *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
510CXXStaticCastExpr *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
517CXXDynamicCastExpr *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
534CXXDynamicCastExpr *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); }
549bool 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
571CXXReinterpretCastExpr *
572CXXReinterpretCastExpr::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
587CXXReinterpretCastExpr *
588CXXReinterpretCastExpr::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
594CXXConstCastExpr *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
602CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(ASTContext &C) {
603  return new (C) CXXConstCastExpr(EmptyShell());
604}
605
606CXXFunctionalCastExpr *
607CXXFunctionalCastExpr::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
620CXXFunctionalCastExpr *
621CXXFunctionalCastExpr::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
627UserDefinedLiteral::LiteralOperatorKind
628UserDefinedLiteral::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
649Expr *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
657const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {
658  return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();
659}
660
661CXXDefaultArgExpr *
662CXXDefaultArgExpr::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
669CXXTemporary *CXXTemporary::Create(ASTContext &C,
670                                   const CXXDestructorDecl *Destructor) {
671  return new (C) CXXTemporary(Destructor);
672}
673
674CXXBindTemporaryExpr *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
684CXXTemporaryObjectExpr::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
701SourceRange CXXTemporaryObjectExpr::getSourceRange() const {
702  return SourceRange(Type->getTypeLoc().getBeginLoc(),
703                     getParenRange().getEnd());
704}
705
706CXXConstructExpr *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
722CXXConstructExpr::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
759LambdaExpr::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
783LambdaCaptureKind LambdaExpr::Capture::getCaptureKind() const {
784  if (capturesThis())
785    return LCK_This;
786
787  return (VarAndBits.getInt() & Capture_ByCopy)? LCK_ByCopy : LCK_ByRef;
788}
789
790LambdaExpr::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                       unsigned ManglingNumber,
801                       Decl *ContextDecl)
802  : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary,
803         T->isDependentType(), T->isDependentType(), T->isDependentType(),
804         /*ContainsUnexpandedParameterPack=*/false),
805    IntroducerRange(IntroducerRange),
806    NumCaptures(Captures.size()),
807    CaptureDefault(CaptureDefault),
808    ExplicitParams(ExplicitParams),
809    ExplicitResultType(ExplicitResultType),
810    ClosingBrace(ClosingBrace)
811{
812  assert(CaptureInits.size() == Captures.size() && "Wrong number of arguments");
813  CXXRecordDecl *Class = getLambdaClass();
814  CXXRecordDecl::LambdaDefinitionData &Data = Class->getLambdaData();
815
816  // FIXME: Propagate "has unexpanded parameter pack" bit.
817
818  // Copy captures.
819  ASTContext &Context = Class->getASTContext();
820  Data.NumCaptures = NumCaptures;
821  Data.NumExplicitCaptures = 0;
822  Data.ManglingNumber = ManglingNumber;
823  Data.ContextDecl = ContextDecl;
824  Data.Captures = (Capture *)Context.Allocate(sizeof(Capture) * NumCaptures);
825  Capture *ToCapture = Data.Captures;
826  for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
827    if (Captures[I].isExplicit())
828      ++Data.NumExplicitCaptures;
829
830    *ToCapture++ = Captures[I];
831  }
832
833  // Copy initialization expressions for the non-static data members.
834  Stmt **Stored = getStoredStmts();
835  for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
836    *Stored++ = CaptureInits[I];
837
838  // Copy the body of the lambda.
839  *Stored++ = getCallOperator()->getBody();
840
841  // Copy the array index variables, if any.
842  HasArrayIndexVars = !ArrayIndexVars.empty();
843  if (HasArrayIndexVars) {
844    assert(ArrayIndexStarts.size() == NumCaptures);
845    memcpy(getArrayIndexVars(), ArrayIndexVars.data(),
846           sizeof(VarDecl *) * ArrayIndexVars.size());
847    memcpy(getArrayIndexStarts(), ArrayIndexStarts.data(),
848           sizeof(unsigned) * Captures.size());
849    getArrayIndexStarts()[Captures.size()] = ArrayIndexVars.size();
850  }
851
852  if (ManglingNumber)
853    Class->ClearLinkageCache();
854}
855
856LambdaExpr *LambdaExpr::Create(ASTContext &Context,
857                               CXXRecordDecl *Class,
858                               SourceRange IntroducerRange,
859                               LambdaCaptureDefault CaptureDefault,
860                               ArrayRef<Capture> Captures,
861                               bool ExplicitParams,
862                               bool ExplicitResultType,
863                               ArrayRef<Expr *> CaptureInits,
864                               ArrayRef<VarDecl *> ArrayIndexVars,
865                               ArrayRef<unsigned> ArrayIndexStarts,
866                               SourceLocation ClosingBrace,
867                               unsigned ManglingNumber,
868                               Decl *ContextDecl) {
869  // Determine the type of the expression (i.e., the type of the
870  // function object we're creating).
871  QualType T = Context.getTypeDeclType(Class);
872
873  unsigned Size = sizeof(LambdaExpr) + sizeof(Stmt *) * (Captures.size() + 1);
874  if (!ArrayIndexVars.empty())
875    Size += sizeof(VarDecl *) * ArrayIndexVars.size()
876          + sizeof(unsigned) * (Captures.size() + 1);
877  void *Mem = Context.Allocate(Size);
878  return new (Mem) LambdaExpr(T, IntroducerRange, CaptureDefault,
879                              Captures, ExplicitParams, ExplicitResultType,
880                              CaptureInits, ArrayIndexVars, ArrayIndexStarts,
881                              ClosingBrace, ManglingNumber, ContextDecl);
882}
883
884LambdaExpr *LambdaExpr::CreateDeserialized(ASTContext &C, unsigned NumCaptures,
885                                           unsigned NumArrayIndexVars) {
886  unsigned Size = sizeof(LambdaExpr) + sizeof(Stmt *) * (NumCaptures + 1);
887  if (NumArrayIndexVars)
888    Size += sizeof(VarDecl) * NumArrayIndexVars
889          + sizeof(unsigned) * (NumCaptures + 1);
890  void *Mem = C.Allocate(Size);
891  return new (Mem) LambdaExpr(EmptyShell(), NumCaptures, NumArrayIndexVars > 0);
892}
893
894LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
895  return getLambdaClass()->getLambdaData().Captures;
896}
897
898LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
899  return capture_begin() + NumCaptures;
900}
901
902LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
903  return capture_begin();
904}
905
906LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
907  struct CXXRecordDecl::LambdaDefinitionData &Data
908    = getLambdaClass()->getLambdaData();
909  return Data.Captures + Data.NumExplicitCaptures;
910}
911
912LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
913  return explicit_capture_end();
914}
915
916LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
917  return capture_end();
918}
919
920ArrayRef<VarDecl *>
921LambdaExpr::getCaptureInitIndexVars(capture_init_iterator Iter) const {
922  assert(HasArrayIndexVars && "No array index-var data?");
923
924  unsigned Index = Iter - capture_init_begin();
925  assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
926         "Capture index out-of-range");
927  VarDecl **IndexVars = getArrayIndexVars();
928  unsigned *IndexStarts = getArrayIndexStarts();
929  return ArrayRef<VarDecl *>(IndexVars + IndexStarts[Index],
930                             IndexVars + IndexStarts[Index + 1]);
931}
932
933CXXRecordDecl *LambdaExpr::getLambdaClass() const {
934  return getType()->getAsCXXRecordDecl();
935}
936
937CXXMethodDecl *LambdaExpr::getCallOperator() const {
938  CXXRecordDecl *Record = getLambdaClass();
939  DeclarationName Name
940    = Record->getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
941  DeclContext::lookup_result Calls = Record->lookup(Name);
942  assert(Calls.first != Calls.second && "Missing lambda call operator!");
943  CXXMethodDecl *Result = cast<CXXMethodDecl>(*Calls.first++);
944  assert(Calls.first == Calls.second && "More than lambda one call operator?");
945  return Result;
946}
947
948CompoundStmt *LambdaExpr::getBody() const {
949  if (!getStoredStmts()[NumCaptures])
950    getStoredStmts()[NumCaptures] = getCallOperator()->getBody();
951
952  return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
953}
954
955bool LambdaExpr::isMutable() const {
956  return (getCallOperator()->getTypeQualifiers() & Qualifiers::Const) == 0;
957}
958
959ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
960                                   ArrayRef<CleanupObject> objects)
961  : Expr(ExprWithCleanupsClass, subexpr->getType(),
962         subexpr->getValueKind(), subexpr->getObjectKind(),
963         subexpr->isTypeDependent(), subexpr->isValueDependent(),
964         subexpr->isInstantiationDependent(),
965         subexpr->containsUnexpandedParameterPack()),
966    SubExpr(subexpr) {
967  ExprWithCleanupsBits.NumObjects = objects.size();
968  for (unsigned i = 0, e = objects.size(); i != e; ++i)
969    getObjectsBuffer()[i] = objects[i];
970}
971
972ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C, Expr *subexpr,
973                                           ArrayRef<CleanupObject> objects) {
974  size_t size = sizeof(ExprWithCleanups)
975              + objects.size() * sizeof(CleanupObject);
976  void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
977  return new (buffer) ExprWithCleanups(subexpr, objects);
978}
979
980ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
981  : Expr(ExprWithCleanupsClass, empty) {
982  ExprWithCleanupsBits.NumObjects = numObjects;
983}
984
985ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C, EmptyShell empty,
986                                           unsigned numObjects) {
987  size_t size = sizeof(ExprWithCleanups) + numObjects * sizeof(CleanupObject);
988  void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
989  return new (buffer) ExprWithCleanups(empty, numObjects);
990}
991
992CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
993                                                 SourceLocation LParenLoc,
994                                                 Expr **Args,
995                                                 unsigned NumArgs,
996                                                 SourceLocation RParenLoc)
997  : Expr(CXXUnresolvedConstructExprClass,
998         Type->getType().getNonReferenceType(),
999         (Type->getType()->isLValueReferenceType() ? VK_LValue
1000          :Type->getType()->isRValueReferenceType()? VK_XValue
1001          :VK_RValue),
1002         OK_Ordinary,
1003         Type->getType()->isDependentType(), true, true,
1004         Type->getType()->containsUnexpandedParameterPack()),
1005    Type(Type),
1006    LParenLoc(LParenLoc),
1007    RParenLoc(RParenLoc),
1008    NumArgs(NumArgs) {
1009  Stmt **StoredArgs = reinterpret_cast<Stmt **>(this + 1);
1010  for (unsigned I = 0; I != NumArgs; ++I) {
1011    if (Args[I]->containsUnexpandedParameterPack())
1012      ExprBits.ContainsUnexpandedParameterPack = true;
1013
1014    StoredArgs[I] = Args[I];
1015  }
1016}
1017
1018CXXUnresolvedConstructExpr *
1019CXXUnresolvedConstructExpr::Create(ASTContext &C,
1020                                   TypeSourceInfo *Type,
1021                                   SourceLocation LParenLoc,
1022                                   Expr **Args,
1023                                   unsigned NumArgs,
1024                                   SourceLocation RParenLoc) {
1025  void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
1026                         sizeof(Expr *) * NumArgs);
1027  return new (Mem) CXXUnresolvedConstructExpr(Type, LParenLoc,
1028                                              Args, NumArgs, RParenLoc);
1029}
1030
1031CXXUnresolvedConstructExpr *
1032CXXUnresolvedConstructExpr::CreateEmpty(ASTContext &C, unsigned NumArgs) {
1033  Stmt::EmptyShell Empty;
1034  void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
1035                         sizeof(Expr *) * NumArgs);
1036  return new (Mem) CXXUnresolvedConstructExpr(Empty, NumArgs);
1037}
1038
1039SourceRange CXXUnresolvedConstructExpr::getSourceRange() const {
1040  return SourceRange(Type->getTypeLoc().getBeginLoc(), RParenLoc);
1041}
1042
1043CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(ASTContext &C,
1044                                                 Expr *Base, QualType BaseType,
1045                                                 bool IsArrow,
1046                                                 SourceLocation OperatorLoc,
1047                                          NestedNameSpecifierLoc QualifierLoc,
1048                                          SourceLocation TemplateKWLoc,
1049                                          NamedDecl *FirstQualifierFoundInScope,
1050                                          DeclarationNameInfo MemberNameInfo,
1051                                   const TemplateArgumentListInfo *TemplateArgs)
1052  : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
1053         VK_LValue, OK_Ordinary, true, true, true,
1054         ((Base && Base->containsUnexpandedParameterPack()) ||
1055          (QualifierLoc &&
1056           QualifierLoc.getNestedNameSpecifier()
1057                                       ->containsUnexpandedParameterPack()) ||
1058          MemberNameInfo.containsUnexpandedParameterPack())),
1059    Base(Base), BaseType(BaseType), IsArrow(IsArrow),
1060    HasTemplateKWAndArgsInfo(TemplateArgs != 0 || TemplateKWLoc.isValid()),
1061    OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
1062    FirstQualifierFoundInScope(FirstQualifierFoundInScope),
1063    MemberNameInfo(MemberNameInfo) {
1064  if (TemplateArgs) {
1065    bool Dependent = true;
1066    bool InstantiationDependent = true;
1067    bool ContainsUnexpandedParameterPack = false;
1068    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
1069                                               Dependent,
1070                                               InstantiationDependent,
1071                                               ContainsUnexpandedParameterPack);
1072    if (ContainsUnexpandedParameterPack)
1073      ExprBits.ContainsUnexpandedParameterPack = true;
1074  } else if (TemplateKWLoc.isValid()) {
1075    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1076  }
1077}
1078
1079CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(ASTContext &C,
1080                          Expr *Base, QualType BaseType,
1081                          bool IsArrow,
1082                          SourceLocation OperatorLoc,
1083                          NestedNameSpecifierLoc QualifierLoc,
1084                          NamedDecl *FirstQualifierFoundInScope,
1085                          DeclarationNameInfo MemberNameInfo)
1086  : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
1087         VK_LValue, OK_Ordinary, true, true, true,
1088         ((Base && Base->containsUnexpandedParameterPack()) ||
1089          (QualifierLoc &&
1090           QualifierLoc.getNestedNameSpecifier()->
1091                                         containsUnexpandedParameterPack()) ||
1092          MemberNameInfo.containsUnexpandedParameterPack())),
1093    Base(Base), BaseType(BaseType), IsArrow(IsArrow),
1094    HasTemplateKWAndArgsInfo(false),
1095    OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
1096    FirstQualifierFoundInScope(FirstQualifierFoundInScope),
1097    MemberNameInfo(MemberNameInfo) { }
1098
1099CXXDependentScopeMemberExpr *
1100CXXDependentScopeMemberExpr::Create(ASTContext &C,
1101                                Expr *Base, QualType BaseType, bool IsArrow,
1102                                SourceLocation OperatorLoc,
1103                                NestedNameSpecifierLoc QualifierLoc,
1104                                SourceLocation TemplateKWLoc,
1105                                NamedDecl *FirstQualifierFoundInScope,
1106                                DeclarationNameInfo MemberNameInfo,
1107                                const TemplateArgumentListInfo *TemplateArgs) {
1108  if (!TemplateArgs && !TemplateKWLoc.isValid())
1109    return new (C) CXXDependentScopeMemberExpr(C, Base, BaseType,
1110                                               IsArrow, OperatorLoc,
1111                                               QualifierLoc,
1112                                               FirstQualifierFoundInScope,
1113                                               MemberNameInfo);
1114
1115  unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1116  std::size_t size = sizeof(CXXDependentScopeMemberExpr)
1117    + ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1118
1119  void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
1120  return new (Mem) CXXDependentScopeMemberExpr(C, Base, BaseType,
1121                                               IsArrow, OperatorLoc,
1122                                               QualifierLoc,
1123                                               TemplateKWLoc,
1124                                               FirstQualifierFoundInScope,
1125                                               MemberNameInfo, TemplateArgs);
1126}
1127
1128CXXDependentScopeMemberExpr *
1129CXXDependentScopeMemberExpr::CreateEmpty(ASTContext &C,
1130                                         bool HasTemplateKWAndArgsInfo,
1131                                         unsigned NumTemplateArgs) {
1132  if (!HasTemplateKWAndArgsInfo)
1133    return new (C) CXXDependentScopeMemberExpr(C, 0, QualType(),
1134                                               0, SourceLocation(),
1135                                               NestedNameSpecifierLoc(), 0,
1136                                               DeclarationNameInfo());
1137
1138  std::size_t size = sizeof(CXXDependentScopeMemberExpr) +
1139                     ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1140  void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
1141  CXXDependentScopeMemberExpr *E
1142    =  new (Mem) CXXDependentScopeMemberExpr(C, 0, QualType(),
1143                                             0, SourceLocation(),
1144                                             NestedNameSpecifierLoc(),
1145                                             SourceLocation(), 0,
1146                                             DeclarationNameInfo(), 0);
1147  E->HasTemplateKWAndArgsInfo = true;
1148  return E;
1149}
1150
1151bool CXXDependentScopeMemberExpr::isImplicitAccess() const {
1152  if (Base == 0)
1153    return true;
1154
1155  return cast<Expr>(Base)->isImplicitCXXThis();
1156}
1157
1158static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1159                                            UnresolvedSetIterator end) {
1160  do {
1161    NamedDecl *decl = *begin;
1162    if (isa<UnresolvedUsingValueDecl>(decl))
1163      return false;
1164    if (isa<UsingShadowDecl>(decl))
1165      decl = cast<UsingShadowDecl>(decl)->getUnderlyingDecl();
1166
1167    // Unresolved member expressions should only contain methods and
1168    // method templates.
1169    assert(isa<CXXMethodDecl>(decl) || isa<FunctionTemplateDecl>(decl));
1170
1171    if (isa<FunctionTemplateDecl>(decl))
1172      decl = cast<FunctionTemplateDecl>(decl)->getTemplatedDecl();
1173    if (cast<CXXMethodDecl>(decl)->isStatic())
1174      return false;
1175  } while (++begin != end);
1176
1177  return true;
1178}
1179
1180UnresolvedMemberExpr::UnresolvedMemberExpr(ASTContext &C,
1181                                           bool HasUnresolvedUsing,
1182                                           Expr *Base, QualType BaseType,
1183                                           bool IsArrow,
1184                                           SourceLocation OperatorLoc,
1185                                           NestedNameSpecifierLoc QualifierLoc,
1186                                           SourceLocation TemplateKWLoc,
1187                                   const DeclarationNameInfo &MemberNameInfo,
1188                                   const TemplateArgumentListInfo *TemplateArgs,
1189                                           UnresolvedSetIterator Begin,
1190                                           UnresolvedSetIterator End)
1191  : OverloadExpr(UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc,
1192                 MemberNameInfo, TemplateArgs, Begin, End,
1193                 // Dependent
1194                 ((Base && Base->isTypeDependent()) ||
1195                  BaseType->isDependentType()),
1196                 ((Base && Base->isInstantiationDependent()) ||
1197                   BaseType->isInstantiationDependentType()),
1198                 // Contains unexpanded parameter pack
1199                 ((Base && Base->containsUnexpandedParameterPack()) ||
1200                  BaseType->containsUnexpandedParameterPack())),
1201    IsArrow(IsArrow), HasUnresolvedUsing(HasUnresolvedUsing),
1202    Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1203
1204  // Check whether all of the members are non-static member functions,
1205  // and if so, mark give this bound-member type instead of overload type.
1206  if (hasOnlyNonStaticMemberFunctions(Begin, End))
1207    setType(C.BoundMemberTy);
1208}
1209
1210bool UnresolvedMemberExpr::isImplicitAccess() const {
1211  if (Base == 0)
1212    return true;
1213
1214  return cast<Expr>(Base)->isImplicitCXXThis();
1215}
1216
1217UnresolvedMemberExpr *
1218UnresolvedMemberExpr::Create(ASTContext &C,
1219                             bool HasUnresolvedUsing,
1220                             Expr *Base, QualType BaseType, bool IsArrow,
1221                             SourceLocation OperatorLoc,
1222                             NestedNameSpecifierLoc QualifierLoc,
1223                             SourceLocation TemplateKWLoc,
1224                             const DeclarationNameInfo &MemberNameInfo,
1225                             const TemplateArgumentListInfo *TemplateArgs,
1226                             UnresolvedSetIterator Begin,
1227                             UnresolvedSetIterator End) {
1228  std::size_t size = sizeof(UnresolvedMemberExpr);
1229  if (TemplateArgs)
1230    size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
1231  else if (TemplateKWLoc.isValid())
1232    size += ASTTemplateKWAndArgsInfo::sizeFor(0);
1233
1234  void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
1235  return new (Mem) UnresolvedMemberExpr(C,
1236                             HasUnresolvedUsing, Base, BaseType,
1237                             IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1238                             MemberNameInfo, TemplateArgs, Begin, End);
1239}
1240
1241UnresolvedMemberExpr *
1242UnresolvedMemberExpr::CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
1243                                  unsigned NumTemplateArgs) {
1244  std::size_t size = sizeof(UnresolvedMemberExpr);
1245  if (HasTemplateKWAndArgsInfo)
1246    size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1247
1248  void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
1249  UnresolvedMemberExpr *E = new (Mem) UnresolvedMemberExpr(EmptyShell());
1250  E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
1251  return E;
1252}
1253
1254CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() const {
1255  // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1256
1257  // If there was a nested name specifier, it names the naming class.
1258  // It can't be dependent: after all, we were actually able to do the
1259  // lookup.
1260  CXXRecordDecl *Record = 0;
1261  if (getQualifier()) {
1262    const Type *T = getQualifier()->getAsType();
1263    assert(T && "qualifier in member expression does not name type");
1264    Record = T->getAsCXXRecordDecl();
1265    assert(Record && "qualifier in member expression does not name record");
1266  }
1267  // Otherwise the naming class must have been the base class.
1268  else {
1269    QualType BaseType = getBaseType().getNonReferenceType();
1270    if (isArrow()) {
1271      const PointerType *PT = BaseType->getAs<PointerType>();
1272      assert(PT && "base of arrow member access is not pointer");
1273      BaseType = PT->getPointeeType();
1274    }
1275
1276    Record = BaseType->getAsCXXRecordDecl();
1277    assert(Record && "base of member expression does not name record");
1278  }
1279
1280  return Record;
1281}
1282
1283SubstNonTypeTemplateParmPackExpr::
1284SubstNonTypeTemplateParmPackExpr(QualType T,
1285                                 NonTypeTemplateParmDecl *Param,
1286                                 SourceLocation NameLoc,
1287                                 const TemplateArgument &ArgPack)
1288  : Expr(SubstNonTypeTemplateParmPackExprClass, T, VK_RValue, OK_Ordinary,
1289         true, true, true, true),
1290    Param(Param), Arguments(ArgPack.pack_begin()),
1291    NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) { }
1292
1293TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1294  return TemplateArgument(Arguments, NumArguments);
1295}
1296
1297TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1298                             ArrayRef<TypeSourceInfo *> Args,
1299                             SourceLocation RParenLoc,
1300                             bool Value)
1301  : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary,
1302         /*TypeDependent=*/false,
1303         /*ValueDependent=*/false,
1304         /*InstantiationDependent=*/false,
1305         /*ContainsUnexpandedParameterPack=*/false),
1306    Loc(Loc), RParenLoc(RParenLoc)
1307{
1308  TypeTraitExprBits.Kind = Kind;
1309  TypeTraitExprBits.Value = Value;
1310  TypeTraitExprBits.NumArgs = Args.size();
1311
1312  TypeSourceInfo **ToArgs = getTypeSourceInfos();
1313
1314  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
1315    if (Args[I]->getType()->isDependentType())
1316      setValueDependent(true);
1317    if (Args[I]->getType()->isInstantiationDependentType())
1318      setInstantiationDependent(true);
1319    if (Args[I]->getType()->containsUnexpandedParameterPack())
1320      setContainsUnexpandedParameterPack(true);
1321
1322    ToArgs[I] = Args[I];
1323  }
1324}
1325
1326TypeTraitExpr *TypeTraitExpr::Create(ASTContext &C, QualType T,
1327                                     SourceLocation Loc,
1328                                     TypeTrait Kind,
1329                                     ArrayRef<TypeSourceInfo *> Args,
1330                                     SourceLocation RParenLoc,
1331                                     bool Value) {
1332  unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * Args.size();
1333  void *Mem = C.Allocate(Size);
1334  return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1335}
1336
1337TypeTraitExpr *TypeTraitExpr::CreateDeserialized(ASTContext &C,
1338                                                 unsigned NumArgs) {
1339  unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * NumArgs;
1340  void *Mem = C.Allocate(Size);
1341  return new (Mem) TypeTraitExpr(EmptyShell());
1342}
1343
1344void ArrayTypeTraitExpr::anchor() { }
1345