1//===--- ExprCXX.h - Classes for representing expressions -------*- C++ -*-===//
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/// \file
11/// \brief Defines the clang::Expr interface and subclasses for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_EXPRCXX_H
16#define LLVM_CLANG_AST_EXPRCXX_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/TemplateBase.h"
21#include "clang/AST/UnresolvedSet.h"
22#include "clang/Basic/ExpressionTraits.h"
23#include "clang/Basic/Lambda.h"
24#include "clang/Basic/TypeTraits.h"
25#include "llvm/Support/Compiler.h"
26
27namespace clang {
28
29class CXXConstructorDecl;
30class CXXDestructorDecl;
31class CXXMethodDecl;
32class CXXTemporary;
33class MSPropertyDecl;
34class TemplateArgumentListInfo;
35class UuidAttr;
36
37//===--------------------------------------------------------------------===//
38// C++ Expressions.
39//===--------------------------------------------------------------------===//
40
41/// \brief A call to an overloaded operator written using operator
42/// syntax.
43///
44/// Represents a call to an overloaded operator written using operator
45/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
46/// normal call, this AST node provides better information about the
47/// syntactic representation of the call.
48///
49/// In a C++ template, this expression node kind will be used whenever
50/// any of the arguments are type-dependent. In this case, the
51/// function itself will be a (possibly empty) set of functions and
52/// function templates that were found by name lookup at template
53/// definition time.
54class CXXOperatorCallExpr : public CallExpr {
55  /// \brief The overloaded operator.
56  OverloadedOperatorKind Operator;
57  SourceRange Range;
58
59  // Record the FP_CONTRACT state that applies to this operator call. Only
60  // meaningful for floating point types. For other types this value can be
61  // set to false.
62  unsigned FPContractable : 1;
63
64  SourceRange getSourceRangeImpl() const LLVM_READONLY;
65public:
66  CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn,
67                      ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
68                      SourceLocation operatorloc, bool fpContractable)
69    : CallExpr(C, CXXOperatorCallExprClass, fn, 0, args, t, VK,
70               operatorloc),
71      Operator(Op), FPContractable(fpContractable) {
72    Range = getSourceRangeImpl();
73  }
74  explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) :
75    CallExpr(C, CXXOperatorCallExprClass, Empty) { }
76
77
78  /// \brief Returns the kind of overloaded operator that this
79  /// expression refers to.
80  OverloadedOperatorKind getOperator() const { return Operator; }
81
82  /// \brief Returns the location of the operator symbol in the expression.
83  ///
84  /// When \c getOperator()==OO_Call, this is the location of the right
85  /// parentheses; when \c getOperator()==OO_Subscript, this is the location
86  /// of the right bracket.
87  SourceLocation getOperatorLoc() const { return getRParenLoc(); }
88
89  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
90  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
91  SourceRange getSourceRange() const { return Range; }
92
93  static bool classof(const Stmt *T) {
94    return T->getStmtClass() == CXXOperatorCallExprClass;
95  }
96
97  // Set the FP contractability status of this operator. Only meaningful for
98  // operations on floating point types.
99  void setFPContractable(bool FPC) { FPContractable = FPC; }
100
101  // Get the FP contractability status of this operator. Only meaningful for
102  // operations on floating point types.
103  bool isFPContractable() const { return FPContractable; }
104
105  friend class ASTStmtReader;
106  friend class ASTStmtWriter;
107};
108
109/// Represents a call to a member function that
110/// may be written either with member call syntax (e.g., "obj.func()"
111/// or "objptr->func()") or with normal function-call syntax
112/// ("func()") within a member function that ends up calling a member
113/// function. The callee in either case is a MemberExpr that contains
114/// both the object argument and the member function, while the
115/// arguments are the arguments within the parentheses (not including
116/// the object argument).
117class CXXMemberCallExpr : public CallExpr {
118public:
119  CXXMemberCallExpr(ASTContext &C, Expr *fn, ArrayRef<Expr*> args,
120                    QualType t, ExprValueKind VK, SourceLocation RP)
121    : CallExpr(C, CXXMemberCallExprClass, fn, 0, args, t, VK, RP) {}
122
123  CXXMemberCallExpr(ASTContext &C, EmptyShell Empty)
124    : CallExpr(C, CXXMemberCallExprClass, Empty) { }
125
126  /// \brief Retrieves the implicit object argument for the member call.
127  ///
128  /// For example, in "x.f(5)", this returns the sub-expression "x".
129  Expr *getImplicitObjectArgument() const;
130
131  /// \brief Retrieves the declaration of the called method.
132  CXXMethodDecl *getMethodDecl() const;
133
134  /// \brief Retrieves the CXXRecordDecl for the underlying type of
135  /// the implicit object argument.
136  ///
137  /// Note that this is may not be the same declaration as that of the class
138  /// context of the CXXMethodDecl which this function is calling.
139  /// FIXME: Returns 0 for member pointer call exprs.
140  CXXRecordDecl *getRecordDecl() const;
141
142  static bool classof(const Stmt *T) {
143    return T->getStmtClass() == CXXMemberCallExprClass;
144  }
145};
146
147/// \brief Represents a call to a CUDA kernel function.
148class CUDAKernelCallExpr : public CallExpr {
149private:
150  enum { CONFIG, END_PREARG };
151
152public:
153  CUDAKernelCallExpr(ASTContext &C, Expr *fn, CallExpr *Config,
154                     ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
155                     SourceLocation RP)
156    : CallExpr(C, CUDAKernelCallExprClass, fn, END_PREARG, args, t, VK, RP) {
157    setConfig(Config);
158  }
159
160  CUDAKernelCallExpr(ASTContext &C, EmptyShell Empty)
161    : CallExpr(C, CUDAKernelCallExprClass, END_PREARG, Empty) { }
162
163  const CallExpr *getConfig() const {
164    return cast_or_null<CallExpr>(getPreArg(CONFIG));
165  }
166  CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
167  void setConfig(CallExpr *E) { setPreArg(CONFIG, E); }
168
169  static bool classof(const Stmt *T) {
170    return T->getStmtClass() == CUDAKernelCallExprClass;
171  }
172};
173
174/// \brief Abstract class common to all of the C++ "named"/"keyword" casts.
175///
176/// This abstract class is inherited by all of the classes
177/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
178/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
179/// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
180class CXXNamedCastExpr : public ExplicitCastExpr {
181private:
182  SourceLocation Loc; // the location of the casting op
183  SourceLocation RParenLoc; // the location of the right parenthesis
184  SourceRange AngleBrackets; // range for '<' '>'
185
186protected:
187  CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
188                   CastKind kind, Expr *op, unsigned PathSize,
189                   TypeSourceInfo *writtenTy, SourceLocation l,
190                   SourceLocation RParenLoc,
191                   SourceRange AngleBrackets)
192    : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
193      RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
194
195  explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
196    : ExplicitCastExpr(SC, Shell, PathSize) { }
197
198  friend class ASTStmtReader;
199
200public:
201  const char *getCastName() const;
202
203  /// \brief Retrieve the location of the cast operator keyword, e.g.,
204  /// \c static_cast.
205  SourceLocation getOperatorLoc() const { return Loc; }
206
207  /// \brief Retrieve the location of the closing parenthesis.
208  SourceLocation getRParenLoc() const { return RParenLoc; }
209
210  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
211  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
212  SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
213
214  static bool classof(const Stmt *T) {
215    switch (T->getStmtClass()) {
216    case CXXStaticCastExprClass:
217    case CXXDynamicCastExprClass:
218    case CXXReinterpretCastExprClass:
219    case CXXConstCastExprClass:
220      return true;
221    default:
222      return false;
223    }
224  }
225};
226
227/// \brief A C++ \c static_cast expression (C++ [expr.static.cast]).
228///
229/// This expression node represents a C++ static cast, e.g.,
230/// \c static_cast<int>(1.0).
231class CXXStaticCastExpr : public CXXNamedCastExpr {
232  CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
233                    unsigned pathSize, TypeSourceInfo *writtenTy,
234                    SourceLocation l, SourceLocation RParenLoc,
235                    SourceRange AngleBrackets)
236    : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
237                       writtenTy, l, RParenLoc, AngleBrackets) {}
238
239  explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
240    : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) { }
241
242public:
243  static CXXStaticCastExpr *Create(ASTContext &Context, QualType T,
244                                   ExprValueKind VK, CastKind K, Expr *Op,
245                                   const CXXCastPath *Path,
246                                   TypeSourceInfo *Written, SourceLocation L,
247                                   SourceLocation RParenLoc,
248                                   SourceRange AngleBrackets);
249  static CXXStaticCastExpr *CreateEmpty(ASTContext &Context,
250                                        unsigned PathSize);
251
252  static bool classof(const Stmt *T) {
253    return T->getStmtClass() == CXXStaticCastExprClass;
254  }
255};
256
257/// \brief A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
258///
259/// This expression node represents a dynamic cast, e.g.,
260/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
261/// check to determine how to perform the type conversion.
262class CXXDynamicCastExpr : public CXXNamedCastExpr {
263  CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
264                     Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
265                     SourceLocation l, SourceLocation RParenLoc,
266                     SourceRange AngleBrackets)
267    : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
268                       writtenTy, l, RParenLoc, AngleBrackets) {}
269
270  explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
271    : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) { }
272
273public:
274  static CXXDynamicCastExpr *Create(ASTContext &Context, QualType T,
275                                    ExprValueKind VK, CastKind Kind, Expr *Op,
276                                    const CXXCastPath *Path,
277                                    TypeSourceInfo *Written, SourceLocation L,
278                                    SourceLocation RParenLoc,
279                                    SourceRange AngleBrackets);
280
281  static CXXDynamicCastExpr *CreateEmpty(ASTContext &Context,
282                                         unsigned pathSize);
283
284  bool isAlwaysNull() const;
285
286  static bool classof(const Stmt *T) {
287    return T->getStmtClass() == CXXDynamicCastExprClass;
288  }
289};
290
291/// \brief A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
292///
293/// This expression node represents a reinterpret cast, e.g.,
294/// @c reinterpret_cast<int>(VoidPtr).
295///
296/// A reinterpret_cast provides a differently-typed view of a value but
297/// (in Clang, as in most C++ implementations) performs no actual work at
298/// run time.
299class CXXReinterpretCastExpr : public CXXNamedCastExpr {
300  CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
301                         Expr *op, unsigned pathSize,
302                         TypeSourceInfo *writtenTy, SourceLocation l,
303                         SourceLocation RParenLoc,
304                         SourceRange AngleBrackets)
305    : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
306                       pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
307
308  CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
309    : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) { }
310
311public:
312  static CXXReinterpretCastExpr *Create(ASTContext &Context, QualType T,
313                                        ExprValueKind VK, CastKind Kind,
314                                        Expr *Op, const CXXCastPath *Path,
315                                 TypeSourceInfo *WrittenTy, SourceLocation L,
316                                        SourceLocation RParenLoc,
317                                        SourceRange AngleBrackets);
318  static CXXReinterpretCastExpr *CreateEmpty(ASTContext &Context,
319                                             unsigned pathSize);
320
321  static bool classof(const Stmt *T) {
322    return T->getStmtClass() == CXXReinterpretCastExprClass;
323  }
324};
325
326/// \brief A C++ \c const_cast expression (C++ [expr.const.cast]).
327///
328/// This expression node represents a const cast, e.g.,
329/// \c const_cast<char*>(PtrToConstChar).
330///
331/// A const_cast can remove type qualifiers but does not change the underlying
332/// value.
333class CXXConstCastExpr : public CXXNamedCastExpr {
334  CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
335                   TypeSourceInfo *writtenTy, SourceLocation l,
336                   SourceLocation RParenLoc, SourceRange AngleBrackets)
337    : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
338                       0, writtenTy, l, RParenLoc, AngleBrackets) {}
339
340  explicit CXXConstCastExpr(EmptyShell Empty)
341    : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) { }
342
343public:
344  static CXXConstCastExpr *Create(ASTContext &Context, QualType T,
345                                  ExprValueKind VK, Expr *Op,
346                                  TypeSourceInfo *WrittenTy, SourceLocation L,
347                                  SourceLocation RParenLoc,
348                                  SourceRange AngleBrackets);
349  static CXXConstCastExpr *CreateEmpty(ASTContext &Context);
350
351  static bool classof(const Stmt *T) {
352    return T->getStmtClass() == CXXConstCastExprClass;
353  }
354};
355
356/// \brief A call to a literal operator (C++11 [over.literal])
357/// written as a user-defined literal (C++11 [lit.ext]).
358///
359/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
360/// is semantically equivalent to a normal call, this AST node provides better
361/// information about the syntactic representation of the literal.
362///
363/// Since literal operators are never found by ADL and can only be declared at
364/// namespace scope, a user-defined literal is never dependent.
365class UserDefinedLiteral : public CallExpr {
366  /// \brief The location of a ud-suffix within the literal.
367  SourceLocation UDSuffixLoc;
368
369public:
370  UserDefinedLiteral(ASTContext &C, Expr *Fn, ArrayRef<Expr*> Args,
371                     QualType T, ExprValueKind VK, SourceLocation LitEndLoc,
372                     SourceLocation SuffixLoc)
373    : CallExpr(C, UserDefinedLiteralClass, Fn, 0, Args, T, VK, LitEndLoc),
374      UDSuffixLoc(SuffixLoc) {}
375  explicit UserDefinedLiteral(ASTContext &C, EmptyShell Empty)
376    : CallExpr(C, UserDefinedLiteralClass, Empty) {}
377
378  /// The kind of literal operator which is invoked.
379  enum LiteralOperatorKind {
380    LOK_Raw,      ///< Raw form: operator "" X (const char *)
381    LOK_Template, ///< Raw form: operator "" X<cs...> ()
382    LOK_Integer,  ///< operator "" X (unsigned long long)
383    LOK_Floating, ///< operator "" X (long double)
384    LOK_String,   ///< operator "" X (const CharT *, size_t)
385    LOK_Character ///< operator "" X (CharT)
386  };
387
388  /// \brief Returns the kind of literal operator invocation
389  /// which this expression represents.
390  LiteralOperatorKind getLiteralOperatorKind() const;
391
392  /// \brief If this is not a raw user-defined literal, get the
393  /// underlying cooked literal (representing the literal with the suffix
394  /// removed).
395  Expr *getCookedLiteral();
396  const Expr *getCookedLiteral() const {
397    return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
398  }
399
400  SourceLocation getLocStart() const {
401    if (getLiteralOperatorKind() == LOK_Template)
402      return getRParenLoc();
403    return getArg(0)->getLocStart();
404  }
405  SourceLocation getLocEnd() const { return getRParenLoc(); }
406
407
408  /// \brief Returns the location of a ud-suffix in the expression.
409  ///
410  /// For a string literal, there may be multiple identical suffixes. This
411  /// returns the first.
412  SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
413
414  /// \brief Returns the ud-suffix specified for this literal.
415  const IdentifierInfo *getUDSuffix() const;
416
417  static bool classof(const Stmt *S) {
418    return S->getStmtClass() == UserDefinedLiteralClass;
419  }
420
421  friend class ASTStmtReader;
422  friend class ASTStmtWriter;
423};
424
425/// \brief A boolean literal, per ([C++ lex.bool] Boolean literals).
426///
427class CXXBoolLiteralExpr : public Expr {
428  bool Value;
429  SourceLocation Loc;
430public:
431  CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) :
432    Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
433         false, false),
434    Value(val), Loc(l) {}
435
436  explicit CXXBoolLiteralExpr(EmptyShell Empty)
437    : Expr(CXXBoolLiteralExprClass, Empty) { }
438
439  bool getValue() const { return Value; }
440  void setValue(bool V) { Value = V; }
441
442  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
443  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
444
445  SourceLocation getLocation() const { return Loc; }
446  void setLocation(SourceLocation L) { Loc = L; }
447
448  static bool classof(const Stmt *T) {
449    return T->getStmtClass() == CXXBoolLiteralExprClass;
450  }
451
452  // Iterators
453  child_range children() { return child_range(); }
454};
455
456/// \brief The null pointer literal (C++11 [lex.nullptr])
457///
458/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
459class CXXNullPtrLiteralExpr : public Expr {
460  SourceLocation Loc;
461public:
462  CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l) :
463    Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
464         false, false),
465    Loc(l) {}
466
467  explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
468    : Expr(CXXNullPtrLiteralExprClass, Empty) { }
469
470  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
471  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
472
473  SourceLocation getLocation() const { return Loc; }
474  void setLocation(SourceLocation L) { Loc = L; }
475
476  static bool classof(const Stmt *T) {
477    return T->getStmtClass() == CXXNullPtrLiteralExprClass;
478  }
479
480  child_range children() { return child_range(); }
481};
482
483/// \brief Implicit construction of a std::initializer_list<T> object from an
484/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
485class CXXStdInitializerListExpr : public Expr {
486  Stmt *SubExpr;
487
488  CXXStdInitializerListExpr(EmptyShell Empty)
489    : Expr(CXXStdInitializerListExprClass, Empty), SubExpr(0) {}
490
491public:
492  CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
493    : Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
494           Ty->isDependentType(), SubExpr->isValueDependent(),
495           SubExpr->isInstantiationDependent(),
496           SubExpr->containsUnexpandedParameterPack()),
497      SubExpr(SubExpr) {}
498
499  Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
500  const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
501
502  SourceLocation getLocStart() const LLVM_READONLY {
503    return SubExpr->getLocStart();
504  }
505  SourceLocation getLocEnd() const LLVM_READONLY {
506    return SubExpr->getLocEnd();
507  }
508  SourceRange getSourceRange() const LLVM_READONLY {
509    return SubExpr->getSourceRange();
510  }
511
512  static bool classof(const Stmt *S) {
513    return S->getStmtClass() == CXXStdInitializerListExprClass;
514  }
515
516  child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
517
518  friend class ASTReader;
519  friend class ASTStmtReader;
520};
521
522/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
523/// the \c type_info that corresponds to the supplied type, or the (possibly
524/// dynamic) type of the supplied expression.
525///
526/// This represents code like \c typeid(int) or \c typeid(*objPtr)
527class CXXTypeidExpr : public Expr {
528private:
529  llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
530  SourceRange Range;
531
532public:
533  CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
534    : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
535           // typeid is never type-dependent (C++ [temp.dep.expr]p4)
536           false,
537           // typeid is value-dependent if the type or expression are dependent
538           Operand->getType()->isDependentType(),
539           Operand->getType()->isInstantiationDependentType(),
540           Operand->getType()->containsUnexpandedParameterPack()),
541      Operand(Operand), Range(R) { }
542
543  CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
544    : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
545        // typeid is never type-dependent (C++ [temp.dep.expr]p4)
546           false,
547        // typeid is value-dependent if the type or expression are dependent
548           Operand->isTypeDependent() || Operand->isValueDependent(),
549           Operand->isInstantiationDependent(),
550           Operand->containsUnexpandedParameterPack()),
551      Operand(Operand), Range(R) { }
552
553  CXXTypeidExpr(EmptyShell Empty, bool isExpr)
554    : Expr(CXXTypeidExprClass, Empty) {
555    if (isExpr)
556      Operand = (Expr*)0;
557    else
558      Operand = (TypeSourceInfo*)0;
559  }
560
561  /// Determine whether this typeid has a type operand which is potentially
562  /// evaluated, per C++11 [expr.typeid]p3.
563  bool isPotentiallyEvaluated() const;
564
565  bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
566
567  /// \brief Retrieves the type operand of this typeid() expression after
568  /// various required adjustments (removing reference types, cv-qualifiers).
569  QualType getTypeOperand() const;
570
571  /// \brief Retrieve source information for the type operand.
572  TypeSourceInfo *getTypeOperandSourceInfo() const {
573    assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
574    return Operand.get<TypeSourceInfo *>();
575  }
576
577  void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
578    assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
579    Operand = TSI;
580  }
581
582  Expr *getExprOperand() const {
583    assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
584    return static_cast<Expr*>(Operand.get<Stmt *>());
585  }
586
587  void setExprOperand(Expr *E) {
588    assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
589    Operand = E;
590  }
591
592  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
593  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
594  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
595  void setSourceRange(SourceRange R) { Range = R; }
596
597  static bool classof(const Stmt *T) {
598    return T->getStmtClass() == CXXTypeidExprClass;
599  }
600
601  // Iterators
602  child_range children() {
603    if (isTypeOperand()) return child_range();
604    Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
605    return child_range(begin, begin + 1);
606  }
607};
608
609/// \brief A member reference to an MSPropertyDecl.
610///
611/// This expression always has pseudo-object type, and therefore it is
612/// typically not encountered in a fully-typechecked expression except
613/// within the syntactic form of a PseudoObjectExpr.
614class MSPropertyRefExpr : public Expr {
615  Expr *BaseExpr;
616  MSPropertyDecl *TheDecl;
617  SourceLocation MemberLoc;
618  bool IsArrow;
619  NestedNameSpecifierLoc QualifierLoc;
620
621public:
622  MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
623                    QualType ty, ExprValueKind VK,
624                    NestedNameSpecifierLoc qualifierLoc,
625                    SourceLocation nameLoc)
626  : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
627         /*type-dependent*/ false, baseExpr->isValueDependent(),
628         baseExpr->isInstantiationDependent(),
629         baseExpr->containsUnexpandedParameterPack()),
630    BaseExpr(baseExpr), TheDecl(decl),
631    MemberLoc(nameLoc), IsArrow(isArrow),
632    QualifierLoc(qualifierLoc) {}
633
634  MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
635
636  SourceRange getSourceRange() const LLVM_READONLY {
637    return SourceRange(getLocStart(), getLocEnd());
638  }
639  bool isImplicitAccess() const {
640    return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
641  }
642  SourceLocation getLocStart() const {
643    if (!isImplicitAccess())
644      return BaseExpr->getLocStart();
645    else if (QualifierLoc)
646      return QualifierLoc.getBeginLoc();
647    else
648        return MemberLoc;
649  }
650  SourceLocation getLocEnd() const { return getMemberLoc(); }
651
652  child_range children() {
653    return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
654  }
655  static bool classof(const Stmt *T) {
656    return T->getStmtClass() == MSPropertyRefExprClass;
657  }
658
659  Expr *getBaseExpr() const { return BaseExpr; }
660  MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
661  bool isArrow() const { return IsArrow; }
662  SourceLocation getMemberLoc() const { return MemberLoc; }
663  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
664
665  friend class ASTStmtReader;
666};
667
668/// A Microsoft C++ @c __uuidof expression, which gets
669/// the _GUID that corresponds to the supplied type or expression.
670///
671/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
672class CXXUuidofExpr : public Expr {
673private:
674  llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
675  SourceRange Range;
676
677public:
678  CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
679    : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
680           false, Operand->getType()->isDependentType(),
681           Operand->getType()->isInstantiationDependentType(),
682           Operand->getType()->containsUnexpandedParameterPack()),
683      Operand(Operand), Range(R) { }
684
685  CXXUuidofExpr(QualType Ty, Expr *Operand, SourceRange R)
686    : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
687           false, Operand->isTypeDependent(),
688           Operand->isInstantiationDependent(),
689           Operand->containsUnexpandedParameterPack()),
690      Operand(Operand), Range(R) { }
691
692  CXXUuidofExpr(EmptyShell Empty, bool isExpr)
693    : Expr(CXXUuidofExprClass, Empty) {
694    if (isExpr)
695      Operand = (Expr*)0;
696    else
697      Operand = (TypeSourceInfo*)0;
698  }
699
700  bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
701
702  /// \brief Retrieves the type operand of this __uuidof() expression after
703  /// various required adjustments (removing reference types, cv-qualifiers).
704  QualType getTypeOperand() const;
705
706  /// \brief Retrieve source information for the type operand.
707  TypeSourceInfo *getTypeOperandSourceInfo() const {
708    assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
709    return Operand.get<TypeSourceInfo *>();
710  }
711
712  void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
713    assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
714    Operand = TSI;
715  }
716
717  Expr *getExprOperand() const {
718    assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
719    return static_cast<Expr*>(Operand.get<Stmt *>());
720  }
721
722  void setExprOperand(Expr *E) {
723    assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
724    Operand = E;
725  }
726
727  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
728  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
729  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
730  void setSourceRange(SourceRange R) { Range = R; }
731
732  static bool classof(const Stmt *T) {
733    return T->getStmtClass() == CXXUuidofExprClass;
734  }
735
736  /// Grabs __declspec(uuid()) off a type, or returns 0 if there is none.
737  static UuidAttr *GetUuidAttrOfType(QualType QT);
738
739  // Iterators
740  child_range children() {
741    if (isTypeOperand()) return child_range();
742    Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
743    return child_range(begin, begin + 1);
744  }
745};
746
747/// \brief Represents the \c this expression in C++.
748///
749/// This is a pointer to the object on which the current member function is
750/// executing (C++ [expr.prim]p3). Example:
751///
752/// \code
753/// class Foo {
754/// public:
755///   void bar();
756///   void test() { this->bar(); }
757/// };
758/// \endcode
759class CXXThisExpr : public Expr {
760  SourceLocation Loc;
761  bool Implicit : 1;
762
763public:
764  CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
765    : Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
766           // 'this' is type-dependent if the class type of the enclosing
767           // member function is dependent (C++ [temp.dep.expr]p2)
768           Type->isDependentType(), Type->isDependentType(),
769           Type->isInstantiationDependentType(),
770           /*ContainsUnexpandedParameterPack=*/false),
771      Loc(L), Implicit(isImplicit) { }
772
773  CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
774
775  SourceLocation getLocation() const { return Loc; }
776  void setLocation(SourceLocation L) { Loc = L; }
777
778  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
779  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
780
781  bool isImplicit() const { return Implicit; }
782  void setImplicit(bool I) { Implicit = I; }
783
784  static bool classof(const Stmt *T) {
785    return T->getStmtClass() == CXXThisExprClass;
786  }
787
788  // Iterators
789  child_range children() { return child_range(); }
790};
791
792/// \brief A C++ throw-expression (C++ [except.throw]).
793///
794/// This handles 'throw' (for re-throwing the current exception) and
795/// 'throw' assignment-expression.  When assignment-expression isn't
796/// present, Op will be null.
797class CXXThrowExpr : public Expr {
798  Stmt *Op;
799  SourceLocation ThrowLoc;
800  /// \brief Whether the thrown variable (if any) is in scope.
801  unsigned IsThrownVariableInScope : 1;
802
803  friend class ASTStmtReader;
804
805public:
806  // \p Ty is the void type which is used as the result type of the
807  // expression.  The \p l is the location of the throw keyword.  \p expr
808  // can by null, if the optional expression to throw isn't present.
809  CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l,
810               bool IsThrownVariableInScope) :
811    Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
812         expr && expr->isInstantiationDependent(),
813         expr && expr->containsUnexpandedParameterPack()),
814    Op(expr), ThrowLoc(l), IsThrownVariableInScope(IsThrownVariableInScope) {}
815  CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
816
817  const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); }
818  Expr *getSubExpr() { return cast_or_null<Expr>(Op); }
819
820  SourceLocation getThrowLoc() const { return ThrowLoc; }
821
822  /// \brief Determines whether the variable thrown by this expression (if any!)
823  /// is within the innermost try block.
824  ///
825  /// This information is required to determine whether the NRVO can apply to
826  /// this variable.
827  bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
828
829  SourceLocation getLocStart() const LLVM_READONLY { return ThrowLoc; }
830  SourceLocation getLocEnd() const LLVM_READONLY {
831    if (getSubExpr() == 0)
832      return ThrowLoc;
833    return getSubExpr()->getLocEnd();
834  }
835
836  static bool classof(const Stmt *T) {
837    return T->getStmtClass() == CXXThrowExprClass;
838  }
839
840  // Iterators
841  child_range children() {
842    return child_range(&Op, Op ? &Op+1 : &Op);
843  }
844};
845
846/// \brief A default argument (C++ [dcl.fct.default]).
847///
848/// This wraps up a function call argument that was created from the
849/// corresponding parameter's default argument, when the call did not
850/// explicitly supply arguments for all of the parameters.
851class CXXDefaultArgExpr : public Expr {
852  /// \brief The parameter whose default is being used.
853  ///
854  /// When the bit is set, the subexpression is stored after the
855  /// CXXDefaultArgExpr itself. When the bit is clear, the parameter's
856  /// actual default expression is the subexpression.
857  llvm::PointerIntPair<ParmVarDecl *, 1, bool> Param;
858
859  /// \brief The location where the default argument expression was used.
860  SourceLocation Loc;
861
862  CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
863    : Expr(SC,
864           param->hasUnparsedDefaultArg()
865             ? param->getType().getNonReferenceType()
866             : param->getDefaultArg()->getType(),
867           param->getDefaultArg()->getValueKind(),
868           param->getDefaultArg()->getObjectKind(), false, false, false, false),
869      Param(param, false), Loc(Loc) { }
870
871  CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param,
872                    Expr *SubExpr)
873    : Expr(SC, SubExpr->getType(),
874           SubExpr->getValueKind(), SubExpr->getObjectKind(),
875           false, false, false, false),
876      Param(param, true), Loc(Loc) {
877    *reinterpret_cast<Expr **>(this + 1) = SubExpr;
878  }
879
880public:
881  CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
882
883  // \p Param is the parameter whose default argument is used by this
884  // expression.
885  static CXXDefaultArgExpr *Create(ASTContext &C, SourceLocation Loc,
886                                   ParmVarDecl *Param) {
887    return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
888  }
889
890  // \p Param is the parameter whose default argument is used by this
891  // expression, and \p SubExpr is the expression that will actually be used.
892  static CXXDefaultArgExpr *Create(ASTContext &C,
893                                   SourceLocation Loc,
894                                   ParmVarDecl *Param,
895                                   Expr *SubExpr);
896
897  // Retrieve the parameter that the argument was created from.
898  const ParmVarDecl *getParam() const { return Param.getPointer(); }
899  ParmVarDecl *getParam() { return Param.getPointer(); }
900
901  // Retrieve the actual argument to the function call.
902  const Expr *getExpr() const {
903    if (Param.getInt())
904      return *reinterpret_cast<Expr const * const*> (this + 1);
905    return getParam()->getDefaultArg();
906  }
907  Expr *getExpr() {
908    if (Param.getInt())
909      return *reinterpret_cast<Expr **> (this + 1);
910    return getParam()->getDefaultArg();
911  }
912
913  /// \brief Retrieve the location where this default argument was actually
914  /// used.
915  SourceLocation getUsedLocation() const { return Loc; }
916
917  /// Default argument expressions have no representation in the
918  /// source, so they have an empty source range.
919  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
920  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
921
922  SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
923
924  static bool classof(const Stmt *T) {
925    return T->getStmtClass() == CXXDefaultArgExprClass;
926  }
927
928  // Iterators
929  child_range children() { return child_range(); }
930
931  friend class ASTStmtReader;
932  friend class ASTStmtWriter;
933};
934
935/// \brief A use of a default initializer in a constructor or in aggregate
936/// initialization.
937///
938/// This wraps a use of a C++ default initializer (technically,
939/// a brace-or-equal-initializer for a non-static data member) when it
940/// is implicitly used in a mem-initializer-list in a constructor
941/// (C++11 [class.base.init]p8) or in aggregate initialization
942/// (C++1y [dcl.init.aggr]p7).
943class CXXDefaultInitExpr : public Expr {
944  /// \brief The field whose default is being used.
945  FieldDecl *Field;
946
947  /// \brief The location where the default initializer expression was used.
948  SourceLocation Loc;
949
950  CXXDefaultInitExpr(ASTContext &C, SourceLocation Loc, FieldDecl *Field,
951                     QualType T);
952
953  CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
954
955public:
956  /// \p Field is the non-static data member whose default initializer is used
957  /// by this expression.
958  static CXXDefaultInitExpr *Create(ASTContext &C, SourceLocation Loc,
959                                    FieldDecl *Field) {
960    return new (C) CXXDefaultInitExpr(C, Loc, Field, Field->getType());
961  }
962
963  /// \brief Get the field whose initializer will be used.
964  FieldDecl *getField() { return Field; }
965  const FieldDecl *getField() const { return Field; }
966
967  /// \brief Get the initialization expression that will be used.
968  const Expr *getExpr() const { return Field->getInClassInitializer(); }
969  Expr *getExpr() { return Field->getInClassInitializer(); }
970
971  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
972  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
973
974  static bool classof(const Stmt *T) {
975    return T->getStmtClass() == CXXDefaultInitExprClass;
976  }
977
978  // Iterators
979  child_range children() { return child_range(); }
980
981  friend class ASTReader;
982  friend class ASTStmtReader;
983};
984
985/// \brief Represents a C++ temporary.
986class CXXTemporary {
987  /// \brief The destructor that needs to be called.
988  const CXXDestructorDecl *Destructor;
989
990  explicit CXXTemporary(const CXXDestructorDecl *destructor)
991    : Destructor(destructor) { }
992
993public:
994  static CXXTemporary *Create(ASTContext &C,
995                              const CXXDestructorDecl *Destructor);
996
997  const CXXDestructorDecl *getDestructor() const { return Destructor; }
998  void setDestructor(const CXXDestructorDecl *Dtor) {
999    Destructor = Dtor;
1000  }
1001};
1002
1003/// \brief Represents binding an expression to a temporary.
1004///
1005/// This ensures the destructor is called for the temporary. It should only be
1006/// needed for non-POD, non-trivially destructable class types. For example:
1007///
1008/// \code
1009///   struct S {
1010///     S() { }  // User defined constructor makes S non-POD.
1011///     ~S() { } // User defined destructor makes it non-trivial.
1012///   };
1013///   void test() {
1014///     const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1015///   }
1016/// \endcode
1017class CXXBindTemporaryExpr : public Expr {
1018  CXXTemporary *Temp;
1019
1020  Stmt *SubExpr;
1021
1022  CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
1023   : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
1024          VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
1025          SubExpr->isValueDependent(),
1026          SubExpr->isInstantiationDependent(),
1027          SubExpr->containsUnexpandedParameterPack()),
1028     Temp(temp), SubExpr(SubExpr) { }
1029
1030public:
1031  CXXBindTemporaryExpr(EmptyShell Empty)
1032    : Expr(CXXBindTemporaryExprClass, Empty), Temp(0), SubExpr(0) {}
1033
1034  static CXXBindTemporaryExpr *Create(ASTContext &C, CXXTemporary *Temp,
1035                                      Expr* SubExpr);
1036
1037  CXXTemporary *getTemporary() { return Temp; }
1038  const CXXTemporary *getTemporary() const { return Temp; }
1039  void setTemporary(CXXTemporary *T) { Temp = T; }
1040
1041  const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1042  Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1043  void setSubExpr(Expr *E) { SubExpr = E; }
1044
1045  SourceLocation getLocStart() const LLVM_READONLY {
1046    return SubExpr->getLocStart();
1047  }
1048  SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
1049
1050  // Implement isa/cast/dyncast/etc.
1051  static bool classof(const Stmt *T) {
1052    return T->getStmtClass() == CXXBindTemporaryExprClass;
1053  }
1054
1055  // Iterators
1056  child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1057};
1058
1059/// \brief Represents a call to a C++ constructor.
1060class CXXConstructExpr : public Expr {
1061public:
1062  enum ConstructionKind {
1063    CK_Complete,
1064    CK_NonVirtualBase,
1065    CK_VirtualBase,
1066    CK_Delegating
1067  };
1068
1069private:
1070  CXXConstructorDecl *Constructor;
1071
1072  SourceLocation Loc;
1073  SourceRange ParenRange;
1074  unsigned NumArgs : 16;
1075  bool Elidable : 1;
1076  bool HadMultipleCandidates : 1;
1077  bool ListInitialization : 1;
1078  bool ZeroInitialization : 1;
1079  unsigned ConstructKind : 2;
1080  Stmt **Args;
1081
1082protected:
1083  CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T,
1084                   SourceLocation Loc,
1085                   CXXConstructorDecl *d, bool elidable,
1086                   ArrayRef<Expr *> Args,
1087                   bool HadMultipleCandidates,
1088                   bool ListInitialization,
1089                   bool ZeroInitialization,
1090                   ConstructionKind ConstructKind,
1091                   SourceRange ParenRange);
1092
1093  /// \brief Construct an empty C++ construction expression.
1094  CXXConstructExpr(StmtClass SC, EmptyShell Empty)
1095    : Expr(SC, Empty), Constructor(0), NumArgs(0), Elidable(false),
1096      HadMultipleCandidates(false), ListInitialization(false),
1097      ZeroInitialization(false), ConstructKind(0), Args(0)
1098  { }
1099
1100public:
1101  /// \brief Construct an empty C++ construction expression.
1102  explicit CXXConstructExpr(EmptyShell Empty)
1103    : Expr(CXXConstructExprClass, Empty), Constructor(0),
1104      NumArgs(0), Elidable(false), HadMultipleCandidates(false),
1105      ListInitialization(false), ZeroInitialization(false),
1106      ConstructKind(0), Args(0)
1107  { }
1108
1109  static CXXConstructExpr *Create(ASTContext &C, QualType T,
1110                                  SourceLocation Loc,
1111                                  CXXConstructorDecl *D, bool Elidable,
1112                                  ArrayRef<Expr *> Args,
1113                                  bool HadMultipleCandidates,
1114                                  bool ListInitialization,
1115                                  bool ZeroInitialization,
1116                                  ConstructionKind ConstructKind,
1117                                  SourceRange ParenRange);
1118
1119  CXXConstructorDecl* getConstructor() const { return Constructor; }
1120  void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
1121
1122  SourceLocation getLocation() const { return Loc; }
1123  void setLocation(SourceLocation Loc) { this->Loc = Loc; }
1124
1125  /// \brief Whether this construction is elidable.
1126  bool isElidable() const { return Elidable; }
1127  void setElidable(bool E) { Elidable = E; }
1128
1129  /// \brief Whether the referred constructor was resolved from
1130  /// an overloaded set having size greater than 1.
1131  bool hadMultipleCandidates() const { return HadMultipleCandidates; }
1132  void setHadMultipleCandidates(bool V) { HadMultipleCandidates = V; }
1133
1134  /// \brief Whether this constructor call was written as list-initialization.
1135  bool isListInitialization() const { return ListInitialization; }
1136  void setListInitialization(bool V) { ListInitialization = V; }
1137
1138  /// \brief Whether this construction first requires
1139  /// zero-initialization before the initializer is called.
1140  bool requiresZeroInitialization() const { return ZeroInitialization; }
1141  void setRequiresZeroInitialization(bool ZeroInit) {
1142    ZeroInitialization = ZeroInit;
1143  }
1144
1145  /// \brief Determine whether this constructor is actually constructing
1146  /// a base class (rather than a complete object).
1147  ConstructionKind getConstructionKind() const {
1148    return (ConstructionKind)ConstructKind;
1149  }
1150  void setConstructionKind(ConstructionKind CK) {
1151    ConstructKind = CK;
1152  }
1153
1154  typedef ExprIterator arg_iterator;
1155  typedef ConstExprIterator const_arg_iterator;
1156
1157  arg_iterator arg_begin() { return Args; }
1158  arg_iterator arg_end() { return Args + NumArgs; }
1159  const_arg_iterator arg_begin() const { return Args; }
1160  const_arg_iterator arg_end() const { return Args + NumArgs; }
1161
1162  Expr **getArgs() const { return reinterpret_cast<Expr **>(Args); }
1163  unsigned getNumArgs() const { return NumArgs; }
1164
1165  /// \brief Return the specified argument.
1166  Expr *getArg(unsigned Arg) {
1167    assert(Arg < NumArgs && "Arg access out of range!");
1168    return cast<Expr>(Args[Arg]);
1169  }
1170  const Expr *getArg(unsigned Arg) const {
1171    assert(Arg < NumArgs && "Arg access out of range!");
1172    return cast<Expr>(Args[Arg]);
1173  }
1174
1175  /// \brief Set the specified argument.
1176  void setArg(unsigned Arg, Expr *ArgExpr) {
1177    assert(Arg < NumArgs && "Arg access out of range!");
1178    Args[Arg] = ArgExpr;
1179  }
1180
1181  SourceLocation getLocStart() const LLVM_READONLY;
1182  SourceLocation getLocEnd() const LLVM_READONLY;
1183  SourceRange getParenRange() const { return ParenRange; }
1184  void setParenRange(SourceRange Range) { ParenRange = Range; }
1185
1186  static bool classof(const Stmt *T) {
1187    return T->getStmtClass() == CXXConstructExprClass ||
1188      T->getStmtClass() == CXXTemporaryObjectExprClass;
1189  }
1190
1191  // Iterators
1192  child_range children() {
1193    return child_range(&Args[0], &Args[0]+NumArgs);
1194  }
1195
1196  friend class ASTStmtReader;
1197};
1198
1199/// \brief Represents an explicit C++ type conversion that uses "functional"
1200/// notation (C++ [expr.type.conv]).
1201///
1202/// Example:
1203/// \code
1204///   x = int(0.5);
1205/// \endcode
1206class CXXFunctionalCastExpr : public ExplicitCastExpr {
1207  SourceLocation TyBeginLoc;
1208  SourceLocation RParenLoc;
1209
1210  CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1211                        TypeSourceInfo *writtenTy,
1212                        SourceLocation tyBeginLoc, CastKind kind,
1213                        Expr *castExpr, unsigned pathSize,
1214                        SourceLocation rParenLoc)
1215    : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
1216                       castExpr, pathSize, writtenTy),
1217      TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {}
1218
1219  explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
1220    : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) { }
1221
1222public:
1223  static CXXFunctionalCastExpr *Create(ASTContext &Context, QualType T,
1224                                       ExprValueKind VK,
1225                                       TypeSourceInfo *Written,
1226                                       SourceLocation TyBeginLoc,
1227                                       CastKind Kind, Expr *Op,
1228                                       const CXXCastPath *Path,
1229                                       SourceLocation RPLoc);
1230  static CXXFunctionalCastExpr *CreateEmpty(ASTContext &Context,
1231                                            unsigned PathSize);
1232
1233  SourceLocation getTypeBeginLoc() const { return TyBeginLoc; }
1234  void setTypeBeginLoc(SourceLocation L) { TyBeginLoc = L; }
1235  SourceLocation getRParenLoc() const { return RParenLoc; }
1236  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1237
1238  SourceLocation getLocStart() const LLVM_READONLY { return TyBeginLoc; }
1239  SourceLocation getLocEnd() const LLVM_READONLY {
1240    return RParenLoc.isValid() ? RParenLoc : getSubExpr()->getLocEnd();
1241  }
1242
1243  static bool classof(const Stmt *T) {
1244    return T->getStmtClass() == CXXFunctionalCastExprClass;
1245  }
1246};
1247
1248/// @brief Represents a C++ functional cast expression that builds a
1249/// temporary object.
1250///
1251/// This expression type represents a C++ "functional" cast
1252/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1253/// constructor to build a temporary object. With N == 1 arguments the
1254/// functional cast expression will be represented by CXXFunctionalCastExpr.
1255/// Example:
1256/// \code
1257/// struct X { X(int, float); }
1258///
1259/// X create_X() {
1260///   return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1261/// };
1262/// \endcode
1263class CXXTemporaryObjectExpr : public CXXConstructExpr {
1264  TypeSourceInfo *Type;
1265
1266public:
1267  CXXTemporaryObjectExpr(ASTContext &C, CXXConstructorDecl *Cons,
1268                         TypeSourceInfo *Type,
1269                         ArrayRef<Expr *> Args,
1270                         SourceRange parenRange,
1271                         bool HadMultipleCandidates,
1272                         bool ListInitialization,
1273                         bool ZeroInitialization);
1274  explicit CXXTemporaryObjectExpr(EmptyShell Empty)
1275    : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty), Type() { }
1276
1277  TypeSourceInfo *getTypeSourceInfo() const { return Type; }
1278
1279  SourceLocation getLocStart() const LLVM_READONLY;
1280  SourceLocation getLocEnd() const LLVM_READONLY;
1281
1282  static bool classof(const Stmt *T) {
1283    return T->getStmtClass() == CXXTemporaryObjectExprClass;
1284  }
1285
1286  friend class ASTStmtReader;
1287};
1288
1289/// \brief A C++ lambda expression, which produces a function object
1290/// (of unspecified type) that can be invoked later.
1291///
1292/// Example:
1293/// \code
1294/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1295///   values.erase(std::remove_if(values.begin(), values.end(),
1296///                               [=](double value) { return value > cutoff; });
1297/// }
1298/// \endcode
1299///
1300/// C++11 lambda expressions can capture local variables, either by copying
1301/// the values of those local variables at the time the function
1302/// object is constructed (not when it is called!) or by holding a
1303/// reference to the local variable. These captures can occur either
1304/// implicitly or can be written explicitly between the square
1305/// brackets ([...]) that start the lambda expression.
1306///
1307/// C++1y introduces a new form of "capture" called an init-capture that
1308/// includes an initializing expression (rather than capturing a variable),
1309/// and which can never occur implicitly.
1310class LambdaExpr : public Expr {
1311  enum {
1312    /// \brief Flag used by the Capture class to indicate that the given
1313    /// capture was implicit.
1314    Capture_Implicit = 0x01,
1315
1316    /// \brief Flag used by the Capture class to indicate that the
1317    /// given capture was by-copy.
1318    ///
1319    /// This includes the case of a non-reference init-capture.
1320    Capture_ByCopy = 0x02
1321  };
1322
1323  /// \brief The source range that covers the lambda introducer ([...]).
1324  SourceRange IntroducerRange;
1325
1326  /// \brief The number of captures.
1327  unsigned NumCaptures : 16;
1328
1329  /// \brief The default capture kind, which is a value of type
1330  /// LambdaCaptureDefault.
1331  unsigned CaptureDefault : 2;
1332
1333  /// \brief Whether this lambda had an explicit parameter list vs. an
1334  /// implicit (and empty) parameter list.
1335  unsigned ExplicitParams : 1;
1336
1337  /// \brief Whether this lambda had the result type explicitly specified.
1338  unsigned ExplicitResultType : 1;
1339
1340  /// \brief Whether there are any array index variables stored at the end of
1341  /// this lambda expression.
1342  unsigned HasArrayIndexVars : 1;
1343
1344  /// \brief The location of the closing brace ('}') that completes
1345  /// the lambda.
1346  ///
1347  /// The location of the brace is also available by looking up the
1348  /// function call operator in the lambda class. However, it is
1349  /// stored here to improve the performance of getSourceRange(), and
1350  /// to avoid having to deserialize the function call operator from a
1351  /// module file just to determine the source range.
1352  SourceLocation ClosingBrace;
1353
1354  // Note: The capture initializers are stored directly after the lambda
1355  // expression, along with the index variables used to initialize by-copy
1356  // array captures.
1357
1358public:
1359  /// \brief Describes the capture of a variable or of \c this, or of a
1360  /// C++1y init-capture.
1361  class Capture {
1362    llvm::PointerIntPair<Decl *, 2> DeclAndBits;
1363    SourceLocation Loc;
1364    SourceLocation EllipsisLoc;
1365
1366    friend class ASTStmtReader;
1367    friend class ASTStmtWriter;
1368
1369  public:
1370    /// \brief Create a new capture of a variable or of \c this.
1371    ///
1372    /// \param Loc The source location associated with this capture.
1373    ///
1374    /// \param Kind The kind of capture (this, byref, bycopy), which must
1375    /// not be init-capture.
1376    ///
1377    /// \param Implicit Whether the capture was implicit or explicit.
1378    ///
1379    /// \param Var The local variable being captured, or null if capturing
1380    /// \c this.
1381    ///
1382    /// \param EllipsisLoc The location of the ellipsis (...) for a
1383    /// capture that is a pack expansion, or an invalid source
1384    /// location to indicate that this is not a pack expansion.
1385    Capture(SourceLocation Loc, bool Implicit,
1386            LambdaCaptureKind Kind, VarDecl *Var = 0,
1387            SourceLocation EllipsisLoc = SourceLocation());
1388
1389    /// \brief Create a new init-capture.
1390    Capture(FieldDecl *Field);
1391
1392    /// \brief Determine the kind of capture.
1393    LambdaCaptureKind getCaptureKind() const;
1394
1395    /// \brief Determine whether this capture handles the C++ \c this
1396    /// pointer.
1397    bool capturesThis() const { return DeclAndBits.getPointer() == 0; }
1398
1399    /// \brief Determine whether this capture handles a variable.
1400    bool capturesVariable() const {
1401      return dyn_cast_or_null<VarDecl>(DeclAndBits.getPointer());
1402    }
1403
1404    /// \brief Determine whether this is an init-capture.
1405    bool isInitCapture() const { return getCaptureKind() == LCK_Init; }
1406
1407    /// \brief Retrieve the declaration of the local variable being
1408    /// captured.
1409    ///
1410    /// This operation is only valid if this capture is a variable capture
1411    /// (other than a capture of \c this).
1412    VarDecl *getCapturedVar() const {
1413      assert(capturesVariable() && "No variable available for 'this' capture");
1414      return cast<VarDecl>(DeclAndBits.getPointer());
1415    }
1416
1417    /// \brief Retrieve the field for an init-capture.
1418    ///
1419    /// This works only for an init-capture.  To retrieve the FieldDecl for
1420    /// a captured variable or for a capture of \c this, use
1421    /// LambdaExpr::getLambdaClass and CXXRecordDecl::getCaptureFields.
1422    FieldDecl *getInitCaptureField() const {
1423      assert(getCaptureKind() == LCK_Init && "no field for non-init-capture");
1424      return cast<FieldDecl>(DeclAndBits.getPointer());
1425    }
1426
1427    /// \brief Determine whether this was an implicit capture (not
1428    /// written between the square brackets introducing the lambda).
1429    bool isImplicit() const { return DeclAndBits.getInt() & Capture_Implicit; }
1430
1431    /// \brief Determine whether this was an explicit capture (written
1432    /// between the square brackets introducing the lambda).
1433    bool isExplicit() const { return !isImplicit(); }
1434
1435    /// \brief Retrieve the source location of the capture.
1436    ///
1437    /// For an explicit capture, this returns the location of the
1438    /// explicit capture in the source. For an implicit capture, this
1439    /// returns the location at which the variable or \c this was first
1440    /// used.
1441    SourceLocation getLocation() const { return Loc; }
1442
1443    /// \brief Determine whether this capture is a pack expansion,
1444    /// which captures a function parameter pack.
1445    bool isPackExpansion() const { return EllipsisLoc.isValid(); }
1446
1447    /// \brief Retrieve the location of the ellipsis for a capture
1448    /// that is a pack expansion.
1449    SourceLocation getEllipsisLoc() const {
1450      assert(isPackExpansion() && "No ellipsis location for a non-expansion");
1451      return EllipsisLoc;
1452    }
1453  };
1454
1455private:
1456  /// \brief Construct a lambda expression.
1457  LambdaExpr(QualType T, SourceRange IntroducerRange,
1458             LambdaCaptureDefault CaptureDefault,
1459             ArrayRef<Capture> Captures,
1460             bool ExplicitParams,
1461             bool ExplicitResultType,
1462             ArrayRef<Expr *> CaptureInits,
1463             ArrayRef<VarDecl *> ArrayIndexVars,
1464             ArrayRef<unsigned> ArrayIndexStarts,
1465             SourceLocation ClosingBrace,
1466             bool ContainsUnexpandedParameterPack);
1467
1468  /// \brief Construct an empty lambda expression.
1469  LambdaExpr(EmptyShell Empty, unsigned NumCaptures, bool HasArrayIndexVars)
1470    : Expr(LambdaExprClass, Empty),
1471      NumCaptures(NumCaptures), CaptureDefault(LCD_None), ExplicitParams(false),
1472      ExplicitResultType(false), HasArrayIndexVars(true) {
1473    getStoredStmts()[NumCaptures] = 0;
1474  }
1475
1476  Stmt **getStoredStmts() const {
1477    return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
1478  }
1479
1480  /// \brief Retrieve the mapping from captures to the first array index
1481  /// variable.
1482  unsigned *getArrayIndexStarts() const {
1483    return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
1484  }
1485
1486  /// \brief Retrieve the complete set of array-index variables.
1487  VarDecl **getArrayIndexVars() const {
1488    unsigned ArrayIndexSize =
1489        llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
1490                                 llvm::alignOf<VarDecl*>());
1491    return reinterpret_cast<VarDecl **>(
1492        reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
1493  }
1494
1495public:
1496  /// \brief Construct a new lambda expression.
1497  static LambdaExpr *Create(ASTContext &C,
1498                            CXXRecordDecl *Class,
1499                            SourceRange IntroducerRange,
1500                            LambdaCaptureDefault CaptureDefault,
1501                            ArrayRef<Capture> Captures,
1502                            bool ExplicitParams,
1503                            bool ExplicitResultType,
1504                            ArrayRef<Expr *> CaptureInits,
1505                            ArrayRef<VarDecl *> ArrayIndexVars,
1506                            ArrayRef<unsigned> ArrayIndexStarts,
1507                            SourceLocation ClosingBrace,
1508                            bool ContainsUnexpandedParameterPack);
1509
1510  /// \brief Construct a new lambda expression that will be deserialized from
1511  /// an external source.
1512  static LambdaExpr *CreateDeserialized(ASTContext &C, unsigned NumCaptures,
1513                                        unsigned NumArrayIndexVars);
1514
1515  /// \brief Determine the default capture kind for this lambda.
1516  LambdaCaptureDefault getCaptureDefault() const {
1517    return static_cast<LambdaCaptureDefault>(CaptureDefault);
1518  }
1519
1520  /// \brief An iterator that walks over the captures of the lambda,
1521  /// both implicit and explicit.
1522  typedef const Capture *capture_iterator;
1523
1524  /// \brief Retrieve an iterator pointing to the first lambda capture.
1525  capture_iterator capture_begin() const;
1526
1527  /// \brief Retrieve an iterator pointing past the end of the
1528  /// sequence of lambda captures.
1529  capture_iterator capture_end() const;
1530
1531  /// \brief Determine the number of captures in this lambda.
1532  unsigned capture_size() const { return NumCaptures; }
1533
1534  /// \brief Retrieve an iterator pointing to the first explicit
1535  /// lambda capture.
1536  capture_iterator explicit_capture_begin() const;
1537
1538  /// \brief Retrieve an iterator pointing past the end of the sequence of
1539  /// explicit lambda captures.
1540  capture_iterator explicit_capture_end() const;
1541
1542  /// \brief Retrieve an iterator pointing to the first implicit
1543  /// lambda capture.
1544  capture_iterator implicit_capture_begin() const;
1545
1546  /// \brief Retrieve an iterator pointing past the end of the sequence of
1547  /// implicit lambda captures.
1548  capture_iterator implicit_capture_end() const;
1549
1550  /// \brief Iterator that walks over the capture initialization
1551  /// arguments.
1552  typedef Expr **capture_init_iterator;
1553
1554  /// \brief Retrieve the first initialization argument for this
1555  /// lambda expression (which initializes the first capture field).
1556  capture_init_iterator capture_init_begin() const {
1557    return reinterpret_cast<Expr **>(getStoredStmts());
1558  }
1559
1560  /// \brief Retrieve the iterator pointing one past the last
1561  /// initialization argument for this lambda expression.
1562  capture_init_iterator capture_init_end() const {
1563    return capture_init_begin() + NumCaptures;
1564  }
1565
1566  /// \brief Retrieve the initializer for an init-capture.
1567  Expr *getInitCaptureInit(capture_iterator Capture) {
1568    assert(Capture >= explicit_capture_begin() &&
1569           Capture <= explicit_capture_end() && Capture->isInitCapture());
1570    return capture_init_begin()[Capture - capture_begin()];
1571  }
1572  const Expr *getInitCaptureInit(capture_iterator Capture) const {
1573    return const_cast<LambdaExpr*>(this)->getInitCaptureInit(Capture);
1574  }
1575
1576  /// \brief Retrieve the set of index variables used in the capture
1577  /// initializer of an array captured by copy.
1578  ///
1579  /// \param Iter The iterator that points at the capture initializer for
1580  /// which we are extracting the corresponding index variables.
1581  ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) const;
1582
1583  /// \brief Retrieve the source range covering the lambda introducer,
1584  /// which contains the explicit capture list surrounded by square
1585  /// brackets ([...]).
1586  SourceRange getIntroducerRange() const { return IntroducerRange; }
1587
1588  /// \brief Retrieve the class that corresponds to the lambda.
1589  ///
1590  /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
1591  /// captures in its fields and provides the various operations permitted
1592  /// on a lambda (copying, calling).
1593  CXXRecordDecl *getLambdaClass() const;
1594
1595  /// \brief Retrieve the function call operator associated with this
1596  /// lambda expression.
1597  CXXMethodDecl *getCallOperator() const;
1598
1599  /// \brief Retrieve the body of the lambda.
1600  CompoundStmt *getBody() const;
1601
1602  /// \brief Determine whether the lambda is mutable, meaning that any
1603  /// captures values can be modified.
1604  bool isMutable() const;
1605
1606  /// \brief Determine whether this lambda has an explicit parameter
1607  /// list vs. an implicit (empty) parameter list.
1608  bool hasExplicitParameters() const { return ExplicitParams; }
1609
1610  /// \brief Whether this lambda had its result type explicitly specified.
1611  bool hasExplicitResultType() const { return ExplicitResultType; }
1612
1613  static bool classof(const Stmt *T) {
1614    return T->getStmtClass() == LambdaExprClass;
1615  }
1616
1617  SourceLocation getLocStart() const LLVM_READONLY {
1618    return IntroducerRange.getBegin();
1619  }
1620  SourceLocation getLocEnd() const LLVM_READONLY { return ClosingBrace; }
1621
1622  child_range children() {
1623    return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
1624  }
1625
1626  friend class ASTStmtReader;
1627  friend class ASTStmtWriter;
1628};
1629
1630/// An expression "T()" which creates a value-initialized rvalue of type
1631/// T, which is a non-class type.  See (C++98 [5.2.3p2]).
1632class CXXScalarValueInitExpr : public Expr {
1633  SourceLocation RParenLoc;
1634  TypeSourceInfo *TypeInfo;
1635
1636  friend class ASTStmtReader;
1637
1638public:
1639  /// \brief Create an explicitly-written scalar-value initialization
1640  /// expression.
1641  CXXScalarValueInitExpr(QualType Type,
1642                         TypeSourceInfo *TypeInfo,
1643                         SourceLocation rParenLoc ) :
1644    Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
1645         false, false, Type->isInstantiationDependentType(), false),
1646    RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
1647
1648  explicit CXXScalarValueInitExpr(EmptyShell Shell)
1649    : Expr(CXXScalarValueInitExprClass, Shell) { }
1650
1651  TypeSourceInfo *getTypeSourceInfo() const {
1652    return TypeInfo;
1653  }
1654
1655  SourceLocation getRParenLoc() const { return RParenLoc; }
1656
1657  SourceLocation getLocStart() const LLVM_READONLY;
1658  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1659
1660  static bool classof(const Stmt *T) {
1661    return T->getStmtClass() == CXXScalarValueInitExprClass;
1662  }
1663
1664  // Iterators
1665  child_range children() { return child_range(); }
1666};
1667
1668/// \brief Represents a new-expression for memory allocation and constructor
1669/// calls, e.g: "new CXXNewExpr(foo)".
1670class CXXNewExpr : public Expr {
1671  /// Contains an optional array size expression, an optional initialization
1672  /// expression, and any number of optional placement arguments, in that order.
1673  Stmt **SubExprs;
1674  /// \brief Points to the allocation function used.
1675  FunctionDecl *OperatorNew;
1676  /// \brief Points to the deallocation function used in case of error. May be
1677  /// null.
1678  FunctionDecl *OperatorDelete;
1679
1680  /// \brief The allocated type-source information, as written in the source.
1681  TypeSourceInfo *AllocatedTypeInfo;
1682
1683  /// \brief If the allocated type was expressed as a parenthesized type-id,
1684  /// the source range covering the parenthesized type-id.
1685  SourceRange TypeIdParens;
1686
1687  /// \brief Range of the entire new expression.
1688  SourceRange Range;
1689
1690  /// \brief Source-range of a paren-delimited initializer.
1691  SourceRange DirectInitRange;
1692
1693  /// Was the usage ::new, i.e. is the global new to be used?
1694  bool GlobalNew : 1;
1695  /// Do we allocate an array? If so, the first SubExpr is the size expression.
1696  bool Array : 1;
1697  /// If this is an array allocation, does the usual deallocation
1698  /// function for the allocated type want to know the allocated size?
1699  bool UsualArrayDeleteWantsSize : 1;
1700  /// The number of placement new arguments.
1701  unsigned NumPlacementArgs : 13;
1702  /// What kind of initializer do we have? Could be none, parens, or braces.
1703  /// In storage, we distinguish between "none, and no initializer expr", and
1704  /// "none, but an implicit initializer expr".
1705  unsigned StoredInitializationStyle : 2;
1706
1707  friend class ASTStmtReader;
1708  friend class ASTStmtWriter;
1709public:
1710  enum InitializationStyle {
1711    NoInit,   ///< New-expression has no initializer as written.
1712    CallInit, ///< New-expression has a C++98 paren-delimited initializer.
1713    ListInit  ///< New-expression has a C++11 list-initializer.
1714  };
1715
1716  CXXNewExpr(ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
1717             FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
1718             ArrayRef<Expr*> placementArgs,
1719             SourceRange typeIdParens, Expr *arraySize,
1720             InitializationStyle initializationStyle, Expr *initializer,
1721             QualType ty, TypeSourceInfo *AllocatedTypeInfo,
1722             SourceRange Range, SourceRange directInitRange);
1723  explicit CXXNewExpr(EmptyShell Shell)
1724    : Expr(CXXNewExprClass, Shell), SubExprs(0) { }
1725
1726  void AllocateArgsArray(ASTContext &C, bool isArray, unsigned numPlaceArgs,
1727                         bool hasInitializer);
1728
1729  QualType getAllocatedType() const {
1730    assert(getType()->isPointerType());
1731    return getType()->getAs<PointerType>()->getPointeeType();
1732  }
1733
1734  TypeSourceInfo *getAllocatedTypeSourceInfo() const {
1735    return AllocatedTypeInfo;
1736  }
1737
1738  /// \brief True if the allocation result needs to be null-checked.
1739  ///
1740  /// C++11 [expr.new]p13:
1741  ///   If the allocation function returns null, initialization shall
1742  ///   not be done, the deallocation function shall not be called,
1743  ///   and the value of the new-expression shall be null.
1744  ///
1745  /// An allocation function is not allowed to return null unless it
1746  /// has a non-throwing exception-specification.  The '03 rule is
1747  /// identical except that the definition of a non-throwing
1748  /// exception specification is just "is it throw()?".
1749  bool shouldNullCheckAllocation(ASTContext &Ctx) const;
1750
1751  FunctionDecl *getOperatorNew() const { return OperatorNew; }
1752  void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
1753  FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1754  void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
1755
1756  bool isArray() const { return Array; }
1757  Expr *getArraySize() {
1758    return Array ? cast<Expr>(SubExprs[0]) : 0;
1759  }
1760  const Expr *getArraySize() const {
1761    return Array ? cast<Expr>(SubExprs[0]) : 0;
1762  }
1763
1764  unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
1765  Expr **getPlacementArgs() {
1766    return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
1767  }
1768
1769  Expr *getPlacementArg(unsigned i) {
1770    assert(i < NumPlacementArgs && "Index out of range");
1771    return getPlacementArgs()[i];
1772  }
1773  const Expr *getPlacementArg(unsigned i) const {
1774    assert(i < NumPlacementArgs && "Index out of range");
1775    return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
1776  }
1777
1778  bool isParenTypeId() const { return TypeIdParens.isValid(); }
1779  SourceRange getTypeIdParens() const { return TypeIdParens; }
1780
1781  bool isGlobalNew() const { return GlobalNew; }
1782
1783  /// \brief Whether this new-expression has any initializer at all.
1784  bool hasInitializer() const { return StoredInitializationStyle > 0; }
1785
1786  /// \brief The kind of initializer this new-expression has.
1787  InitializationStyle getInitializationStyle() const {
1788    if (StoredInitializationStyle == 0)
1789      return NoInit;
1790    return static_cast<InitializationStyle>(StoredInitializationStyle-1);
1791  }
1792
1793  /// \brief The initializer of this new-expression.
1794  Expr *getInitializer() {
1795    return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
1796  }
1797  const Expr *getInitializer() const {
1798    return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
1799  }
1800
1801  /// \brief Returns the CXXConstructExpr from this new-expression, or null.
1802  const CXXConstructExpr* getConstructExpr() const {
1803    return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
1804  }
1805
1806  /// Answers whether the usual array deallocation function for the
1807  /// allocated type expects the size of the allocation as a
1808  /// parameter.
1809  bool doesUsualArrayDeleteWantSize() const {
1810    return UsualArrayDeleteWantsSize;
1811  }
1812
1813  typedef ExprIterator arg_iterator;
1814  typedef ConstExprIterator const_arg_iterator;
1815
1816  arg_iterator placement_arg_begin() {
1817    return SubExprs + Array + hasInitializer();
1818  }
1819  arg_iterator placement_arg_end() {
1820    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1821  }
1822  const_arg_iterator placement_arg_begin() const {
1823    return SubExprs + Array + hasInitializer();
1824  }
1825  const_arg_iterator placement_arg_end() const {
1826    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1827  }
1828
1829  typedef Stmt **raw_arg_iterator;
1830  raw_arg_iterator raw_arg_begin() { return SubExprs; }
1831  raw_arg_iterator raw_arg_end() {
1832    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1833  }
1834  const_arg_iterator raw_arg_begin() const { return SubExprs; }
1835  const_arg_iterator raw_arg_end() const {
1836    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
1837  }
1838
1839  SourceLocation getStartLoc() const { return Range.getBegin(); }
1840  SourceLocation getEndLoc() const { return Range.getEnd(); }
1841
1842  SourceRange getDirectInitRange() const { return DirectInitRange; }
1843
1844  SourceRange getSourceRange() const LLVM_READONLY {
1845    return Range;
1846  }
1847  SourceLocation getLocStart() const LLVM_READONLY { return getStartLoc(); }
1848  SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1849
1850  static bool classof(const Stmt *T) {
1851    return T->getStmtClass() == CXXNewExprClass;
1852  }
1853
1854  // Iterators
1855  child_range children() {
1856    return child_range(raw_arg_begin(), raw_arg_end());
1857  }
1858};
1859
1860/// \brief Represents a \c delete expression for memory deallocation and
1861/// destructor calls, e.g. "delete[] pArray".
1862class CXXDeleteExpr : public Expr {
1863  /// Points to the operator delete overload that is used. Could be a member.
1864  FunctionDecl *OperatorDelete;
1865  /// The pointer expression to be deleted.
1866  Stmt *Argument;
1867  /// Location of the expression.
1868  SourceLocation Loc;
1869  /// Is this a forced global delete, i.e. "::delete"?
1870  bool GlobalDelete : 1;
1871  /// Is this the array form of delete, i.e. "delete[]"?
1872  bool ArrayForm : 1;
1873  /// ArrayFormAsWritten can be different from ArrayForm if 'delete' is applied
1874  /// to pointer-to-array type (ArrayFormAsWritten will be false while ArrayForm
1875  /// will be true).
1876  bool ArrayFormAsWritten : 1;
1877  /// Does the usual deallocation function for the element type require
1878  /// a size_t argument?
1879  bool UsualArrayDeleteWantsSize : 1;
1880public:
1881  CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
1882                bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
1883                FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc)
1884    : Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
1885           arg->isInstantiationDependent(),
1886           arg->containsUnexpandedParameterPack()),
1887      OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
1888      GlobalDelete(globalDelete),
1889      ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
1890      UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) { }
1891  explicit CXXDeleteExpr(EmptyShell Shell)
1892    : Expr(CXXDeleteExprClass, Shell), OperatorDelete(0), Argument(0) { }
1893
1894  bool isGlobalDelete() const { return GlobalDelete; }
1895  bool isArrayForm() const { return ArrayForm; }
1896  bool isArrayFormAsWritten() const { return ArrayFormAsWritten; }
1897
1898  /// Answers whether the usual array deallocation function for the
1899  /// allocated type expects the size of the allocation as a
1900  /// parameter.  This can be true even if the actual deallocation
1901  /// function that we're using doesn't want a size.
1902  bool doesUsualArrayDeleteWantSize() const {
1903    return UsualArrayDeleteWantsSize;
1904  }
1905
1906  FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
1907
1908  Expr *getArgument() { return cast<Expr>(Argument); }
1909  const Expr *getArgument() const { return cast<Expr>(Argument); }
1910
1911  /// \brief Retrieve the type being destroyed.
1912  ///
1913  /// If the type being destroyed is a dependent type which may or may not
1914  /// be a pointer, return an invalid type.
1915  QualType getDestroyedType() const;
1916
1917  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1918  SourceLocation getLocEnd() const LLVM_READONLY {return Argument->getLocEnd();}
1919
1920  static bool classof(const Stmt *T) {
1921    return T->getStmtClass() == CXXDeleteExprClass;
1922  }
1923
1924  // Iterators
1925  child_range children() { return child_range(&Argument, &Argument+1); }
1926
1927  friend class ASTStmtReader;
1928};
1929
1930/// \brief Stores the type being destroyed by a pseudo-destructor expression.
1931class PseudoDestructorTypeStorage {
1932  /// \brief Either the type source information or the name of the type, if
1933  /// it couldn't be resolved due to type-dependence.
1934  llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
1935
1936  /// \brief The starting source location of the pseudo-destructor type.
1937  SourceLocation Location;
1938
1939public:
1940  PseudoDestructorTypeStorage() { }
1941
1942  PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
1943    : Type(II), Location(Loc) { }
1944
1945  PseudoDestructorTypeStorage(TypeSourceInfo *Info);
1946
1947  TypeSourceInfo *getTypeSourceInfo() const {
1948    return Type.dyn_cast<TypeSourceInfo *>();
1949  }
1950
1951  IdentifierInfo *getIdentifier() const {
1952    return Type.dyn_cast<IdentifierInfo *>();
1953  }
1954
1955  SourceLocation getLocation() const { return Location; }
1956};
1957
1958/// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
1959///
1960/// A pseudo-destructor is an expression that looks like a member access to a
1961/// destructor of a scalar type, except that scalar types don't have
1962/// destructors. For example:
1963///
1964/// \code
1965/// typedef int T;
1966/// void f(int *p) {
1967///   p->T::~T();
1968/// }
1969/// \endcode
1970///
1971/// Pseudo-destructors typically occur when instantiating templates such as:
1972///
1973/// \code
1974/// template<typename T>
1975/// void destroy(T* ptr) {
1976///   ptr->T::~T();
1977/// }
1978/// \endcode
1979///
1980/// for scalar types. A pseudo-destructor expression has no run-time semantics
1981/// beyond evaluating the base expression.
1982class CXXPseudoDestructorExpr : public Expr {
1983  /// \brief The base expression (that is being destroyed).
1984  Stmt *Base;
1985
1986  /// \brief Whether the operator was an arrow ('->'); otherwise, it was a
1987  /// period ('.').
1988  bool IsArrow : 1;
1989
1990  /// \brief The location of the '.' or '->' operator.
1991  SourceLocation OperatorLoc;
1992
1993  /// \brief The nested-name-specifier that follows the operator, if present.
1994  NestedNameSpecifierLoc QualifierLoc;
1995
1996  /// \brief The type that precedes the '::' in a qualified pseudo-destructor
1997  /// expression.
1998  TypeSourceInfo *ScopeType;
1999
2000  /// \brief The location of the '::' in a qualified pseudo-destructor
2001  /// expression.
2002  SourceLocation ColonColonLoc;
2003
2004  /// \brief The location of the '~'.
2005  SourceLocation TildeLoc;
2006
2007  /// \brief The type being destroyed, or its name if we were unable to
2008  /// resolve the name.
2009  PseudoDestructorTypeStorage DestroyedType;
2010
2011  friend class ASTStmtReader;
2012
2013public:
2014  CXXPseudoDestructorExpr(ASTContext &Context,
2015                          Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2016                          NestedNameSpecifierLoc QualifierLoc,
2017                          TypeSourceInfo *ScopeType,
2018                          SourceLocation ColonColonLoc,
2019                          SourceLocation TildeLoc,
2020                          PseudoDestructorTypeStorage DestroyedType);
2021
2022  explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2023    : Expr(CXXPseudoDestructorExprClass, Shell),
2024      Base(0), IsArrow(false), QualifierLoc(), ScopeType(0) { }
2025
2026  Expr *getBase() const { return cast<Expr>(Base); }
2027
2028  /// \brief Determines whether this member expression actually had
2029  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2030  /// x->Base::foo.
2031  bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2032
2033  /// \brief Retrieves the nested-name-specifier that qualifies the type name,
2034  /// with source-location information.
2035  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2036
2037  /// \brief If the member name was qualified, retrieves the
2038  /// nested-name-specifier that precedes the member name. Otherwise, returns
2039  /// null.
2040  NestedNameSpecifier *getQualifier() const {
2041    return QualifierLoc.getNestedNameSpecifier();
2042  }
2043
2044  /// \brief Determine whether this pseudo-destructor expression was written
2045  /// using an '->' (otherwise, it used a '.').
2046  bool isArrow() const { return IsArrow; }
2047
2048  /// \brief Retrieve the location of the '.' or '->' operator.
2049  SourceLocation getOperatorLoc() const { return OperatorLoc; }
2050
2051  /// \brief Retrieve the scope type in a qualified pseudo-destructor
2052  /// expression.
2053  ///
2054  /// Pseudo-destructor expressions can have extra qualification within them
2055  /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2056  /// Here, if the object type of the expression is (or may be) a scalar type,
2057  /// \p T may also be a scalar type and, therefore, cannot be part of a
2058  /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2059  /// destructor expression.
2060  TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2061
2062  /// \brief Retrieve the location of the '::' in a qualified pseudo-destructor
2063  /// expression.
2064  SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2065
2066  /// \brief Retrieve the location of the '~'.
2067  SourceLocation getTildeLoc() const { return TildeLoc; }
2068
2069  /// \brief Retrieve the source location information for the type
2070  /// being destroyed.
2071  ///
2072  /// This type-source information is available for non-dependent
2073  /// pseudo-destructor expressions and some dependent pseudo-destructor
2074  /// expressions. Returns null if we only have the identifier for a
2075  /// dependent pseudo-destructor expression.
2076  TypeSourceInfo *getDestroyedTypeInfo() const {
2077    return DestroyedType.getTypeSourceInfo();
2078  }
2079
2080  /// \brief In a dependent pseudo-destructor expression for which we do not
2081  /// have full type information on the destroyed type, provides the name
2082  /// of the destroyed type.
2083  IdentifierInfo *getDestroyedTypeIdentifier() const {
2084    return DestroyedType.getIdentifier();
2085  }
2086
2087  /// \brief Retrieve the type being destroyed.
2088  QualType getDestroyedType() const;
2089
2090  /// \brief Retrieve the starting location of the type being destroyed.
2091  SourceLocation getDestroyedTypeLoc() const {
2092    return DestroyedType.getLocation();
2093  }
2094
2095  /// \brief Set the name of destroyed type for a dependent pseudo-destructor
2096  /// expression.
2097  void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2098    DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2099  }
2100
2101  /// \brief Set the destroyed type.
2102  void setDestroyedType(TypeSourceInfo *Info) {
2103    DestroyedType = PseudoDestructorTypeStorage(Info);
2104  }
2105
2106  SourceLocation getLocStart() const LLVM_READONLY {return Base->getLocStart();}
2107  SourceLocation getLocEnd() const LLVM_READONLY;
2108
2109  static bool classof(const Stmt *T) {
2110    return T->getStmtClass() == CXXPseudoDestructorExprClass;
2111  }
2112
2113  // Iterators
2114  child_range children() { return child_range(&Base, &Base + 1); }
2115};
2116
2117/// \brief Represents a GCC or MS unary type trait, as used in the
2118/// implementation of TR1/C++11 type trait templates.
2119///
2120/// Example:
2121/// \code
2122///   __is_pod(int) == true
2123///   __is_enum(std::string) == false
2124/// \endcode
2125class UnaryTypeTraitExpr : public Expr {
2126  /// \brief The trait. A UnaryTypeTrait enum in MSVC compatible unsigned.
2127  unsigned UTT : 31;
2128  /// The value of the type trait. Unspecified if dependent.
2129  bool Value : 1;
2130
2131  /// \brief The location of the type trait keyword.
2132  SourceLocation Loc;
2133
2134  /// \brief The location of the closing paren.
2135  SourceLocation RParen;
2136
2137  /// \brief The type being queried.
2138  TypeSourceInfo *QueriedType;
2139
2140public:
2141  UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt,
2142                     TypeSourceInfo *queried, bool value,
2143                     SourceLocation rparen, QualType ty)
2144    : Expr(UnaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2145           false,  queried->getType()->isDependentType(),
2146           queried->getType()->isInstantiationDependentType(),
2147           queried->getType()->containsUnexpandedParameterPack()),
2148      UTT(utt), Value(value), Loc(loc), RParen(rparen), QueriedType(queried) { }
2149
2150  explicit UnaryTypeTraitExpr(EmptyShell Empty)
2151    : Expr(UnaryTypeTraitExprClass, Empty), UTT(0), Value(false),
2152      QueriedType() { }
2153
2154  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2155  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2156
2157  UnaryTypeTrait getTrait() const { return static_cast<UnaryTypeTrait>(UTT); }
2158
2159  QualType getQueriedType() const { return QueriedType->getType(); }
2160
2161  TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2162
2163  bool getValue() const { return Value; }
2164
2165  static bool classof(const Stmt *T) {
2166    return T->getStmtClass() == UnaryTypeTraitExprClass;
2167  }
2168
2169  // Iterators
2170  child_range children() { return child_range(); }
2171
2172  friend class ASTStmtReader;
2173};
2174
2175/// \brief Represents a GCC or MS binary type trait, as used in the
2176/// implementation of TR1/C++11 type trait templates.
2177///
2178/// Example:
2179/// \code
2180///   __is_base_of(Base, Derived) == true
2181/// \endcode
2182class BinaryTypeTraitExpr : public Expr {
2183  /// \brief The trait. A BinaryTypeTrait enum in MSVC compatible unsigned.
2184  unsigned BTT : 8;
2185
2186  /// The value of the type trait. Unspecified if dependent.
2187  bool Value : 1;
2188
2189  /// \brief The location of the type trait keyword.
2190  SourceLocation Loc;
2191
2192  /// \brief The location of the closing paren.
2193  SourceLocation RParen;
2194
2195  /// \brief The lhs type being queried.
2196  TypeSourceInfo *LhsType;
2197
2198  /// \brief The rhs type being queried.
2199  TypeSourceInfo *RhsType;
2200
2201public:
2202  BinaryTypeTraitExpr(SourceLocation loc, BinaryTypeTrait btt,
2203                     TypeSourceInfo *lhsType, TypeSourceInfo *rhsType,
2204                     bool value, SourceLocation rparen, QualType ty)
2205    : Expr(BinaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary, false,
2206           lhsType->getType()->isDependentType() ||
2207           rhsType->getType()->isDependentType(),
2208           (lhsType->getType()->isInstantiationDependentType() ||
2209            rhsType->getType()->isInstantiationDependentType()),
2210           (lhsType->getType()->containsUnexpandedParameterPack() ||
2211            rhsType->getType()->containsUnexpandedParameterPack())),
2212      BTT(btt), Value(value), Loc(loc), RParen(rparen),
2213      LhsType(lhsType), RhsType(rhsType) { }
2214
2215
2216  explicit BinaryTypeTraitExpr(EmptyShell Empty)
2217    : Expr(BinaryTypeTraitExprClass, Empty), BTT(0), Value(false),
2218      LhsType(), RhsType() { }
2219
2220  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2221  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2222
2223  BinaryTypeTrait getTrait() const {
2224    return static_cast<BinaryTypeTrait>(BTT);
2225  }
2226
2227  QualType getLhsType() const { return LhsType->getType(); }
2228  QualType getRhsType() const { return RhsType->getType(); }
2229
2230  TypeSourceInfo *getLhsTypeSourceInfo() const { return LhsType; }
2231  TypeSourceInfo *getRhsTypeSourceInfo() const { return RhsType; }
2232
2233  bool getValue() const { assert(!isTypeDependent()); return Value; }
2234
2235  static bool classof(const Stmt *T) {
2236    return T->getStmtClass() == BinaryTypeTraitExprClass;
2237  }
2238
2239  // Iterators
2240  child_range children() { return child_range(); }
2241
2242  friend class ASTStmtReader;
2243};
2244
2245/// \brief A type trait used in the implementation of various C++11 and
2246/// Library TR1 trait templates.
2247///
2248/// \code
2249///   __is_trivially_constructible(vector<int>, int*, int*)
2250/// \endcode
2251class TypeTraitExpr : public Expr {
2252  /// \brief The location of the type trait keyword.
2253  SourceLocation Loc;
2254
2255  /// \brief  The location of the closing parenthesis.
2256  SourceLocation RParenLoc;
2257
2258  // Note: The TypeSourceInfos for the arguments are allocated after the
2259  // TypeTraitExpr.
2260
2261  TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2262                ArrayRef<TypeSourceInfo *> Args,
2263                SourceLocation RParenLoc,
2264                bool Value);
2265
2266  TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) { }
2267
2268  /// \brief Retrieve the argument types.
2269  TypeSourceInfo **getTypeSourceInfos() {
2270    return reinterpret_cast<TypeSourceInfo **>(this+1);
2271  }
2272
2273  /// \brief Retrieve the argument types.
2274  TypeSourceInfo * const *getTypeSourceInfos() const {
2275    return reinterpret_cast<TypeSourceInfo * const*>(this+1);
2276  }
2277
2278public:
2279  /// \brief Create a new type trait expression.
2280  static TypeTraitExpr *Create(ASTContext &C, QualType T, SourceLocation Loc,
2281                               TypeTrait Kind,
2282                               ArrayRef<TypeSourceInfo *> Args,
2283                               SourceLocation RParenLoc,
2284                               bool Value);
2285
2286  static TypeTraitExpr *CreateDeserialized(ASTContext &C, unsigned NumArgs);
2287
2288  /// \brief Determine which type trait this expression uses.
2289  TypeTrait getTrait() const {
2290    return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2291  }
2292
2293  bool getValue() const {
2294    assert(!isValueDependent());
2295    return TypeTraitExprBits.Value;
2296  }
2297
2298  /// \brief Determine the number of arguments to this type trait.
2299  unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2300
2301  /// \brief Retrieve the Ith argument.
2302  TypeSourceInfo *getArg(unsigned I) const {
2303    assert(I < getNumArgs() && "Argument out-of-range");
2304    return getArgs()[I];
2305  }
2306
2307  /// \brief Retrieve the argument types.
2308  ArrayRef<TypeSourceInfo *> getArgs() const {
2309    return ArrayRef<TypeSourceInfo *>(getTypeSourceInfos(), getNumArgs());
2310  }
2311
2312  typedef TypeSourceInfo **arg_iterator;
2313  arg_iterator arg_begin() {
2314    return getTypeSourceInfos();
2315  }
2316  arg_iterator arg_end() {
2317    return getTypeSourceInfos() + getNumArgs();
2318  }
2319
2320  typedef TypeSourceInfo const * const *arg_const_iterator;
2321  arg_const_iterator arg_begin() const { return getTypeSourceInfos(); }
2322  arg_const_iterator arg_end() const {
2323    return getTypeSourceInfos() + getNumArgs();
2324  }
2325
2326  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2327  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2328
2329  static bool classof(const Stmt *T) {
2330    return T->getStmtClass() == TypeTraitExprClass;
2331  }
2332
2333  // Iterators
2334  child_range children() { return child_range(); }
2335
2336  friend class ASTStmtReader;
2337  friend class ASTStmtWriter;
2338
2339};
2340
2341/// \brief An Embarcadero array type trait, as used in the implementation of
2342/// __array_rank and __array_extent.
2343///
2344/// Example:
2345/// \code
2346///   __array_rank(int[10][20]) == 2
2347///   __array_extent(int, 1)    == 20
2348/// \endcode
2349class ArrayTypeTraitExpr : public Expr {
2350  virtual void anchor();
2351
2352  /// \brief The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2353  unsigned ATT : 2;
2354
2355  /// \brief The value of the type trait. Unspecified if dependent.
2356  uint64_t Value;
2357
2358  /// \brief The array dimension being queried, or -1 if not used.
2359  Expr *Dimension;
2360
2361  /// \brief The location of the type trait keyword.
2362  SourceLocation Loc;
2363
2364  /// \brief The location of the closing paren.
2365  SourceLocation RParen;
2366
2367  /// \brief The type being queried.
2368  TypeSourceInfo *QueriedType;
2369
2370public:
2371  ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2372                     TypeSourceInfo *queried, uint64_t value,
2373                     Expr *dimension, SourceLocation rparen, QualType ty)
2374    : Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2375           false, queried->getType()->isDependentType(),
2376           (queried->getType()->isInstantiationDependentType() ||
2377            (dimension && dimension->isInstantiationDependent())),
2378           queried->getType()->containsUnexpandedParameterPack()),
2379      ATT(att), Value(value), Dimension(dimension),
2380      Loc(loc), RParen(rparen), QueriedType(queried) { }
2381
2382
2383  explicit ArrayTypeTraitExpr(EmptyShell Empty)
2384    : Expr(ArrayTypeTraitExprClass, Empty), ATT(0), Value(false),
2385      QueriedType() { }
2386
2387  virtual ~ArrayTypeTraitExpr() { }
2388
2389  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2390  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2391
2392  ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2393
2394  QualType getQueriedType() const { return QueriedType->getType(); }
2395
2396  TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2397
2398  uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
2399
2400  Expr *getDimensionExpression() const { return Dimension; }
2401
2402  static bool classof(const Stmt *T) {
2403    return T->getStmtClass() == ArrayTypeTraitExprClass;
2404  }
2405
2406  // Iterators
2407  child_range children() { return child_range(); }
2408
2409  friend class ASTStmtReader;
2410};
2411
2412/// \brief An expression trait intrinsic.
2413///
2414/// Example:
2415/// \code
2416///   __is_lvalue_expr(std::cout) == true
2417///   __is_lvalue_expr(1) == false
2418/// \endcode
2419class ExpressionTraitExpr : public Expr {
2420  /// \brief The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2421  unsigned ET : 31;
2422  /// \brief The value of the type trait. Unspecified if dependent.
2423  bool Value : 1;
2424
2425  /// \brief The location of the type trait keyword.
2426  SourceLocation Loc;
2427
2428  /// \brief The location of the closing paren.
2429  SourceLocation RParen;
2430
2431  /// \brief The expression being queried.
2432  Expr* QueriedExpression;
2433public:
2434  ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
2435                     Expr *queried, bool value,
2436                     SourceLocation rparen, QualType resultType)
2437    : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2438           false, // Not type-dependent
2439           // Value-dependent if the argument is type-dependent.
2440           queried->isTypeDependent(),
2441           queried->isInstantiationDependent(),
2442           queried->containsUnexpandedParameterPack()),
2443      ET(et), Value(value), Loc(loc), RParen(rparen),
2444      QueriedExpression(queried) { }
2445
2446  explicit ExpressionTraitExpr(EmptyShell Empty)
2447    : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false),
2448      QueriedExpression() { }
2449
2450  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
2451  SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
2452
2453  ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2454
2455  Expr *getQueriedExpression() const { return QueriedExpression; }
2456
2457  bool getValue() const { return Value; }
2458
2459  static bool classof(const Stmt *T) {
2460    return T->getStmtClass() == ExpressionTraitExprClass;
2461  }
2462
2463  // Iterators
2464  child_range children() { return child_range(); }
2465
2466  friend class ASTStmtReader;
2467};
2468
2469
2470/// \brief A reference to an overloaded function set, either an
2471/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2472class OverloadExpr : public Expr {
2473  /// \brief The common name of these declarations.
2474  DeclarationNameInfo NameInfo;
2475
2476  /// \brief The nested-name-specifier that qualifies the name, if any.
2477  NestedNameSpecifierLoc QualifierLoc;
2478
2479  /// The results.  These are undesugared, which is to say, they may
2480  /// include UsingShadowDecls.  Access is relative to the naming
2481  /// class.
2482  // FIXME: Allocate this data after the OverloadExpr subclass.
2483  DeclAccessPair *Results;
2484  unsigned NumResults;
2485
2486protected:
2487  /// \brief Whether the name includes info for explicit template
2488  /// keyword and arguments.
2489  bool HasTemplateKWAndArgsInfo;
2490
2491  /// \brief Return the optional template keyword and arguments info.
2492  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo(); // defined far below.
2493
2494  /// \brief Return the optional template keyword and arguments info.
2495  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2496    return const_cast<OverloadExpr*>(this)->getTemplateKWAndArgsInfo();
2497  }
2498
2499  OverloadExpr(StmtClass K, ASTContext &C,
2500               NestedNameSpecifierLoc QualifierLoc,
2501               SourceLocation TemplateKWLoc,
2502               const DeclarationNameInfo &NameInfo,
2503               const TemplateArgumentListInfo *TemplateArgs,
2504               UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2505               bool KnownDependent,
2506               bool KnownInstantiationDependent,
2507               bool KnownContainsUnexpandedParameterPack);
2508
2509  OverloadExpr(StmtClass K, EmptyShell Empty)
2510    : Expr(K, Empty), QualifierLoc(), Results(0), NumResults(0),
2511      HasTemplateKWAndArgsInfo(false) { }
2512
2513  void initializeResults(ASTContext &C,
2514                         UnresolvedSetIterator Begin,
2515                         UnresolvedSetIterator End);
2516
2517public:
2518  struct FindResult {
2519    OverloadExpr *Expression;
2520    bool IsAddressOfOperand;
2521    bool HasFormOfMemberPointer;
2522  };
2523
2524  /// \brief Finds the overloaded expression in the given expression \p E of
2525  /// OverloadTy.
2526  ///
2527  /// \return the expression (which must be there) and true if it has
2528  /// the particular form of a member pointer expression
2529  static FindResult find(Expr *E) {
2530    assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
2531
2532    FindResult Result;
2533
2534    E = E->IgnoreParens();
2535    if (isa<UnaryOperator>(E)) {
2536      assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
2537      E = cast<UnaryOperator>(E)->getSubExpr();
2538      OverloadExpr *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2539
2540      Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2541      Result.IsAddressOfOperand = true;
2542      Result.Expression = Ovl;
2543    } else {
2544      Result.HasFormOfMemberPointer = false;
2545      Result.IsAddressOfOperand = false;
2546      Result.Expression = cast<OverloadExpr>(E);
2547    }
2548
2549    return Result;
2550  }
2551
2552  /// \brief Gets the naming class of this lookup, if any.
2553  CXXRecordDecl *getNamingClass() const;
2554
2555  typedef UnresolvedSetImpl::iterator decls_iterator;
2556  decls_iterator decls_begin() const { return UnresolvedSetIterator(Results); }
2557  decls_iterator decls_end() const {
2558    return UnresolvedSetIterator(Results + NumResults);
2559  }
2560
2561  /// \brief Gets the number of declarations in the unresolved set.
2562  unsigned getNumDecls() const { return NumResults; }
2563
2564  /// \brief Gets the full name info.
2565  const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2566
2567  /// \brief Gets the name looked up.
2568  DeclarationName getName() const { return NameInfo.getName(); }
2569
2570  /// \brief Gets the location of the name.
2571  SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2572
2573  /// \brief Fetches the nested-name qualifier, if one was given.
2574  NestedNameSpecifier *getQualifier() const {
2575    return QualifierLoc.getNestedNameSpecifier();
2576  }
2577
2578  /// \brief Fetches the nested-name qualifier with source-location
2579  /// information, if one was given.
2580  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2581
2582  /// \brief Retrieve the location of the template keyword preceding
2583  /// this name, if any.
2584  SourceLocation getTemplateKeywordLoc() const {
2585    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2586    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2587  }
2588
2589  /// \brief Retrieve the location of the left angle bracket starting the
2590  /// explicit template argument list following the name, if any.
2591  SourceLocation getLAngleLoc() const {
2592    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2593    return getTemplateKWAndArgsInfo()->LAngleLoc;
2594  }
2595
2596  /// \brief Retrieve the location of the right angle bracket ending the
2597  /// explicit template argument list following the name, if any.
2598  SourceLocation getRAngleLoc() const {
2599    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2600    return getTemplateKWAndArgsInfo()->RAngleLoc;
2601  }
2602
2603  /// \brief Determines whether the name was preceded by the template keyword.
2604  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2605
2606  /// \brief Determines whether this expression had explicit template arguments.
2607  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2608
2609  // Note that, inconsistently with the explicit-template-argument AST
2610  // nodes, users are *forbidden* from calling these methods on objects
2611  // without explicit template arguments.
2612
2613  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2614    assert(hasExplicitTemplateArgs());
2615    return *getTemplateKWAndArgsInfo();
2616  }
2617
2618  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2619    return const_cast<OverloadExpr*>(this)->getExplicitTemplateArgs();
2620  }
2621
2622  TemplateArgumentLoc const *getTemplateArgs() const {
2623    return getExplicitTemplateArgs().getTemplateArgs();
2624  }
2625
2626  unsigned getNumTemplateArgs() const {
2627    return getExplicitTemplateArgs().NumTemplateArgs;
2628  }
2629
2630  /// \brief Copies the template arguments into the given structure.
2631  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2632    getExplicitTemplateArgs().copyInto(List);
2633  }
2634
2635  /// \brief Retrieves the optional explicit template arguments.
2636  ///
2637  /// This points to the same data as getExplicitTemplateArgs(), but
2638  /// returns null if there are no explicit template arguments.
2639  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2640    if (!hasExplicitTemplateArgs()) return 0;
2641    return &getExplicitTemplateArgs();
2642  }
2643
2644  static bool classof(const Stmt *T) {
2645    return T->getStmtClass() == UnresolvedLookupExprClass ||
2646           T->getStmtClass() == UnresolvedMemberExprClass;
2647  }
2648
2649  friend class ASTStmtReader;
2650  friend class ASTStmtWriter;
2651};
2652
2653/// \brief A reference to a name which we were able to look up during
2654/// parsing but could not resolve to a specific declaration.
2655///
2656/// This arises in several ways:
2657///   * we might be waiting for argument-dependent lookup;
2658///   * the name might resolve to an overloaded function;
2659/// and eventually:
2660///   * the lookup might have included a function template.
2661///
2662/// These never include UnresolvedUsingValueDecls, which are always class
2663/// members and therefore appear only in UnresolvedMemberLookupExprs.
2664class UnresolvedLookupExpr : public OverloadExpr {
2665  /// True if these lookup results should be extended by
2666  /// argument-dependent lookup if this is the operand of a function
2667  /// call.
2668  bool RequiresADL;
2669
2670  /// True if these lookup results are overloaded.  This is pretty
2671  /// trivially rederivable if we urgently need to kill this field.
2672  bool Overloaded;
2673
2674  /// The naming class (C++ [class.access.base]p5) of the lookup, if
2675  /// any.  This can generally be recalculated from the context chain,
2676  /// but that can be fairly expensive for unqualified lookups.  If we
2677  /// want to improve memory use here, this could go in a union
2678  /// against the qualified-lookup bits.
2679  CXXRecordDecl *NamingClass;
2680
2681  UnresolvedLookupExpr(ASTContext &C,
2682                       CXXRecordDecl *NamingClass,
2683                       NestedNameSpecifierLoc QualifierLoc,
2684                       SourceLocation TemplateKWLoc,
2685                       const DeclarationNameInfo &NameInfo,
2686                       bool RequiresADL, bool Overloaded,
2687                       const TemplateArgumentListInfo *TemplateArgs,
2688                       UnresolvedSetIterator Begin, UnresolvedSetIterator End)
2689    : OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWLoc,
2690                   NameInfo, TemplateArgs, Begin, End, false, false, false),
2691      RequiresADL(RequiresADL),
2692      Overloaded(Overloaded), NamingClass(NamingClass)
2693  {}
2694
2695  UnresolvedLookupExpr(EmptyShell Empty)
2696    : OverloadExpr(UnresolvedLookupExprClass, Empty),
2697      RequiresADL(false), Overloaded(false), NamingClass(0)
2698  {}
2699
2700  friend class ASTStmtReader;
2701
2702public:
2703  static UnresolvedLookupExpr *Create(ASTContext &C,
2704                                      CXXRecordDecl *NamingClass,
2705                                      NestedNameSpecifierLoc QualifierLoc,
2706                                      const DeclarationNameInfo &NameInfo,
2707                                      bool ADL, bool Overloaded,
2708                                      UnresolvedSetIterator Begin,
2709                                      UnresolvedSetIterator End) {
2710    return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
2711                                       SourceLocation(), NameInfo,
2712                                       ADL, Overloaded, 0, Begin, End);
2713  }
2714
2715  static UnresolvedLookupExpr *Create(ASTContext &C,
2716                                      CXXRecordDecl *NamingClass,
2717                                      NestedNameSpecifierLoc QualifierLoc,
2718                                      SourceLocation TemplateKWLoc,
2719                                      const DeclarationNameInfo &NameInfo,
2720                                      bool ADL,
2721                                      const TemplateArgumentListInfo *Args,
2722                                      UnresolvedSetIterator Begin,
2723                                      UnresolvedSetIterator End);
2724
2725  static UnresolvedLookupExpr *CreateEmpty(ASTContext &C,
2726                                           bool HasTemplateKWAndArgsInfo,
2727                                           unsigned NumTemplateArgs);
2728
2729  /// True if this declaration should be extended by
2730  /// argument-dependent lookup.
2731  bool requiresADL() const { return RequiresADL; }
2732
2733  /// True if this lookup is overloaded.
2734  bool isOverloaded() const { return Overloaded; }
2735
2736  /// Gets the 'naming class' (in the sense of C++0x
2737  /// [class.access.base]p5) of the lookup.  This is the scope
2738  /// that was looked in to find these results.
2739  CXXRecordDecl *getNamingClass() const { return NamingClass; }
2740
2741  SourceLocation getLocStart() const LLVM_READONLY {
2742    if (NestedNameSpecifierLoc l = getQualifierLoc())
2743      return l.getBeginLoc();
2744    return getNameInfo().getLocStart();
2745  }
2746  SourceLocation getLocEnd() const LLVM_READONLY {
2747    if (hasExplicitTemplateArgs())
2748      return getRAngleLoc();
2749    return getNameInfo().getLocEnd();
2750  }
2751
2752  child_range children() { return child_range(); }
2753
2754  static bool classof(const Stmt *T) {
2755    return T->getStmtClass() == UnresolvedLookupExprClass;
2756  }
2757};
2758
2759/// \brief A qualified reference to a name whose declaration cannot
2760/// yet be resolved.
2761///
2762/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
2763/// it expresses a reference to a declaration such as
2764/// X<T>::value. The difference, however, is that an
2765/// DependentScopeDeclRefExpr node is used only within C++ templates when
2766/// the qualification (e.g., X<T>::) refers to a dependent type. In
2767/// this case, X<T>::value cannot resolve to a declaration because the
2768/// declaration will differ from on instantiation of X<T> to the
2769/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
2770/// qualifier (X<T>::) and the name of the entity being referenced
2771/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
2772/// declaration can be found.
2773class DependentScopeDeclRefExpr : public Expr {
2774  /// \brief The nested-name-specifier that qualifies this unresolved
2775  /// declaration name.
2776  NestedNameSpecifierLoc QualifierLoc;
2777
2778  /// \brief The name of the entity we will be referencing.
2779  DeclarationNameInfo NameInfo;
2780
2781  /// \brief Whether the name includes info for explicit template
2782  /// keyword and arguments.
2783  bool HasTemplateKWAndArgsInfo;
2784
2785  /// \brief Return the optional template keyword and arguments info.
2786  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2787    if (!HasTemplateKWAndArgsInfo) return 0;
2788    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
2789  }
2790  /// \brief Return the optional template keyword and arguments info.
2791  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2792    return const_cast<DependentScopeDeclRefExpr*>(this)
2793      ->getTemplateKWAndArgsInfo();
2794  }
2795
2796  DependentScopeDeclRefExpr(QualType T,
2797                            NestedNameSpecifierLoc QualifierLoc,
2798                            SourceLocation TemplateKWLoc,
2799                            const DeclarationNameInfo &NameInfo,
2800                            const TemplateArgumentListInfo *Args);
2801
2802public:
2803  static DependentScopeDeclRefExpr *Create(ASTContext &C,
2804                                           NestedNameSpecifierLoc QualifierLoc,
2805                                           SourceLocation TemplateKWLoc,
2806                                           const DeclarationNameInfo &NameInfo,
2807                              const TemplateArgumentListInfo *TemplateArgs);
2808
2809  static DependentScopeDeclRefExpr *CreateEmpty(ASTContext &C,
2810                                                bool HasTemplateKWAndArgsInfo,
2811                                                unsigned NumTemplateArgs);
2812
2813  /// \brief Retrieve the name that this expression refers to.
2814  const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2815
2816  /// \brief Retrieve the name that this expression refers to.
2817  DeclarationName getDeclName() const { return NameInfo.getName(); }
2818
2819  /// \brief Retrieve the location of the name within the expression.
2820  SourceLocation getLocation() const { return NameInfo.getLoc(); }
2821
2822  /// \brief Retrieve the nested-name-specifier that qualifies the
2823  /// name, with source location information.
2824  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2825
2826
2827  /// \brief Retrieve the nested-name-specifier that qualifies this
2828  /// declaration.
2829  NestedNameSpecifier *getQualifier() const {
2830    return QualifierLoc.getNestedNameSpecifier();
2831  }
2832
2833  /// \brief Retrieve the location of the template keyword preceding
2834  /// this name, if any.
2835  SourceLocation getTemplateKeywordLoc() const {
2836    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2837    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2838  }
2839
2840  /// \brief Retrieve the location of the left angle bracket starting the
2841  /// explicit template argument list following the name, if any.
2842  SourceLocation getLAngleLoc() const {
2843    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2844    return getTemplateKWAndArgsInfo()->LAngleLoc;
2845  }
2846
2847  /// \brief Retrieve the location of the right angle bracket ending the
2848  /// explicit template argument list following the name, if any.
2849  SourceLocation getRAngleLoc() const {
2850    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2851    return getTemplateKWAndArgsInfo()->RAngleLoc;
2852  }
2853
2854  /// Determines whether the name was preceded by the template keyword.
2855  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2856
2857  /// Determines whether this lookup had explicit template arguments.
2858  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2859
2860  // Note that, inconsistently with the explicit-template-argument AST
2861  // nodes, users are *forbidden* from calling these methods on objects
2862  // without explicit template arguments.
2863
2864  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2865    assert(hasExplicitTemplateArgs());
2866    return *reinterpret_cast<ASTTemplateArgumentListInfo*>(this + 1);
2867  }
2868
2869  /// Gets a reference to the explicit template argument list.
2870  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2871    assert(hasExplicitTemplateArgs());
2872    return *reinterpret_cast<const ASTTemplateArgumentListInfo*>(this + 1);
2873  }
2874
2875  /// \brief Retrieves the optional explicit template arguments.
2876  ///
2877  /// This points to the same data as getExplicitTemplateArgs(), but
2878  /// returns null if there are no explicit template arguments.
2879  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2880    if (!hasExplicitTemplateArgs()) return 0;
2881    return &getExplicitTemplateArgs();
2882  }
2883
2884  /// \brief Copies the template arguments (if present) into the given
2885  /// structure.
2886  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2887    getExplicitTemplateArgs().copyInto(List);
2888  }
2889
2890  TemplateArgumentLoc const *getTemplateArgs() const {
2891    return getExplicitTemplateArgs().getTemplateArgs();
2892  }
2893
2894  unsigned getNumTemplateArgs() const {
2895    return getExplicitTemplateArgs().NumTemplateArgs;
2896  }
2897
2898  SourceLocation getLocStart() const LLVM_READONLY {
2899    return QualifierLoc.getBeginLoc();
2900  }
2901  SourceLocation getLocEnd() const LLVM_READONLY {
2902    if (hasExplicitTemplateArgs())
2903      return getRAngleLoc();
2904    return getLocation();
2905  }
2906
2907  static bool classof(const Stmt *T) {
2908    return T->getStmtClass() == DependentScopeDeclRefExprClass;
2909  }
2910
2911  child_range children() { return child_range(); }
2912
2913  friend class ASTStmtReader;
2914  friend class ASTStmtWriter;
2915};
2916
2917/// Represents an expression -- generally a full-expression -- that
2918/// introduces cleanups to be run at the end of the sub-expression's
2919/// evaluation.  The most common source of expression-introduced
2920/// cleanups is temporary objects in C++, but several other kinds of
2921/// expressions can create cleanups, including basically every
2922/// call in ARC that returns an Objective-C pointer.
2923///
2924/// This expression also tracks whether the sub-expression contains a
2925/// potentially-evaluated block literal.  The lifetime of a block
2926/// literal is the extent of the enclosing scope.
2927class ExprWithCleanups : public Expr {
2928public:
2929  /// The type of objects that are kept in the cleanup.
2930  /// It's useful to remember the set of blocks;  we could also
2931  /// remember the set of temporaries, but there's currently
2932  /// no need.
2933  typedef BlockDecl *CleanupObject;
2934
2935private:
2936  Stmt *SubExpr;
2937
2938  ExprWithCleanups(EmptyShell, unsigned NumObjects);
2939  ExprWithCleanups(Expr *SubExpr, ArrayRef<CleanupObject> Objects);
2940
2941  CleanupObject *getObjectsBuffer() {
2942    return reinterpret_cast<CleanupObject*>(this + 1);
2943  }
2944  const CleanupObject *getObjectsBuffer() const {
2945    return reinterpret_cast<const CleanupObject*>(this + 1);
2946  }
2947  friend class ASTStmtReader;
2948
2949public:
2950  static ExprWithCleanups *Create(ASTContext &C, EmptyShell empty,
2951                                  unsigned numObjects);
2952
2953  static ExprWithCleanups *Create(ASTContext &C, Expr *subexpr,
2954                                  ArrayRef<CleanupObject> objects);
2955
2956  ArrayRef<CleanupObject> getObjects() const {
2957    return ArrayRef<CleanupObject>(getObjectsBuffer(), getNumObjects());
2958  }
2959
2960  unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
2961
2962  CleanupObject getObject(unsigned i) const {
2963    assert(i < getNumObjects() && "Index out of range");
2964    return getObjects()[i];
2965  }
2966
2967  Expr *getSubExpr() { return cast<Expr>(SubExpr); }
2968  const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
2969
2970  /// As with any mutator of the AST, be very careful
2971  /// when modifying an existing AST to preserve its invariants.
2972  void setSubExpr(Expr *E) { SubExpr = E; }
2973
2974  SourceLocation getLocStart() const LLVM_READONLY {
2975    return SubExpr->getLocStart();
2976  }
2977  SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
2978
2979  // Implement isa/cast/dyncast/etc.
2980  static bool classof(const Stmt *T) {
2981    return T->getStmtClass() == ExprWithCleanupsClass;
2982  }
2983
2984  // Iterators
2985  child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
2986};
2987
2988/// \brief Describes an explicit type conversion that uses functional
2989/// notion but could not be resolved because one or more arguments are
2990/// type-dependent.
2991///
2992/// The explicit type conversions expressed by
2993/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
2994/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
2995/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
2996/// type-dependent. For example, this would occur in a template such
2997/// as:
2998///
2999/// \code
3000///   template<typename T, typename A1>
3001///   inline T make_a(const A1& a1) {
3002///     return T(a1);
3003///   }
3004/// \endcode
3005///
3006/// When the returned expression is instantiated, it may resolve to a
3007/// constructor call, conversion function call, or some kind of type
3008/// conversion.
3009class CXXUnresolvedConstructExpr : public Expr {
3010  /// \brief The type being constructed.
3011  TypeSourceInfo *Type;
3012
3013  /// \brief The location of the left parentheses ('(').
3014  SourceLocation LParenLoc;
3015
3016  /// \brief The location of the right parentheses (')').
3017  SourceLocation RParenLoc;
3018
3019  /// \brief The number of arguments used to construct the type.
3020  unsigned NumArgs;
3021
3022  CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
3023                             SourceLocation LParenLoc,
3024                             ArrayRef<Expr*> Args,
3025                             SourceLocation RParenLoc);
3026
3027  CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3028    : Expr(CXXUnresolvedConstructExprClass, Empty), Type(), NumArgs(NumArgs) { }
3029
3030  friend class ASTStmtReader;
3031
3032public:
3033  static CXXUnresolvedConstructExpr *Create(ASTContext &C,
3034                                            TypeSourceInfo *Type,
3035                                            SourceLocation LParenLoc,
3036                                            ArrayRef<Expr*> Args,
3037                                            SourceLocation RParenLoc);
3038
3039  static CXXUnresolvedConstructExpr *CreateEmpty(ASTContext &C,
3040                                                 unsigned NumArgs);
3041
3042  /// \brief Retrieve the type that is being constructed, as specified
3043  /// in the source code.
3044  QualType getTypeAsWritten() const { return Type->getType(); }
3045
3046  /// \brief Retrieve the type source information for the type being
3047  /// constructed.
3048  TypeSourceInfo *getTypeSourceInfo() const { return Type; }
3049
3050  /// \brief Retrieve the location of the left parentheses ('(') that
3051  /// precedes the argument list.
3052  SourceLocation getLParenLoc() const { return LParenLoc; }
3053  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3054
3055  /// \brief Retrieve the location of the right parentheses (')') that
3056  /// follows the argument list.
3057  SourceLocation getRParenLoc() const { return RParenLoc; }
3058  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3059
3060  /// \brief Retrieve the number of arguments.
3061  unsigned arg_size() const { return NumArgs; }
3062
3063  typedef Expr** arg_iterator;
3064  arg_iterator arg_begin() { return reinterpret_cast<Expr**>(this + 1); }
3065  arg_iterator arg_end() { return arg_begin() + NumArgs; }
3066
3067  typedef const Expr* const * const_arg_iterator;
3068  const_arg_iterator arg_begin() const {
3069    return reinterpret_cast<const Expr* const *>(this + 1);
3070  }
3071  const_arg_iterator arg_end() const {
3072    return arg_begin() + NumArgs;
3073  }
3074
3075  Expr *getArg(unsigned I) {
3076    assert(I < NumArgs && "Argument index out-of-range");
3077    return *(arg_begin() + I);
3078  }
3079
3080  const Expr *getArg(unsigned I) const {
3081    assert(I < NumArgs && "Argument index out-of-range");
3082    return *(arg_begin() + I);
3083  }
3084
3085  void setArg(unsigned I, Expr *E) {
3086    assert(I < NumArgs && "Argument index out-of-range");
3087    *(arg_begin() + I) = E;
3088  }
3089
3090  SourceLocation getLocStart() const LLVM_READONLY;
3091  SourceLocation getLocEnd() const LLVM_READONLY {
3092    assert(RParenLoc.isValid() || NumArgs == 1);
3093    return RParenLoc.isValid() ? RParenLoc : getArg(0)->getLocEnd();
3094  }
3095
3096  static bool classof(const Stmt *T) {
3097    return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3098  }
3099
3100  // Iterators
3101  child_range children() {
3102    Stmt **begin = reinterpret_cast<Stmt**>(this+1);
3103    return child_range(begin, begin + NumArgs);
3104  }
3105};
3106
3107/// \brief Represents a C++ member access expression where the actual
3108/// member referenced could not be resolved because the base
3109/// expression or the member name was dependent.
3110///
3111/// Like UnresolvedMemberExprs, these can be either implicit or
3112/// explicit accesses.  It is only possible to get one of these with
3113/// an implicit access if a qualifier is provided.
3114class CXXDependentScopeMemberExpr : public Expr {
3115  /// \brief The expression for the base pointer or class reference,
3116  /// e.g., the \c x in x.f.  Can be null in implicit accesses.
3117  Stmt *Base;
3118
3119  /// \brief The type of the base expression.  Never null, even for
3120  /// implicit accesses.
3121  QualType BaseType;
3122
3123  /// \brief Whether this member expression used the '->' operator or
3124  /// the '.' operator.
3125  bool IsArrow : 1;
3126
3127  /// \brief Whether this member expression has info for explicit template
3128  /// keyword and arguments.
3129  bool HasTemplateKWAndArgsInfo : 1;
3130
3131  /// \brief The location of the '->' or '.' operator.
3132  SourceLocation OperatorLoc;
3133
3134  /// \brief The nested-name-specifier that precedes the member name, if any.
3135  NestedNameSpecifierLoc QualifierLoc;
3136
3137  /// \brief In a qualified member access expression such as t->Base::f, this
3138  /// member stores the resolves of name lookup in the context of the member
3139  /// access expression, to be used at instantiation time.
3140  ///
3141  /// FIXME: This member, along with the QualifierLoc, could
3142  /// be stuck into a structure that is optionally allocated at the end of
3143  /// the CXXDependentScopeMemberExpr, to save space in the common case.
3144  NamedDecl *FirstQualifierFoundInScope;
3145
3146  /// \brief The member to which this member expression refers, which
3147  /// can be name, overloaded operator, or destructor.
3148  ///
3149  /// FIXME: could also be a template-id
3150  DeclarationNameInfo MemberNameInfo;
3151
3152  /// \brief Return the optional template keyword and arguments info.
3153  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
3154    if (!HasTemplateKWAndArgsInfo) return 0;
3155    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
3156  }
3157  /// \brief Return the optional template keyword and arguments info.
3158  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
3159    return const_cast<CXXDependentScopeMemberExpr*>(this)
3160      ->getTemplateKWAndArgsInfo();
3161  }
3162
3163  CXXDependentScopeMemberExpr(ASTContext &C,
3164                          Expr *Base, QualType BaseType, bool IsArrow,
3165                          SourceLocation OperatorLoc,
3166                          NestedNameSpecifierLoc QualifierLoc,
3167                          SourceLocation TemplateKWLoc,
3168                          NamedDecl *FirstQualifierFoundInScope,
3169                          DeclarationNameInfo MemberNameInfo,
3170                          const TemplateArgumentListInfo *TemplateArgs);
3171
3172public:
3173  CXXDependentScopeMemberExpr(ASTContext &C,
3174                              Expr *Base, QualType BaseType,
3175                              bool IsArrow,
3176                              SourceLocation OperatorLoc,
3177                              NestedNameSpecifierLoc QualifierLoc,
3178                              NamedDecl *FirstQualifierFoundInScope,
3179                              DeclarationNameInfo MemberNameInfo);
3180
3181  static CXXDependentScopeMemberExpr *
3182  Create(ASTContext &C,
3183         Expr *Base, QualType BaseType, bool IsArrow,
3184         SourceLocation OperatorLoc,
3185         NestedNameSpecifierLoc QualifierLoc,
3186         SourceLocation TemplateKWLoc,
3187         NamedDecl *FirstQualifierFoundInScope,
3188         DeclarationNameInfo MemberNameInfo,
3189         const TemplateArgumentListInfo *TemplateArgs);
3190
3191  static CXXDependentScopeMemberExpr *
3192  CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
3193              unsigned NumTemplateArgs);
3194
3195  /// \brief True if this is an implicit access, i.e. one in which the
3196  /// member being accessed was not written in the source.  The source
3197  /// location of the operator is invalid in this case.
3198  bool isImplicitAccess() const;
3199
3200  /// \brief Retrieve the base object of this member expressions,
3201  /// e.g., the \c x in \c x.m.
3202  Expr *getBase() const {
3203    assert(!isImplicitAccess());
3204    return cast<Expr>(Base);
3205  }
3206
3207  QualType getBaseType() const { return BaseType; }
3208
3209  /// \brief Determine whether this member expression used the '->'
3210  /// operator; otherwise, it used the '.' operator.
3211  bool isArrow() const { return IsArrow; }
3212
3213  /// \brief Retrieve the location of the '->' or '.' operator.
3214  SourceLocation getOperatorLoc() const { return OperatorLoc; }
3215
3216  /// \brief Retrieve the nested-name-specifier that qualifies the member
3217  /// name.
3218  NestedNameSpecifier *getQualifier() const {
3219    return QualifierLoc.getNestedNameSpecifier();
3220  }
3221
3222  /// \brief Retrieve the nested-name-specifier that qualifies the member
3223  /// name, with source location information.
3224  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3225
3226
3227  /// \brief Retrieve the first part of the nested-name-specifier that was
3228  /// found in the scope of the member access expression when the member access
3229  /// was initially parsed.
3230  ///
3231  /// This function only returns a useful result when member access expression
3232  /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3233  /// returned by this function describes what was found by unqualified name
3234  /// lookup for the identifier "Base" within the scope of the member access
3235  /// expression itself. At template instantiation time, this information is
3236  /// combined with the results of name lookup into the type of the object
3237  /// expression itself (the class type of x).
3238  NamedDecl *getFirstQualifierFoundInScope() const {
3239    return FirstQualifierFoundInScope;
3240  }
3241
3242  /// \brief Retrieve the name of the member that this expression
3243  /// refers to.
3244  const DeclarationNameInfo &getMemberNameInfo() const {
3245    return MemberNameInfo;
3246  }
3247
3248  /// \brief Retrieve the name of the member that this expression
3249  /// refers to.
3250  DeclarationName getMember() const { return MemberNameInfo.getName(); }
3251
3252  // \brief Retrieve the location of the name of the member that this
3253  // expression refers to.
3254  SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3255
3256  /// \brief Retrieve the location of the template keyword preceding the
3257  /// member name, if any.
3258  SourceLocation getTemplateKeywordLoc() const {
3259    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3260    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
3261  }
3262
3263  /// \brief Retrieve the location of the left angle bracket starting the
3264  /// explicit template argument list following the member name, if any.
3265  SourceLocation getLAngleLoc() const {
3266    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3267    return getTemplateKWAndArgsInfo()->LAngleLoc;
3268  }
3269
3270  /// \brief Retrieve the location of the right angle bracket ending the
3271  /// explicit template argument list following the member name, if any.
3272  SourceLocation getRAngleLoc() const {
3273    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
3274    return getTemplateKWAndArgsInfo()->RAngleLoc;
3275  }
3276
3277  /// Determines whether the member name was preceded by the template keyword.
3278  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3279
3280  /// \brief Determines whether this member expression actually had a C++
3281  /// template argument list explicitly specified, e.g., x.f<int>.
3282  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3283
3284  /// \brief Retrieve the explicit template argument list that followed the
3285  /// member template name, if any.
3286  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
3287    assert(hasExplicitTemplateArgs());
3288    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
3289  }
3290
3291  /// \brief Retrieve the explicit template argument list that followed the
3292  /// member template name, if any.
3293  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
3294    return const_cast<CXXDependentScopeMemberExpr *>(this)
3295             ->getExplicitTemplateArgs();
3296  }
3297
3298  /// \brief Retrieves the optional explicit template arguments.
3299  ///
3300  /// This points to the same data as getExplicitTemplateArgs(), but
3301  /// returns null if there are no explicit template arguments.
3302  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
3303    if (!hasExplicitTemplateArgs()) return 0;
3304    return &getExplicitTemplateArgs();
3305  }
3306
3307  /// \brief Copies the template arguments (if present) into the given
3308  /// structure.
3309  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3310    getExplicitTemplateArgs().copyInto(List);
3311  }
3312
3313  /// \brief Initializes the template arguments using the given structure.
3314  void initializeTemplateArgumentsFrom(const TemplateArgumentListInfo &List) {
3315    getExplicitTemplateArgs().initializeFrom(List);
3316  }
3317
3318  /// \brief Retrieve the template arguments provided as part of this
3319  /// template-id.
3320  const TemplateArgumentLoc *getTemplateArgs() const {
3321    return getExplicitTemplateArgs().getTemplateArgs();
3322  }
3323
3324  /// \brief Retrieve the number of template arguments provided as part of this
3325  /// template-id.
3326  unsigned getNumTemplateArgs() const {
3327    return getExplicitTemplateArgs().NumTemplateArgs;
3328  }
3329
3330  SourceLocation getLocStart() const LLVM_READONLY {
3331    if (!isImplicitAccess())
3332      return Base->getLocStart();
3333    if (getQualifier())
3334      return getQualifierLoc().getBeginLoc();
3335    return MemberNameInfo.getBeginLoc();
3336
3337  }
3338  SourceLocation getLocEnd() const LLVM_READONLY {
3339    if (hasExplicitTemplateArgs())
3340      return getRAngleLoc();
3341    return MemberNameInfo.getEndLoc();
3342  }
3343
3344  static bool classof(const Stmt *T) {
3345    return T->getStmtClass() == CXXDependentScopeMemberExprClass;
3346  }
3347
3348  // Iterators
3349  child_range children() {
3350    if (isImplicitAccess()) return child_range();
3351    return child_range(&Base, &Base + 1);
3352  }
3353
3354  friend class ASTStmtReader;
3355  friend class ASTStmtWriter;
3356};
3357
3358/// \brief Represents a C++ member access expression for which lookup
3359/// produced a set of overloaded functions.
3360///
3361/// The member access may be explicit or implicit:
3362/// \code
3363///    struct A {
3364///      int a, b;
3365///      int explicitAccess() { return this->a + this->A::b; }
3366///      int implicitAccess() { return a + A::b; }
3367///    };
3368/// \endcode
3369///
3370/// In the final AST, an explicit access always becomes a MemberExpr.
3371/// An implicit access may become either a MemberExpr or a
3372/// DeclRefExpr, depending on whether the member is static.
3373class UnresolvedMemberExpr : public OverloadExpr {
3374  /// \brief Whether this member expression used the '->' operator or
3375  /// the '.' operator.
3376  bool IsArrow : 1;
3377
3378  /// \brief Whether the lookup results contain an unresolved using
3379  /// declaration.
3380  bool HasUnresolvedUsing : 1;
3381
3382  /// \brief The expression for the base pointer or class reference,
3383  /// e.g., the \c x in x.f.
3384  ///
3385  /// This can be null if this is an 'unbased' member expression.
3386  Stmt *Base;
3387
3388  /// \brief The type of the base expression; never null.
3389  QualType BaseType;
3390
3391  /// \brief The location of the '->' or '.' operator.
3392  SourceLocation OperatorLoc;
3393
3394  UnresolvedMemberExpr(ASTContext &C, bool HasUnresolvedUsing,
3395                       Expr *Base, QualType BaseType, bool IsArrow,
3396                       SourceLocation OperatorLoc,
3397                       NestedNameSpecifierLoc QualifierLoc,
3398                       SourceLocation TemplateKWLoc,
3399                       const DeclarationNameInfo &MemberNameInfo,
3400                       const TemplateArgumentListInfo *TemplateArgs,
3401                       UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3402
3403  UnresolvedMemberExpr(EmptyShell Empty)
3404    : OverloadExpr(UnresolvedMemberExprClass, Empty), IsArrow(false),
3405      HasUnresolvedUsing(false), Base(0) { }
3406
3407  friend class ASTStmtReader;
3408
3409public:
3410  static UnresolvedMemberExpr *
3411  Create(ASTContext &C, bool HasUnresolvedUsing,
3412         Expr *Base, QualType BaseType, bool IsArrow,
3413         SourceLocation OperatorLoc,
3414         NestedNameSpecifierLoc QualifierLoc,
3415         SourceLocation TemplateKWLoc,
3416         const DeclarationNameInfo &MemberNameInfo,
3417         const TemplateArgumentListInfo *TemplateArgs,
3418         UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3419
3420  static UnresolvedMemberExpr *
3421  CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
3422              unsigned NumTemplateArgs);
3423
3424  /// \brief True if this is an implicit access, i.e., one in which the
3425  /// member being accessed was not written in the source.
3426  ///
3427  /// The source location of the operator is invalid in this case.
3428  bool isImplicitAccess() const;
3429
3430  /// \brief Retrieve the base object of this member expressions,
3431  /// e.g., the \c x in \c x.m.
3432  Expr *getBase() {
3433    assert(!isImplicitAccess());
3434    return cast<Expr>(Base);
3435  }
3436  const Expr *getBase() const {
3437    assert(!isImplicitAccess());
3438    return cast<Expr>(Base);
3439  }
3440
3441  QualType getBaseType() const { return BaseType; }
3442
3443  /// \brief Determine whether the lookup results contain an unresolved using
3444  /// declaration.
3445  bool hasUnresolvedUsing() const { return HasUnresolvedUsing; }
3446
3447  /// \brief Determine whether this member expression used the '->'
3448  /// operator; otherwise, it used the '.' operator.
3449  bool isArrow() const { return IsArrow; }
3450
3451  /// \brief Retrieve the location of the '->' or '.' operator.
3452  SourceLocation getOperatorLoc() const { return OperatorLoc; }
3453
3454  /// \brief Retrieve the naming class of this lookup.
3455  CXXRecordDecl *getNamingClass() const;
3456
3457  /// \brief Retrieve the full name info for the member that this expression
3458  /// refers to.
3459  const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
3460
3461  /// \brief Retrieve the name of the member that this expression
3462  /// refers to.
3463  DeclarationName getMemberName() const { return getName(); }
3464
3465  // \brief Retrieve the location of the name of the member that this
3466  // expression refers to.
3467  SourceLocation getMemberLoc() const { return getNameLoc(); }
3468
3469  // \brief Return the preferred location (the member name) for the arrow when
3470  // diagnosing a problem with this expression.
3471  SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
3472
3473  SourceLocation getLocStart() const LLVM_READONLY {
3474    if (!isImplicitAccess())
3475      return Base->getLocStart();
3476    if (NestedNameSpecifierLoc l = getQualifierLoc())
3477      return l.getBeginLoc();
3478    return getMemberNameInfo().getLocStart();
3479  }
3480  SourceLocation getLocEnd() const LLVM_READONLY {
3481    if (hasExplicitTemplateArgs())
3482      return getRAngleLoc();
3483    return getMemberNameInfo().getLocEnd();
3484  }
3485
3486  static bool classof(const Stmt *T) {
3487    return T->getStmtClass() == UnresolvedMemberExprClass;
3488  }
3489
3490  // Iterators
3491  child_range children() {
3492    if (isImplicitAccess()) return child_range();
3493    return child_range(&Base, &Base + 1);
3494  }
3495};
3496
3497/// \brief Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
3498///
3499/// The noexcept expression tests whether a given expression might throw. Its
3500/// result is a boolean constant.
3501class CXXNoexceptExpr : public Expr {
3502  bool Value : 1;
3503  Stmt *Operand;
3504  SourceRange Range;
3505
3506  friend class ASTStmtReader;
3507
3508public:
3509  CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
3510                  SourceLocation Keyword, SourceLocation RParen)
3511    : Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
3512           /*TypeDependent*/false,
3513           /*ValueDependent*/Val == CT_Dependent,
3514           Val == CT_Dependent || Operand->isInstantiationDependent(),
3515           Operand->containsUnexpandedParameterPack()),
3516      Value(Val == CT_Cannot), Operand(Operand), Range(Keyword, RParen)
3517  { }
3518
3519  CXXNoexceptExpr(EmptyShell Empty)
3520    : Expr(CXXNoexceptExprClass, Empty)
3521  { }
3522
3523  Expr *getOperand() const { return static_cast<Expr*>(Operand); }
3524
3525  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
3526  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
3527  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
3528
3529  bool getValue() const { return Value; }
3530
3531  static bool classof(const Stmt *T) {
3532    return T->getStmtClass() == CXXNoexceptExprClass;
3533  }
3534
3535  // Iterators
3536  child_range children() { return child_range(&Operand, &Operand + 1); }
3537};
3538
3539/// \brief Represents a C++11 pack expansion that produces a sequence of
3540/// expressions.
3541///
3542/// A pack expansion expression contains a pattern (which itself is an
3543/// expression) followed by an ellipsis. For example:
3544///
3545/// \code
3546/// template<typename F, typename ...Types>
3547/// void forward(F f, Types &&...args) {
3548///   f(static_cast<Types&&>(args)...);
3549/// }
3550/// \endcode
3551///
3552/// Here, the argument to the function object \c f is a pack expansion whose
3553/// pattern is \c static_cast<Types&&>(args). When the \c forward function
3554/// template is instantiated, the pack expansion will instantiate to zero or
3555/// or more function arguments to the function object \c f.
3556class PackExpansionExpr : public Expr {
3557  SourceLocation EllipsisLoc;
3558
3559  /// \brief The number of expansions that will be produced by this pack
3560  /// expansion expression, if known.
3561  ///
3562  /// When zero, the number of expansions is not known. Otherwise, this value
3563  /// is the number of expansions + 1.
3564  unsigned NumExpansions;
3565
3566  Stmt *Pattern;
3567
3568  friend class ASTStmtReader;
3569  friend class ASTStmtWriter;
3570
3571public:
3572  PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
3573                    Optional<unsigned> NumExpansions)
3574    : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
3575           Pattern->getObjectKind(), /*TypeDependent=*/true,
3576           /*ValueDependent=*/true, /*InstantiationDependent=*/true,
3577           /*ContainsUnexpandedParameterPack=*/false),
3578      EllipsisLoc(EllipsisLoc),
3579      NumExpansions(NumExpansions? *NumExpansions + 1 : 0),
3580      Pattern(Pattern) { }
3581
3582  PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) { }
3583
3584  /// \brief Retrieve the pattern of the pack expansion.
3585  Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
3586
3587  /// \brief Retrieve the pattern of the pack expansion.
3588  const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
3589
3590  /// \brief Retrieve the location of the ellipsis that describes this pack
3591  /// expansion.
3592  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
3593
3594  /// \brief Determine the number of expansions that will be produced when
3595  /// this pack expansion is instantiated, if already known.
3596  Optional<unsigned> getNumExpansions() const {
3597    if (NumExpansions)
3598      return NumExpansions - 1;
3599
3600    return None;
3601  }
3602
3603  SourceLocation getLocStart() const LLVM_READONLY {
3604    return Pattern->getLocStart();
3605  }
3606  SourceLocation getLocEnd() const LLVM_READONLY { return EllipsisLoc; }
3607
3608  static bool classof(const Stmt *T) {
3609    return T->getStmtClass() == PackExpansionExprClass;
3610  }
3611
3612  // Iterators
3613  child_range children() {
3614    return child_range(&Pattern, &Pattern + 1);
3615  }
3616};
3617
3618inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
3619  if (!HasTemplateKWAndArgsInfo) return 0;
3620  if (isa<UnresolvedLookupExpr>(this))
3621    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
3622      (cast<UnresolvedLookupExpr>(this) + 1);
3623  else
3624    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
3625      (cast<UnresolvedMemberExpr>(this) + 1);
3626}
3627
3628/// \brief Represents an expression that computes the length of a parameter
3629/// pack.
3630///
3631/// \code
3632/// template<typename ...Types>
3633/// struct count {
3634///   static const unsigned value = sizeof...(Types);
3635/// };
3636/// \endcode
3637class SizeOfPackExpr : public Expr {
3638  /// \brief The location of the \c sizeof keyword.
3639  SourceLocation OperatorLoc;
3640
3641  /// \brief The location of the name of the parameter pack.
3642  SourceLocation PackLoc;
3643
3644  /// \brief The location of the closing parenthesis.
3645  SourceLocation RParenLoc;
3646
3647  /// \brief The length of the parameter pack, if known.
3648  ///
3649  /// When this expression is value-dependent, the length of the parameter pack
3650  /// is unknown. When this expression is not value-dependent, the length is
3651  /// known.
3652  unsigned Length;
3653
3654  /// \brief The parameter pack itself.
3655  NamedDecl *Pack;
3656
3657  friend class ASTStmtReader;
3658  friend class ASTStmtWriter;
3659
3660public:
3661  /// \brief Create a value-dependent expression that computes the length of
3662  /// the given parameter pack.
3663  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
3664                 SourceLocation PackLoc, SourceLocation RParenLoc)
3665    : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
3666           /*TypeDependent=*/false, /*ValueDependent=*/true,
3667           /*InstantiationDependent=*/true,
3668           /*ContainsUnexpandedParameterPack=*/false),
3669      OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
3670      Length(0), Pack(Pack) { }
3671
3672  /// \brief Create an expression that computes the length of
3673  /// the given parameter pack, which is already known.
3674  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
3675                 SourceLocation PackLoc, SourceLocation RParenLoc,
3676                 unsigned Length)
3677  : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
3678         /*TypeDependent=*/false, /*ValueDependent=*/false,
3679         /*InstantiationDependent=*/false,
3680         /*ContainsUnexpandedParameterPack=*/false),
3681    OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
3682    Length(Length), Pack(Pack) { }
3683
3684  /// \brief Create an empty expression.
3685  SizeOfPackExpr(EmptyShell Empty) : Expr(SizeOfPackExprClass, Empty) { }
3686
3687  /// \brief Determine the location of the 'sizeof' keyword.
3688  SourceLocation getOperatorLoc() const { return OperatorLoc; }
3689
3690  /// \brief Determine the location of the parameter pack.
3691  SourceLocation getPackLoc() const { return PackLoc; }
3692
3693  /// \brief Determine the location of the right parenthesis.
3694  SourceLocation getRParenLoc() const { return RParenLoc; }
3695
3696  /// \brief Retrieve the parameter pack.
3697  NamedDecl *getPack() const { return Pack; }
3698
3699  /// \brief Retrieve the length of the parameter pack.
3700  ///
3701  /// This routine may only be invoked when the expression is not
3702  /// value-dependent.
3703  unsigned getPackLength() const {
3704    assert(!isValueDependent() &&
3705           "Cannot get the length of a value-dependent pack size expression");
3706    return Length;
3707  }
3708
3709  SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
3710  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3711
3712  static bool classof(const Stmt *T) {
3713    return T->getStmtClass() == SizeOfPackExprClass;
3714  }
3715
3716  // Iterators
3717  child_range children() { return child_range(); }
3718};
3719
3720/// \brief Represents a reference to a non-type template parameter
3721/// that has been substituted with a template argument.
3722class SubstNonTypeTemplateParmExpr : public Expr {
3723  /// \brief The replaced parameter.
3724  NonTypeTemplateParmDecl *Param;
3725
3726  /// \brief The replacement expression.
3727  Stmt *Replacement;
3728
3729  /// \brief The location of the non-type template parameter reference.
3730  SourceLocation NameLoc;
3731
3732  friend class ASTReader;
3733  friend class ASTStmtReader;
3734  explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
3735    : Expr(SubstNonTypeTemplateParmExprClass, Empty) { }
3736
3737public:
3738  SubstNonTypeTemplateParmExpr(QualType type,
3739                               ExprValueKind valueKind,
3740                               SourceLocation loc,
3741                               NonTypeTemplateParmDecl *param,
3742                               Expr *replacement)
3743    : Expr(SubstNonTypeTemplateParmExprClass, type, valueKind, OK_Ordinary,
3744           replacement->isTypeDependent(), replacement->isValueDependent(),
3745           replacement->isInstantiationDependent(),
3746           replacement->containsUnexpandedParameterPack()),
3747      Param(param), Replacement(replacement), NameLoc(loc) {}
3748
3749  SourceLocation getNameLoc() const { return NameLoc; }
3750  SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3751  SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3752
3753  Expr *getReplacement() const { return cast<Expr>(Replacement); }
3754
3755  NonTypeTemplateParmDecl *getParameter() const { return Param; }
3756
3757  static bool classof(const Stmt *s) {
3758    return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
3759  }
3760
3761  // Iterators
3762  child_range children() { return child_range(&Replacement, &Replacement+1); }
3763};
3764
3765/// \brief Represents a reference to a non-type template parameter pack that
3766/// has been substituted with a non-template argument pack.
3767///
3768/// When a pack expansion in the source code contains multiple parameter packs
3769/// and those parameter packs correspond to different levels of template
3770/// parameter lists, this node is used to represent a non-type template
3771/// parameter pack from an outer level, which has already had its argument pack
3772/// substituted but that still lives within a pack expansion that itself
3773/// could not be instantiated. When actually performing a substitution into
3774/// that pack expansion (e.g., when all template parameters have corresponding
3775/// arguments), this type will be replaced with the appropriate underlying
3776/// expression at the current pack substitution index.
3777class SubstNonTypeTemplateParmPackExpr : public Expr {
3778  /// \brief The non-type template parameter pack itself.
3779  NonTypeTemplateParmDecl *Param;
3780
3781  /// \brief A pointer to the set of template arguments that this
3782  /// parameter pack is instantiated with.
3783  const TemplateArgument *Arguments;
3784
3785  /// \brief The number of template arguments in \c Arguments.
3786  unsigned NumArguments;
3787
3788  /// \brief The location of the non-type template parameter pack reference.
3789  SourceLocation NameLoc;
3790
3791  friend class ASTReader;
3792  friend class ASTStmtReader;
3793  explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
3794    : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) { }
3795
3796public:
3797  SubstNonTypeTemplateParmPackExpr(QualType T,
3798                                   NonTypeTemplateParmDecl *Param,
3799                                   SourceLocation NameLoc,
3800                                   const TemplateArgument &ArgPack);
3801
3802  /// \brief Retrieve the non-type template parameter pack being substituted.
3803  NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
3804
3805  /// \brief Retrieve the location of the parameter pack name.
3806  SourceLocation getParameterPackLocation() const { return NameLoc; }
3807
3808  /// \brief Retrieve the template argument pack containing the substituted
3809  /// template arguments.
3810  TemplateArgument getArgumentPack() const;
3811
3812  SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3813  SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3814
3815  static bool classof(const Stmt *T) {
3816    return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
3817  }
3818
3819  // Iterators
3820  child_range children() { return child_range(); }
3821};
3822
3823/// \brief Represents a reference to a function parameter pack that has been
3824/// substituted but not yet expanded.
3825///
3826/// When a pack expansion contains multiple parameter packs at different levels,
3827/// this node is used to represent a function parameter pack at an outer level
3828/// which we have already substituted to refer to expanded parameters, but where
3829/// the containing pack expansion cannot yet be expanded.
3830///
3831/// \code
3832/// template<typename...Ts> struct S {
3833///   template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
3834/// };
3835/// template struct S<int, int>;
3836/// \endcode
3837class FunctionParmPackExpr : public Expr {
3838  /// \brief The function parameter pack which was referenced.
3839  ParmVarDecl *ParamPack;
3840
3841  /// \brief The location of the function parameter pack reference.
3842  SourceLocation NameLoc;
3843
3844  /// \brief The number of expansions of this pack.
3845  unsigned NumParameters;
3846
3847  FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
3848                       SourceLocation NameLoc, unsigned NumParams,
3849                       Decl * const *Params);
3850
3851  friend class ASTReader;
3852  friend class ASTStmtReader;
3853
3854public:
3855  static FunctionParmPackExpr *Create(ASTContext &Context, QualType T,
3856                                      ParmVarDecl *ParamPack,
3857                                      SourceLocation NameLoc,
3858                                      ArrayRef<Decl *> Params);
3859  static FunctionParmPackExpr *CreateEmpty(ASTContext &Context,
3860                                           unsigned NumParams);
3861
3862  /// \brief Get the parameter pack which this expression refers to.
3863  ParmVarDecl *getParameterPack() const { return ParamPack; }
3864
3865  /// \brief Get the location of the parameter pack.
3866  SourceLocation getParameterPackLocation() const { return NameLoc; }
3867
3868  /// \brief Iterators over the parameters which the parameter pack expanded
3869  /// into.
3870  typedef ParmVarDecl * const *iterator;
3871  iterator begin() const { return reinterpret_cast<iterator>(this+1); }
3872  iterator end() const { return begin() + NumParameters; }
3873
3874  /// \brief Get the number of parameters in this parameter pack.
3875  unsigned getNumExpansions() const { return NumParameters; }
3876
3877  /// \brief Get an expansion of the parameter pack by index.
3878  ParmVarDecl *getExpansion(unsigned I) const { return begin()[I]; }
3879
3880  SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
3881  SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
3882
3883  static bool classof(const Stmt *T) {
3884    return T->getStmtClass() == FunctionParmPackExprClass;
3885  }
3886
3887  child_range children() { return child_range(); }
3888};
3889
3890/// \brief Represents a prvalue temporary that is written into memory so that
3891/// a reference can bind to it.
3892///
3893/// Prvalue expressions are materialized when they need to have an address
3894/// in memory for a reference to bind to. This happens when binding a
3895/// reference to the result of a conversion, e.g.,
3896///
3897/// \code
3898/// const int &r = 1.0;
3899/// \endcode
3900///
3901/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
3902/// then materialized via a \c MaterializeTemporaryExpr, and the reference
3903/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
3904/// (either an lvalue or an xvalue, depending on the kind of reference binding
3905/// to it), maintaining the invariant that references always bind to glvalues.
3906///
3907/// Reference binding and copy-elision can both extend the lifetime of a
3908/// temporary. When either happens, the expression will also track the
3909/// declaration which is responsible for the lifetime extension.
3910class MaterializeTemporaryExpr : public Expr {
3911public:
3912  /// \brief The temporary-generating expression whose value will be
3913  /// materialized.
3914  Stmt *Temporary;
3915
3916  /// \brief The declaration which lifetime-extended this reference, if any.
3917  /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3918  const ValueDecl *ExtendingDecl;
3919
3920  friend class ASTStmtReader;
3921  friend class ASTStmtWriter;
3922
3923public:
3924  MaterializeTemporaryExpr(QualType T, Expr *Temporary,
3925                           bool BoundToLvalueReference,
3926                           const ValueDecl *ExtendedBy)
3927    : Expr(MaterializeTemporaryExprClass, T,
3928           BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
3929           Temporary->isTypeDependent(), Temporary->isValueDependent(),
3930           Temporary->isInstantiationDependent(),
3931           Temporary->containsUnexpandedParameterPack()),
3932      Temporary(Temporary), ExtendingDecl(ExtendedBy) {
3933  }
3934
3935  MaterializeTemporaryExpr(EmptyShell Empty)
3936    : Expr(MaterializeTemporaryExprClass, Empty) { }
3937
3938  /// \brief Retrieve the temporary-generating subexpression whose value will
3939  /// be materialized into a glvalue.
3940  Expr *GetTemporaryExpr() const { return static_cast<Expr *>(Temporary); }
3941
3942  /// \brief Retrieve the storage duration for the materialized temporary.
3943  StorageDuration getStorageDuration() const {
3944    if (!ExtendingDecl)
3945      return SD_FullExpression;
3946    // FIXME: This is not necessarily correct for a temporary materialized
3947    // within a default initializer.
3948    if (isa<FieldDecl>(ExtendingDecl))
3949      return SD_Automatic;
3950    return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
3951  }
3952
3953  /// \brief Get the declaration which triggered the lifetime-extension of this
3954  /// temporary, if any.
3955  const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3956
3957  void setExtendingDecl(const ValueDecl *ExtendedBy) {
3958    ExtendingDecl = ExtendedBy;
3959  }
3960
3961  /// \brief Determine whether this materialized temporary is bound to an
3962  /// lvalue reference; otherwise, it's bound to an rvalue reference.
3963  bool isBoundToLvalueReference() const {
3964    return getValueKind() == VK_LValue;
3965  }
3966
3967  SourceLocation getLocStart() const LLVM_READONLY {
3968    return Temporary->getLocStart();
3969  }
3970  SourceLocation getLocEnd() const LLVM_READONLY {
3971    return Temporary->getLocEnd();
3972  }
3973
3974  static bool classof(const Stmt *T) {
3975    return T->getStmtClass() == MaterializeTemporaryExprClass;
3976  }
3977
3978  // Iterators
3979  child_range children() { return child_range(&Temporary, &Temporary + 1); }
3980};
3981
3982}  // end namespace clang
3983
3984#endif
3985