Expr.h revision 561f81243f665cf2001caadc45df505f826b72d6
1//===--- Expr.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//  This file defines the Expr interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/Stmt.h"
19#include "clang/AST/Type.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/ASTVector.h"
23#include "clang/AST/UsuallyTinyPtrVector.h"
24#include "clang/Basic/TypeTraits.h"
25#include "llvm/ADT/APSInt.h"
26#include "llvm/ADT/APFloat.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include <cctype>
30
31namespace clang {
32  class ASTContext;
33  class APValue;
34  class Decl;
35  class IdentifierInfo;
36  class ParmVarDecl;
37  class NamedDecl;
38  class ValueDecl;
39  class BlockDecl;
40  class CXXBaseSpecifier;
41  class CXXOperatorCallExpr;
42  class CXXMemberCallExpr;
43  class ObjCPropertyRefExpr;
44  class TemplateArgumentLoc;
45  class TemplateArgumentListInfo;
46  class OpaqueValueExpr;
47
48/// \brief A simple array of base specifiers.
49typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
50
51/// Expr - This represents one expression.  Note that Expr's are subclasses of
52/// Stmt.  This allows an expression to be transparently used any place a Stmt
53/// is required.
54///
55class Expr : public Stmt {
56  QualType TR;
57
58protected:
59  Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
60       bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
61    : Stmt(SC)
62  {
63    ExprBits.TypeDependent = TD;
64    ExprBits.ValueDependent = VD;
65    ExprBits.InstantiationDependent = ID;
66    ExprBits.ValueKind = VK;
67    ExprBits.ObjectKind = OK;
68    ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
69    setType(T);
70  }
71
72  /// \brief Construct an empty expression.
73  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
74
75public:
76  QualType getType() const { return TR; }
77  void setType(QualType t) {
78    // In C++, the type of an expression is always adjusted so that it
79    // will not have reference type an expression will never have
80    // reference type (C++ [expr]p6). Use
81    // QualType::getNonReferenceType() to retrieve the non-reference
82    // type. Additionally, inspect Expr::isLvalue to determine whether
83    // an expression that is adjusted in this manner should be
84    // considered an lvalue.
85    assert((t.isNull() || !t->isReferenceType()) &&
86           "Expressions can't have reference type");
87
88    TR = t;
89  }
90
91  /// isValueDependent - Determines whether this expression is
92  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
93  /// array bound of "Chars" in the following example is
94  /// value-dependent.
95  /// @code
96  /// template<int Size, char (&Chars)[Size]> struct meta_string;
97  /// @endcode
98  bool isValueDependent() const { return ExprBits.ValueDependent; }
99
100  /// \brief Set whether this expression is value-dependent or not.
101  void setValueDependent(bool VD) {
102    ExprBits.ValueDependent = VD;
103    if (VD)
104      ExprBits.InstantiationDependent = true;
105  }
106
107  /// isTypeDependent - Determines whether this expression is
108  /// type-dependent (C++ [temp.dep.expr]), which means that its type
109  /// could change from one template instantiation to the next. For
110  /// example, the expressions "x" and "x + y" are type-dependent in
111  /// the following code, but "y" is not type-dependent:
112  /// @code
113  /// template<typename T>
114  /// void add(T x, int y) {
115  ///   x + y;
116  /// }
117  /// @endcode
118  bool isTypeDependent() const { return ExprBits.TypeDependent; }
119
120  /// \brief Set whether this expression is type-dependent or not.
121  void setTypeDependent(bool TD) {
122    ExprBits.TypeDependent = TD;
123    if (TD)
124      ExprBits.InstantiationDependent = true;
125  }
126
127  /// \brief Whether this expression is instantiation-dependent, meaning that
128  /// it depends in some way on a template parameter, even if neither its type
129  /// nor (constant) value can change due to the template instantiation.
130  ///
131  /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
132  /// instantiation-dependent (since it involves a template parameter \c T), but
133  /// is neither type- nor value-dependent, since the type of the inner
134  /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
135  /// \c sizeof is known.
136  ///
137  /// \code
138  /// template<typename T>
139  /// void f(T x, T y) {
140  ///   sizeof(sizeof(T() + T());
141  /// }
142  /// \endcode
143  ///
144  bool isInstantiationDependent() const {
145    return ExprBits.InstantiationDependent;
146  }
147
148  /// \brief Set whether this expression is instantiation-dependent or not.
149  void setInstantiationDependent(bool ID) {
150    ExprBits.InstantiationDependent = ID;
151  }
152
153  /// \brief Whether this expression contains an unexpanded parameter
154  /// pack (for C++0x variadic templates).
155  ///
156  /// Given the following function template:
157  ///
158  /// \code
159  /// template<typename F, typename ...Types>
160  /// void forward(const F &f, Types &&...args) {
161  ///   f(static_cast<Types&&>(args)...);
162  /// }
163  /// \endcode
164  ///
165  /// The expressions \c args and \c static_cast<Types&&>(args) both
166  /// contain parameter packs.
167  bool containsUnexpandedParameterPack() const {
168    return ExprBits.ContainsUnexpandedParameterPack;
169  }
170
171  /// \brief Set the bit that describes whether this expression
172  /// contains an unexpanded parameter pack.
173  void setContainsUnexpandedParameterPack(bool PP = true) {
174    ExprBits.ContainsUnexpandedParameterPack = PP;
175  }
176
177  /// getExprLoc - Return the preferred location for the arrow when diagnosing
178  /// a problem with a generic expression.
179  SourceLocation getExprLoc() const;
180
181  /// isUnusedResultAWarning - Return true if this immediate expression should
182  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
183  /// with location to warn on and the source range[s] to report with the
184  /// warning.
185  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
186                              SourceRange &R2, ASTContext &Ctx) const;
187
188  /// isLValue - True if this expression is an "l-value" according to
189  /// the rules of the current language.  C and C++ give somewhat
190  /// different rules for this concept, but in general, the result of
191  /// an l-value expression identifies a specific object whereas the
192  /// result of an r-value expression is a value detached from any
193  /// specific storage.
194  ///
195  /// C++0x divides the concept of "r-value" into pure r-values
196  /// ("pr-values") and so-called expiring values ("x-values"), which
197  /// identify specific objects that can be safely cannibalized for
198  /// their resources.  This is an unfortunate abuse of terminology on
199  /// the part of the C++ committee.  In Clang, when we say "r-value",
200  /// we generally mean a pr-value.
201  bool isLValue() const { return getValueKind() == VK_LValue; }
202  bool isRValue() const { return getValueKind() == VK_RValue; }
203  bool isXValue() const { return getValueKind() == VK_XValue; }
204  bool isGLValue() const { return getValueKind() != VK_RValue; }
205
206  enum LValueClassification {
207    LV_Valid,
208    LV_NotObjectType,
209    LV_IncompleteVoidType,
210    LV_DuplicateVectorComponents,
211    LV_InvalidExpression,
212    LV_InvalidMessageExpression,
213    LV_MemberFunction,
214    LV_SubObjCPropertySetting,
215    LV_ClassTemporary
216  };
217  /// Reasons why an expression might not be an l-value.
218  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
219
220  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
221  /// does not have an incomplete type, does not have a const-qualified type,
222  /// and if it is a structure or union, does not have any member (including,
223  /// recursively, any member or element of all contained aggregates or unions)
224  /// with a const-qualified type.
225  ///
226  /// \param Loc [in] [out] - A source location which *may* be filled
227  /// in with the location of the expression making this a
228  /// non-modifiable lvalue, if specified.
229  enum isModifiableLvalueResult {
230    MLV_Valid,
231    MLV_NotObjectType,
232    MLV_IncompleteVoidType,
233    MLV_DuplicateVectorComponents,
234    MLV_InvalidExpression,
235    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
236    MLV_IncompleteType,
237    MLV_ConstQualified,
238    MLV_ArrayType,
239    MLV_NotBlockQualified,
240    MLV_ReadonlyProperty,
241    MLV_NoSetterProperty,
242    MLV_MemberFunction,
243    MLV_SubObjCPropertySetting,
244    MLV_InvalidMessageExpression,
245    MLV_ClassTemporary
246  };
247  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
248                                              SourceLocation *Loc = 0) const;
249
250  /// \brief The return type of classify(). Represents the C++0x expression
251  ///        taxonomy.
252  class Classification {
253  public:
254    /// \brief The various classification results. Most of these mean prvalue.
255    enum Kinds {
256      CL_LValue,
257      CL_XValue,
258      CL_Function, // Functions cannot be lvalues in C.
259      CL_Void, // Void cannot be an lvalue in C.
260      CL_AddressableVoid, // Void expression whose address can be taken in C.
261      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
262      CL_MemberFunction, // An expression referring to a member function
263      CL_SubObjCPropertySetting,
264      CL_ClassTemporary, // A prvalue of class type
265      CL_ObjCMessageRValue, // ObjC message is an rvalue
266      CL_PRValue // A prvalue for any other reason, of any other type
267    };
268    /// \brief The results of modification testing.
269    enum ModifiableType {
270      CM_Untested, // testModifiable was false.
271      CM_Modifiable,
272      CM_RValue, // Not modifiable because it's an rvalue
273      CM_Function, // Not modifiable because it's a function; C++ only
274      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
275      CM_NotBlockQualified, // Not captured in the closure
276      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
277      CM_ConstQualified,
278      CM_ArrayType,
279      CM_IncompleteType
280    };
281
282  private:
283    friend class Expr;
284
285    unsigned short Kind;
286    unsigned short Modifiable;
287
288    explicit Classification(Kinds k, ModifiableType m)
289      : Kind(k), Modifiable(m)
290    {}
291
292  public:
293    Classification() {}
294
295    Kinds getKind() const { return static_cast<Kinds>(Kind); }
296    ModifiableType getModifiable() const {
297      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
298      return static_cast<ModifiableType>(Modifiable);
299    }
300    bool isLValue() const { return Kind == CL_LValue; }
301    bool isXValue() const { return Kind == CL_XValue; }
302    bool isGLValue() const { return Kind <= CL_XValue; }
303    bool isPRValue() const { return Kind >= CL_Function; }
304    bool isRValue() const { return Kind >= CL_XValue; }
305    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
306
307    /// \brief Create a simple, modifiably lvalue
308    static Classification makeSimpleLValue() {
309      return Classification(CL_LValue, CM_Modifiable);
310    }
311
312  };
313  /// \brief Classify - Classify this expression according to the C++0x
314  ///        expression taxonomy.
315  ///
316  /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the
317  /// old lvalue vs rvalue. This function determines the type of expression this
318  /// is. There are three expression types:
319  /// - lvalues are classical lvalues as in C++03.
320  /// - prvalues are equivalent to rvalues in C++03.
321  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
322  ///   function returning an rvalue reference.
323  /// lvalues and xvalues are collectively referred to as glvalues, while
324  /// prvalues and xvalues together form rvalues.
325  Classification Classify(ASTContext &Ctx) const {
326    return ClassifyImpl(Ctx, 0);
327  }
328
329  /// \brief ClassifyModifiable - Classify this expression according to the
330  ///        C++0x expression taxonomy, and see if it is valid on the left side
331  ///        of an assignment.
332  ///
333  /// This function extends classify in that it also tests whether the
334  /// expression is modifiable (C99 6.3.2.1p1).
335  /// \param Loc A source location that might be filled with a relevant location
336  ///            if the expression is not modifiable.
337  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
338    return ClassifyImpl(Ctx, &Loc);
339  }
340
341  /// getValueKindForType - Given a formal return or parameter type,
342  /// give its value kind.
343  static ExprValueKind getValueKindForType(QualType T) {
344    if (const ReferenceType *RT = T->getAs<ReferenceType>())
345      return (isa<LValueReferenceType>(RT)
346                ? VK_LValue
347                : (RT->getPointeeType()->isFunctionType()
348                     ? VK_LValue : VK_XValue));
349    return VK_RValue;
350  }
351
352  /// getValueKind - The value kind that this expression produces.
353  ExprValueKind getValueKind() const {
354    return static_cast<ExprValueKind>(ExprBits.ValueKind);
355  }
356
357  /// getObjectKind - The object kind that this expression produces.
358  /// Object kinds are meaningful only for expressions that yield an
359  /// l-value or x-value.
360  ExprObjectKind getObjectKind() const {
361    return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
362  }
363
364  bool isOrdinaryOrBitFieldObject() const {
365    ExprObjectKind OK = getObjectKind();
366    return (OK == OK_Ordinary || OK == OK_BitField);
367  }
368
369  /// setValueKind - Set the value kind produced by this expression.
370  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
371
372  /// setObjectKind - Set the object kind produced by this expression.
373  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
374
375private:
376  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
377
378public:
379
380  /// \brief If this expression refers to a bit-field, retrieve the
381  /// declaration of that bit-field.
382  FieldDecl *getBitField();
383
384  const FieldDecl *getBitField() const {
385    return const_cast<Expr*>(this)->getBitField();
386  }
387
388  /// \brief If this expression is an l-value for an Objective C
389  /// property, find the underlying property reference expression.
390  const ObjCPropertyRefExpr *getObjCProperty() const;
391
392  /// \brief Returns whether this expression refers to a vector element.
393  bool refersToVectorElement() const;
394
395  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
396  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
397  /// but also int expressions which are produced by things like comparisons in
398  /// C.
399  bool isKnownToHaveBooleanValue() const;
400
401  /// isIntegerConstantExpr - Return true if this expression is a valid integer
402  /// constant expression, and, if so, return its value in Result.  If not a
403  /// valid i-c-e, return false and fill in Loc (if specified) with the location
404  /// of the invalid expression.
405  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
406                             SourceLocation *Loc = 0,
407                             bool isEvaluated = true) const;
408  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
409    llvm::APSInt X;
410    return isIntegerConstantExpr(X, Ctx, Loc);
411  }
412  /// isConstantInitializer - Returns true if this expression is a constant
413  /// initializer, which can be emitted at compile-time.
414  bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
415
416  /// EvalResult is a struct with detailed info about an evaluated expression.
417  struct EvalResult {
418    /// Val - This is the value the expression can be folded to.
419    APValue Val;
420
421    /// HasSideEffects - Whether the evaluated expression has side effects.
422    /// For example, (f() && 0) can be folded, but it still has side effects.
423    bool HasSideEffects;
424
425    /// Diag - If the expression is unfoldable, then Diag contains a note
426    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
427    /// position for the error, and DiagExpr is the expression that caused
428    /// the error.
429    /// If the expression is foldable, but not an integer constant expression,
430    /// Diag contains a note diagnostic that describes why it isn't an integer
431    /// constant expression. If the expression *is* an integer constant
432    /// expression, then Diag will be zero.
433    unsigned Diag;
434    const Expr *DiagExpr;
435    SourceLocation DiagLoc;
436
437    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
438
439    // isGlobalLValue - Return true if the evaluated lvalue expression
440    // is global.
441    bool isGlobalLValue() const;
442    // hasSideEffects - Return true if the evaluated expression has
443    // side effects.
444    bool hasSideEffects() const {
445      return HasSideEffects;
446    }
447  };
448
449  /// Evaluate - Return true if this is a constant which we can fold using
450  /// any crazy technique (that has nothing to do with language standards) that
451  /// we want to.  If this function returns true, it returns the folded constant
452  /// in Result.
453  bool Evaluate(EvalResult &Result, const ASTContext &Ctx) const;
454
455  /// EvaluateAsBooleanCondition - Return true if this is a constant
456  /// which we we can fold and convert to a boolean condition using
457  /// any crazy technique that we want to.
458  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
459
460  /// isEvaluatable - Call Evaluate to see if this expression can be constant
461  /// folded, but discard the result.
462  bool isEvaluatable(const ASTContext &Ctx) const;
463
464  /// HasSideEffects - This routine returns true for all those expressions
465  /// which must be evaluated each time and must not be optimized away
466  /// or evaluated at compile time. Example is a function call, volatile
467  /// variable read.
468  bool HasSideEffects(const ASTContext &Ctx) const;
469
470  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
471  /// must be called on an expression that constant folds to an integer.
472  llvm::APSInt EvaluateAsInt(const ASTContext &Ctx) const;
473
474  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
475  /// with link time known address.
476  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
477
478  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
479  bool EvaluateAsAnyLValue(EvalResult &Result, const ASTContext &Ctx) const;
480
481  /// \brief Enumeration used to describe the kind of Null pointer constant
482  /// returned from \c isNullPointerConstant().
483  enum NullPointerConstantKind {
484    /// \brief Expression is not a Null pointer constant.
485    NPCK_NotNull = 0,
486
487    /// \brief Expression is a Null pointer constant built from a zero integer.
488    NPCK_ZeroInteger,
489
490    /// \brief Expression is a C++0X nullptr.
491    NPCK_CXX0X_nullptr,
492
493    /// \brief Expression is a GNU-style __null constant.
494    NPCK_GNUNull
495  };
496
497  /// \brief Enumeration used to describe how \c isNullPointerConstant()
498  /// should cope with value-dependent expressions.
499  enum NullPointerConstantValueDependence {
500    /// \brief Specifies that the expression should never be value-dependent.
501    NPC_NeverValueDependent = 0,
502
503    /// \brief Specifies that a value-dependent expression of integral or
504    /// dependent type should be considered a null pointer constant.
505    NPC_ValueDependentIsNull,
506
507    /// \brief Specifies that a value-dependent expression should be considered
508    /// to never be a null pointer constant.
509    NPC_ValueDependentIsNotNull
510  };
511
512  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
513  /// a Null pointer constant. The return value can further distinguish the
514  /// kind of NULL pointer constant that was detected.
515  NullPointerConstantKind isNullPointerConstant(
516      ASTContext &Ctx,
517      NullPointerConstantValueDependence NPC) const;
518
519  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
520  /// write barrier.
521  bool isOBJCGCCandidate(ASTContext &Ctx) const;
522
523  /// \brief Returns true if this expression is a bound member function.
524  bool isBoundMemberFunction(ASTContext &Ctx) const;
525
526  /// \brief Given an expression of bound-member type, find the type
527  /// of the member.  Returns null if this is an *overloaded* bound
528  /// member expression.
529  static QualType findBoundMemberType(const Expr *expr);
530
531  /// \brief Result type of CanThrow().
532  enum CanThrowResult {
533    CT_Cannot,
534    CT_Dependent,
535    CT_Can
536  };
537  /// \brief Test if this expression, if evaluated, might throw, according to
538  ///        the rules of C++ [expr.unary.noexcept].
539  CanThrowResult CanThrow(ASTContext &C) const;
540
541  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
542  ///  its subexpression.  If that subexpression is also a ParenExpr,
543  ///  then this method recursively returns its subexpression, and so forth.
544  ///  Otherwise, the method returns the current Expr.
545  Expr *IgnoreParens();
546
547  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
548  /// or CastExprs, returning their operand.
549  Expr *IgnoreParenCasts();
550
551  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off any
552  /// ParenExpr or ImplicitCastExprs, returning their operand.
553  Expr *IgnoreParenImpCasts();
554
555  /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
556  /// call to a conversion operator, return the argument.
557  Expr *IgnoreConversionOperator();
558
559  const Expr *IgnoreConversionOperator() const {
560    return const_cast<Expr*>(this)->IgnoreConversionOperator();
561  }
562
563  const Expr *IgnoreParenImpCasts() const {
564    return const_cast<Expr*>(this)->IgnoreParenImpCasts();
565  }
566
567  /// Ignore parentheses and lvalue casts.  Strip off any ParenExpr and
568  /// CastExprs that represent lvalue casts, returning their operand.
569  Expr *IgnoreParenLValueCasts();
570
571  const Expr *IgnoreParenLValueCasts() const {
572    return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
573  }
574
575  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
576  /// value (including ptr->int casts of the same size).  Strip off any
577  /// ParenExpr or CastExprs, returning their operand.
578  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
579
580  /// \brief Determine whether this expression is a default function argument.
581  ///
582  /// Default arguments are implicitly generated in the abstract syntax tree
583  /// by semantic analysis for function calls, object constructions, etc. in
584  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
585  /// this routine also looks through any implicit casts to determine whether
586  /// the expression is a default argument.
587  bool isDefaultArgument() const;
588
589  /// \brief Determine whether the result of this expression is a
590  /// temporary object of the given class type.
591  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
592
593  /// \brief Whether this expression is an implicit reference to 'this' in C++.
594  bool isImplicitCXXThis() const;
595
596  const Expr *IgnoreParens() const {
597    return const_cast<Expr*>(this)->IgnoreParens();
598  }
599  const Expr *IgnoreParenCasts() const {
600    return const_cast<Expr*>(this)->IgnoreParenCasts();
601  }
602  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
603    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
604  }
605
606  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
607  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
608
609  static bool classof(const Stmt *T) {
610    return T->getStmtClass() >= firstExprConstant &&
611           T->getStmtClass() <= lastExprConstant;
612  }
613  static bool classof(const Expr *) { return true; }
614};
615
616
617//===----------------------------------------------------------------------===//
618// Primary Expressions.
619//===----------------------------------------------------------------------===//
620
621/// OpaqueValueExpr - An expression referring to an opaque object of a
622/// fixed type and value class.  These don't correspond to concrete
623/// syntax; instead they're used to express operations (usually copy
624/// operations) on values whose source is generally obvious from
625/// context.
626class OpaqueValueExpr : public Expr {
627  friend class ASTStmtReader;
628  Expr *SourceExpr;
629  SourceLocation Loc;
630
631public:
632  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
633                  ExprObjectKind OK = OK_Ordinary)
634    : Expr(OpaqueValueExprClass, T, VK, OK,
635           T->isDependentType(), T->isDependentType(),
636           T->isInstantiationDependentType(),
637           false),
638      SourceExpr(0), Loc(Loc) {
639  }
640
641  /// Given an expression which invokes a copy constructor --- i.e.  a
642  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
643  /// find the OpaqueValueExpr that's the source of the construction.
644  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
645
646  explicit OpaqueValueExpr(EmptyShell Empty)
647    : Expr(OpaqueValueExprClass, Empty) { }
648
649  /// \brief Retrieve the location of this expression.
650  SourceLocation getLocation() const { return Loc; }
651
652  SourceRange getSourceRange() const {
653    if (SourceExpr) return SourceExpr->getSourceRange();
654    return Loc;
655  }
656  SourceLocation getExprLoc() const {
657    if (SourceExpr) return SourceExpr->getExprLoc();
658    return Loc;
659  }
660
661  child_range children() { return child_range(); }
662
663  /// The source expression of an opaque value expression is the
664  /// expression which originally generated the value.  This is
665  /// provided as a convenience for analyses that don't wish to
666  /// precisely model the execution behavior of the program.
667  ///
668  /// The source expression is typically set when building the
669  /// expression which binds the opaque value expression in the first
670  /// place.
671  Expr *getSourceExpr() const { return SourceExpr; }
672  void setSourceExpr(Expr *e) { SourceExpr = e; }
673
674  static bool classof(const Stmt *T) {
675    return T->getStmtClass() == OpaqueValueExprClass;
676  }
677  static bool classof(const OpaqueValueExpr *) { return true; }
678};
679
680/// \brief Represents an explicit template argument list in C++, e.g.,
681/// the "<int>" in "sort<int>".
682struct ExplicitTemplateArgumentList {
683  /// \brief The source location of the left angle bracket ('<');
684  SourceLocation LAngleLoc;
685
686  /// \brief The source location of the right angle bracket ('>');
687  SourceLocation RAngleLoc;
688
689  /// \brief The number of template arguments in TemplateArgs.
690  /// The actual template arguments (if any) are stored after the
691  /// ExplicitTemplateArgumentList structure.
692  unsigned NumTemplateArgs;
693
694  /// \brief Retrieve the template arguments
695  TemplateArgumentLoc *getTemplateArgs() {
696    return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
697  }
698
699  /// \brief Retrieve the template arguments
700  const TemplateArgumentLoc *getTemplateArgs() const {
701    return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
702  }
703
704  void initializeFrom(const TemplateArgumentListInfo &List);
705  void initializeFrom(const TemplateArgumentListInfo &List,
706                      bool &Dependent, bool &InstantiationDependent,
707                      bool &ContainsUnexpandedParameterPack);
708  void copyInto(TemplateArgumentListInfo &List) const;
709  static std::size_t sizeFor(unsigned NumTemplateArgs);
710  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
711};
712
713/// \brief A reference to a declared variable, function, enum, etc.
714/// [C99 6.5.1p2]
715///
716/// This encodes all the information about how a declaration is referenced
717/// within an expression.
718///
719/// There are several optional constructs attached to DeclRefExprs only when
720/// they apply in order to conserve memory. These are laid out past the end of
721/// the object, and flags in the DeclRefExprBitfield track whether they exist:
722///
723///   DeclRefExprBits.HasQualifier:
724///       Specifies when this declaration reference expression has a C++
725///       nested-name-specifier.
726///   DeclRefExprBits.HasFoundDecl:
727///       Specifies when this declaration reference expression has a record of
728///       a NamedDecl (different from the referenced ValueDecl) which was found
729///       during name lookup and/or overload resolution.
730///   DeclRefExprBits.HasExplicitTemplateArgs:
731///       Specifies when this declaration reference expression has an explicit
732///       C++ template argument list.
733class DeclRefExpr : public Expr {
734  /// \brief The declaration that we are referencing.
735  ValueDecl *D;
736
737  /// \brief The location of the declaration name itself.
738  SourceLocation Loc;
739
740  /// \brief Provides source/type location info for the declaration name
741  /// embedded in D.
742  DeclarationNameLoc DNLoc;
743
744  /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
745  NestedNameSpecifierLoc &getInternalQualifierLoc() {
746    assert(hasQualifier());
747    return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
748  }
749
750  /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
751  const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
752    return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
753  }
754
755  /// \brief Test whether there is a distinct FoundDecl attached to the end of
756  /// this DRE.
757  bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
758
759  /// \brief Helper to retrieve the optional NamedDecl through which this
760  /// reference occured.
761  NamedDecl *&getInternalFoundDecl() {
762    assert(hasFoundDecl());
763    if (hasQualifier())
764      return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
765    return *reinterpret_cast<NamedDecl **>(this + 1);
766  }
767
768  /// \brief Helper to retrieve the optional NamedDecl through which this
769  /// reference occured.
770  NamedDecl *getInternalFoundDecl() const {
771    return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
772  }
773
774  DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
775              ValueDecl *D, const DeclarationNameInfo &NameInfo,
776              NamedDecl *FoundD,
777              const TemplateArgumentListInfo *TemplateArgs,
778              QualType T, ExprValueKind VK);
779
780  /// \brief Construct an empty declaration reference expression.
781  explicit DeclRefExpr(EmptyShell Empty)
782    : Expr(DeclRefExprClass, Empty) { }
783
784  /// \brief Computes the type- and value-dependence flags for this
785  /// declaration reference expression.
786  void computeDependence();
787
788public:
789  DeclRefExpr(ValueDecl *D, QualType T, ExprValueKind VK, SourceLocation L)
790    : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
791      D(D), Loc(L) {
792    DeclRefExprBits.HasQualifier = 0;
793    DeclRefExprBits.HasExplicitTemplateArgs = 0;
794    DeclRefExprBits.HasFoundDecl = 0;
795    computeDependence();
796  }
797
798  static DeclRefExpr *Create(ASTContext &Context,
799                             NestedNameSpecifierLoc QualifierLoc,
800                             ValueDecl *D,
801                             SourceLocation NameLoc,
802                             QualType T, ExprValueKind VK,
803                             NamedDecl *FoundD = 0,
804                             const TemplateArgumentListInfo *TemplateArgs = 0);
805
806  static DeclRefExpr *Create(ASTContext &Context,
807                             NestedNameSpecifierLoc QualifierLoc,
808                             ValueDecl *D,
809                             const DeclarationNameInfo &NameInfo,
810                             QualType T, ExprValueKind VK,
811                             NamedDecl *FoundD = 0,
812                             const TemplateArgumentListInfo *TemplateArgs = 0);
813
814  /// \brief Construct an empty declaration reference expression.
815  static DeclRefExpr *CreateEmpty(ASTContext &Context,
816                                  bool HasQualifier,
817                                  bool HasFoundDecl,
818                                  bool HasExplicitTemplateArgs,
819                                  unsigned NumTemplateArgs);
820
821  ValueDecl *getDecl() { return D; }
822  const ValueDecl *getDecl() const { return D; }
823  void setDecl(ValueDecl *NewD) { D = NewD; }
824
825  DeclarationNameInfo getNameInfo() const {
826    return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
827  }
828
829  SourceLocation getLocation() const { return Loc; }
830  void setLocation(SourceLocation L) { Loc = L; }
831  SourceRange getSourceRange() const;
832
833  /// \brief Determine whether this declaration reference was preceded by a
834  /// C++ nested-name-specifier, e.g., \c N::foo.
835  bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
836
837  /// \brief If the name was qualified, retrieves the nested-name-specifier
838  /// that precedes the name. Otherwise, returns NULL.
839  NestedNameSpecifier *getQualifier() const {
840    if (!hasQualifier())
841      return 0;
842
843    return getInternalQualifierLoc().getNestedNameSpecifier();
844  }
845
846  /// \brief If the name was qualified, retrieves the nested-name-specifier
847  /// that precedes the name, with source-location information.
848  NestedNameSpecifierLoc getQualifierLoc() const {
849    if (!hasQualifier())
850      return NestedNameSpecifierLoc();
851
852    return getInternalQualifierLoc();
853  }
854
855  /// \brief Get the NamedDecl through which this reference occured.
856  ///
857  /// This Decl may be different from the ValueDecl actually referred to in the
858  /// presence of using declarations, etc. It always returns non-NULL, and may
859  /// simple return the ValueDecl when appropriate.
860  NamedDecl *getFoundDecl() {
861    return hasFoundDecl() ? getInternalFoundDecl() : D;
862  }
863
864  /// \brief Get the NamedDecl through which this reference occurred.
865  /// See non-const variant.
866  const NamedDecl *getFoundDecl() const {
867    return hasFoundDecl() ? getInternalFoundDecl() : D;
868  }
869
870  /// \brief Determines whether this declaration reference was followed by an
871  /// explict template argument list.
872  bool hasExplicitTemplateArgs() const {
873    return DeclRefExprBits.HasExplicitTemplateArgs;
874  }
875
876  /// \brief Retrieve the explicit template argument list that followed the
877  /// member template name.
878  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
879    assert(hasExplicitTemplateArgs());
880    if (hasFoundDecl())
881      return *reinterpret_cast<ExplicitTemplateArgumentList *>(
882        &getInternalFoundDecl() + 1);
883
884    if (hasQualifier())
885      return *reinterpret_cast<ExplicitTemplateArgumentList *>(
886        &getInternalQualifierLoc() + 1);
887
888    return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
889  }
890
891  /// \brief Retrieve the explicit template argument list that followed the
892  /// member template name.
893  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
894    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
895  }
896
897  /// \brief Retrieves the optional explicit template arguments.
898  /// This points to the same data as getExplicitTemplateArgs(), but
899  /// returns null if there are no explicit template arguments.
900  const ExplicitTemplateArgumentList *getExplicitTemplateArgsOpt() const {
901    if (!hasExplicitTemplateArgs()) return 0;
902    return &getExplicitTemplateArgs();
903  }
904
905  /// \brief Copies the template arguments (if present) into the given
906  /// structure.
907  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
908    if (hasExplicitTemplateArgs())
909      getExplicitTemplateArgs().copyInto(List);
910  }
911
912  /// \brief Retrieve the location of the left angle bracket following the
913  /// member name ('<'), if any.
914  SourceLocation getLAngleLoc() const {
915    if (!hasExplicitTemplateArgs())
916      return SourceLocation();
917
918    return getExplicitTemplateArgs().LAngleLoc;
919  }
920
921  /// \brief Retrieve the template arguments provided as part of this
922  /// template-id.
923  const TemplateArgumentLoc *getTemplateArgs() const {
924    if (!hasExplicitTemplateArgs())
925      return 0;
926
927    return getExplicitTemplateArgs().getTemplateArgs();
928  }
929
930  /// \brief Retrieve the number of template arguments provided as part of this
931  /// template-id.
932  unsigned getNumTemplateArgs() const {
933    if (!hasExplicitTemplateArgs())
934      return 0;
935
936    return getExplicitTemplateArgs().NumTemplateArgs;
937  }
938
939  /// \brief Retrieve the location of the right angle bracket following the
940  /// template arguments ('>').
941  SourceLocation getRAngleLoc() const {
942    if (!hasExplicitTemplateArgs())
943      return SourceLocation();
944
945    return getExplicitTemplateArgs().RAngleLoc;
946  }
947
948  static bool classof(const Stmt *T) {
949    return T->getStmtClass() == DeclRefExprClass;
950  }
951  static bool classof(const DeclRefExpr *) { return true; }
952
953  // Iterators
954  child_range children() { return child_range(); }
955
956  friend class ASTStmtReader;
957  friend class ASTStmtWriter;
958};
959
960/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
961class PredefinedExpr : public Expr {
962public:
963  enum IdentType {
964    Func,
965    Function,
966    PrettyFunction,
967    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
968    /// 'virtual' keyword is omitted for virtual member functions.
969    PrettyFunctionNoVirtual
970  };
971
972private:
973  SourceLocation Loc;
974  IdentType Type;
975public:
976  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
977    : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
978           type->isDependentType(), type->isDependentType(),
979           type->isInstantiationDependentType(),
980           /*ContainsUnexpandedParameterPack=*/false),
981      Loc(l), Type(IT) {}
982
983  /// \brief Construct an empty predefined expression.
984  explicit PredefinedExpr(EmptyShell Empty)
985    : Expr(PredefinedExprClass, Empty) { }
986
987  IdentType getIdentType() const { return Type; }
988  void setIdentType(IdentType IT) { Type = IT; }
989
990  SourceLocation getLocation() const { return Loc; }
991  void setLocation(SourceLocation L) { Loc = L; }
992
993  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
994
995  SourceRange getSourceRange() const { return SourceRange(Loc); }
996
997  static bool classof(const Stmt *T) {
998    return T->getStmtClass() == PredefinedExprClass;
999  }
1000  static bool classof(const PredefinedExpr *) { return true; }
1001
1002  // Iterators
1003  child_range children() { return child_range(); }
1004};
1005
1006/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1007/// leaking memory.
1008///
1009/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1010/// to represent these numbers.  Unfortunately, when we use a BumpPtrAllocator
1011/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1012/// the APFloat/APInt values will never get freed. APNumericStorage uses
1013/// ASTContext's allocator for memory allocation.
1014class APNumericStorage {
1015  unsigned BitWidth;
1016  union {
1017    uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
1018    uint64_t *pVal;  ///< Used to store the >64 bits integer value.
1019  };
1020
1021  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1022
1023  APNumericStorage(const APNumericStorage&); // do not implement
1024  APNumericStorage& operator=(const APNumericStorage&); // do not implement
1025
1026protected:
1027  APNumericStorage() : BitWidth(0), VAL(0) { }
1028
1029  llvm::APInt getIntValue() const {
1030    unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1031    if (NumWords > 1)
1032      return llvm::APInt(BitWidth, NumWords, pVal);
1033    else
1034      return llvm::APInt(BitWidth, VAL);
1035  }
1036  void setIntValue(ASTContext &C, const llvm::APInt &Val);
1037};
1038
1039class APIntStorage : public APNumericStorage {
1040public:
1041  llvm::APInt getValue() const { return getIntValue(); }
1042  void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); }
1043};
1044
1045class APFloatStorage : public APNumericStorage {
1046public:
1047  llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); }
1048  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1049    setIntValue(C, Val.bitcastToAPInt());
1050  }
1051};
1052
1053class IntegerLiteral : public Expr {
1054  APIntStorage Num;
1055  SourceLocation Loc;
1056
1057  /// \brief Construct an empty integer literal.
1058  explicit IntegerLiteral(EmptyShell Empty)
1059    : Expr(IntegerLiteralClass, Empty) { }
1060
1061public:
1062  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1063  // or UnsignedLongLongTy
1064  IntegerLiteral(ASTContext &C, const llvm::APInt &V,
1065                 QualType type, SourceLocation l)
1066    : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1067           false, false),
1068      Loc(l) {
1069    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
1070    assert(V.getBitWidth() == C.getIntWidth(type) &&
1071           "Integer type is not the correct size for constant.");
1072    setValue(C, V);
1073  }
1074
1075  /// \brief Returns a new integer literal with value 'V' and type 'type'.
1076  /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1077  /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1078  /// \param V - the value that the returned integer literal contains.
1079  static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V,
1080                                QualType type, SourceLocation l);
1081  /// \brief Returns a new empty integer literal.
1082  static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
1083
1084  llvm::APInt getValue() const { return Num.getValue(); }
1085  SourceRange getSourceRange() const { return SourceRange(Loc); }
1086
1087  /// \brief Retrieve the location of the literal.
1088  SourceLocation getLocation() const { return Loc; }
1089
1090  void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); }
1091  void setLocation(SourceLocation Location) { Loc = Location; }
1092
1093  static bool classof(const Stmt *T) {
1094    return T->getStmtClass() == IntegerLiteralClass;
1095  }
1096  static bool classof(const IntegerLiteral *) { return true; }
1097
1098  // Iterators
1099  child_range children() { return child_range(); }
1100};
1101
1102class CharacterLiteral : public Expr {
1103  unsigned Value;
1104  SourceLocation Loc;
1105  bool IsWide;
1106public:
1107  // type should be IntTy
1108  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
1109    : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1110           false, false),
1111      Value(value), Loc(l), IsWide(iswide) {
1112  }
1113
1114  /// \brief Construct an empty character literal.
1115  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1116
1117  SourceLocation getLocation() const { return Loc; }
1118  bool isWide() const { return IsWide; }
1119
1120  SourceRange getSourceRange() const { return SourceRange(Loc); }
1121
1122  unsigned getValue() const { return Value; }
1123
1124  void setLocation(SourceLocation Location) { Loc = Location; }
1125  void setWide(bool W) { IsWide = W; }
1126  void setValue(unsigned Val) { Value = Val; }
1127
1128  static bool classof(const Stmt *T) {
1129    return T->getStmtClass() == CharacterLiteralClass;
1130  }
1131  static bool classof(const CharacterLiteral *) { return true; }
1132
1133  // Iterators
1134  child_range children() { return child_range(); }
1135};
1136
1137class FloatingLiteral : public Expr {
1138  APFloatStorage Num;
1139  bool IsExact : 1;
1140  SourceLocation Loc;
1141
1142  FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
1143                  QualType Type, SourceLocation L)
1144    : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
1145           false, false),
1146      IsExact(isexact), Loc(L) {
1147    setValue(C, V);
1148  }
1149
1150  /// \brief Construct an empty floating-point literal.
1151  explicit FloatingLiteral(EmptyShell Empty)
1152    : Expr(FloatingLiteralClass, Empty), IsExact(false) { }
1153
1154public:
1155  static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
1156                                 bool isexact, QualType Type, SourceLocation L);
1157  static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
1158
1159  llvm::APFloat getValue() const { return Num.getValue(); }
1160  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1161    Num.setValue(C, Val);
1162  }
1163
1164  bool isExact() const { return IsExact; }
1165  void setExact(bool E) { IsExact = E; }
1166
1167  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1168  /// double.  Note that this may cause loss of precision, but is useful for
1169  /// debugging dumps, etc.
1170  double getValueAsApproximateDouble() const;
1171
1172  SourceLocation getLocation() const { return Loc; }
1173  void setLocation(SourceLocation L) { Loc = L; }
1174
1175  SourceRange getSourceRange() const { return SourceRange(Loc); }
1176
1177  static bool classof(const Stmt *T) {
1178    return T->getStmtClass() == FloatingLiteralClass;
1179  }
1180  static bool classof(const FloatingLiteral *) { return true; }
1181
1182  // Iterators
1183  child_range children() { return child_range(); }
1184};
1185
1186/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1187/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1188/// IntegerLiteral classes.  Instances of this class always have a Complex type
1189/// whose element type matches the subexpression.
1190///
1191class ImaginaryLiteral : public Expr {
1192  Stmt *Val;
1193public:
1194  ImaginaryLiteral(Expr *val, QualType Ty)
1195    : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1196           false, false),
1197      Val(val) {}
1198
1199  /// \brief Build an empty imaginary literal.
1200  explicit ImaginaryLiteral(EmptyShell Empty)
1201    : Expr(ImaginaryLiteralClass, Empty) { }
1202
1203  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1204  Expr *getSubExpr() { return cast<Expr>(Val); }
1205  void setSubExpr(Expr *E) { Val = E; }
1206
1207  SourceRange getSourceRange() const { return Val->getSourceRange(); }
1208  static bool classof(const Stmt *T) {
1209    return T->getStmtClass() == ImaginaryLiteralClass;
1210  }
1211  static bool classof(const ImaginaryLiteral *) { return true; }
1212
1213  // Iterators
1214  child_range children() { return child_range(&Val, &Val+1); }
1215};
1216
1217/// StringLiteral - This represents a string literal expression, e.g. "foo"
1218/// or L"bar" (wide strings).  The actual string is returned by getStrData()
1219/// is NOT null-terminated, and the length of the string is determined by
1220/// calling getByteLength().  The C type for a string is always a
1221/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
1222/// not.
1223///
1224/// Note that strings in C can be formed by concatenation of multiple string
1225/// literal pptokens in translation phase #6.  This keeps track of the locations
1226/// of each of these pieces.
1227///
1228/// Strings in C can also be truncated and extended by assigning into arrays,
1229/// e.g. with constructs like:
1230///   char X[2] = "foobar";
1231/// In this case, getByteLength() will return 6, but the string literal will
1232/// have type "char[2]".
1233class StringLiteral : public Expr {
1234  friend class ASTStmtReader;
1235
1236  const char *StrData;
1237  unsigned ByteLength;
1238  bool IsWide;
1239  bool IsPascal;
1240  unsigned NumConcatenated;
1241  SourceLocation TokLocs[1];
1242
1243  StringLiteral(QualType Ty) :
1244    Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1245         false) {}
1246
1247public:
1248  /// This is the "fully general" constructor that allows representation of
1249  /// strings formed from multiple concatenated tokens.
1250  static StringLiteral *Create(ASTContext &C, llvm::StringRef Str, bool Wide,
1251                               bool Pascal, QualType Ty,
1252                               const SourceLocation *Loc, unsigned NumStrs);
1253
1254  /// Simple constructor for string literals made from one token.
1255  static StringLiteral *Create(ASTContext &C, llvm::StringRef Str, bool Wide,
1256                               bool Pascal, QualType Ty, SourceLocation Loc) {
1257    return Create(C, Str, Wide, Pascal, Ty, &Loc, 1);
1258  }
1259
1260  /// \brief Construct an empty string literal.
1261  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1262
1263  llvm::StringRef getString() const {
1264    return llvm::StringRef(StrData, ByteLength);
1265  }
1266
1267  unsigned getByteLength() const { return ByteLength; }
1268
1269  /// \brief Sets the string data to the given string data.
1270  void setString(ASTContext &C, llvm::StringRef Str);
1271
1272  bool isWide() const { return IsWide; }
1273  bool isPascal() const { return IsPascal; }
1274
1275  bool containsNonAsciiOrNull() const {
1276    llvm::StringRef Str = getString();
1277    for (unsigned i = 0, e = Str.size(); i != e; ++i)
1278      if (!isascii(Str[i]) || !Str[i])
1279        return true;
1280    return false;
1281  }
1282  /// getNumConcatenated - Get the number of string literal tokens that were
1283  /// concatenated in translation phase #6 to form this string literal.
1284  unsigned getNumConcatenated() const { return NumConcatenated; }
1285
1286  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1287    assert(TokNum < NumConcatenated && "Invalid tok number");
1288    return TokLocs[TokNum];
1289  }
1290  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1291    assert(TokNum < NumConcatenated && "Invalid tok number");
1292    TokLocs[TokNum] = L;
1293  }
1294
1295  /// getLocationOfByte - Return a source location that points to the specified
1296  /// byte of this string literal.
1297  ///
1298  /// Strings are amazingly complex.  They can be formed from multiple tokens
1299  /// and can have escape sequences in them in addition to the usual trigraph
1300  /// and escaped newline business.  This routine handles this complexity.
1301  ///
1302  SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1303                                   const LangOptions &Features,
1304                                   const TargetInfo &Target) const;
1305
1306  typedef const SourceLocation *tokloc_iterator;
1307  tokloc_iterator tokloc_begin() const { return TokLocs; }
1308  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1309
1310  SourceRange getSourceRange() const {
1311    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1312  }
1313  static bool classof(const Stmt *T) {
1314    return T->getStmtClass() == StringLiteralClass;
1315  }
1316  static bool classof(const StringLiteral *) { return true; }
1317
1318  // Iterators
1319  child_range children() { return child_range(); }
1320};
1321
1322/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1323/// AST node is only formed if full location information is requested.
1324class ParenExpr : public Expr {
1325  SourceLocation L, R;
1326  Stmt *Val;
1327public:
1328  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1329    : Expr(ParenExprClass, val->getType(),
1330           val->getValueKind(), val->getObjectKind(),
1331           val->isTypeDependent(), val->isValueDependent(),
1332           val->isInstantiationDependent(),
1333           val->containsUnexpandedParameterPack()),
1334      L(l), R(r), Val(val) {}
1335
1336  /// \brief Construct an empty parenthesized expression.
1337  explicit ParenExpr(EmptyShell Empty)
1338    : Expr(ParenExprClass, Empty) { }
1339
1340  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1341  Expr *getSubExpr() { return cast<Expr>(Val); }
1342  void setSubExpr(Expr *E) { Val = E; }
1343
1344  SourceRange getSourceRange() const { return SourceRange(L, R); }
1345
1346  /// \brief Get the location of the left parentheses '('.
1347  SourceLocation getLParen() const { return L; }
1348  void setLParen(SourceLocation Loc) { L = Loc; }
1349
1350  /// \brief Get the location of the right parentheses ')'.
1351  SourceLocation getRParen() const { return R; }
1352  void setRParen(SourceLocation Loc) { R = Loc; }
1353
1354  static bool classof(const Stmt *T) {
1355    return T->getStmtClass() == ParenExprClass;
1356  }
1357  static bool classof(const ParenExpr *) { return true; }
1358
1359  // Iterators
1360  child_range children() { return child_range(&Val, &Val+1); }
1361};
1362
1363
1364/// UnaryOperator - This represents the unary-expression's (except sizeof and
1365/// alignof), the postinc/postdec operators from postfix-expression, and various
1366/// extensions.
1367///
1368/// Notes on various nodes:
1369///
1370/// Real/Imag - These return the real/imag part of a complex operand.  If
1371///   applied to a non-complex value, the former returns its operand and the
1372///   later returns zero in the type of the operand.
1373///
1374class UnaryOperator : public Expr {
1375public:
1376  typedef UnaryOperatorKind Opcode;
1377
1378private:
1379  unsigned Opc : 5;
1380  SourceLocation Loc;
1381  Stmt *Val;
1382public:
1383
1384  UnaryOperator(Expr *input, Opcode opc, QualType type,
1385                ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1386    : Expr(UnaryOperatorClass, type, VK, OK,
1387           input->isTypeDependent() || type->isDependentType(),
1388           input->isValueDependent(),
1389           (input->isInstantiationDependent() ||
1390            type->isInstantiationDependentType()),
1391           input->containsUnexpandedParameterPack()),
1392      Opc(opc), Loc(l), Val(input) {}
1393
1394  /// \brief Build an empty unary operator.
1395  explicit UnaryOperator(EmptyShell Empty)
1396    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1397
1398  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1399  void setOpcode(Opcode O) { Opc = O; }
1400
1401  Expr *getSubExpr() const { return cast<Expr>(Val); }
1402  void setSubExpr(Expr *E) { Val = E; }
1403
1404  /// getOperatorLoc - Return the location of the operator.
1405  SourceLocation getOperatorLoc() const { return Loc; }
1406  void setOperatorLoc(SourceLocation L) { Loc = L; }
1407
1408  /// isPostfix - Return true if this is a postfix operation, like x++.
1409  static bool isPostfix(Opcode Op) {
1410    return Op == UO_PostInc || Op == UO_PostDec;
1411  }
1412
1413  /// isPrefix - Return true if this is a prefix operation, like --x.
1414  static bool isPrefix(Opcode Op) {
1415    return Op == UO_PreInc || Op == UO_PreDec;
1416  }
1417
1418  bool isPrefix() const { return isPrefix(getOpcode()); }
1419  bool isPostfix() const { return isPostfix(getOpcode()); }
1420  bool isIncrementOp() const {
1421    return Opc == UO_PreInc || Opc == UO_PostInc;
1422  }
1423  bool isIncrementDecrementOp() const {
1424    return Opc <= UO_PreDec;
1425  }
1426  static bool isArithmeticOp(Opcode Op) {
1427    return Op >= UO_Plus && Op <= UO_LNot;
1428  }
1429  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1430
1431  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1432  /// corresponds to, e.g. "sizeof" or "[pre]++"
1433  static const char *getOpcodeStr(Opcode Op);
1434
1435  /// \brief Retrieve the unary opcode that corresponds to the given
1436  /// overloaded operator.
1437  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1438
1439  /// \brief Retrieve the overloaded operator kind that corresponds to
1440  /// the given unary opcode.
1441  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1442
1443  SourceRange getSourceRange() const {
1444    if (isPostfix())
1445      return SourceRange(Val->getLocStart(), Loc);
1446    else
1447      return SourceRange(Loc, Val->getLocEnd());
1448  }
1449  SourceLocation getExprLoc() const { return Loc; }
1450
1451  static bool classof(const Stmt *T) {
1452    return T->getStmtClass() == UnaryOperatorClass;
1453  }
1454  static bool classof(const UnaryOperator *) { return true; }
1455
1456  // Iterators
1457  child_range children() { return child_range(&Val, &Val+1); }
1458};
1459
1460/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1461/// offsetof(record-type, member-designator). For example, given:
1462/// @code
1463/// struct S {
1464///   float f;
1465///   double d;
1466/// };
1467/// struct T {
1468///   int i;
1469///   struct S s[10];
1470/// };
1471/// @endcode
1472/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1473
1474class OffsetOfExpr : public Expr {
1475public:
1476  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1477  class OffsetOfNode {
1478  public:
1479    /// \brief The kind of offsetof node we have.
1480    enum Kind {
1481      /// \brief An index into an array.
1482      Array = 0x00,
1483      /// \brief A field.
1484      Field = 0x01,
1485      /// \brief A field in a dependent type, known only by its name.
1486      Identifier = 0x02,
1487      /// \brief An implicit indirection through a C++ base class, when the
1488      /// field found is in a base class.
1489      Base = 0x03
1490    };
1491
1492  private:
1493    enum { MaskBits = 2, Mask = 0x03 };
1494
1495    /// \brief The source range that covers this part of the designator.
1496    SourceRange Range;
1497
1498    /// \brief The data describing the designator, which comes in three
1499    /// different forms, depending on the lower two bits.
1500    ///   - An unsigned index into the array of Expr*'s stored after this node
1501    ///     in memory, for [constant-expression] designators.
1502    ///   - A FieldDecl*, for references to a known field.
1503    ///   - An IdentifierInfo*, for references to a field with a given name
1504    ///     when the class type is dependent.
1505    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1506    ///     base class.
1507    uintptr_t Data;
1508
1509  public:
1510    /// \brief Create an offsetof node that refers to an array element.
1511    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1512                 SourceLocation RBracketLoc)
1513      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1514
1515    /// \brief Create an offsetof node that refers to a field.
1516    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1517                 SourceLocation NameLoc)
1518      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1519        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1520
1521    /// \brief Create an offsetof node that refers to an identifier.
1522    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1523                 SourceLocation NameLoc)
1524      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1525        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1526
1527    /// \brief Create an offsetof node that refers into a C++ base class.
1528    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1529      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1530
1531    /// \brief Determine what kind of offsetof node this is.
1532    Kind getKind() const {
1533      return static_cast<Kind>(Data & Mask);
1534    }
1535
1536    /// \brief For an array element node, returns the index into the array
1537    /// of expressions.
1538    unsigned getArrayExprIndex() const {
1539      assert(getKind() == Array);
1540      return Data >> 2;
1541    }
1542
1543    /// \brief For a field offsetof node, returns the field.
1544    FieldDecl *getField() const {
1545      assert(getKind() == Field);
1546      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1547    }
1548
1549    /// \brief For a field or identifier offsetof node, returns the name of
1550    /// the field.
1551    IdentifierInfo *getFieldName() const;
1552
1553    /// \brief For a base class node, returns the base specifier.
1554    CXXBaseSpecifier *getBase() const {
1555      assert(getKind() == Base);
1556      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1557    }
1558
1559    /// \brief Retrieve the source range that covers this offsetof node.
1560    ///
1561    /// For an array element node, the source range contains the locations of
1562    /// the square brackets. For a field or identifier node, the source range
1563    /// contains the location of the period (if there is one) and the
1564    /// identifier.
1565    SourceRange getSourceRange() const { return Range; }
1566  };
1567
1568private:
1569
1570  SourceLocation OperatorLoc, RParenLoc;
1571  // Base type;
1572  TypeSourceInfo *TSInfo;
1573  // Number of sub-components (i.e. instances of OffsetOfNode).
1574  unsigned NumComps;
1575  // Number of sub-expressions (i.e. array subscript expressions).
1576  unsigned NumExprs;
1577
1578  OffsetOfExpr(ASTContext &C, QualType type,
1579               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1580               OffsetOfNode* compsPtr, unsigned numComps,
1581               Expr** exprsPtr, unsigned numExprs,
1582               SourceLocation RParenLoc);
1583
1584  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1585    : Expr(OffsetOfExprClass, EmptyShell()),
1586      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1587
1588public:
1589
1590  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1591                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1592                              OffsetOfNode* compsPtr, unsigned numComps,
1593                              Expr** exprsPtr, unsigned numExprs,
1594                              SourceLocation RParenLoc);
1595
1596  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1597                                   unsigned NumComps, unsigned NumExprs);
1598
1599  /// getOperatorLoc - Return the location of the operator.
1600  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1601  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1602
1603  /// \brief Return the location of the right parentheses.
1604  SourceLocation getRParenLoc() const { return RParenLoc; }
1605  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1606
1607  TypeSourceInfo *getTypeSourceInfo() const {
1608    return TSInfo;
1609  }
1610  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1611    TSInfo = tsi;
1612  }
1613
1614  const OffsetOfNode &getComponent(unsigned Idx) const {
1615    assert(Idx < NumComps && "Subscript out of range");
1616    return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1617  }
1618
1619  void setComponent(unsigned Idx, OffsetOfNode ON) {
1620    assert(Idx < NumComps && "Subscript out of range");
1621    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1622  }
1623
1624  unsigned getNumComponents() const {
1625    return NumComps;
1626  }
1627
1628  Expr* getIndexExpr(unsigned Idx) {
1629    assert(Idx < NumExprs && "Subscript out of range");
1630    return reinterpret_cast<Expr **>(
1631                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1632  }
1633  const Expr *getIndexExpr(unsigned Idx) const {
1634    return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1635  }
1636
1637  void setIndexExpr(unsigned Idx, Expr* E) {
1638    assert(Idx < NumComps && "Subscript out of range");
1639    reinterpret_cast<Expr **>(
1640                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1641  }
1642
1643  unsigned getNumExpressions() const {
1644    return NumExprs;
1645  }
1646
1647  SourceRange getSourceRange() const {
1648    return SourceRange(OperatorLoc, RParenLoc);
1649  }
1650
1651  static bool classof(const Stmt *T) {
1652    return T->getStmtClass() == OffsetOfExprClass;
1653  }
1654
1655  static bool classof(const OffsetOfExpr *) { return true; }
1656
1657  // Iterators
1658  child_range children() {
1659    Stmt **begin =
1660      reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1661                               + NumComps);
1662    return child_range(begin, begin + NumExprs);
1663  }
1664};
1665
1666/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1667/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
1668/// vec_step (OpenCL 1.1 6.11.12).
1669class UnaryExprOrTypeTraitExpr : public Expr {
1670  unsigned Kind : 2;
1671  bool isType : 1;    // true if operand is a type, false if an expression
1672  union {
1673    TypeSourceInfo *Ty;
1674    Stmt *Ex;
1675  } Argument;
1676  SourceLocation OpLoc, RParenLoc;
1677
1678public:
1679  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1680                           QualType resultType, SourceLocation op,
1681                           SourceLocation rp) :
1682      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1683           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1684           // Value-dependent if the argument is type-dependent.
1685           TInfo->getType()->isDependentType(),
1686           TInfo->getType()->isInstantiationDependentType(),
1687           TInfo->getType()->containsUnexpandedParameterPack()),
1688      Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) {
1689    Argument.Ty = TInfo;
1690  }
1691
1692  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1693                           QualType resultType, SourceLocation op,
1694                           SourceLocation rp) :
1695      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1696           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1697           // Value-dependent if the argument is type-dependent.
1698           E->isTypeDependent(),
1699           E->isInstantiationDependent(),
1700           E->containsUnexpandedParameterPack()),
1701      Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) {
1702    Argument.Ex = E;
1703  }
1704
1705  /// \brief Construct an empty sizeof/alignof expression.
1706  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1707    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1708
1709  UnaryExprOrTypeTrait getKind() const {
1710    return static_cast<UnaryExprOrTypeTrait>(Kind);
1711  }
1712  void setKind(UnaryExprOrTypeTrait K) { Kind = K; }
1713
1714  bool isArgumentType() const { return isType; }
1715  QualType getArgumentType() const {
1716    return getArgumentTypeInfo()->getType();
1717  }
1718  TypeSourceInfo *getArgumentTypeInfo() const {
1719    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1720    return Argument.Ty;
1721  }
1722  Expr *getArgumentExpr() {
1723    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1724    return static_cast<Expr*>(Argument.Ex);
1725  }
1726  const Expr *getArgumentExpr() const {
1727    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
1728  }
1729
1730  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1731  void setArgument(TypeSourceInfo *TInfo) {
1732    Argument.Ty = TInfo;
1733    isType = true;
1734  }
1735
1736  /// Gets the argument type, or the type of the argument expression, whichever
1737  /// is appropriate.
1738  QualType getTypeOfArgument() const {
1739    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1740  }
1741
1742  SourceLocation getOperatorLoc() const { return OpLoc; }
1743  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1744
1745  SourceLocation getRParenLoc() const { return RParenLoc; }
1746  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1747
1748  SourceRange getSourceRange() const {
1749    return SourceRange(OpLoc, RParenLoc);
1750  }
1751
1752  static bool classof(const Stmt *T) {
1753    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
1754  }
1755  static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; }
1756
1757  // Iterators
1758  child_range children();
1759};
1760
1761//===----------------------------------------------------------------------===//
1762// Postfix Operators.
1763//===----------------------------------------------------------------------===//
1764
1765/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1766class ArraySubscriptExpr : public Expr {
1767  enum { LHS, RHS, END_EXPR=2 };
1768  Stmt* SubExprs[END_EXPR];
1769  SourceLocation RBracketLoc;
1770public:
1771  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1772                     ExprValueKind VK, ExprObjectKind OK,
1773                     SourceLocation rbracketloc)
1774  : Expr(ArraySubscriptExprClass, t, VK, OK,
1775         lhs->isTypeDependent() || rhs->isTypeDependent(),
1776         lhs->isValueDependent() || rhs->isValueDependent(),
1777         (lhs->isInstantiationDependent() ||
1778          rhs->isInstantiationDependent()),
1779         (lhs->containsUnexpandedParameterPack() ||
1780          rhs->containsUnexpandedParameterPack())),
1781    RBracketLoc(rbracketloc) {
1782    SubExprs[LHS] = lhs;
1783    SubExprs[RHS] = rhs;
1784  }
1785
1786  /// \brief Create an empty array subscript expression.
1787  explicit ArraySubscriptExpr(EmptyShell Shell)
1788    : Expr(ArraySubscriptExprClass, Shell) { }
1789
1790  /// An array access can be written A[4] or 4[A] (both are equivalent).
1791  /// - getBase() and getIdx() always present the normalized view: A[4].
1792  ///    In this case getBase() returns "A" and getIdx() returns "4".
1793  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1794  ///    4[A] getLHS() returns "4".
1795  /// Note: Because vector element access is also written A[4] we must
1796  /// predicate the format conversion in getBase and getIdx only on the
1797  /// the type of the RHS, as it is possible for the LHS to be a vector of
1798  /// integer type
1799  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1800  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1801  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1802
1803  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1804  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1805  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1806
1807  Expr *getBase() {
1808    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1809  }
1810
1811  const Expr *getBase() const {
1812    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1813  }
1814
1815  Expr *getIdx() {
1816    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1817  }
1818
1819  const Expr *getIdx() const {
1820    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1821  }
1822
1823  SourceRange getSourceRange() const {
1824    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1825  }
1826
1827  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1828  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1829
1830  SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1831
1832  static bool classof(const Stmt *T) {
1833    return T->getStmtClass() == ArraySubscriptExprClass;
1834  }
1835  static bool classof(const ArraySubscriptExpr *) { return true; }
1836
1837  // Iterators
1838  child_range children() {
1839    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
1840  }
1841};
1842
1843
1844/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1845/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1846/// while its subclasses may represent alternative syntax that (semantically)
1847/// results in a function call. For example, CXXOperatorCallExpr is
1848/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1849/// "str1 + str2" to resolve to a function call.
1850class CallExpr : public Expr {
1851  enum { FN=0, PREARGS_START=1 };
1852  Stmt **SubExprs;
1853  unsigned NumArgs;
1854  SourceLocation RParenLoc;
1855
1856protected:
1857  // These versions of the constructor are for derived classes.
1858  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
1859           Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
1860           SourceLocation rparenloc);
1861  CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
1862
1863  Stmt *getPreArg(unsigned i) {
1864    assert(i < getNumPreArgs() && "Prearg access out of range!");
1865    return SubExprs[PREARGS_START+i];
1866  }
1867  const Stmt *getPreArg(unsigned i) const {
1868    assert(i < getNumPreArgs() && "Prearg access out of range!");
1869    return SubExprs[PREARGS_START+i];
1870  }
1871  void setPreArg(unsigned i, Stmt *PreArg) {
1872    assert(i < getNumPreArgs() && "Prearg access out of range!");
1873    SubExprs[PREARGS_START+i] = PreArg;
1874  }
1875
1876  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
1877
1878public:
1879  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1880           ExprValueKind VK, SourceLocation rparenloc);
1881
1882  /// \brief Build an empty call expression.
1883  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1884
1885  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1886  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1887  void setCallee(Expr *F) { SubExprs[FN] = F; }
1888
1889  Decl *getCalleeDecl();
1890  const Decl *getCalleeDecl() const {
1891    return const_cast<CallExpr*>(this)->getCalleeDecl();
1892  }
1893
1894  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1895  FunctionDecl *getDirectCallee();
1896  const FunctionDecl *getDirectCallee() const {
1897    return const_cast<CallExpr*>(this)->getDirectCallee();
1898  }
1899
1900  /// getNumArgs - Return the number of actual arguments to this call.
1901  ///
1902  unsigned getNumArgs() const { return NumArgs; }
1903
1904  /// \brief Retrieve the call arguments.
1905  Expr **getArgs() {
1906    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
1907  }
1908
1909  /// getArg - Return the specified argument.
1910  Expr *getArg(unsigned Arg) {
1911    assert(Arg < NumArgs && "Arg access out of range!");
1912    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1913  }
1914  const Expr *getArg(unsigned Arg) const {
1915    assert(Arg < NumArgs && "Arg access out of range!");
1916    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1917  }
1918
1919  /// setArg - Set the specified argument.
1920  void setArg(unsigned Arg, Expr *ArgExpr) {
1921    assert(Arg < NumArgs && "Arg access out of range!");
1922    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
1923  }
1924
1925  /// setNumArgs - This changes the number of arguments present in this call.
1926  /// Any orphaned expressions are deleted by this, and any new operands are set
1927  /// to null.
1928  void setNumArgs(ASTContext& C, unsigned NumArgs);
1929
1930  typedef ExprIterator arg_iterator;
1931  typedef ConstExprIterator const_arg_iterator;
1932
1933  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
1934  arg_iterator arg_end() {
1935    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1936  }
1937  const_arg_iterator arg_begin() const {
1938    return SubExprs+PREARGS_START+getNumPreArgs();
1939  }
1940  const_arg_iterator arg_end() const {
1941    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1942  }
1943
1944  /// getNumCommas - Return the number of commas that must have been present in
1945  /// this function call.
1946  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1947
1948  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1949  /// not, return 0.
1950  unsigned isBuiltinCall(const ASTContext &Context) const;
1951
1952  /// getCallReturnType - Get the return type of the call expr. This is not
1953  /// always the type of the expr itself, if the return type is a reference
1954  /// type.
1955  QualType getCallReturnType() const;
1956
1957  SourceLocation getRParenLoc() const { return RParenLoc; }
1958  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1959
1960  SourceRange getSourceRange() const;
1961
1962  static bool classof(const Stmt *T) {
1963    return T->getStmtClass() >= firstCallExprConstant &&
1964           T->getStmtClass() <= lastCallExprConstant;
1965  }
1966  static bool classof(const CallExpr *) { return true; }
1967
1968  // Iterators
1969  child_range children() {
1970    return child_range(&SubExprs[0],
1971                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
1972  }
1973};
1974
1975/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1976///
1977class MemberExpr : public Expr {
1978  /// Extra data stored in some member expressions.
1979  struct MemberNameQualifier {
1980    /// \brief The nested-name-specifier that qualifies the name, including
1981    /// source-location information.
1982    NestedNameSpecifierLoc QualifierLoc;
1983
1984    /// \brief The DeclAccessPair through which the MemberDecl was found due to
1985    /// name qualifiers.
1986    DeclAccessPair FoundDecl;
1987  };
1988
1989  /// Base - the expression for the base pointer or structure references.  In
1990  /// X.F, this is "X".
1991  Stmt *Base;
1992
1993  /// MemberDecl - This is the decl being referenced by the field/member name.
1994  /// In X.F, this is the decl referenced by F.
1995  ValueDecl *MemberDecl;
1996
1997  /// MemberLoc - This is the location of the member name.
1998  SourceLocation MemberLoc;
1999
2000  /// MemberDNLoc - Provides source/type location info for the
2001  /// declaration name embedded in MemberDecl.
2002  DeclarationNameLoc MemberDNLoc;
2003
2004  /// IsArrow - True if this is "X->F", false if this is "X.F".
2005  bool IsArrow : 1;
2006
2007  /// \brief True if this member expression used a nested-name-specifier to
2008  /// refer to the member, e.g., "x->Base::f", or found its member via a using
2009  /// declaration.  When true, a MemberNameQualifier
2010  /// structure is allocated immediately after the MemberExpr.
2011  bool HasQualifierOrFoundDecl : 1;
2012
2013  /// \brief True if this member expression specified a template argument list
2014  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
2015  /// structure (and its TemplateArguments) are allocated immediately after
2016  /// the MemberExpr or, if the member expression also has a qualifier, after
2017  /// the MemberNameQualifier structure.
2018  bool HasExplicitTemplateArgumentList : 1;
2019
2020  /// \brief Retrieve the qualifier that preceded the member name, if any.
2021  MemberNameQualifier *getMemberQualifier() {
2022    assert(HasQualifierOrFoundDecl);
2023    return reinterpret_cast<MemberNameQualifier *> (this + 1);
2024  }
2025
2026  /// \brief Retrieve the qualifier that preceded the member name, if any.
2027  const MemberNameQualifier *getMemberQualifier() const {
2028    return const_cast<MemberExpr *>(this)->getMemberQualifier();
2029  }
2030
2031public:
2032  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2033             const DeclarationNameInfo &NameInfo, QualType ty,
2034             ExprValueKind VK, ExprObjectKind OK)
2035    : Expr(MemberExprClass, ty, VK, OK,
2036           base->isTypeDependent(),
2037           base->isValueDependent(),
2038           base->isInstantiationDependent(),
2039           base->containsUnexpandedParameterPack()),
2040      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
2041      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
2042      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {
2043    assert(memberdecl->getDeclName() == NameInfo.getName());
2044  }
2045
2046  // NOTE: this constructor should be used only when it is known that
2047  // the member name can not provide additional syntactic info
2048  // (i.e., source locations for C++ operator names or type source info
2049  // for constructors, destructors and conversion oeprators).
2050  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2051             SourceLocation l, QualType ty,
2052             ExprValueKind VK, ExprObjectKind OK)
2053    : Expr(MemberExprClass, ty, VK, OK,
2054           base->isTypeDependent(), base->isValueDependent(),
2055           base->isInstantiationDependent(),
2056           base->containsUnexpandedParameterPack()),
2057      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
2058      IsArrow(isarrow),
2059      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
2060
2061  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
2062                            NestedNameSpecifierLoc QualifierLoc,
2063                            ValueDecl *memberdecl, DeclAccessPair founddecl,
2064                            DeclarationNameInfo MemberNameInfo,
2065                            const TemplateArgumentListInfo *targs,
2066                            QualType ty, ExprValueKind VK, ExprObjectKind OK);
2067
2068  void setBase(Expr *E) { Base = E; }
2069  Expr *getBase() const { return cast<Expr>(Base); }
2070
2071  /// \brief Retrieve the member declaration to which this expression refers.
2072  ///
2073  /// The returned declaration will either be a FieldDecl or (in C++)
2074  /// a CXXMethodDecl.
2075  ValueDecl *getMemberDecl() const { return MemberDecl; }
2076  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2077
2078  /// \brief Retrieves the declaration found by lookup.
2079  DeclAccessPair getFoundDecl() const {
2080    if (!HasQualifierOrFoundDecl)
2081      return DeclAccessPair::make(getMemberDecl(),
2082                                  getMemberDecl()->getAccess());
2083    return getMemberQualifier()->FoundDecl;
2084  }
2085
2086  /// \brief Determines whether this member expression actually had
2087  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2088  /// x->Base::foo.
2089  bool hasQualifier() const { return getQualifier() != 0; }
2090
2091  /// \brief If the member name was qualified, retrieves the
2092  /// nested-name-specifier that precedes the member name. Otherwise, returns
2093  /// NULL.
2094  NestedNameSpecifier *getQualifier() const {
2095    if (!HasQualifierOrFoundDecl)
2096      return 0;
2097
2098    return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2099  }
2100
2101  /// \brief If the member name was qualified, retrieves the
2102  /// nested-name-specifier that precedes the member name, with source-location
2103  /// information.
2104  NestedNameSpecifierLoc getQualifierLoc() const {
2105    if (!hasQualifier())
2106      return NestedNameSpecifierLoc();
2107
2108    return getMemberQualifier()->QualifierLoc;
2109  }
2110
2111  /// \brief Determines whether this member expression actually had a C++
2112  /// template argument list explicitly specified, e.g., x.f<int>.
2113  bool hasExplicitTemplateArgs() const {
2114    return HasExplicitTemplateArgumentList;
2115  }
2116
2117  /// \brief Copies the template arguments (if present) into the given
2118  /// structure.
2119  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2120    if (hasExplicitTemplateArgs())
2121      getExplicitTemplateArgs().copyInto(List);
2122  }
2123
2124  /// \brief Retrieve the explicit template argument list that
2125  /// follow the member template name.  This must only be called on an
2126  /// expression with explicit template arguments.
2127  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
2128    assert(HasExplicitTemplateArgumentList);
2129    if (!HasQualifierOrFoundDecl)
2130      return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
2131
2132    return *reinterpret_cast<ExplicitTemplateArgumentList *>(
2133                                                      getMemberQualifier() + 1);
2134  }
2135
2136  /// \brief Retrieve the explicit template argument list that
2137  /// followed the member template name.  This must only be called on
2138  /// an expression with explicit template arguments.
2139  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
2140    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2141  }
2142
2143  /// \brief Retrieves the optional explicit template arguments.
2144  /// This points to the same data as getExplicitTemplateArgs(), but
2145  /// returns null if there are no explicit template arguments.
2146  const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const {
2147    if (!hasExplicitTemplateArgs()) return 0;
2148    return &getExplicitTemplateArgs();
2149  }
2150
2151  /// \brief Retrieve the location of the left angle bracket following the
2152  /// member name ('<'), if any.
2153  SourceLocation getLAngleLoc() const {
2154    if (!HasExplicitTemplateArgumentList)
2155      return SourceLocation();
2156
2157    return getExplicitTemplateArgs().LAngleLoc;
2158  }
2159
2160  /// \brief Retrieve the template arguments provided as part of this
2161  /// template-id.
2162  const TemplateArgumentLoc *getTemplateArgs() const {
2163    if (!HasExplicitTemplateArgumentList)
2164      return 0;
2165
2166    return getExplicitTemplateArgs().getTemplateArgs();
2167  }
2168
2169  /// \brief Retrieve the number of template arguments provided as part of this
2170  /// template-id.
2171  unsigned getNumTemplateArgs() const {
2172    if (!HasExplicitTemplateArgumentList)
2173      return 0;
2174
2175    return getExplicitTemplateArgs().NumTemplateArgs;
2176  }
2177
2178  /// \brief Retrieve the location of the right angle bracket following the
2179  /// template arguments ('>').
2180  SourceLocation getRAngleLoc() const {
2181    if (!HasExplicitTemplateArgumentList)
2182      return SourceLocation();
2183
2184    return getExplicitTemplateArgs().RAngleLoc;
2185  }
2186
2187  /// \brief Retrieve the member declaration name info.
2188  DeclarationNameInfo getMemberNameInfo() const {
2189    return DeclarationNameInfo(MemberDecl->getDeclName(),
2190                               MemberLoc, MemberDNLoc);
2191  }
2192
2193  bool isArrow() const { return IsArrow; }
2194  void setArrow(bool A) { IsArrow = A; }
2195
2196  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2197  /// location of 'F'.
2198  SourceLocation getMemberLoc() const { return MemberLoc; }
2199  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2200
2201  SourceRange getSourceRange() const;
2202
2203  SourceLocation getExprLoc() const { return MemberLoc; }
2204
2205  /// \brief Determine whether the base of this explicit is implicit.
2206  bool isImplicitAccess() const {
2207    return getBase() && getBase()->isImplicitCXXThis();
2208  }
2209
2210  static bool classof(const Stmt *T) {
2211    return T->getStmtClass() == MemberExprClass;
2212  }
2213  static bool classof(const MemberExpr *) { return true; }
2214
2215  // Iterators
2216  child_range children() { return child_range(&Base, &Base+1); }
2217
2218  friend class ASTReader;
2219  friend class ASTStmtWriter;
2220};
2221
2222/// CompoundLiteralExpr - [C99 6.5.2.5]
2223///
2224class CompoundLiteralExpr : public Expr {
2225  /// LParenLoc - If non-null, this is the location of the left paren in a
2226  /// compound literal like "(int){4}".  This can be null if this is a
2227  /// synthesized compound expression.
2228  SourceLocation LParenLoc;
2229
2230  /// The type as written.  This can be an incomplete array type, in
2231  /// which case the actual expression type will be different.
2232  TypeSourceInfo *TInfo;
2233  Stmt *Init;
2234  bool FileScope;
2235public:
2236  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2237                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2238    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2239           tinfo->getType()->isDependentType(),
2240           init->isValueDependent(),
2241           (init->isInstantiationDependent() ||
2242            tinfo->getType()->isInstantiationDependentType()),
2243           init->containsUnexpandedParameterPack()),
2244      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
2245
2246  /// \brief Construct an empty compound literal.
2247  explicit CompoundLiteralExpr(EmptyShell Empty)
2248    : Expr(CompoundLiteralExprClass, Empty) { }
2249
2250  const Expr *getInitializer() const { return cast<Expr>(Init); }
2251  Expr *getInitializer() { return cast<Expr>(Init); }
2252  void setInitializer(Expr *E) { Init = E; }
2253
2254  bool isFileScope() const { return FileScope; }
2255  void setFileScope(bool FS) { FileScope = FS; }
2256
2257  SourceLocation getLParenLoc() const { return LParenLoc; }
2258  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2259
2260  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
2261  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
2262
2263  SourceRange getSourceRange() const {
2264    // FIXME: Init should never be null.
2265    if (!Init)
2266      return SourceRange();
2267    if (LParenLoc.isInvalid())
2268      return Init->getSourceRange();
2269    return SourceRange(LParenLoc, Init->getLocEnd());
2270  }
2271
2272  static bool classof(const Stmt *T) {
2273    return T->getStmtClass() == CompoundLiteralExprClass;
2274  }
2275  static bool classof(const CompoundLiteralExpr *) { return true; }
2276
2277  // Iterators
2278  child_range children() { return child_range(&Init, &Init+1); }
2279};
2280
2281/// CastExpr - Base class for type casts, including both implicit
2282/// casts (ImplicitCastExpr) and explicit casts that have some
2283/// representation in the source code (ExplicitCastExpr's derived
2284/// classes).
2285class CastExpr : public Expr {
2286public:
2287  typedef clang::CastKind CastKind;
2288
2289private:
2290  Stmt *Op;
2291
2292  void CheckCastConsistency() const {
2293#ifndef NDEBUG
2294    switch (getCastKind()) {
2295    case CK_DerivedToBase:
2296    case CK_UncheckedDerivedToBase:
2297    case CK_DerivedToBaseMemberPointer:
2298    case CK_BaseToDerived:
2299    case CK_BaseToDerivedMemberPointer:
2300      assert(!path_empty() && "Cast kind should have a base path!");
2301      break;
2302
2303    // These should not have an inheritance path.
2304    case CK_BitCast:
2305    case CK_Dynamic:
2306    case CK_ToUnion:
2307    case CK_ArrayToPointerDecay:
2308    case CK_FunctionToPointerDecay:
2309    case CK_NullToMemberPointer:
2310    case CK_NullToPointer:
2311    case CK_ConstructorConversion:
2312    case CK_IntegralToPointer:
2313    case CK_PointerToIntegral:
2314    case CK_ToVoid:
2315    case CK_VectorSplat:
2316    case CK_IntegralCast:
2317    case CK_IntegralToFloating:
2318    case CK_FloatingToIntegral:
2319    case CK_FloatingCast:
2320    case CK_AnyPointerToObjCPointerCast:
2321    case CK_AnyPointerToBlockPointerCast:
2322    case CK_ObjCObjectLValueCast:
2323    case CK_FloatingRealToComplex:
2324    case CK_FloatingComplexToReal:
2325    case CK_FloatingComplexCast:
2326    case CK_FloatingComplexToIntegralComplex:
2327    case CK_IntegralRealToComplex:
2328    case CK_IntegralComplexToReal:
2329    case CK_IntegralComplexCast:
2330    case CK_IntegralComplexToFloatingComplex:
2331    case CK_ObjCProduceObject:
2332    case CK_ObjCConsumeObject:
2333      assert(!getType()->isBooleanType() && "unheralded conversion to bool");
2334      // fallthrough to check for null base path
2335
2336    case CK_Dependent:
2337    case CK_LValueToRValue:
2338    case CK_GetObjCProperty:
2339    case CK_NoOp:
2340    case CK_PointerToBoolean:
2341    case CK_IntegralToBoolean:
2342    case CK_FloatingToBoolean:
2343    case CK_MemberPointerToBoolean:
2344    case CK_FloatingComplexToBoolean:
2345    case CK_IntegralComplexToBoolean:
2346    case CK_LValueBitCast:            // -> bool&
2347    case CK_UserDefinedConversion:    // operator bool()
2348      assert(path_empty() && "Cast kind should not have a base path!");
2349      break;
2350    }
2351#endif
2352  }
2353
2354  const CXXBaseSpecifier * const *path_buffer() const {
2355    return const_cast<CastExpr*>(this)->path_buffer();
2356  }
2357  CXXBaseSpecifier **path_buffer();
2358
2359  void setBasePathSize(unsigned basePathSize) {
2360    CastExprBits.BasePathSize = basePathSize;
2361    assert(CastExprBits.BasePathSize == basePathSize &&
2362           "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2363  }
2364
2365protected:
2366  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2367           const CastKind kind, Expr *op, unsigned BasePathSize) :
2368    Expr(SC, ty, VK, OK_Ordinary,
2369         // Cast expressions are type-dependent if the type is
2370         // dependent (C++ [temp.dep.expr]p3).
2371         ty->isDependentType(),
2372         // Cast expressions are value-dependent if the type is
2373         // dependent or if the subexpression is value-dependent.
2374         ty->isDependentType() || (op && op->isValueDependent()),
2375         (ty->isInstantiationDependentType() ||
2376          (op && op->isInstantiationDependent())),
2377         (ty->containsUnexpandedParameterPack() ||
2378          op->containsUnexpandedParameterPack())),
2379    Op(op) {
2380    assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2381    CastExprBits.Kind = kind;
2382    setBasePathSize(BasePathSize);
2383    CheckCastConsistency();
2384  }
2385
2386  /// \brief Construct an empty cast.
2387  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2388    : Expr(SC, Empty) {
2389    setBasePathSize(BasePathSize);
2390  }
2391
2392public:
2393  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2394  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2395  const char *getCastKindName() const;
2396
2397  Expr *getSubExpr() { return cast<Expr>(Op); }
2398  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2399  void setSubExpr(Expr *E) { Op = E; }
2400
2401  /// \brief Retrieve the cast subexpression as it was written in the source
2402  /// code, looking through any implicit casts or other intermediate nodes
2403  /// introduced by semantic analysis.
2404  Expr *getSubExprAsWritten();
2405  const Expr *getSubExprAsWritten() const {
2406    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2407  }
2408
2409  typedef CXXBaseSpecifier **path_iterator;
2410  typedef const CXXBaseSpecifier * const *path_const_iterator;
2411  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2412  unsigned path_size() const { return CastExprBits.BasePathSize; }
2413  path_iterator path_begin() { return path_buffer(); }
2414  path_iterator path_end() { return path_buffer() + path_size(); }
2415  path_const_iterator path_begin() const { return path_buffer(); }
2416  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2417
2418  void setCastPath(const CXXCastPath &Path);
2419
2420  static bool classof(const Stmt *T) {
2421    return T->getStmtClass() >= firstCastExprConstant &&
2422           T->getStmtClass() <= lastCastExprConstant;
2423  }
2424  static bool classof(const CastExpr *) { return true; }
2425
2426  // Iterators
2427  child_range children() { return child_range(&Op, &Op+1); }
2428};
2429
2430/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2431/// conversions, which have no direct representation in the original
2432/// source code. For example: converting T[]->T*, void f()->void
2433/// (*f)(), float->double, short->int, etc.
2434///
2435/// In C, implicit casts always produce rvalues. However, in C++, an
2436/// implicit cast whose result is being bound to a reference will be
2437/// an lvalue or xvalue. For example:
2438///
2439/// @code
2440/// class Base { };
2441/// class Derived : public Base { };
2442/// Derived &&ref();
2443/// void f(Derived d) {
2444///   Base& b = d; // initializer is an ImplicitCastExpr
2445///                // to an lvalue of type Base
2446///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2447///                     // to an xvalue of type Base
2448/// }
2449/// @endcode
2450class ImplicitCastExpr : public CastExpr {
2451private:
2452  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2453                   unsigned BasePathLength, ExprValueKind VK)
2454    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2455  }
2456
2457  /// \brief Construct an empty implicit cast.
2458  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2459    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2460
2461public:
2462  enum OnStack_t { OnStack };
2463  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2464                   ExprValueKind VK)
2465    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2466  }
2467
2468  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2469                                  CastKind Kind, Expr *Operand,
2470                                  const CXXCastPath *BasePath,
2471                                  ExprValueKind Cat);
2472
2473  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2474
2475  SourceRange getSourceRange() const {
2476    return getSubExpr()->getSourceRange();
2477  }
2478
2479  static bool classof(const Stmt *T) {
2480    return T->getStmtClass() == ImplicitCastExprClass;
2481  }
2482  static bool classof(const ImplicitCastExpr *) { return true; }
2483};
2484
2485/// ExplicitCastExpr - An explicit cast written in the source
2486/// code.
2487///
2488/// This class is effectively an abstract class, because it provides
2489/// the basic representation of an explicitly-written cast without
2490/// specifying which kind of cast (C cast, functional cast, static
2491/// cast, etc.) was written; specific derived classes represent the
2492/// particular style of cast and its location information.
2493///
2494/// Unlike implicit casts, explicit cast nodes have two different
2495/// types: the type that was written into the source code, and the
2496/// actual type of the expression as determined by semantic
2497/// analysis. These types may differ slightly. For example, in C++ one
2498/// can cast to a reference type, which indicates that the resulting
2499/// expression will be an lvalue or xvalue. The reference type, however,
2500/// will not be used as the type of the expression.
2501class ExplicitCastExpr : public CastExpr {
2502  /// TInfo - Source type info for the (written) type
2503  /// this expression is casting to.
2504  TypeSourceInfo *TInfo;
2505
2506protected:
2507  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2508                   CastKind kind, Expr *op, unsigned PathSize,
2509                   TypeSourceInfo *writtenTy)
2510    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2511
2512  /// \brief Construct an empty explicit cast.
2513  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2514    : CastExpr(SC, Shell, PathSize) { }
2515
2516public:
2517  /// getTypeInfoAsWritten - Returns the type source info for the type
2518  /// that this expression is casting to.
2519  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2520  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2521
2522  /// getTypeAsWritten - Returns the type that this expression is
2523  /// casting to, as written in the source code.
2524  QualType getTypeAsWritten() const { return TInfo->getType(); }
2525
2526  static bool classof(const Stmt *T) {
2527     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2528            T->getStmtClass() <= lastExplicitCastExprConstant;
2529  }
2530  static bool classof(const ExplicitCastExpr *) { return true; }
2531};
2532
2533/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2534/// cast in C++ (C++ [expr.cast]), which uses the syntax
2535/// (Type)expr. For example: @c (int)f.
2536class CStyleCastExpr : public ExplicitCastExpr {
2537  SourceLocation LPLoc; // the location of the left paren
2538  SourceLocation RPLoc; // the location of the right paren
2539
2540  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2541                 unsigned PathSize, TypeSourceInfo *writtenTy,
2542                 SourceLocation l, SourceLocation r)
2543    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2544                       writtenTy), LPLoc(l), RPLoc(r) {}
2545
2546  /// \brief Construct an empty C-style explicit cast.
2547  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2548    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2549
2550public:
2551  static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2552                                ExprValueKind VK, CastKind K,
2553                                Expr *Op, const CXXCastPath *BasePath,
2554                                TypeSourceInfo *WrittenTy, SourceLocation L,
2555                                SourceLocation R);
2556
2557  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2558
2559  SourceLocation getLParenLoc() const { return LPLoc; }
2560  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2561
2562  SourceLocation getRParenLoc() const { return RPLoc; }
2563  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2564
2565  SourceRange getSourceRange() const {
2566    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2567  }
2568  static bool classof(const Stmt *T) {
2569    return T->getStmtClass() == CStyleCastExprClass;
2570  }
2571  static bool classof(const CStyleCastExpr *) { return true; }
2572};
2573
2574/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2575///
2576/// This expression node kind describes a builtin binary operation,
2577/// such as "x + y" for integer values "x" and "y". The operands will
2578/// already have been converted to appropriate types (e.g., by
2579/// performing promotions or conversions).
2580///
2581/// In C++, where operators may be overloaded, a different kind of
2582/// expression node (CXXOperatorCallExpr) is used to express the
2583/// invocation of an overloaded operator with operator syntax. Within
2584/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2585/// used to store an expression "x + y" depends on the subexpressions
2586/// for x and y. If neither x or y is type-dependent, and the "+"
2587/// operator resolves to a built-in operation, BinaryOperator will be
2588/// used to express the computation (x and y may still be
2589/// value-dependent). If either x or y is type-dependent, or if the
2590/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2591/// be used to express the computation.
2592class BinaryOperator : public Expr {
2593public:
2594  typedef BinaryOperatorKind Opcode;
2595
2596private:
2597  unsigned Opc : 6;
2598  SourceLocation OpLoc;
2599
2600  enum { LHS, RHS, END_EXPR };
2601  Stmt* SubExprs[END_EXPR];
2602public:
2603
2604  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2605                 ExprValueKind VK, ExprObjectKind OK,
2606                 SourceLocation opLoc)
2607    : Expr(BinaryOperatorClass, ResTy, VK, OK,
2608           lhs->isTypeDependent() || rhs->isTypeDependent(),
2609           lhs->isValueDependent() || rhs->isValueDependent(),
2610           (lhs->isInstantiationDependent() ||
2611            rhs->isInstantiationDependent()),
2612           (lhs->containsUnexpandedParameterPack() ||
2613            rhs->containsUnexpandedParameterPack())),
2614      Opc(opc), OpLoc(opLoc) {
2615    SubExprs[LHS] = lhs;
2616    SubExprs[RHS] = rhs;
2617    assert(!isCompoundAssignmentOp() &&
2618           "Use ArithAssignBinaryOperator for compound assignments");
2619  }
2620
2621  /// \brief Construct an empty binary operator.
2622  explicit BinaryOperator(EmptyShell Empty)
2623    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2624
2625  SourceLocation getOperatorLoc() const { return OpLoc; }
2626  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2627
2628  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2629  void setOpcode(Opcode O) { Opc = O; }
2630
2631  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2632  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2633  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2634  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2635
2636  SourceRange getSourceRange() const {
2637    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2638  }
2639
2640  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2641  /// corresponds to, e.g. "<<=".
2642  static const char *getOpcodeStr(Opcode Op);
2643
2644  const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2645
2646  /// \brief Retrieve the binary opcode that corresponds to the given
2647  /// overloaded operator.
2648  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2649
2650  /// \brief Retrieve the overloaded operator kind that corresponds to
2651  /// the given binary opcode.
2652  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2653
2654  /// predicates to categorize the respective opcodes.
2655  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2656  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2657  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2658  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2659  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2660  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2661
2662  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2663  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2664
2665  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2666  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2667
2668  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2669  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2670
2671  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2672  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2673
2674  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2675  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2676
2677  static bool isAssignmentOp(Opcode Opc) {
2678    return Opc >= BO_Assign && Opc <= BO_OrAssign;
2679  }
2680  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2681
2682  static bool isCompoundAssignmentOp(Opcode Opc) {
2683    return Opc > BO_Assign && Opc <= BO_OrAssign;
2684  }
2685  bool isCompoundAssignmentOp() const {
2686    return isCompoundAssignmentOp(getOpcode());
2687  }
2688
2689  static bool isShiftAssignOp(Opcode Opc) {
2690    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2691  }
2692  bool isShiftAssignOp() const {
2693    return isShiftAssignOp(getOpcode());
2694  }
2695
2696  static bool classof(const Stmt *S) {
2697    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2698           S->getStmtClass() <= lastBinaryOperatorConstant;
2699  }
2700  static bool classof(const BinaryOperator *) { return true; }
2701
2702  // Iterators
2703  child_range children() {
2704    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2705  }
2706
2707protected:
2708  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2709                 ExprValueKind VK, ExprObjectKind OK,
2710                 SourceLocation opLoc, bool dead)
2711    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
2712           lhs->isTypeDependent() || rhs->isTypeDependent(),
2713           lhs->isValueDependent() || rhs->isValueDependent(),
2714           (lhs->isInstantiationDependent() ||
2715            rhs->isInstantiationDependent()),
2716           (lhs->containsUnexpandedParameterPack() ||
2717            rhs->containsUnexpandedParameterPack())),
2718      Opc(opc), OpLoc(opLoc) {
2719    SubExprs[LHS] = lhs;
2720    SubExprs[RHS] = rhs;
2721  }
2722
2723  BinaryOperator(StmtClass SC, EmptyShell Empty)
2724    : Expr(SC, Empty), Opc(BO_MulAssign) { }
2725};
2726
2727/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2728/// track of the type the operation is performed in.  Due to the semantics of
2729/// these operators, the operands are promoted, the aritmetic performed, an
2730/// implicit conversion back to the result type done, then the assignment takes
2731/// place.  This captures the intermediate type which the computation is done
2732/// in.
2733class CompoundAssignOperator : public BinaryOperator {
2734  QualType ComputationLHSType;
2735  QualType ComputationResultType;
2736public:
2737  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
2738                         ExprValueKind VK, ExprObjectKind OK,
2739                         QualType CompLHSType, QualType CompResultType,
2740                         SourceLocation OpLoc)
2741    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true),
2742      ComputationLHSType(CompLHSType),
2743      ComputationResultType(CompResultType) {
2744    assert(isCompoundAssignmentOp() &&
2745           "Only should be used for compound assignments");
2746  }
2747
2748  /// \brief Build an empty compound assignment operator expression.
2749  explicit CompoundAssignOperator(EmptyShell Empty)
2750    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2751
2752  // The two computation types are the type the LHS is converted
2753  // to for the computation and the type of the result; the two are
2754  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2755  QualType getComputationLHSType() const { return ComputationLHSType; }
2756  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2757
2758  QualType getComputationResultType() const { return ComputationResultType; }
2759  void setComputationResultType(QualType T) { ComputationResultType = T; }
2760
2761  static bool classof(const CompoundAssignOperator *) { return true; }
2762  static bool classof(const Stmt *S) {
2763    return S->getStmtClass() == CompoundAssignOperatorClass;
2764  }
2765};
2766
2767/// AbstractConditionalOperator - An abstract base class for
2768/// ConditionalOperator and BinaryConditionalOperator.
2769class AbstractConditionalOperator : public Expr {
2770  SourceLocation QuestionLoc, ColonLoc;
2771  friend class ASTStmtReader;
2772
2773protected:
2774  AbstractConditionalOperator(StmtClass SC, QualType T,
2775                              ExprValueKind VK, ExprObjectKind OK,
2776                              bool TD, bool VD, bool ID,
2777                              bool ContainsUnexpandedParameterPack,
2778                              SourceLocation qloc,
2779                              SourceLocation cloc)
2780    : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
2781      QuestionLoc(qloc), ColonLoc(cloc) {}
2782
2783  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
2784    : Expr(SC, Empty) { }
2785
2786public:
2787  // getCond - Return the expression representing the condition for
2788  //   the ?: operator.
2789  Expr *getCond() const;
2790
2791  // getTrueExpr - Return the subexpression representing the value of
2792  //   the expression if the condition evaluates to true.
2793  Expr *getTrueExpr() const;
2794
2795  // getFalseExpr - Return the subexpression representing the value of
2796  //   the expression if the condition evaluates to false.  This is
2797  //   the same as getRHS.
2798  Expr *getFalseExpr() const;
2799
2800  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2801  SourceLocation getColonLoc() const { return ColonLoc; }
2802
2803  static bool classof(const Stmt *T) {
2804    return T->getStmtClass() == ConditionalOperatorClass ||
2805           T->getStmtClass() == BinaryConditionalOperatorClass;
2806  }
2807  static bool classof(const AbstractConditionalOperator *) { return true; }
2808};
2809
2810/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
2811/// middle" extension is a BinaryConditionalOperator.
2812class ConditionalOperator : public AbstractConditionalOperator {
2813  enum { COND, LHS, RHS, END_EXPR };
2814  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2815
2816  friend class ASTStmtReader;
2817public:
2818  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2819                      SourceLocation CLoc, Expr *rhs,
2820                      QualType t, ExprValueKind VK, ExprObjectKind OK)
2821    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
2822           // FIXME: the type of the conditional operator doesn't
2823           // depend on the type of the conditional, but the standard
2824           // seems to imply that it could. File a bug!
2825           (lhs->isTypeDependent() || rhs->isTypeDependent()),
2826           (cond->isValueDependent() || lhs->isValueDependent() ||
2827            rhs->isValueDependent()),
2828           (cond->isInstantiationDependent() ||
2829            lhs->isInstantiationDependent() ||
2830            rhs->isInstantiationDependent()),
2831           (cond->containsUnexpandedParameterPack() ||
2832            lhs->containsUnexpandedParameterPack() ||
2833            rhs->containsUnexpandedParameterPack()),
2834                                  QLoc, CLoc) {
2835    SubExprs[COND] = cond;
2836    SubExprs[LHS] = lhs;
2837    SubExprs[RHS] = rhs;
2838  }
2839
2840  /// \brief Build an empty conditional operator.
2841  explicit ConditionalOperator(EmptyShell Empty)
2842    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
2843
2844  // getCond - Return the expression representing the condition for
2845  //   the ?: operator.
2846  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2847
2848  // getTrueExpr - Return the subexpression representing the value of
2849  //   the expression if the condition evaluates to true.
2850  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
2851
2852  // getFalseExpr - Return the subexpression representing the value of
2853  //   the expression if the condition evaluates to false.  This is
2854  //   the same as getRHS.
2855  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2856
2857  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2858  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2859
2860  SourceRange getSourceRange() const {
2861    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2862  }
2863  static bool classof(const Stmt *T) {
2864    return T->getStmtClass() == ConditionalOperatorClass;
2865  }
2866  static bool classof(const ConditionalOperator *) { return true; }
2867
2868  // Iterators
2869  child_range children() {
2870    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2871  }
2872};
2873
2874/// BinaryConditionalOperator - The GNU extension to the conditional
2875/// operator which allows the middle operand to be omitted.
2876///
2877/// This is a different expression kind on the assumption that almost
2878/// every client ends up needing to know that these are different.
2879class BinaryConditionalOperator : public AbstractConditionalOperator {
2880  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
2881
2882  /// - the common condition/left-hand-side expression, which will be
2883  ///   evaluated as the opaque value
2884  /// - the condition, expressed in terms of the opaque value
2885  /// - the left-hand-side, expressed in terms of the opaque value
2886  /// - the right-hand-side
2887  Stmt *SubExprs[NUM_SUBEXPRS];
2888  OpaqueValueExpr *OpaqueValue;
2889
2890  friend class ASTStmtReader;
2891public:
2892  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
2893                            Expr *cond, Expr *lhs, Expr *rhs,
2894                            SourceLocation qloc, SourceLocation cloc,
2895                            QualType t, ExprValueKind VK, ExprObjectKind OK)
2896    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
2897           (common->isTypeDependent() || rhs->isTypeDependent()),
2898           (common->isValueDependent() || rhs->isValueDependent()),
2899           (common->isInstantiationDependent() ||
2900            rhs->isInstantiationDependent()),
2901           (common->containsUnexpandedParameterPack() ||
2902            rhs->containsUnexpandedParameterPack()),
2903                                  qloc, cloc),
2904      OpaqueValue(opaqueValue) {
2905    SubExprs[COMMON] = common;
2906    SubExprs[COND] = cond;
2907    SubExprs[LHS] = lhs;
2908    SubExprs[RHS] = rhs;
2909
2910    OpaqueValue->setSourceExpr(common);
2911  }
2912
2913  /// \brief Build an empty conditional operator.
2914  explicit BinaryConditionalOperator(EmptyShell Empty)
2915    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
2916
2917  /// \brief getCommon - Return the common expression, written to the
2918  ///   left of the condition.  The opaque value will be bound to the
2919  ///   result of this expression.
2920  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
2921
2922  /// \brief getOpaqueValue - Return the opaque value placeholder.
2923  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
2924
2925  /// \brief getCond - Return the condition expression; this is defined
2926  ///   in terms of the opaque value.
2927  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2928
2929  /// \brief getTrueExpr - Return the subexpression which will be
2930  ///   evaluated if the condition evaluates to true;  this is defined
2931  ///   in terms of the opaque value.
2932  Expr *getTrueExpr() const {
2933    return cast<Expr>(SubExprs[LHS]);
2934  }
2935
2936  /// \brief getFalseExpr - Return the subexpression which will be
2937  ///   evaluated if the condnition evaluates to false; this is
2938  ///   defined in terms of the opaque value.
2939  Expr *getFalseExpr() const {
2940    return cast<Expr>(SubExprs[RHS]);
2941  }
2942
2943  SourceRange getSourceRange() const {
2944    return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd());
2945  }
2946  static bool classof(const Stmt *T) {
2947    return T->getStmtClass() == BinaryConditionalOperatorClass;
2948  }
2949  static bool classof(const BinaryConditionalOperator *) { return true; }
2950
2951  // Iterators
2952  child_range children() {
2953    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
2954  }
2955};
2956
2957inline Expr *AbstractConditionalOperator::getCond() const {
2958  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2959    return co->getCond();
2960  return cast<BinaryConditionalOperator>(this)->getCond();
2961}
2962
2963inline Expr *AbstractConditionalOperator::getTrueExpr() const {
2964  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2965    return co->getTrueExpr();
2966  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
2967}
2968
2969inline Expr *AbstractConditionalOperator::getFalseExpr() const {
2970  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2971    return co->getFalseExpr();
2972  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
2973}
2974
2975/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2976class AddrLabelExpr : public Expr {
2977  SourceLocation AmpAmpLoc, LabelLoc;
2978  LabelDecl *Label;
2979public:
2980  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
2981                QualType t)
2982    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
2983           false),
2984      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2985
2986  /// \brief Build an empty address of a label expression.
2987  explicit AddrLabelExpr(EmptyShell Empty)
2988    : Expr(AddrLabelExprClass, Empty) { }
2989
2990  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2991  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2992  SourceLocation getLabelLoc() const { return LabelLoc; }
2993  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2994
2995  SourceRange getSourceRange() const {
2996    return SourceRange(AmpAmpLoc, LabelLoc);
2997  }
2998
2999  LabelDecl *getLabel() const { return Label; }
3000  void setLabel(LabelDecl *L) { Label = L; }
3001
3002  static bool classof(const Stmt *T) {
3003    return T->getStmtClass() == AddrLabelExprClass;
3004  }
3005  static bool classof(const AddrLabelExpr *) { return true; }
3006
3007  // Iterators
3008  child_range children() { return child_range(); }
3009};
3010
3011/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3012/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3013/// takes the value of the last subexpression.
3014///
3015/// A StmtExpr is always an r-value; values "returned" out of a
3016/// StmtExpr will be copied.
3017class StmtExpr : public Expr {
3018  Stmt *SubStmt;
3019  SourceLocation LParenLoc, RParenLoc;
3020public:
3021  // FIXME: Does type-dependence need to be computed differently?
3022  // FIXME: Do we need to compute instantiation instantiation-dependence for
3023  // statements? (ugh!)
3024  StmtExpr(CompoundStmt *substmt, QualType T,
3025           SourceLocation lp, SourceLocation rp) :
3026    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3027         T->isDependentType(), false, false, false),
3028    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3029
3030  /// \brief Build an empty statement expression.
3031  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3032
3033  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3034  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3035  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3036
3037  SourceRange getSourceRange() const {
3038    return SourceRange(LParenLoc, RParenLoc);
3039  }
3040
3041  SourceLocation getLParenLoc() const { return LParenLoc; }
3042  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3043  SourceLocation getRParenLoc() const { return RParenLoc; }
3044  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3045
3046  static bool classof(const Stmt *T) {
3047    return T->getStmtClass() == StmtExprClass;
3048  }
3049  static bool classof(const StmtExpr *) { return true; }
3050
3051  // Iterators
3052  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3053};
3054
3055
3056/// ShuffleVectorExpr - clang-specific builtin-in function
3057/// __builtin_shufflevector.
3058/// This AST node represents a operator that does a constant
3059/// shuffle, similar to LLVM's shufflevector instruction. It takes
3060/// two vectors and a variable number of constant indices,
3061/// and returns the appropriately shuffled vector.
3062class ShuffleVectorExpr : public Expr {
3063  SourceLocation BuiltinLoc, RParenLoc;
3064
3065  // SubExprs - the list of values passed to the __builtin_shufflevector
3066  // function. The first two are vectors, and the rest are constant
3067  // indices.  The number of values in this list is always
3068  // 2+the number of indices in the vector type.
3069  Stmt **SubExprs;
3070  unsigned NumExprs;
3071
3072public:
3073  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3074                    QualType Type, SourceLocation BLoc,
3075                    SourceLocation RP);
3076
3077  /// \brief Build an empty vector-shuffle expression.
3078  explicit ShuffleVectorExpr(EmptyShell Empty)
3079    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3080
3081  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3082  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3083
3084  SourceLocation getRParenLoc() const { return RParenLoc; }
3085  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3086
3087  SourceRange getSourceRange() const {
3088    return SourceRange(BuiltinLoc, RParenLoc);
3089  }
3090  static bool classof(const Stmt *T) {
3091    return T->getStmtClass() == ShuffleVectorExprClass;
3092  }
3093  static bool classof(const ShuffleVectorExpr *) { return true; }
3094
3095  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
3096  /// constant expression, the actual arguments passed in, and the function
3097  /// pointers.
3098  unsigned getNumSubExprs() const { return NumExprs; }
3099
3100  /// \brief Retrieve the array of expressions.
3101  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3102
3103  /// getExpr - Return the Expr at the specified index.
3104  Expr *getExpr(unsigned Index) {
3105    assert((Index < NumExprs) && "Arg access out of range!");
3106    return cast<Expr>(SubExprs[Index]);
3107  }
3108  const Expr *getExpr(unsigned Index) const {
3109    assert((Index < NumExprs) && "Arg access out of range!");
3110    return cast<Expr>(SubExprs[Index]);
3111  }
3112
3113  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
3114
3115  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
3116    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3117    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
3118  }
3119
3120  // Iterators
3121  child_range children() {
3122    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3123  }
3124};
3125
3126/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3127/// This AST node is similar to the conditional operator (?:) in C, with
3128/// the following exceptions:
3129/// - the test expression must be a integer constant expression.
3130/// - the expression returned acts like the chosen subexpression in every
3131///   visible way: the type is the same as that of the chosen subexpression,
3132///   and all predicates (whether it's an l-value, whether it's an integer
3133///   constant expression, etc.) return the same result as for the chosen
3134///   sub-expression.
3135class ChooseExpr : public Expr {
3136  enum { COND, LHS, RHS, END_EXPR };
3137  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3138  SourceLocation BuiltinLoc, RParenLoc;
3139public:
3140  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3141             QualType t, ExprValueKind VK, ExprObjectKind OK,
3142             SourceLocation RP, bool TypeDependent, bool ValueDependent)
3143    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3144           (cond->isInstantiationDependent() ||
3145            lhs->isInstantiationDependent() ||
3146            rhs->isInstantiationDependent()),
3147           (cond->containsUnexpandedParameterPack() ||
3148            lhs->containsUnexpandedParameterPack() ||
3149            rhs->containsUnexpandedParameterPack())),
3150      BuiltinLoc(BLoc), RParenLoc(RP) {
3151      SubExprs[COND] = cond;
3152      SubExprs[LHS] = lhs;
3153      SubExprs[RHS] = rhs;
3154    }
3155
3156  /// \brief Build an empty __builtin_choose_expr.
3157  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3158
3159  /// isConditionTrue - Return whether the condition is true (i.e. not
3160  /// equal to zero).
3161  bool isConditionTrue(const ASTContext &C) const;
3162
3163  /// getChosenSubExpr - Return the subexpression chosen according to the
3164  /// condition.
3165  Expr *getChosenSubExpr(const ASTContext &C) const {
3166    return isConditionTrue(C) ? getLHS() : getRHS();
3167  }
3168
3169  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3170  void setCond(Expr *E) { SubExprs[COND] = E; }
3171  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3172  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3173  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3174  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3175
3176  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3177  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3178
3179  SourceLocation getRParenLoc() const { return RParenLoc; }
3180  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3181
3182  SourceRange getSourceRange() const {
3183    return SourceRange(BuiltinLoc, RParenLoc);
3184  }
3185  static bool classof(const Stmt *T) {
3186    return T->getStmtClass() == ChooseExprClass;
3187  }
3188  static bool classof(const ChooseExpr *) { return true; }
3189
3190  // Iterators
3191  child_range children() {
3192    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3193  }
3194};
3195
3196/// GNUNullExpr - Implements the GNU __null extension, which is a name
3197/// for a null pointer constant that has integral type (e.g., int or
3198/// long) and is the same size and alignment as a pointer. The __null
3199/// extension is typically only used by system headers, which define
3200/// NULL as __null in C++ rather than using 0 (which is an integer
3201/// that may not match the size of a pointer).
3202class GNUNullExpr : public Expr {
3203  /// TokenLoc - The location of the __null keyword.
3204  SourceLocation TokenLoc;
3205
3206public:
3207  GNUNullExpr(QualType Ty, SourceLocation Loc)
3208    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3209           false),
3210      TokenLoc(Loc) { }
3211
3212  /// \brief Build an empty GNU __null expression.
3213  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3214
3215  /// getTokenLocation - The location of the __null token.
3216  SourceLocation getTokenLocation() const { return TokenLoc; }
3217  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3218
3219  SourceRange getSourceRange() const {
3220    return SourceRange(TokenLoc);
3221  }
3222  static bool classof(const Stmt *T) {
3223    return T->getStmtClass() == GNUNullExprClass;
3224  }
3225  static bool classof(const GNUNullExpr *) { return true; }
3226
3227  // Iterators
3228  child_range children() { return child_range(); }
3229};
3230
3231/// VAArgExpr, used for the builtin function __builtin_va_arg.
3232class VAArgExpr : public Expr {
3233  Stmt *Val;
3234  TypeSourceInfo *TInfo;
3235  SourceLocation BuiltinLoc, RParenLoc;
3236public:
3237  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3238            SourceLocation RPLoc, QualType t)
3239    : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3240           t->isDependentType(), false,
3241           (TInfo->getType()->isInstantiationDependentType() ||
3242            e->isInstantiationDependent()),
3243           (TInfo->getType()->containsUnexpandedParameterPack() ||
3244            e->containsUnexpandedParameterPack())),
3245      Val(e), TInfo(TInfo),
3246      BuiltinLoc(BLoc),
3247      RParenLoc(RPLoc) { }
3248
3249  /// \brief Create an empty __builtin_va_arg expression.
3250  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3251
3252  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3253  Expr *getSubExpr() { return cast<Expr>(Val); }
3254  void setSubExpr(Expr *E) { Val = E; }
3255
3256  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3257  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3258
3259  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3260  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3261
3262  SourceLocation getRParenLoc() const { return RParenLoc; }
3263  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3264
3265  SourceRange getSourceRange() const {
3266    return SourceRange(BuiltinLoc, RParenLoc);
3267  }
3268  static bool classof(const Stmt *T) {
3269    return T->getStmtClass() == VAArgExprClass;
3270  }
3271  static bool classof(const VAArgExpr *) { return true; }
3272
3273  // Iterators
3274  child_range children() { return child_range(&Val, &Val+1); }
3275};
3276
3277/// @brief Describes an C or C++ initializer list.
3278///
3279/// InitListExpr describes an initializer list, which can be used to
3280/// initialize objects of different types, including
3281/// struct/class/union types, arrays, and vectors. For example:
3282///
3283/// @code
3284/// struct foo x = { 1, { 2, 3 } };
3285/// @endcode
3286///
3287/// Prior to semantic analysis, an initializer list will represent the
3288/// initializer list as written by the user, but will have the
3289/// placeholder type "void". This initializer list is called the
3290/// syntactic form of the initializer, and may contain C99 designated
3291/// initializers (represented as DesignatedInitExprs), initializations
3292/// of subobject members without explicit braces, and so on. Clients
3293/// interested in the original syntax of the initializer list should
3294/// use the syntactic form of the initializer list.
3295///
3296/// After semantic analysis, the initializer list will represent the
3297/// semantic form of the initializer, where the initializations of all
3298/// subobjects are made explicit with nested InitListExpr nodes and
3299/// C99 designators have been eliminated by placing the designated
3300/// initializations into the subobject they initialize. Additionally,
3301/// any "holes" in the initialization, where no initializer has been
3302/// specified for a particular subobject, will be replaced with
3303/// implicitly-generated ImplicitValueInitExpr expressions that
3304/// value-initialize the subobjects. Note, however, that the
3305/// initializer lists may still have fewer initializers than there are
3306/// elements to initialize within the object.
3307///
3308/// Given the semantic form of the initializer list, one can retrieve
3309/// the original syntactic form of that initializer list (if it
3310/// exists) using getSyntacticForm(). Since many initializer lists
3311/// have the same syntactic and semantic forms, getSyntacticForm() may
3312/// return NULL, indicating that the current initializer list also
3313/// serves as its syntactic form.
3314class InitListExpr : public Expr {
3315  // FIXME: Eliminate this vector in favor of ASTContext allocation
3316  typedef ASTVector<Stmt *> InitExprsTy;
3317  InitExprsTy InitExprs;
3318  SourceLocation LBraceLoc, RBraceLoc;
3319
3320  /// Contains the initializer list that describes the syntactic form
3321  /// written in the source code.
3322  InitListExpr *SyntacticForm;
3323
3324  /// \brief Either:
3325  ///  If this initializer list initializes an array with more elements than
3326  ///  there are initializers in the list, specifies an expression to be used
3327  ///  for value initialization of the rest of the elements.
3328  /// Or
3329  ///  If this initializer list initializes a union, specifies which
3330  ///  field within the union will be initialized.
3331  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3332
3333  /// Whether this initializer list originally had a GNU array-range
3334  /// designator in it. This is a temporary marker used by CodeGen.
3335  bool HadArrayRangeDesignator;
3336
3337public:
3338  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3339               Expr **initexprs, unsigned numinits,
3340               SourceLocation rbraceloc);
3341
3342  /// \brief Build an empty initializer list.
3343  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
3344    : Expr(InitListExprClass, Empty), InitExprs(C) { }
3345
3346  unsigned getNumInits() const { return InitExprs.size(); }
3347
3348  /// \brief Retrieve the set of initializers.
3349  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3350
3351  const Expr *getInit(unsigned Init) const {
3352    assert(Init < getNumInits() && "Initializer access out of range!");
3353    return cast_or_null<Expr>(InitExprs[Init]);
3354  }
3355
3356  Expr *getInit(unsigned Init) {
3357    assert(Init < getNumInits() && "Initializer access out of range!");
3358    return cast_or_null<Expr>(InitExprs[Init]);
3359  }
3360
3361  void setInit(unsigned Init, Expr *expr) {
3362    assert(Init < getNumInits() && "Initializer access out of range!");
3363    InitExprs[Init] = expr;
3364  }
3365
3366  /// \brief Reserve space for some number of initializers.
3367  void reserveInits(ASTContext &C, unsigned NumInits);
3368
3369  /// @brief Specify the number of initializers
3370  ///
3371  /// If there are more than @p NumInits initializers, the remaining
3372  /// initializers will be destroyed. If there are fewer than @p
3373  /// NumInits initializers, NULL expressions will be added for the
3374  /// unknown initializers.
3375  void resizeInits(ASTContext &Context, unsigned NumInits);
3376
3377  /// @brief Updates the initializer at index @p Init with the new
3378  /// expression @p expr, and returns the old expression at that
3379  /// location.
3380  ///
3381  /// When @p Init is out of range for this initializer list, the
3382  /// initializer list will be extended with NULL expressions to
3383  /// accommodate the new entry.
3384  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3385
3386  /// \brief If this initializer list initializes an array with more elements
3387  /// than there are initializers in the list, specifies an expression to be
3388  /// used for value initialization of the rest of the elements.
3389  Expr *getArrayFiller() {
3390    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3391  }
3392  const Expr *getArrayFiller() const {
3393    return const_cast<InitListExpr *>(this)->getArrayFiller();
3394  }
3395  void setArrayFiller(Expr *filler);
3396
3397  /// \brief If this initializes a union, specifies which field in the
3398  /// union to initialize.
3399  ///
3400  /// Typically, this field is the first named field within the
3401  /// union. However, a designated initializer can specify the
3402  /// initialization of a different field within the union.
3403  FieldDecl *getInitializedFieldInUnion() {
3404    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3405  }
3406  const FieldDecl *getInitializedFieldInUnion() const {
3407    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3408  }
3409  void setInitializedFieldInUnion(FieldDecl *FD) {
3410    ArrayFillerOrUnionFieldInit = FD;
3411  }
3412
3413  // Explicit InitListExpr's originate from source code (and have valid source
3414  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3415  bool isExplicit() {
3416    return LBraceLoc.isValid() && RBraceLoc.isValid();
3417  }
3418
3419  SourceLocation getLBraceLoc() const { return LBraceLoc; }
3420  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3421  SourceLocation getRBraceLoc() const { return RBraceLoc; }
3422  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3423
3424  /// @brief Retrieve the initializer list that describes the
3425  /// syntactic form of the initializer.
3426  ///
3427  ///
3428  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
3429  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
3430
3431  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
3432  void sawArrayRangeDesignator(bool ARD = true) {
3433    HadArrayRangeDesignator = ARD;
3434  }
3435
3436  SourceRange getSourceRange() const;
3437
3438  static bool classof(const Stmt *T) {
3439    return T->getStmtClass() == InitListExprClass;
3440  }
3441  static bool classof(const InitListExpr *) { return true; }
3442
3443  // Iterators
3444  child_range children() {
3445    if (InitExprs.empty()) return child_range();
3446    return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3447  }
3448
3449  typedef InitExprsTy::iterator iterator;
3450  typedef InitExprsTy::const_iterator const_iterator;
3451  typedef InitExprsTy::reverse_iterator reverse_iterator;
3452  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3453
3454  iterator begin() { return InitExprs.begin(); }
3455  const_iterator begin() const { return InitExprs.begin(); }
3456  iterator end() { return InitExprs.end(); }
3457  const_iterator end() const { return InitExprs.end(); }
3458  reverse_iterator rbegin() { return InitExprs.rbegin(); }
3459  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3460  reverse_iterator rend() { return InitExprs.rend(); }
3461  const_reverse_iterator rend() const { return InitExprs.rend(); }
3462
3463  friend class ASTStmtReader;
3464  friend class ASTStmtWriter;
3465};
3466
3467/// @brief Represents a C99 designated initializer expression.
3468///
3469/// A designated initializer expression (C99 6.7.8) contains one or
3470/// more designators (which can be field designators, array
3471/// designators, or GNU array-range designators) followed by an
3472/// expression that initializes the field or element(s) that the
3473/// designators refer to. For example, given:
3474///
3475/// @code
3476/// struct point {
3477///   double x;
3478///   double y;
3479/// };
3480/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3481/// @endcode
3482///
3483/// The InitListExpr contains three DesignatedInitExprs, the first of
3484/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3485/// designators, one array designator for @c [2] followed by one field
3486/// designator for @c .y. The initalization expression will be 1.0.
3487class DesignatedInitExpr : public Expr {
3488public:
3489  /// \brief Forward declaration of the Designator class.
3490  class Designator;
3491
3492private:
3493  /// The location of the '=' or ':' prior to the actual initializer
3494  /// expression.
3495  SourceLocation EqualOrColonLoc;
3496
3497  /// Whether this designated initializer used the GNU deprecated
3498  /// syntax rather than the C99 '=' syntax.
3499  bool GNUSyntax : 1;
3500
3501  /// The number of designators in this initializer expression.
3502  unsigned NumDesignators : 15;
3503
3504  /// \brief The designators in this designated initialization
3505  /// expression.
3506  Designator *Designators;
3507
3508  /// The number of subexpressions of this initializer expression,
3509  /// which contains both the initializer and any additional
3510  /// expressions used by array and array-range designators.
3511  unsigned NumSubExprs : 16;
3512
3513
3514  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3515                     const Designator *Designators,
3516                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
3517                     Expr **IndexExprs, unsigned NumIndexExprs,
3518                     Expr *Init);
3519
3520  explicit DesignatedInitExpr(unsigned NumSubExprs)
3521    : Expr(DesignatedInitExprClass, EmptyShell()),
3522      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3523
3524public:
3525  /// A field designator, e.g., ".x".
3526  struct FieldDesignator {
3527    /// Refers to the field that is being initialized. The low bit
3528    /// of this field determines whether this is actually a pointer
3529    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3530    /// initially constructed, a field designator will store an
3531    /// IdentifierInfo*. After semantic analysis has resolved that
3532    /// name, the field designator will instead store a FieldDecl*.
3533    uintptr_t NameOrField;
3534
3535    /// The location of the '.' in the designated initializer.
3536    unsigned DotLoc;
3537
3538    /// The location of the field name in the designated initializer.
3539    unsigned FieldLoc;
3540  };
3541
3542  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3543  struct ArrayOrRangeDesignator {
3544    /// Location of the first index expression within the designated
3545    /// initializer expression's list of subexpressions.
3546    unsigned Index;
3547    /// The location of the '[' starting the array range designator.
3548    unsigned LBracketLoc;
3549    /// The location of the ellipsis separating the start and end
3550    /// indices. Only valid for GNU array-range designators.
3551    unsigned EllipsisLoc;
3552    /// The location of the ']' terminating the array range designator.
3553    unsigned RBracketLoc;
3554  };
3555
3556  /// @brief Represents a single C99 designator.
3557  ///
3558  /// @todo This class is infuriatingly similar to clang::Designator,
3559  /// but minor differences (storing indices vs. storing pointers)
3560  /// keep us from reusing it. Try harder, later, to rectify these
3561  /// differences.
3562  class Designator {
3563    /// @brief The kind of designator this describes.
3564    enum {
3565      FieldDesignator,
3566      ArrayDesignator,
3567      ArrayRangeDesignator
3568    } Kind;
3569
3570    union {
3571      /// A field designator, e.g., ".x".
3572      struct FieldDesignator Field;
3573      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3574      struct ArrayOrRangeDesignator ArrayOrRange;
3575    };
3576    friend class DesignatedInitExpr;
3577
3578  public:
3579    Designator() {}
3580
3581    /// @brief Initializes a field designator.
3582    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3583               SourceLocation FieldLoc)
3584      : Kind(FieldDesignator) {
3585      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3586      Field.DotLoc = DotLoc.getRawEncoding();
3587      Field.FieldLoc = FieldLoc.getRawEncoding();
3588    }
3589
3590    /// @brief Initializes an array designator.
3591    Designator(unsigned Index, SourceLocation LBracketLoc,
3592               SourceLocation RBracketLoc)
3593      : Kind(ArrayDesignator) {
3594      ArrayOrRange.Index = Index;
3595      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3596      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3597      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3598    }
3599
3600    /// @brief Initializes a GNU array-range designator.
3601    Designator(unsigned Index, SourceLocation LBracketLoc,
3602               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3603      : Kind(ArrayRangeDesignator) {
3604      ArrayOrRange.Index = Index;
3605      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3606      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3607      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3608    }
3609
3610    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3611    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3612    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3613
3614    IdentifierInfo *getFieldName() const;
3615
3616    FieldDecl *getField() const {
3617      assert(Kind == FieldDesignator && "Only valid on a field designator");
3618      if (Field.NameOrField & 0x01)
3619        return 0;
3620      else
3621        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3622    }
3623
3624    void setField(FieldDecl *FD) {
3625      assert(Kind == FieldDesignator && "Only valid on a field designator");
3626      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3627    }
3628
3629    SourceLocation getDotLoc() const {
3630      assert(Kind == FieldDesignator && "Only valid on a field designator");
3631      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3632    }
3633
3634    SourceLocation getFieldLoc() const {
3635      assert(Kind == FieldDesignator && "Only valid on a field designator");
3636      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3637    }
3638
3639    SourceLocation getLBracketLoc() const {
3640      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3641             "Only valid on an array or array-range designator");
3642      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3643    }
3644
3645    SourceLocation getRBracketLoc() const {
3646      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3647             "Only valid on an array or array-range designator");
3648      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3649    }
3650
3651    SourceLocation getEllipsisLoc() const {
3652      assert(Kind == ArrayRangeDesignator &&
3653             "Only valid on an array-range designator");
3654      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3655    }
3656
3657    unsigned getFirstExprIndex() const {
3658      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3659             "Only valid on an array or array-range designator");
3660      return ArrayOrRange.Index;
3661    }
3662
3663    SourceLocation getStartLocation() const {
3664      if (Kind == FieldDesignator)
3665        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3666      else
3667        return getLBracketLoc();
3668    }
3669    SourceLocation getEndLocation() const {
3670      return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
3671    }
3672    SourceRange getSourceRange() const {
3673      return SourceRange(getStartLocation(), getEndLocation());
3674    }
3675  };
3676
3677  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3678                                    unsigned NumDesignators,
3679                                    Expr **IndexExprs, unsigned NumIndexExprs,
3680                                    SourceLocation EqualOrColonLoc,
3681                                    bool GNUSyntax, Expr *Init);
3682
3683  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3684
3685  /// @brief Returns the number of designators in this initializer.
3686  unsigned size() const { return NumDesignators; }
3687
3688  // Iterator access to the designators.
3689  typedef Designator *designators_iterator;
3690  designators_iterator designators_begin() { return Designators; }
3691  designators_iterator designators_end() {
3692    return Designators + NumDesignators;
3693  }
3694
3695  typedef const Designator *const_designators_iterator;
3696  const_designators_iterator designators_begin() const { return Designators; }
3697  const_designators_iterator designators_end() const {
3698    return Designators + NumDesignators;
3699  }
3700
3701  typedef std::reverse_iterator<designators_iterator>
3702          reverse_designators_iterator;
3703  reverse_designators_iterator designators_rbegin() {
3704    return reverse_designators_iterator(designators_end());
3705  }
3706  reverse_designators_iterator designators_rend() {
3707    return reverse_designators_iterator(designators_begin());
3708  }
3709
3710  typedef std::reverse_iterator<const_designators_iterator>
3711          const_reverse_designators_iterator;
3712  const_reverse_designators_iterator designators_rbegin() const {
3713    return const_reverse_designators_iterator(designators_end());
3714  }
3715  const_reverse_designators_iterator designators_rend() const {
3716    return const_reverse_designators_iterator(designators_begin());
3717  }
3718
3719  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3720
3721  void setDesignators(ASTContext &C, const Designator *Desigs,
3722                      unsigned NumDesigs);
3723
3724  Expr *getArrayIndex(const Designator& D);
3725  Expr *getArrayRangeStart(const Designator& D);
3726  Expr *getArrayRangeEnd(const Designator& D);
3727
3728  /// @brief Retrieve the location of the '=' that precedes the
3729  /// initializer value itself, if present.
3730  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3731  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3732
3733  /// @brief Determines whether this designated initializer used the
3734  /// deprecated GNU syntax for designated initializers.
3735  bool usesGNUSyntax() const { return GNUSyntax; }
3736  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3737
3738  /// @brief Retrieve the initializer value.
3739  Expr *getInit() const {
3740    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3741  }
3742
3743  void setInit(Expr *init) {
3744    *child_begin() = init;
3745  }
3746
3747  /// \brief Retrieve the total number of subexpressions in this
3748  /// designated initializer expression, including the actual
3749  /// initialized value and any expressions that occur within array
3750  /// and array-range designators.
3751  unsigned getNumSubExprs() const { return NumSubExprs; }
3752
3753  Expr *getSubExpr(unsigned Idx) {
3754    assert(Idx < NumSubExprs && "Subscript out of range");
3755    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3756    Ptr += sizeof(DesignatedInitExpr);
3757    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3758  }
3759
3760  void setSubExpr(unsigned Idx, Expr *E) {
3761    assert(Idx < NumSubExprs && "Subscript out of range");
3762    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3763    Ptr += sizeof(DesignatedInitExpr);
3764    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3765  }
3766
3767  /// \brief Replaces the designator at index @p Idx with the series
3768  /// of designators in [First, Last).
3769  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3770                        const Designator *Last);
3771
3772  SourceRange getDesignatorsSourceRange() const;
3773
3774  SourceRange getSourceRange() const;
3775
3776  static bool classof(const Stmt *T) {
3777    return T->getStmtClass() == DesignatedInitExprClass;
3778  }
3779  static bool classof(const DesignatedInitExpr *) { return true; }
3780
3781  // Iterators
3782  child_range children() {
3783    Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
3784    return child_range(begin, begin + NumSubExprs);
3785  }
3786};
3787
3788/// \brief Represents an implicitly-generated value initialization of
3789/// an object of a given type.
3790///
3791/// Implicit value initializations occur within semantic initializer
3792/// list expressions (InitListExpr) as placeholders for subobject
3793/// initializations not explicitly specified by the user.
3794///
3795/// \see InitListExpr
3796class ImplicitValueInitExpr : public Expr {
3797public:
3798  explicit ImplicitValueInitExpr(QualType ty)
3799    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
3800           false, false, ty->isInstantiationDependentType(), false) { }
3801
3802  /// \brief Construct an empty implicit value initialization.
3803  explicit ImplicitValueInitExpr(EmptyShell Empty)
3804    : Expr(ImplicitValueInitExprClass, Empty) { }
3805
3806  static bool classof(const Stmt *T) {
3807    return T->getStmtClass() == ImplicitValueInitExprClass;
3808  }
3809  static bool classof(const ImplicitValueInitExpr *) { return true; }
3810
3811  SourceRange getSourceRange() const {
3812    return SourceRange();
3813  }
3814
3815  // Iterators
3816  child_range children() { return child_range(); }
3817};
3818
3819
3820class ParenListExpr : public Expr {
3821  Stmt **Exprs;
3822  unsigned NumExprs;
3823  SourceLocation LParenLoc, RParenLoc;
3824
3825public:
3826  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3827                unsigned numexprs, SourceLocation rparenloc, QualType T);
3828
3829  /// \brief Build an empty paren list.
3830  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3831
3832  unsigned getNumExprs() const { return NumExprs; }
3833
3834  const Expr* getExpr(unsigned Init) const {
3835    assert(Init < getNumExprs() && "Initializer access out of range!");
3836    return cast_or_null<Expr>(Exprs[Init]);
3837  }
3838
3839  Expr* getExpr(unsigned Init) {
3840    assert(Init < getNumExprs() && "Initializer access out of range!");
3841    return cast_or_null<Expr>(Exprs[Init]);
3842  }
3843
3844  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3845
3846  SourceLocation getLParenLoc() const { return LParenLoc; }
3847  SourceLocation getRParenLoc() const { return RParenLoc; }
3848
3849  SourceRange getSourceRange() const {
3850    return SourceRange(LParenLoc, RParenLoc);
3851  }
3852  static bool classof(const Stmt *T) {
3853    return T->getStmtClass() == ParenListExprClass;
3854  }
3855  static bool classof(const ParenListExpr *) { return true; }
3856
3857  // Iterators
3858  child_range children() {
3859    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
3860  }
3861
3862  friend class ASTStmtReader;
3863  friend class ASTStmtWriter;
3864};
3865
3866
3867/// \brief Represents a C1X generic selection.
3868///
3869/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling
3870/// expression, followed by one or more generic associations.  Each generic
3871/// association specifies a type name and an expression, or "default" and an
3872/// expression (in which case it is known as a default generic association).
3873/// The type and value of the generic selection are identical to those of its
3874/// result expression, which is defined as the expression in the generic
3875/// association with a type name that is compatible with the type of the
3876/// controlling expression, or the expression in the default generic association
3877/// if no types are compatible.  For example:
3878///
3879/// @code
3880/// _Generic(X, double: 1, float: 2, default: 3)
3881/// @endcode
3882///
3883/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
3884/// or 3 if "hello".
3885///
3886/// As an extension, generic selections are allowed in C++, where the following
3887/// additional semantics apply:
3888///
3889/// Any generic selection whose controlling expression is type-dependent or
3890/// which names a dependent type in its association list is result-dependent,
3891/// which means that the choice of result expression is dependent.
3892/// Result-dependent generic associations are both type- and value-dependent.
3893class GenericSelectionExpr : public Expr {
3894  enum { CONTROLLING, END_EXPR };
3895  TypeSourceInfo **AssocTypes;
3896  Stmt **SubExprs;
3897  unsigned NumAssocs, ResultIndex;
3898  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
3899
3900public:
3901  GenericSelectionExpr(ASTContext &Context,
3902                       SourceLocation GenericLoc, Expr *ControllingExpr,
3903                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3904                       unsigned NumAssocs, SourceLocation DefaultLoc,
3905                       SourceLocation RParenLoc,
3906                       bool ContainsUnexpandedParameterPack,
3907                       unsigned ResultIndex);
3908
3909  /// This constructor is used in the result-dependent case.
3910  GenericSelectionExpr(ASTContext &Context,
3911                       SourceLocation GenericLoc, Expr *ControllingExpr,
3912                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3913                       unsigned NumAssocs, SourceLocation DefaultLoc,
3914                       SourceLocation RParenLoc,
3915                       bool ContainsUnexpandedParameterPack);
3916
3917  explicit GenericSelectionExpr(EmptyShell Empty)
3918    : Expr(GenericSelectionExprClass, Empty) { }
3919
3920  unsigned getNumAssocs() const { return NumAssocs; }
3921
3922  SourceLocation getGenericLoc() const { return GenericLoc; }
3923  SourceLocation getDefaultLoc() const { return DefaultLoc; }
3924  SourceLocation getRParenLoc() const { return RParenLoc; }
3925
3926  const Expr *getAssocExpr(unsigned i) const {
3927    return cast<Expr>(SubExprs[END_EXPR+i]);
3928  }
3929  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
3930
3931  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
3932    return AssocTypes[i];
3933  }
3934  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
3935
3936  QualType getAssocType(unsigned i) const {
3937    if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
3938      return TS->getType();
3939    else
3940      return QualType();
3941  }
3942
3943  const Expr *getControllingExpr() const {
3944    return cast<Expr>(SubExprs[CONTROLLING]);
3945  }
3946  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
3947
3948  /// Whether this generic selection is result-dependent.
3949  bool isResultDependent() const { return ResultIndex == -1U; }
3950
3951  /// The zero-based index of the result expression's generic association in
3952  /// the generic selection's association list.  Defined only if the
3953  /// generic selection is not result-dependent.
3954  unsigned getResultIndex() const {
3955    assert(!isResultDependent() && "Generic selection is result-dependent");
3956    return ResultIndex;
3957  }
3958
3959  /// The generic selection's result expression.  Defined only if the
3960  /// generic selection is not result-dependent.
3961  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
3962  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
3963
3964  SourceRange getSourceRange() const {
3965    return SourceRange(GenericLoc, RParenLoc);
3966  }
3967  static bool classof(const Stmt *T) {
3968    return T->getStmtClass() == GenericSelectionExprClass;
3969  }
3970  static bool classof(const GenericSelectionExpr *) { return true; }
3971
3972  child_range children() {
3973    return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
3974  }
3975
3976  friend class ASTStmtReader;
3977};
3978
3979//===----------------------------------------------------------------------===//
3980// Clang Extensions
3981//===----------------------------------------------------------------------===//
3982
3983
3984/// ExtVectorElementExpr - This represents access to specific elements of a
3985/// vector, and may occur on the left hand side or right hand side.  For example
3986/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3987///
3988/// Note that the base may have either vector or pointer to vector type, just
3989/// like a struct field reference.
3990///
3991class ExtVectorElementExpr : public Expr {
3992  Stmt *Base;
3993  IdentifierInfo *Accessor;
3994  SourceLocation AccessorLoc;
3995public:
3996  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
3997                       IdentifierInfo &accessor, SourceLocation loc)
3998    : Expr(ExtVectorElementExprClass, ty, VK,
3999           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4000           base->isTypeDependent(), base->isValueDependent(),
4001           base->isInstantiationDependent(),
4002           base->containsUnexpandedParameterPack()),
4003      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4004
4005  /// \brief Build an empty vector element expression.
4006  explicit ExtVectorElementExpr(EmptyShell Empty)
4007    : Expr(ExtVectorElementExprClass, Empty) { }
4008
4009  const Expr *getBase() const { return cast<Expr>(Base); }
4010  Expr *getBase() { return cast<Expr>(Base); }
4011  void setBase(Expr *E) { Base = E; }
4012
4013  IdentifierInfo &getAccessor() const { return *Accessor; }
4014  void setAccessor(IdentifierInfo *II) { Accessor = II; }
4015
4016  SourceLocation getAccessorLoc() const { return AccessorLoc; }
4017  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4018
4019  /// getNumElements - Get the number of components being selected.
4020  unsigned getNumElements() const;
4021
4022  /// containsDuplicateElements - Return true if any element access is
4023  /// repeated.
4024  bool containsDuplicateElements() const;
4025
4026  /// getEncodedElementAccess - Encode the elements accessed into an llvm
4027  /// aggregate Constant of ConstantInt(s).
4028  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
4029
4030  SourceRange getSourceRange() const {
4031    return SourceRange(getBase()->getLocStart(), AccessorLoc);
4032  }
4033
4034  /// isArrow - Return true if the base expression is a pointer to vector,
4035  /// return false if the base expression is a vector.
4036  bool isArrow() const;
4037
4038  static bool classof(const Stmt *T) {
4039    return T->getStmtClass() == ExtVectorElementExprClass;
4040  }
4041  static bool classof(const ExtVectorElementExpr *) { return true; }
4042
4043  // Iterators
4044  child_range children() { return child_range(&Base, &Base+1); }
4045};
4046
4047
4048/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4049/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4050class BlockExpr : public Expr {
4051protected:
4052  BlockDecl *TheBlock;
4053public:
4054  BlockExpr(BlockDecl *BD, QualType ty)
4055    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4056           ty->isDependentType(), false,
4057           // FIXME: Check for instantiate-dependence in the statement?
4058           ty->isInstantiationDependentType(),
4059           false),
4060      TheBlock(BD) {}
4061
4062  /// \brief Build an empty block expression.
4063  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4064
4065  const BlockDecl *getBlockDecl() const { return TheBlock; }
4066  BlockDecl *getBlockDecl() { return TheBlock; }
4067  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4068
4069  // Convenience functions for probing the underlying BlockDecl.
4070  SourceLocation getCaretLocation() const;
4071  const Stmt *getBody() const;
4072  Stmt *getBody();
4073
4074  SourceRange getSourceRange() const {
4075    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
4076  }
4077
4078  /// getFunctionType - Return the underlying function type for this block.
4079  const FunctionType *getFunctionType() const;
4080
4081  static bool classof(const Stmt *T) {
4082    return T->getStmtClass() == BlockExprClass;
4083  }
4084  static bool classof(const BlockExpr *) { return true; }
4085
4086  // Iterators
4087  child_range children() { return child_range(); }
4088};
4089
4090/// BlockDeclRefExpr - A reference to a local variable declared in an
4091/// enclosing scope.
4092class BlockDeclRefExpr : public Expr {
4093  VarDecl *D;
4094  SourceLocation Loc;
4095  bool IsByRef : 1;
4096  bool ConstQualAdded : 1;
4097public:
4098  BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
4099                   SourceLocation l, bool ByRef, bool constAdded = false);
4100
4101  // \brief Build an empty reference to a declared variable in a
4102  // block.
4103  explicit BlockDeclRefExpr(EmptyShell Empty)
4104    : Expr(BlockDeclRefExprClass, Empty) { }
4105
4106  VarDecl *getDecl() { return D; }
4107  const VarDecl *getDecl() const { return D; }
4108  void setDecl(VarDecl *VD) { D = VD; }
4109
4110  SourceLocation getLocation() const { return Loc; }
4111  void setLocation(SourceLocation L) { Loc = L; }
4112
4113  SourceRange getSourceRange() const { return SourceRange(Loc); }
4114
4115  bool isByRef() const { return IsByRef; }
4116  void setByRef(bool BR) { IsByRef = BR; }
4117
4118  bool isConstQualAdded() const { return ConstQualAdded; }
4119  void setConstQualAdded(bool C) { ConstQualAdded = C; }
4120
4121  static bool classof(const Stmt *T) {
4122    return T->getStmtClass() == BlockDeclRefExprClass;
4123  }
4124  static bool classof(const BlockDeclRefExpr *) { return true; }
4125
4126  // Iterators
4127  child_range children() { return child_range(); }
4128};
4129
4130/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4131/// This AST node provides support for reinterpreting a type to another
4132/// type of the same size.
4133class AsTypeExpr : public Expr {
4134private:
4135  Expr* SrcExpr;
4136  QualType DstType;
4137  SourceLocation BuiltinLoc, RParenLoc;
4138
4139public:
4140  AsTypeExpr(Expr* SrcExpr, QualType DstType,
4141             ExprValueKind VK, ExprObjectKind OK,
4142             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4143    : Expr(AsTypeExprClass, DstType, VK, OK,
4144           DstType->isDependentType(),
4145           DstType->isDependentType() || SrcExpr->isValueDependent(),
4146           (DstType->isInstantiationDependentType() ||
4147            SrcExpr->isInstantiationDependent()),
4148           (DstType->containsUnexpandedParameterPack() ||
4149            SrcExpr->containsUnexpandedParameterPack())),
4150  SrcExpr(SrcExpr), DstType(DstType),
4151  BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4152
4153  /// \brief Build an empty __builtin_astype
4154  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4155
4156  /// getSrcExpr - Return the Expr to be converted.
4157  Expr *getSrcExpr() const { return SrcExpr; }
4158  QualType getDstType() const { return DstType; }
4159
4160  SourceRange getSourceRange() const {
4161    return SourceRange(BuiltinLoc, RParenLoc);
4162  }
4163
4164  static bool classof(const Stmt *T) {
4165    return T->getStmtClass() == AsTypeExprClass;
4166  }
4167  static bool classof(const AsTypeExpr *) { return true; }
4168
4169  // Iterators
4170  child_range children() { return child_range(); }
4171};
4172}  // end namespace clang
4173
4174#endif
4175