Expr.h revision cdef2b75aa60cde1ca00e0aa3f89139ac89c6ae4
1639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//
3639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//                     The LLVM Compiler Infrastructure
4639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//
5639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org// This file is distributed under the University of Illinois Open Source
6639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org// License. See LICENSE.TXT for details.
7639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//
8639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//===----------------------------------------------------------------------===//
9639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//
10639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//  This file defines the Expr interface and subclasses.
11639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//
12639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org//===----------------------------------------------------------------------===//
13639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
14639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#ifndef LLVM_CLANG_AST_EXPR_H
15639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#define LLVM_CLANG_AST_EXPR_H
16639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
17639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include "clang/AST/APValue.h"
18639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include "clang/AST/Stmt.h"
19639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include "clang/AST/Type.h"
20639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include "llvm/ADT/APSInt.h"
21639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include "llvm/ADT/APFloat.h"
22639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include "llvm/ADT/SmallVector.h"
23639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org#include <vector>
24639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
25639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.orgnamespace clang {
26639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class ASTContext;
27639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class APValue;
28639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class Decl;
29639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class IdentifierInfo;
30639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class ParmVarDecl;
31639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class NamedDecl;
3263ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  class ValueDecl;
33639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class BlockDecl;
34639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class CXXOperatorCallExpr;
35639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  class CXXMemberCallExpr;
36639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
37639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org/// Expr - This represents one expression.  Note that Expr's are subclasses of
38639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org/// Stmt.  This allows an expression to be transparently used any place a Stmt
39639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org/// is required.
4037be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org///
41639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.orgclass Expr : public Stmt {
42639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  QualType TR;
43639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
44639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.orgprotected:
4537be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org  /// TypeDependent - Whether this expression is type-dependent
4663ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// (C++ [temp.dep.expr]).
47639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  bool TypeDependent : 1;
48639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
49639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// ValueDependent - Whether this expression is value-dependent
5063ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// (C++ [temp.dep.constexpr]).
5137be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org  bool ValueDependent : 1;
52639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
53639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  // FIXME: Eventually, this constructor should go away and we should
54639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  // require every subclass to provide type/value-dependence
55639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  // information.
5663ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  Expr(StmtClass SC, QualType T)
5763ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org    : Stmt(SC), TypeDependent(false), ValueDependent(false) {
58639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    setType(T);
59639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  }
60639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
61639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  Expr(StmtClass SC, QualType T, bool TD, bool VD)
62639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    : Stmt(SC), TypeDependent(TD), ValueDependent(VD) {
63639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    setType(T);
64639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  }
65639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
66639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// \brief Construct an empty expression.
67639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
68639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
69639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.orgpublic:
70639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  QualType getType() const { return TR; }
71639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  void setType(QualType t) {
72639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    // In C++, the type of an expression is always adjusted so that it
73639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    // will not have reference type an expression will never have
74639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    // reference type (C++ [expr]p6). Use
7563ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org    // QualType::getNonReferenceType() to retrieve the non-reference
7663ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org    // type. Additionally, inspect Expr::isLvalue to determine whether
77639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    // an expression that is adjusted in this manner should be
78639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    // considered an lvalue.
79639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    assert((TR.isNull() || !TR->isReferenceType()) &&
80639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org           "Expressions can't have reference type");
81639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
82639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org    TR = t;
83639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  }
84639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
85639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// isValueDependent - Determines whether this expression is
86639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
87639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// array bound of "Chars" in the following example is
88639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// value-dependent.
89639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// @code
90639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// template<int Size, char (&Chars)[Size]> struct meta_string;
91639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// @endcode
92639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  bool isValueDependent() const { return ValueDependent; }
93639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
94639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// \brief Set whether this expression is value-dependent or not.
95639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  void setValueDependent(bool VD) { ValueDependent = VD; }
96639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
97639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// isTypeDependent - Determines whether this expression is
98639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// type-dependent (C++ [temp.dep.expr]), which means that its type
99639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// could change from one template instantiation to the next. For
100639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// example, the expressions "x" and "x + y" are type-dependent in
101639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// the following code, but "y" is not type-dependent:
102639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// @code
103639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// template<typename T>
104639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// void add(T x, int y) {
105639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  ///   x + y;
106639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// }
107639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// @endcode
108639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  bool isTypeDependent() const { return TypeDependent; }
109639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org
110639bac0c5319f96e1bbe3399fb7f7f37344928bddslomov@chromium.org  /// \brief Set whether this expression is type-dependent or not.
11163ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  void setTypeDependent(bool TD) { TypeDependent = TD; }
11263ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org
11363ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// SourceLocation tokens are not useful in isolation - they are low level
11463ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// value objects created/interpreted by SourceManager. We assume AST
11563ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// clients will have a pointer to the respective SourceManager.
11663ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  virtual SourceRange getSourceRange() const = 0;
11763ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org
11863ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// getExprLoc - Return the preferred location for the arrow when diagnosing
11963ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// a problem with a generic expression.
12063ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  virtual SourceLocation getExprLoc() const { return getLocStart(); }
12163ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org
12263ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// isUnusedResultAWarning - Return true if this immediate expression should
12363ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
12463ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// with location to warn on and the source range[s] to report with the
12563ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// warning.
12637be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
12737be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org                              SourceRange &R2) const;
12837be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org
12963ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
13063ea3d20e0c5531a4bb0853218d5f746117edea1mvstanton@chromium.org  /// incomplete type other than void. Nonarray expressions that can be lvalues:
13137be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org  ///  - name, where name must be a variable
13237be408adf363bbe682921a4a690752fa0ec33femachenbach@chromium.org  ///  - e[i]
133  ///  - (e), where e must be an lvalue
134  ///  - e.name, where e must be an lvalue
135  ///  - e->name
136  ///  - *e, the type of e cannot be a function type
137  ///  - string-constant
138  ///  - reference type [C++ [expr]]
139  ///  - b ? x : y, where x and y are lvalues of suitable types [C++]
140  ///
141  enum isLvalueResult {
142    LV_Valid,
143    LV_NotObjectType,
144    LV_IncompleteVoidType,
145    LV_DuplicateVectorComponents,
146    LV_InvalidExpression,
147    LV_MemberFunction
148  };
149  isLvalueResult isLvalue(ASTContext &Ctx) const;
150
151  // Same as above, but excluding checks for non-object and void types in C
152  isLvalueResult isLvalueInternal(ASTContext &Ctx) const;
153
154  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
155  /// does not have an incomplete type, does not have a const-qualified type,
156  /// and if it is a structure or union, does not have any member (including,
157  /// recursively, any member or element of all contained aggregates or unions)
158  /// with a const-qualified type.
159  ///
160  /// \param Loc [in] [out] - A source location which *may* be filled
161  /// in with the location of the expression making this a
162  /// non-modifiable lvalue, if specified.
163  enum isModifiableLvalueResult {
164    MLV_Valid,
165    MLV_NotObjectType,
166    MLV_IncompleteVoidType,
167    MLV_DuplicateVectorComponents,
168    MLV_InvalidExpression,
169    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
170    MLV_IncompleteType,
171    MLV_ConstQualified,
172    MLV_ArrayType,
173    MLV_NotBlockQualified,
174    MLV_ReadonlyProperty,
175    MLV_NoSetterProperty,
176    MLV_MemberFunction
177  };
178  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
179                                              SourceLocation *Loc = 0) const;
180
181  /// \brief If this expression refers to a bit-field, retrieve the
182  /// declaration of that bit-field.
183  FieldDecl *getBitField();
184
185  const FieldDecl *getBitField() const {
186    return const_cast<Expr*>(this)->getBitField();
187  }
188
189  /// isIntegerConstantExpr - Return true if this expression is a valid integer
190  /// constant expression, and, if so, return its value in Result.  If not a
191  /// valid i-c-e, return false and fill in Loc (if specified) with the location
192  /// of the invalid expression.
193  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
194                             SourceLocation *Loc = 0,
195                             bool isEvaluated = true) const;
196  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
197    llvm::APSInt X;
198    return isIntegerConstantExpr(X, Ctx, Loc);
199  }
200  /// isConstantInitializer - Returns true if this expression is a constant
201  /// initializer, which can be emitted at compile-time.
202  bool isConstantInitializer(ASTContext &Ctx) const;
203
204  /// EvalResult is a struct with detailed info about an evaluated expression.
205  struct EvalResult {
206    /// Val - This is the value the expression can be folded to.
207    APValue Val;
208
209    /// HasSideEffects - Whether the evaluated expression has side effects.
210    /// For example, (f() && 0) can be folded, but it still has side effects.
211    bool HasSideEffects;
212
213    /// Diag - If the expression is unfoldable, then Diag contains a note
214    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
215    /// position for the error, and DiagExpr is the expression that caused
216    /// the error.
217    /// If the expression is foldable, but not an integer constant expression,
218    /// Diag contains a note diagnostic that describes why it isn't an integer
219    /// constant expression. If the expression *is* an integer constant
220    /// expression, then Diag will be zero.
221    unsigned Diag;
222    const Expr *DiagExpr;
223    SourceLocation DiagLoc;
224
225    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
226  };
227
228  /// Evaluate - Return true if this is a constant which we can fold using
229  /// any crazy technique (that has nothing to do with language standards) that
230  /// we want to.  If this function returns true, it returns the folded constant
231  /// in Result.
232  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
233
234  /// isEvaluatable - Call Evaluate to see if this expression can be constant
235  /// folded, but discard the result.
236  bool isEvaluatable(ASTContext &Ctx) const;
237
238  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
239  /// must be called on an expression that constant folds to an integer.
240  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
241
242  /// EvaluateAsLValue - Evaluate an expression to see if it's a valid LValue.
243  bool EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const;
244
245  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
246  /// integer constant expression with the value zero, or if this is one that is
247  /// cast to void*.
248  bool isNullPointerConstant(ASTContext &Ctx) const;
249
250  /// hasGlobalStorage - Return true if this expression has static storage
251  /// duration.  This means that the address of this expression is a link-time
252  /// constant.
253  bool hasGlobalStorage() const;
254
255  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
256  /// write barrier.
257  bool isOBJCGCCandidate(ASTContext &Ctx) const;
258
259  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
260  ///  its subexpression.  If that subexpression is also a ParenExpr,
261  ///  then this method recursively returns its subexpression, and so forth.
262  ///  Otherwise, the method returns the current Expr.
263  Expr* IgnoreParens();
264
265  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
266  /// or CastExprs, returning their operand.
267  Expr *IgnoreParenCasts();
268
269  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
270  /// value (including ptr->int casts of the same size).  Strip off any
271  /// ParenExpr or CastExprs, returning their operand.
272  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
273
274  const Expr* IgnoreParens() const {
275    return const_cast<Expr*>(this)->IgnoreParens();
276  }
277  const Expr *IgnoreParenCasts() const {
278    return const_cast<Expr*>(this)->IgnoreParenCasts();
279  }
280  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
281    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
282  }
283
284  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
285  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
286
287  static bool classof(const Stmt *T) {
288    return T->getStmtClass() >= firstExprConstant &&
289           T->getStmtClass() <= lastExprConstant;
290  }
291  static bool classof(const Expr *) { return true; }
292};
293
294
295//===----------------------------------------------------------------------===//
296// Primary Expressions.
297//===----------------------------------------------------------------------===//
298
299/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
300/// enum, etc.
301class DeclRefExpr : public Expr {
302  NamedDecl *D;
303  SourceLocation Loc;
304
305protected:
306  // FIXME: Eventually, this constructor will go away and all subclasses
307  // will have to provide the type- and value-dependent flags.
308  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l) :
309    Expr(SC, t), D(d), Loc(l) {}
310
311  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l, bool TD,
312              bool VD) :
313    Expr(SC, t, TD, VD), D(d), Loc(l) {}
314
315public:
316  // FIXME: Eventually, this constructor will go away and all clients
317  // will have to provide the type- and value-dependent flags.
318  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) :
319    Expr(DeclRefExprClass, t), D(d), Loc(l) {}
320
321  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD) :
322    Expr(DeclRefExprClass, t, TD, VD), D(d), Loc(l) {}
323
324  /// \brief Construct an empty declaration reference expression.
325  explicit DeclRefExpr(EmptyShell Empty)
326    : Expr(DeclRefExprClass, Empty) { }
327
328  NamedDecl *getDecl() { return D; }
329  const NamedDecl *getDecl() const { return D; }
330  void setDecl(NamedDecl *NewD) { D = NewD; }
331
332  SourceLocation getLocation() const { return Loc; }
333  void setLocation(SourceLocation L) { Loc = L; }
334  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
335
336  static bool classof(const Stmt *T) {
337    return T->getStmtClass() == DeclRefExprClass ||
338           T->getStmtClass() == CXXConditionDeclExprClass ||
339           T->getStmtClass() == QualifiedDeclRefExprClass;
340  }
341  static bool classof(const DeclRefExpr *) { return true; }
342
343  // Iterators
344  virtual child_iterator child_begin();
345  virtual child_iterator child_end();
346};
347
348/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
349class PredefinedExpr : public Expr {
350public:
351  enum IdentType {
352    Func,
353    Function,
354    PrettyFunction
355  };
356
357private:
358  SourceLocation Loc;
359  IdentType Type;
360public:
361  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
362    : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {}
363
364  /// \brief Construct an empty predefined expression.
365  explicit PredefinedExpr(EmptyShell Empty)
366    : Expr(PredefinedExprClass, Empty) { }
367
368  PredefinedExpr* Clone(ASTContext &C) const;
369
370  IdentType getIdentType() const { return Type; }
371  void setIdentType(IdentType IT) { Type = IT; }
372
373  SourceLocation getLocation() const { return Loc; }
374  void setLocation(SourceLocation L) { Loc = L; }
375
376  // FIXME: The logic for computing the value of a predefined expr should go
377  // into a method here that takes the inner-most code decl (a block, function
378  // or objc method) that the expr lives in.  This would allow sema and codegen
379  // to be consistent for things like sizeof(__func__) etc.
380
381  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
382
383  static bool classof(const Stmt *T) {
384    return T->getStmtClass() == PredefinedExprClass;
385  }
386  static bool classof(const PredefinedExpr *) { return true; }
387
388  // Iterators
389  virtual child_iterator child_begin();
390  virtual child_iterator child_end();
391};
392
393class IntegerLiteral : public Expr {
394  llvm::APInt Value;
395  SourceLocation Loc;
396public:
397  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
398  // or UnsignedLongLongTy
399  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
400    : Expr(IntegerLiteralClass, type), Value(V), Loc(l) {
401    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
402  }
403
404  /// \brief Construct an empty integer literal.
405  explicit IntegerLiteral(EmptyShell Empty)
406    : Expr(IntegerLiteralClass, Empty) { }
407
408  IntegerLiteral* Clone(ASTContext &C) const;
409
410  const llvm::APInt &getValue() const { return Value; }
411  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
412
413  /// \brief Retrieve the location of the literal.
414  SourceLocation getLocation() const { return Loc; }
415
416  void setValue(const llvm::APInt &Val) { Value = Val; }
417  void setLocation(SourceLocation Location) { Loc = Location; }
418
419  static bool classof(const Stmt *T) {
420    return T->getStmtClass() == IntegerLiteralClass;
421  }
422  static bool classof(const IntegerLiteral *) { return true; }
423
424  // Iterators
425  virtual child_iterator child_begin();
426  virtual child_iterator child_end();
427};
428
429class CharacterLiteral : public Expr {
430  unsigned Value;
431  SourceLocation Loc;
432  bool IsWide;
433public:
434  // type should be IntTy
435  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
436    : Expr(CharacterLiteralClass, type), Value(value), Loc(l), IsWide(iswide) {
437  }
438
439  /// \brief Construct an empty character literal.
440  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
441
442  CharacterLiteral* Clone(ASTContext &C) const;
443
444  SourceLocation getLoc() const { return Loc; }
445  bool isWide() const { return IsWide; }
446
447  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
448
449  unsigned getValue() const { return Value; }
450
451  void setLocation(SourceLocation Location) { Loc = Location; }
452  void setWide(bool W) { IsWide = W; }
453  void setValue(unsigned Val) { Value = Val; }
454
455  static bool classof(const Stmt *T) {
456    return T->getStmtClass() == CharacterLiteralClass;
457  }
458  static bool classof(const CharacterLiteral *) { return true; }
459
460  // Iterators
461  virtual child_iterator child_begin();
462  virtual child_iterator child_end();
463};
464
465class FloatingLiteral : public Expr {
466  llvm::APFloat Value;
467  bool IsExact : 1;
468  SourceLocation Loc;
469public:
470  FloatingLiteral(const llvm::APFloat &V, bool isexact,
471                  QualType Type, SourceLocation L)
472    : Expr(FloatingLiteralClass, Type), Value(V), IsExact(isexact), Loc(L) {}
473
474  /// \brief Construct an empty floating-point literal.
475  explicit FloatingLiteral(EmptyShell Empty)
476    : Expr(FloatingLiteralClass, Empty), Value(0.0) { }
477
478  FloatingLiteral* Clone(ASTContext &C) const;
479
480  const llvm::APFloat &getValue() const { return Value; }
481  void setValue(const llvm::APFloat &Val) { Value = Val; }
482
483  bool isExact() const { return IsExact; }
484  void setExact(bool E) { IsExact = E; }
485
486  /// getValueAsApproximateDouble - This returns the value as an inaccurate
487  /// double.  Note that this may cause loss of precision, but is useful for
488  /// debugging dumps, etc.
489  double getValueAsApproximateDouble() const;
490
491  SourceLocation getLocation() const { return Loc; }
492  void setLocation(SourceLocation L) { Loc = L; }
493
494  // FIXME: The logic for computing the value of a predefined expr should go
495  // into a method here that takes the inner-most code decl (a block, function
496  // or objc method) that the expr lives in.  This would allow sema and codegen
497  // to be consistent for things like sizeof(__func__) etc.
498
499  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
500
501  static bool classof(const Stmt *T) {
502    return T->getStmtClass() == FloatingLiteralClass;
503  }
504  static bool classof(const FloatingLiteral *) { return true; }
505
506  // Iterators
507  virtual child_iterator child_begin();
508  virtual child_iterator child_end();
509};
510
511/// ImaginaryLiteral - We support imaginary integer and floating point literals,
512/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
513/// IntegerLiteral classes.  Instances of this class always have a Complex type
514/// whose element type matches the subexpression.
515///
516class ImaginaryLiteral : public Expr {
517  Stmt *Val;
518public:
519  ImaginaryLiteral(Expr *val, QualType Ty)
520    : Expr(ImaginaryLiteralClass, Ty), Val(val) {}
521
522  /// \brief Build an empty imaginary literal.
523  explicit ImaginaryLiteral(EmptyShell Empty)
524    : Expr(ImaginaryLiteralClass, Empty) { }
525
526  const Expr *getSubExpr() const { return cast<Expr>(Val); }
527  Expr *getSubExpr() { return cast<Expr>(Val); }
528  void setSubExpr(Expr *E) { Val = E; }
529
530  ImaginaryLiteral* Clone(ASTContext &C) const;
531
532  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
533  static bool classof(const Stmt *T) {
534    return T->getStmtClass() == ImaginaryLiteralClass;
535  }
536  static bool classof(const ImaginaryLiteral *) { return true; }
537
538  // Iterators
539  virtual child_iterator child_begin();
540  virtual child_iterator child_end();
541};
542
543/// StringLiteral - This represents a string literal expression, e.g. "foo"
544/// or L"bar" (wide strings).  The actual string is returned by getStrData()
545/// is NOT null-terminated, and the length of the string is determined by
546/// calling getByteLength().  The C type for a string is always a
547/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
548/// not.
549///
550/// Note that strings in C can be formed by concatenation of multiple string
551/// literal pptokens in translation phase #6.  This keeps track of the locations
552/// of each of these pieces.
553///
554/// Strings in C can also be truncated and extended by assigning into arrays,
555/// e.g. with constructs like:
556///   char X[2] = "foobar";
557/// In this case, getByteLength() will return 6, but the string literal will
558/// have type "char[2]".
559class StringLiteral : public Expr {
560  const char *StrData;
561  unsigned ByteLength;
562  bool IsWide;
563  unsigned NumConcatenated;
564  SourceLocation TokLocs[1];
565
566  StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty) {}
567public:
568  /// This is the "fully general" constructor that allows representation of
569  /// strings formed from multiple concatenated tokens.
570  static StringLiteral *Create(ASTContext &C, const char *StrData,
571                               unsigned ByteLength, bool Wide, QualType Ty,
572                               const SourceLocation *Loc, unsigned NumStrs);
573
574  /// Simple constructor for string literals made from one token.
575  static StringLiteral *Create(ASTContext &C, const char *StrData,
576                               unsigned ByteLength,
577                               bool Wide, QualType Ty, SourceLocation Loc) {
578    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
579  }
580
581  /// \brief Construct an empty string literal.
582  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
583
584  StringLiteral* Clone(ASTContext &C) const;
585  void Destroy(ASTContext &C);
586
587  const char *getStrData() const { return StrData; }
588  unsigned getByteLength() const { return ByteLength; }
589
590  /// \brief Sets the string data to the given string data.
591  void setStrData(ASTContext &C, const char *Str, unsigned Len);
592
593  bool isWide() const { return IsWide; }
594  void setWide(bool W) { IsWide = W; }
595
596  bool containsNonAsciiOrNull() const {
597    for (unsigned i = 0; i < getByteLength(); ++i)
598      if (!isascii(getStrData()[i]) || !getStrData()[i])
599        return true;
600    return false;
601  }
602  /// getNumConcatenated - Get the number of string literal tokens that were
603  /// concatenated in translation phase #6 to form this string literal.
604  unsigned getNumConcatenated() const { return NumConcatenated; }
605
606  SourceLocation getStrTokenLoc(unsigned TokNum) const {
607    assert(TokNum < NumConcatenated && "Invalid tok number");
608    return TokLocs[TokNum];
609  }
610  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
611    assert(TokNum < NumConcatenated && "Invalid tok number");
612    TokLocs[TokNum] = L;
613  }
614
615  typedef const SourceLocation *tokloc_iterator;
616  tokloc_iterator tokloc_begin() const { return TokLocs; }
617  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
618
619  virtual SourceRange getSourceRange() const {
620    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
621  }
622  static bool classof(const Stmt *T) {
623    return T->getStmtClass() == StringLiteralClass;
624  }
625  static bool classof(const StringLiteral *) { return true; }
626
627  // Iterators
628  virtual child_iterator child_begin();
629  virtual child_iterator child_end();
630};
631
632/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
633/// AST node is only formed if full location information is requested.
634class ParenExpr : public Expr {
635  SourceLocation L, R;
636  Stmt *Val;
637public:
638  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
639    : Expr(ParenExprClass, val->getType(),
640           val->isTypeDependent(), val->isValueDependent()),
641      L(l), R(r), Val(val) {}
642
643  /// \brief Construct an empty parenthesized expression.
644  explicit ParenExpr(EmptyShell Empty)
645    : Expr(ParenExprClass, Empty) { }
646
647  const Expr *getSubExpr() const { return cast<Expr>(Val); }
648  Expr *getSubExpr() { return cast<Expr>(Val); }
649  void setSubExpr(Expr *E) { Val = E; }
650
651  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
652
653  /// \brief Get the location of the left parentheses '('.
654  SourceLocation getLParen() const { return L; }
655  void setLParen(SourceLocation Loc) { L = Loc; }
656
657  /// \brief Get the location of the right parentheses ')'.
658  SourceLocation getRParen() const { return R; }
659  void setRParen(SourceLocation Loc) { R = Loc; }
660
661  static bool classof(const Stmt *T) {
662    return T->getStmtClass() == ParenExprClass;
663  }
664  static bool classof(const ParenExpr *) { return true; }
665
666  // Iterators
667  virtual child_iterator child_begin();
668  virtual child_iterator child_end();
669};
670
671
672/// UnaryOperator - This represents the unary-expression's (except sizeof and
673/// alignof), the postinc/postdec operators from postfix-expression, and various
674/// extensions.
675///
676/// Notes on various nodes:
677///
678/// Real/Imag - These return the real/imag part of a complex operand.  If
679///   applied to a non-complex value, the former returns its operand and the
680///   later returns zero in the type of the operand.
681///
682/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
683///   subexpression is a compound literal with the various MemberExpr and
684///   ArraySubscriptExpr's applied to it.
685///
686class UnaryOperator : public Expr {
687public:
688  // Note that additions to this should also update the StmtVisitor class.
689  enum Opcode {
690    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
691    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
692    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
693    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
694    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
695    Real, Imag,       // "__real expr"/"__imag expr" Extension.
696    Extension,        // __extension__ marker.
697    OffsetOf          // __builtin_offsetof
698  };
699private:
700  Stmt *Val;
701  Opcode Opc;
702  SourceLocation Loc;
703public:
704
705  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
706    : Expr(UnaryOperatorClass, type,
707           input->isTypeDependent() && opc != OffsetOf,
708           input->isValueDependent()),
709      Val(input), Opc(opc), Loc(l) {}
710
711  /// \brief Build an empty unary operator.
712  explicit UnaryOperator(EmptyShell Empty)
713    : Expr(UnaryOperatorClass, Empty), Opc(AddrOf) { }
714
715  Opcode getOpcode() const { return Opc; }
716  void setOpcode(Opcode O) { Opc = O; }
717
718  Expr *getSubExpr() const { return cast<Expr>(Val); }
719  void setSubExpr(Expr *E) { Val = E; }
720
721  /// getOperatorLoc - Return the location of the operator.
722  SourceLocation getOperatorLoc() const { return Loc; }
723  void setOperatorLoc(SourceLocation L) { Loc = L; }
724
725  /// isPostfix - Return true if this is a postfix operation, like x++.
726  static bool isPostfix(Opcode Op) {
727    return Op == PostInc || Op == PostDec;
728  }
729
730  /// isPostfix - Return true if this is a prefix operation, like --x.
731  static bool isPrefix(Opcode Op) {
732    return Op == PreInc || Op == PreDec;
733  }
734
735  bool isPrefix() const { return isPrefix(Opc); }
736  bool isPostfix() const { return isPostfix(Opc); }
737  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
738  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
739  bool isOffsetOfOp() const { return Opc == OffsetOf; }
740  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
741  bool isArithmeticOp() const { return isArithmeticOp(Opc); }
742
743  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
744  /// corresponds to, e.g. "sizeof" or "[pre]++"
745  static const char *getOpcodeStr(Opcode Op);
746
747  /// \brief Retrieve the unary opcode that corresponds to the given
748  /// overloaded operator.
749  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
750
751  /// \brief Retrieve the overloaded operator kind that corresponds to
752  /// the given unary opcode.
753  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
754
755  virtual SourceRange getSourceRange() const {
756    if (isPostfix())
757      return SourceRange(Val->getLocStart(), Loc);
758    else
759      return SourceRange(Loc, Val->getLocEnd());
760  }
761  virtual SourceLocation getExprLoc() const { return Loc; }
762
763  static bool classof(const Stmt *T) {
764    return T->getStmtClass() == UnaryOperatorClass;
765  }
766  static bool classof(const UnaryOperator *) { return true; }
767
768  // Iterators
769  virtual child_iterator child_begin();
770  virtual child_iterator child_end();
771};
772
773/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
774/// types and expressions.
775class SizeOfAlignOfExpr : public Expr {
776  bool isSizeof : 1;  // true if sizeof, false if alignof.
777  bool isType : 1;    // true if operand is a type, false if an expression
778  union {
779    void *Ty;
780    Stmt *Ex;
781  } Argument;
782  SourceLocation OpLoc, RParenLoc;
783public:
784  SizeOfAlignOfExpr(bool issizeof, QualType T,
785                    QualType resultType, SourceLocation op,
786                    SourceLocation rp) :
787      Expr(SizeOfAlignOfExprClass, resultType,
788           false, // Never type-dependent (C++ [temp.dep.expr]p3).
789           // Value-dependent if the argument is type-dependent.
790           T->isDependentType()),
791      isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
792    Argument.Ty = T.getAsOpaquePtr();
793  }
794
795  SizeOfAlignOfExpr(bool issizeof, Expr *E,
796                    QualType resultType, SourceLocation op,
797                    SourceLocation rp) :
798      Expr(SizeOfAlignOfExprClass, resultType,
799           false, // Never type-dependent (C++ [temp.dep.expr]p3).
800           // Value-dependent if the argument is type-dependent.
801           E->isTypeDependent()),
802      isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
803    Argument.Ex = E;
804  }
805
806  /// \brief Construct an empty sizeof/alignof expression.
807  explicit SizeOfAlignOfExpr(EmptyShell Empty)
808    : Expr(SizeOfAlignOfExprClass, Empty) { }
809
810  virtual void Destroy(ASTContext& C);
811
812  bool isSizeOf() const { return isSizeof; }
813  void setSizeof(bool S) { isSizeof = S; }
814
815  bool isArgumentType() const { return isType; }
816  QualType getArgumentType() const {
817    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
818    return QualType::getFromOpaquePtr(Argument.Ty);
819  }
820  Expr *getArgumentExpr() {
821    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
822    return static_cast<Expr*>(Argument.Ex);
823  }
824  const Expr *getArgumentExpr() const {
825    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
826  }
827
828  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
829  void setArgument(QualType T) {
830    Argument.Ty = T.getAsOpaquePtr();
831    isType = true;
832  }
833
834  /// Gets the argument type, or the type of the argument expression, whichever
835  /// is appropriate.
836  QualType getTypeOfArgument() const {
837    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
838  }
839
840  SourceLocation getOperatorLoc() const { return OpLoc; }
841  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
842
843  SourceLocation getRParenLoc() const { return RParenLoc; }
844  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
845
846  virtual SourceRange getSourceRange() const {
847    return SourceRange(OpLoc, RParenLoc);
848  }
849
850  static bool classof(const Stmt *T) {
851    return T->getStmtClass() == SizeOfAlignOfExprClass;
852  }
853  static bool classof(const SizeOfAlignOfExpr *) { return true; }
854
855  // Iterators
856  virtual child_iterator child_begin();
857  virtual child_iterator child_end();
858};
859
860//===----------------------------------------------------------------------===//
861// Postfix Operators.
862//===----------------------------------------------------------------------===//
863
864/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
865class ArraySubscriptExpr : public Expr {
866  enum { LHS, RHS, END_EXPR=2 };
867  Stmt* SubExprs[END_EXPR];
868  SourceLocation RBracketLoc;
869public:
870  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
871                     SourceLocation rbracketloc)
872  : Expr(ArraySubscriptExprClass, t,
873         lhs->isTypeDependent() || rhs->isTypeDependent(),
874         lhs->isValueDependent() || rhs->isValueDependent()),
875    RBracketLoc(rbracketloc) {
876    SubExprs[LHS] = lhs;
877    SubExprs[RHS] = rhs;
878  }
879
880  /// \brief Create an empty array subscript expression.
881  explicit ArraySubscriptExpr(EmptyShell Shell)
882    : Expr(ArraySubscriptExprClass, Shell) { }
883
884  /// An array access can be written A[4] or 4[A] (both are equivalent).
885  /// - getBase() and getIdx() always present the normalized view: A[4].
886  ///    In this case getBase() returns "A" and getIdx() returns "4".
887  /// - getLHS() and getRHS() present the syntactic view. e.g. for
888  ///    4[A] getLHS() returns "4".
889  /// Note: Because vector element access is also written A[4] we must
890  /// predicate the format conversion in getBase and getIdx only on the
891  /// the type of the RHS, as it is possible for the LHS to be a vector of
892  /// integer type
893  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
894  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
895  void setLHS(Expr *E) { SubExprs[LHS] = E; }
896
897  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
898  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
899  void setRHS(Expr *E) { SubExprs[RHS] = E; }
900
901  Expr *getBase() {
902    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
903  }
904
905  const Expr *getBase() const {
906    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
907  }
908
909  Expr *getIdx() {
910    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
911  }
912
913  const Expr *getIdx() const {
914    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
915  }
916
917  virtual SourceRange getSourceRange() const {
918    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
919  }
920
921  SourceLocation getRBracketLoc() const { return RBracketLoc; }
922  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
923
924  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
925
926  static bool classof(const Stmt *T) {
927    return T->getStmtClass() == ArraySubscriptExprClass;
928  }
929  static bool classof(const ArraySubscriptExpr *) { return true; }
930
931  // Iterators
932  virtual child_iterator child_begin();
933  virtual child_iterator child_end();
934};
935
936
937/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
938/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
939/// while its subclasses may represent alternative syntax that (semantically)
940/// results in a function call. For example, CXXOperatorCallExpr is
941/// a subclass for overloaded operator calls that use operator syntax, e.g.,
942/// "str1 + str2" to resolve to a function call.
943class CallExpr : public Expr {
944  enum { FN=0, ARGS_START=1 };
945  Stmt **SubExprs;
946  unsigned NumArgs;
947  SourceLocation RParenLoc;
948
949protected:
950  // This version of the constructor is for derived classes.
951  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
952           QualType t, SourceLocation rparenloc);
953
954public:
955  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
956           SourceLocation rparenloc);
957
958  /// \brief Build an empty call expression.
959  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
960
961  ~CallExpr() {}
962
963  void Destroy(ASTContext& C);
964
965  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
966  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
967  void setCallee(Expr *F) { SubExprs[FN] = F; }
968
969  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
970  FunctionDecl *getDirectCallee();
971
972  /// getNumArgs - Return the number of actual arguments to this call.
973  ///
974  unsigned getNumArgs() const { return NumArgs; }
975
976  /// getArg - Return the specified argument.
977  Expr *getArg(unsigned Arg) {
978    assert(Arg < NumArgs && "Arg access out of range!");
979    return cast<Expr>(SubExprs[Arg+ARGS_START]);
980  }
981  const Expr *getArg(unsigned Arg) const {
982    assert(Arg < NumArgs && "Arg access out of range!");
983    return cast<Expr>(SubExprs[Arg+ARGS_START]);
984  }
985
986  /// setArg - Set the specified argument.
987  void setArg(unsigned Arg, Expr *ArgExpr) {
988    assert(Arg < NumArgs && "Arg access out of range!");
989    SubExprs[Arg+ARGS_START] = ArgExpr;
990  }
991
992  /// setNumArgs - This changes the number of arguments present in this call.
993  /// Any orphaned expressions are deleted by this, and any new operands are set
994  /// to null.
995  void setNumArgs(ASTContext& C, unsigned NumArgs);
996
997  typedef ExprIterator arg_iterator;
998  typedef ConstExprIterator const_arg_iterator;
999
1000  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
1001  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
1002  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
1003  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
1004
1005  /// getNumCommas - Return the number of commas that must have been present in
1006  /// this function call.
1007  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1008
1009  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1010  /// not, return 0.
1011  unsigned isBuiltinCall(ASTContext &Context) const;
1012
1013  /// getCallReturnType - Get the return type of the call expr. This is not
1014  /// always the type of the expr itself, if the return type is a reference
1015  /// type.
1016  QualType getCallReturnType() const;
1017
1018  SourceLocation getRParenLoc() const { return RParenLoc; }
1019  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1020
1021  virtual SourceRange getSourceRange() const {
1022    return SourceRange(getCallee()->getLocStart(), RParenLoc);
1023  }
1024
1025  static bool classof(const Stmt *T) {
1026    return T->getStmtClass() == CallExprClass ||
1027           T->getStmtClass() == CXXOperatorCallExprClass ||
1028           T->getStmtClass() == CXXMemberCallExprClass;
1029  }
1030  static bool classof(const CallExpr *) { return true; }
1031  static bool classof(const CXXOperatorCallExpr *) { return true; }
1032  static bool classof(const CXXMemberCallExpr *) { return true; }
1033
1034  // Iterators
1035  virtual child_iterator child_begin();
1036  virtual child_iterator child_end();
1037};
1038
1039/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1040///
1041class MemberExpr : public Expr {
1042  /// Base - the expression for the base pointer or structure references.  In
1043  /// X.F, this is "X".
1044  Stmt *Base;
1045
1046  /// MemberDecl - This is the decl being referenced by the field/member name.
1047  /// In X.F, this is the decl referenced by F.
1048  NamedDecl *MemberDecl;
1049
1050  /// MemberLoc - This is the location of the member name.
1051  SourceLocation MemberLoc;
1052
1053  /// IsArrow - True if this is "X->F", false if this is "X.F".
1054  bool IsArrow;
1055public:
1056  MemberExpr(Expr *base, bool isarrow, NamedDecl *memberdecl, SourceLocation l,
1057             QualType ty)
1058    : Expr(MemberExprClass, ty,
1059           base->isTypeDependent(), base->isValueDependent()),
1060      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
1061
1062  /// \brief Build an empty member reference expression.
1063  explicit MemberExpr(EmptyShell Empty) : Expr(MemberExprClass, Empty) { }
1064
1065  void setBase(Expr *E) { Base = E; }
1066  Expr *getBase() const { return cast<Expr>(Base); }
1067
1068  /// \brief Retrieve the member declaration to which this expression refers.
1069  ///
1070  /// The returned declaration will either be a FieldDecl or (in C++)
1071  /// a CXXMethodDecl.
1072  NamedDecl *getMemberDecl() const { return MemberDecl; }
1073  void setMemberDecl(NamedDecl *D) { MemberDecl = D; }
1074
1075  bool isArrow() const { return IsArrow; }
1076  void setArrow(bool A) { IsArrow = A; }
1077
1078  /// getMemberLoc - Return the location of the "member", in X->F, it is the
1079  /// location of 'F'.
1080  SourceLocation getMemberLoc() const { return MemberLoc; }
1081  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
1082
1083  virtual SourceRange getSourceRange() const {
1084    // If we have an implicit base (like a C++ implicit this),
1085    // make sure not to return its location
1086    SourceLocation BaseLoc = getBase()->getLocStart();
1087    if (BaseLoc.isInvalid())
1088      return SourceRange(MemberLoc, MemberLoc);
1089    return SourceRange(BaseLoc, MemberLoc);
1090  }
1091
1092  virtual SourceLocation getExprLoc() const { return MemberLoc; }
1093
1094  static bool classof(const Stmt *T) {
1095    return T->getStmtClass() == MemberExprClass;
1096  }
1097  static bool classof(const MemberExpr *) { return true; }
1098
1099  // Iterators
1100  virtual child_iterator child_begin();
1101  virtual child_iterator child_end();
1102};
1103
1104/// CompoundLiteralExpr - [C99 6.5.2.5]
1105///
1106class CompoundLiteralExpr : public Expr {
1107  /// LParenLoc - If non-null, this is the location of the left paren in a
1108  /// compound literal like "(int){4}".  This can be null if this is a
1109  /// synthesized compound expression.
1110  SourceLocation LParenLoc;
1111  Stmt *Init;
1112  bool FileScope;
1113public:
1114  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
1115                      bool fileScope)
1116    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
1117      FileScope(fileScope) {}
1118
1119  /// \brief Construct an empty compound literal.
1120  explicit CompoundLiteralExpr(EmptyShell Empty)
1121    : Expr(CompoundLiteralExprClass, Empty) { }
1122
1123  const Expr *getInitializer() const { return cast<Expr>(Init); }
1124  Expr *getInitializer() { return cast<Expr>(Init); }
1125  void setInitializer(Expr *E) { Init = E; }
1126
1127  bool isFileScope() const { return FileScope; }
1128  void setFileScope(bool FS) { FileScope = FS; }
1129
1130  SourceLocation getLParenLoc() const { return LParenLoc; }
1131  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1132
1133  virtual SourceRange getSourceRange() const {
1134    // FIXME: Init should never be null.
1135    if (!Init)
1136      return SourceRange();
1137    if (LParenLoc.isInvalid())
1138      return Init->getSourceRange();
1139    return SourceRange(LParenLoc, Init->getLocEnd());
1140  }
1141
1142  static bool classof(const Stmt *T) {
1143    return T->getStmtClass() == CompoundLiteralExprClass;
1144  }
1145  static bool classof(const CompoundLiteralExpr *) { return true; }
1146
1147  // Iterators
1148  virtual child_iterator child_begin();
1149  virtual child_iterator child_end();
1150};
1151
1152/// CastExpr - Base class for type casts, including both implicit
1153/// casts (ImplicitCastExpr) and explicit casts that have some
1154/// representation in the source code (ExplicitCastExpr's derived
1155/// classes).
1156class CastExpr : public Expr {
1157public:
1158  /// CastKind - the kind of cast this represents.
1159  enum CastKind {
1160    /// CK_Unknown - Unknown cast kind.
1161    /// FIXME: The goal is to get rid of this and make all casts have a
1162    /// kind so that the AST client doesn't have to try to figure out what's
1163    /// going on.
1164    CK_Unknown,
1165
1166    /// CK_BitCast - Used for reinterpret_cast.
1167    CK_BitCast,
1168
1169    /// CK_NoOp - Used for const_cast.
1170    CK_NoOp
1171  };
1172
1173private:
1174  CastKind Kind;
1175  Stmt *Op;
1176protected:
1177  CastExpr(StmtClass SC, QualType ty, CastKind kind, Expr *op) :
1178    Expr(SC, ty,
1179         // Cast expressions are type-dependent if the type is
1180         // dependent (C++ [temp.dep.expr]p3).
1181         ty->isDependentType(),
1182         // Cast expressions are value-dependent if the type is
1183         // dependent or if the subexpression is value-dependent.
1184         ty->isDependentType() || (op && op->isValueDependent())),
1185    Kind(kind), Op(op) {}
1186
1187  /// \brief Construct an empty cast.
1188  CastExpr(StmtClass SC, EmptyShell Empty)
1189    : Expr(SC, Empty) { }
1190
1191public:
1192  CastKind getCastKind() const { return Kind; }
1193  void setCastKind(CastKind K) { Kind = K; }
1194
1195  Expr *getSubExpr() { return cast<Expr>(Op); }
1196  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1197  void setSubExpr(Expr *E) { Op = E; }
1198
1199  static bool classof(const Stmt *T) {
1200    StmtClass SC = T->getStmtClass();
1201    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1202      return true;
1203
1204    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
1205      return true;
1206
1207    return false;
1208  }
1209  static bool classof(const CastExpr *) { return true; }
1210
1211  // Iterators
1212  virtual child_iterator child_begin();
1213  virtual child_iterator child_end();
1214};
1215
1216/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1217/// conversions, which have no direct representation in the original
1218/// source code. For example: converting T[]->T*, void f()->void
1219/// (*f)(), float->double, short->int, etc.
1220///
1221/// In C, implicit casts always produce rvalues. However, in C++, an
1222/// implicit cast whose result is being bound to a reference will be
1223/// an lvalue. For example:
1224///
1225/// @code
1226/// class Base { };
1227/// class Derived : public Base { };
1228/// void f(Derived d) {
1229///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1230/// }
1231/// @endcode
1232class ImplicitCastExpr : public CastExpr {
1233  /// LvalueCast - Whether this cast produces an lvalue.
1234  bool LvalueCast;
1235
1236public:
1237  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op, bool Lvalue) :
1238    CastExpr(ImplicitCastExprClass, ty, kind, op), LvalueCast(Lvalue) { }
1239
1240  /// \brief Construct an empty implicit cast.
1241  explicit ImplicitCastExpr(EmptyShell Shell)
1242    : CastExpr(ImplicitCastExprClass, Shell) { }
1243
1244
1245  virtual SourceRange getSourceRange() const {
1246    return getSubExpr()->getSourceRange();
1247  }
1248
1249  /// isLvalueCast - Whether this cast produces an lvalue.
1250  bool isLvalueCast() const { return LvalueCast; }
1251
1252  /// setLvalueCast - Set whether this cast produces an lvalue.
1253  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1254
1255  static bool classof(const Stmt *T) {
1256    return T->getStmtClass() == ImplicitCastExprClass;
1257  }
1258  static bool classof(const ImplicitCastExpr *) { return true; }
1259};
1260
1261/// ExplicitCastExpr - An explicit cast written in the source
1262/// code.
1263///
1264/// This class is effectively an abstract class, because it provides
1265/// the basic representation of an explicitly-written cast without
1266/// specifying which kind of cast (C cast, functional cast, static
1267/// cast, etc.) was written; specific derived classes represent the
1268/// particular style of cast and its location information.
1269///
1270/// Unlike implicit casts, explicit cast nodes have two different
1271/// types: the type that was written into the source code, and the
1272/// actual type of the expression as determined by semantic
1273/// analysis. These types may differ slightly. For example, in C++ one
1274/// can cast to a reference type, which indicates that the resulting
1275/// expression will be an lvalue. The reference type, however, will
1276/// not be used as the type of the expression.
1277class ExplicitCastExpr : public CastExpr {
1278  /// TypeAsWritten - The type that this expression is casting to, as
1279  /// written in the source code.
1280  QualType TypeAsWritten;
1281
1282protected:
1283  ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind, Expr *op,
1284                   QualType writtenTy)
1285    : CastExpr(SC, exprTy, kind, op), TypeAsWritten(writtenTy) {}
1286
1287  /// \brief Construct an empty explicit cast.
1288  ExplicitCastExpr(StmtClass SC, EmptyShell Shell)
1289    : CastExpr(SC, Shell) { }
1290
1291public:
1292  /// getTypeAsWritten - Returns the type that this expression is
1293  /// casting to, as written in the source code.
1294  QualType getTypeAsWritten() const { return TypeAsWritten; }
1295  void setTypeAsWritten(QualType T) { TypeAsWritten = T; }
1296
1297  static bool classof(const Stmt *T) {
1298    StmtClass SC = T->getStmtClass();
1299    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
1300      return true;
1301    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1302      return true;
1303
1304    return false;
1305  }
1306  static bool classof(const ExplicitCastExpr *) { return true; }
1307};
1308
1309/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1310/// cast in C++ (C++ [expr.cast]), which uses the syntax
1311/// (Type)expr. For example: @c (int)f.
1312class CStyleCastExpr : public ExplicitCastExpr {
1313  SourceLocation LPLoc; // the location of the left paren
1314  SourceLocation RPLoc; // the location of the right paren
1315public:
1316  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op, QualType writtenTy,
1317                    SourceLocation l, SourceLocation r) :
1318    ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, writtenTy),
1319    LPLoc(l), RPLoc(r) {}
1320
1321  /// \brief Construct an empty C-style explicit cast.
1322  explicit CStyleCastExpr(EmptyShell Shell)
1323    : ExplicitCastExpr(CStyleCastExprClass, Shell) { }
1324
1325  SourceLocation getLParenLoc() const { return LPLoc; }
1326  void setLParenLoc(SourceLocation L) { LPLoc = L; }
1327
1328  SourceLocation getRParenLoc() const { return RPLoc; }
1329  void setRParenLoc(SourceLocation L) { RPLoc = L; }
1330
1331  virtual SourceRange getSourceRange() const {
1332    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1333  }
1334  static bool classof(const Stmt *T) {
1335    return T->getStmtClass() == CStyleCastExprClass;
1336  }
1337  static bool classof(const CStyleCastExpr *) { return true; }
1338};
1339
1340/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
1341///
1342/// This expression node kind describes a builtin binary operation,
1343/// such as "x + y" for integer values "x" and "y". The operands will
1344/// already have been converted to appropriate types (e.g., by
1345/// performing promotions or conversions).
1346///
1347/// In C++, where operators may be overloaded, a different kind of
1348/// expression node (CXXOperatorCallExpr) is used to express the
1349/// invocation of an overloaded operator with operator syntax. Within
1350/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
1351/// used to store an expression "x + y" depends on the subexpressions
1352/// for x and y. If neither x or y is type-dependent, and the "+"
1353/// operator resolves to a built-in operation, BinaryOperator will be
1354/// used to express the computation (x and y may still be
1355/// value-dependent). If either x or y is type-dependent, or if the
1356/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
1357/// be used to express the computation.
1358class BinaryOperator : public Expr {
1359public:
1360  enum Opcode {
1361    // Operators listed in order of precedence.
1362    // Note that additions to this should also update the StmtVisitor class.
1363    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1364    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1365    Add, Sub,         // [C99 6.5.6] Additive operators.
1366    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1367    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1368    EQ, NE,           // [C99 6.5.9] Equality operators.
1369    And,              // [C99 6.5.10] Bitwise AND operator.
1370    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1371    Or,               // [C99 6.5.12] Bitwise OR operator.
1372    LAnd,             // [C99 6.5.13] Logical AND operator.
1373    LOr,              // [C99 6.5.14] Logical OR operator.
1374    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1375    DivAssign, RemAssign,
1376    AddAssign, SubAssign,
1377    ShlAssign, ShrAssign,
1378    AndAssign, XorAssign,
1379    OrAssign,
1380    Comma             // [C99 6.5.17] Comma operator.
1381  };
1382private:
1383  enum { LHS, RHS, END_EXPR };
1384  Stmt* SubExprs[END_EXPR];
1385  Opcode Opc;
1386  SourceLocation OpLoc;
1387public:
1388
1389  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1390                 SourceLocation opLoc)
1391    : Expr(BinaryOperatorClass, ResTy,
1392           lhs->isTypeDependent() || rhs->isTypeDependent(),
1393           lhs->isValueDependent() || rhs->isValueDependent()),
1394      Opc(opc), OpLoc(opLoc) {
1395    SubExprs[LHS] = lhs;
1396    SubExprs[RHS] = rhs;
1397    assert(!isCompoundAssignmentOp() &&
1398           "Use ArithAssignBinaryOperator for compound assignments");
1399  }
1400
1401  /// \brief Construct an empty binary operator.
1402  explicit BinaryOperator(EmptyShell Empty)
1403    : Expr(BinaryOperatorClass, Empty), Opc(Comma) { }
1404
1405  SourceLocation getOperatorLoc() const { return OpLoc; }
1406  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1407
1408  Opcode getOpcode() const { return Opc; }
1409  void setOpcode(Opcode O) { Opc = O; }
1410
1411  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1412  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1413  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1414  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1415
1416  virtual SourceRange getSourceRange() const {
1417    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1418  }
1419
1420  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1421  /// corresponds to, e.g. "<<=".
1422  static const char *getOpcodeStr(Opcode Op);
1423
1424  /// \brief Retrieve the binary opcode that corresponds to the given
1425  /// overloaded operator.
1426  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
1427
1428  /// \brief Retrieve the overloaded operator kind that corresponds to
1429  /// the given binary opcode.
1430  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1431
1432  /// predicates to categorize the respective opcodes.
1433  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1434  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1435  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
1436  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
1437
1438  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1439  bool isRelationalOp() const { return isRelationalOp(Opc); }
1440
1441  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1442  bool isEqualityOp() const { return isEqualityOp(Opc); }
1443
1444  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1445  bool isLogicalOp() const { return isLogicalOp(Opc); }
1446
1447  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1448  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1449  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1450
1451  static bool classof(const Stmt *S) {
1452    return S->getStmtClass() == BinaryOperatorClass ||
1453           S->getStmtClass() == CompoundAssignOperatorClass;
1454  }
1455  static bool classof(const BinaryOperator *) { return true; }
1456
1457  // Iterators
1458  virtual child_iterator child_begin();
1459  virtual child_iterator child_end();
1460
1461protected:
1462  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1463                 SourceLocation oploc, bool dead)
1464    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
1465    SubExprs[LHS] = lhs;
1466    SubExprs[RHS] = rhs;
1467  }
1468
1469  BinaryOperator(StmtClass SC, EmptyShell Empty)
1470    : Expr(SC, Empty), Opc(MulAssign) { }
1471};
1472
1473/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1474/// track of the type the operation is performed in.  Due to the semantics of
1475/// these operators, the operands are promoted, the aritmetic performed, an
1476/// implicit conversion back to the result type done, then the assignment takes
1477/// place.  This captures the intermediate type which the computation is done
1478/// in.
1479class CompoundAssignOperator : public BinaryOperator {
1480  QualType ComputationLHSType;
1481  QualType ComputationResultType;
1482public:
1483  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1484                         QualType ResType, QualType CompLHSType,
1485                         QualType CompResultType,
1486                         SourceLocation OpLoc)
1487    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1488      ComputationLHSType(CompLHSType),
1489      ComputationResultType(CompResultType) {
1490    assert(isCompoundAssignmentOp() &&
1491           "Only should be used for compound assignments");
1492  }
1493
1494  /// \brief Build an empty compound assignment operator expression.
1495  explicit CompoundAssignOperator(EmptyShell Empty)
1496    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
1497
1498  // The two computation types are the type the LHS is converted
1499  // to for the computation and the type of the result; the two are
1500  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
1501  QualType getComputationLHSType() const { return ComputationLHSType; }
1502  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
1503
1504  QualType getComputationResultType() const { return ComputationResultType; }
1505  void setComputationResultType(QualType T) { ComputationResultType = T; }
1506
1507  static bool classof(const CompoundAssignOperator *) { return true; }
1508  static bool classof(const Stmt *S) {
1509    return S->getStmtClass() == CompoundAssignOperatorClass;
1510  }
1511};
1512
1513/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1514/// GNU "missing LHS" extension is in use.
1515///
1516class ConditionalOperator : public Expr {
1517  enum { COND, LHS, RHS, END_EXPR };
1518  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1519public:
1520  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1521    : Expr(ConditionalOperatorClass, t,
1522           // FIXME: the type of the conditional operator doesn't
1523           // depend on the type of the conditional, but the standard
1524           // seems to imply that it could. File a bug!
1525           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
1526           (cond->isValueDependent() ||
1527            (lhs && lhs->isValueDependent()) ||
1528            (rhs && rhs->isValueDependent()))) {
1529    SubExprs[COND] = cond;
1530    SubExprs[LHS] = lhs;
1531    SubExprs[RHS] = rhs;
1532  }
1533
1534  /// \brief Build an empty conditional operator.
1535  explicit ConditionalOperator(EmptyShell Empty)
1536    : Expr(ConditionalOperatorClass, Empty) { }
1537
1538  // getCond - Return the expression representing the condition for
1539  //  the ?: operator.
1540  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1541  void setCond(Expr *E) { SubExprs[COND] = E; }
1542
1543  // getTrueExpr - Return the subexpression representing the value of the ?:
1544  //  expression if the condition evaluates to true.  In most cases this value
1545  //  will be the same as getLHS() except a GCC extension allows the left
1546  //  subexpression to be omitted, and instead of the condition be returned.
1547  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1548  //  is only evaluated once.
1549  Expr *getTrueExpr() const {
1550    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1551  }
1552
1553  // getTrueExpr - Return the subexpression representing the value of the ?:
1554  // expression if the condition evaluates to false. This is the same as getRHS.
1555  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1556
1557  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1558  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1559
1560  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1561  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1562
1563  virtual SourceRange getSourceRange() const {
1564    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1565  }
1566  static bool classof(const Stmt *T) {
1567    return T->getStmtClass() == ConditionalOperatorClass;
1568  }
1569  static bool classof(const ConditionalOperator *) { return true; }
1570
1571  // Iterators
1572  virtual child_iterator child_begin();
1573  virtual child_iterator child_end();
1574};
1575
1576/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1577class AddrLabelExpr : public Expr {
1578  SourceLocation AmpAmpLoc, LabelLoc;
1579  LabelStmt *Label;
1580public:
1581  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1582                QualType t)
1583    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1584
1585  /// \brief Build an empty address of a label expression.
1586  explicit AddrLabelExpr(EmptyShell Empty)
1587    : Expr(AddrLabelExprClass, Empty) { }
1588
1589  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
1590  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
1591  SourceLocation getLabelLoc() const { return LabelLoc; }
1592  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
1593
1594  virtual SourceRange getSourceRange() const {
1595    return SourceRange(AmpAmpLoc, LabelLoc);
1596  }
1597
1598  LabelStmt *getLabel() const { return Label; }
1599  void setLabel(LabelStmt *S) { Label = S; }
1600
1601  static bool classof(const Stmt *T) {
1602    return T->getStmtClass() == AddrLabelExprClass;
1603  }
1604  static bool classof(const AddrLabelExpr *) { return true; }
1605
1606  // Iterators
1607  virtual child_iterator child_begin();
1608  virtual child_iterator child_end();
1609};
1610
1611/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1612/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1613/// takes the value of the last subexpression.
1614class StmtExpr : public Expr {
1615  Stmt *SubStmt;
1616  SourceLocation LParenLoc, RParenLoc;
1617public:
1618  StmtExpr(CompoundStmt *substmt, QualType T,
1619           SourceLocation lp, SourceLocation rp) :
1620    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1621
1622  /// \brief Build an empty statement expression.
1623  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
1624
1625  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1626  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1627  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
1628
1629  virtual SourceRange getSourceRange() const {
1630    return SourceRange(LParenLoc, RParenLoc);
1631  }
1632
1633  SourceLocation getLParenLoc() const { return LParenLoc; }
1634  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1635  SourceLocation getRParenLoc() const { return RParenLoc; }
1636  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1637
1638  static bool classof(const Stmt *T) {
1639    return T->getStmtClass() == StmtExprClass;
1640  }
1641  static bool classof(const StmtExpr *) { return true; }
1642
1643  // Iterators
1644  virtual child_iterator child_begin();
1645  virtual child_iterator child_end();
1646};
1647
1648/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
1649/// This AST node represents a function that returns 1 if two *types* (not
1650/// expressions) are compatible. The result of this built-in function can be
1651/// used in integer constant expressions.
1652class TypesCompatibleExpr : public Expr {
1653  QualType Type1;
1654  QualType Type2;
1655  SourceLocation BuiltinLoc, RParenLoc;
1656public:
1657  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1658                      QualType t1, QualType t2, SourceLocation RP) :
1659    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1660    BuiltinLoc(BLoc), RParenLoc(RP) {}
1661
1662  /// \brief Build an empty __builtin_type_compatible_p expression.
1663  explicit TypesCompatibleExpr(EmptyShell Empty)
1664    : Expr(TypesCompatibleExprClass, Empty) { }
1665
1666  QualType getArgType1() const { return Type1; }
1667  void setArgType1(QualType T) { Type1 = T; }
1668  QualType getArgType2() const { return Type2; }
1669  void setArgType2(QualType T) { Type2 = T; }
1670
1671  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1672  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1673
1674  SourceLocation getRParenLoc() const { return RParenLoc; }
1675  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1676
1677  virtual SourceRange getSourceRange() const {
1678    return SourceRange(BuiltinLoc, RParenLoc);
1679  }
1680  static bool classof(const Stmt *T) {
1681    return T->getStmtClass() == TypesCompatibleExprClass;
1682  }
1683  static bool classof(const TypesCompatibleExpr *) { return true; }
1684
1685  // Iterators
1686  virtual child_iterator child_begin();
1687  virtual child_iterator child_end();
1688};
1689
1690/// ShuffleVectorExpr - clang-specific builtin-in function
1691/// __builtin_shufflevector.
1692/// This AST node represents a operator that does a constant
1693/// shuffle, similar to LLVM's shufflevector instruction. It takes
1694/// two vectors and a variable number of constant indices,
1695/// and returns the appropriately shuffled vector.
1696class ShuffleVectorExpr : public Expr {
1697  SourceLocation BuiltinLoc, RParenLoc;
1698
1699  // SubExprs - the list of values passed to the __builtin_shufflevector
1700  // function. The first two are vectors, and the rest are constant
1701  // indices.  The number of values in this list is always
1702  // 2+the number of indices in the vector type.
1703  Stmt **SubExprs;
1704  unsigned NumExprs;
1705
1706public:
1707  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1708                    QualType Type, SourceLocation BLoc,
1709                    SourceLocation RP) :
1710    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1711    RParenLoc(RP), NumExprs(nexpr) {
1712      // FIXME: Allocate in ASTContext!
1713    SubExprs = new Stmt*[nexpr];
1714    for (unsigned i = 0; i < nexpr; i++)
1715      SubExprs[i] = args[i];
1716  }
1717
1718  /// \brief Build an empty vector-shuffle expression.
1719  explicit ShuffleVectorExpr(EmptyShell Empty)
1720    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
1721
1722  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1723  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1724
1725  SourceLocation getRParenLoc() const { return RParenLoc; }
1726  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1727
1728  virtual SourceRange getSourceRange() const {
1729    return SourceRange(BuiltinLoc, RParenLoc);
1730  }
1731  static bool classof(const Stmt *T) {
1732    return T->getStmtClass() == ShuffleVectorExprClass;
1733  }
1734  static bool classof(const ShuffleVectorExpr *) { return true; }
1735
1736  ~ShuffleVectorExpr() {
1737    delete [] SubExprs;
1738  }
1739
1740  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1741  /// constant expression, the actual arguments passed in, and the function
1742  /// pointers.
1743  unsigned getNumSubExprs() const { return NumExprs; }
1744
1745  /// getExpr - Return the Expr at the specified index.
1746  Expr *getExpr(unsigned Index) {
1747    assert((Index < NumExprs) && "Arg access out of range!");
1748    return cast<Expr>(SubExprs[Index]);
1749  }
1750  const Expr *getExpr(unsigned Index) const {
1751    assert((Index < NumExprs) && "Arg access out of range!");
1752    return cast<Expr>(SubExprs[Index]);
1753  }
1754
1755  void setExprs(Expr ** Exprs, unsigned NumExprs);
1756
1757  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1758    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1759    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
1760  }
1761
1762  // Iterators
1763  virtual child_iterator child_begin();
1764  virtual child_iterator child_end();
1765};
1766
1767/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1768/// This AST node is similar to the conditional operator (?:) in C, with
1769/// the following exceptions:
1770/// - the test expression must be a integer constant expression.
1771/// - the expression returned acts like the chosen subexpression in every
1772///   visible way: the type is the same as that of the chosen subexpression,
1773///   and all predicates (whether it's an l-value, whether it's an integer
1774///   constant expression, etc.) return the same result as for the chosen
1775///   sub-expression.
1776class ChooseExpr : public Expr {
1777  enum { COND, LHS, RHS, END_EXPR };
1778  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1779  SourceLocation BuiltinLoc, RParenLoc;
1780public:
1781  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1782             SourceLocation RP)
1783    : Expr(ChooseExprClass, t),
1784      BuiltinLoc(BLoc), RParenLoc(RP) {
1785      SubExprs[COND] = cond;
1786      SubExprs[LHS] = lhs;
1787      SubExprs[RHS] = rhs;
1788    }
1789
1790  /// \brief Build an empty __builtin_choose_expr.
1791  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
1792
1793  /// isConditionTrue - Return whether the condition is true (i.e. not
1794  /// equal to zero).
1795  bool isConditionTrue(ASTContext &C) const;
1796
1797  /// getChosenSubExpr - Return the subexpression chosen according to the
1798  /// condition.
1799  Expr *getChosenSubExpr(ASTContext &C) const {
1800    return isConditionTrue(C) ? getLHS() : getRHS();
1801  }
1802
1803  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1804  void setCond(Expr *E) { SubExprs[COND] = E; }
1805  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1806  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1807  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1808  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1809
1810  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1811  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1812
1813  SourceLocation getRParenLoc() const { return RParenLoc; }
1814  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1815
1816  virtual SourceRange getSourceRange() const {
1817    return SourceRange(BuiltinLoc, RParenLoc);
1818  }
1819  static bool classof(const Stmt *T) {
1820    return T->getStmtClass() == ChooseExprClass;
1821  }
1822  static bool classof(const ChooseExpr *) { return true; }
1823
1824  // Iterators
1825  virtual child_iterator child_begin();
1826  virtual child_iterator child_end();
1827};
1828
1829/// GNUNullExpr - Implements the GNU __null extension, which is a name
1830/// for a null pointer constant that has integral type (e.g., int or
1831/// long) and is the same size and alignment as a pointer. The __null
1832/// extension is typically only used by system headers, which define
1833/// NULL as __null in C++ rather than using 0 (which is an integer
1834/// that may not match the size of a pointer).
1835class GNUNullExpr : public Expr {
1836  /// TokenLoc - The location of the __null keyword.
1837  SourceLocation TokenLoc;
1838
1839public:
1840  GNUNullExpr(QualType Ty, SourceLocation Loc)
1841    : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { }
1842
1843  /// \brief Build an empty GNU __null expression.
1844  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
1845
1846  GNUNullExpr* Clone(ASTContext &C) const;
1847
1848  /// getTokenLocation - The location of the __null token.
1849  SourceLocation getTokenLocation() const { return TokenLoc; }
1850  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
1851
1852  virtual SourceRange getSourceRange() const {
1853    return SourceRange(TokenLoc);
1854  }
1855  static bool classof(const Stmt *T) {
1856    return T->getStmtClass() == GNUNullExprClass;
1857  }
1858  static bool classof(const GNUNullExpr *) { return true; }
1859
1860  // Iterators
1861  virtual child_iterator child_begin();
1862  virtual child_iterator child_end();
1863};
1864
1865/// VAArgExpr, used for the builtin function __builtin_va_start.
1866class VAArgExpr : public Expr {
1867  Stmt *Val;
1868  SourceLocation BuiltinLoc, RParenLoc;
1869public:
1870  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1871    : Expr(VAArgExprClass, t),
1872      Val(e),
1873      BuiltinLoc(BLoc),
1874      RParenLoc(RPLoc) { }
1875
1876  /// \brief Create an empty __builtin_va_start expression.
1877  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
1878
1879  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1880  Expr *getSubExpr() { return cast<Expr>(Val); }
1881  void setSubExpr(Expr *E) { Val = E; }
1882
1883  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1884  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1885
1886  SourceLocation getRParenLoc() const { return RParenLoc; }
1887  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1888
1889  virtual SourceRange getSourceRange() const {
1890    return SourceRange(BuiltinLoc, RParenLoc);
1891  }
1892  static bool classof(const Stmt *T) {
1893    return T->getStmtClass() == VAArgExprClass;
1894  }
1895  static bool classof(const VAArgExpr *) { return true; }
1896
1897  // Iterators
1898  virtual child_iterator child_begin();
1899  virtual child_iterator child_end();
1900};
1901
1902/// @brief Describes an C or C++ initializer list.
1903///
1904/// InitListExpr describes an initializer list, which can be used to
1905/// initialize objects of different types, including
1906/// struct/class/union types, arrays, and vectors. For example:
1907///
1908/// @code
1909/// struct foo x = { 1, { 2, 3 } };
1910/// @endcode
1911///
1912/// Prior to semantic analysis, an initializer list will represent the
1913/// initializer list as written by the user, but will have the
1914/// placeholder type "void". This initializer list is called the
1915/// syntactic form of the initializer, and may contain C99 designated
1916/// initializers (represented as DesignatedInitExprs), initializations
1917/// of subobject members without explicit braces, and so on. Clients
1918/// interested in the original syntax of the initializer list should
1919/// use the syntactic form of the initializer list.
1920///
1921/// After semantic analysis, the initializer list will represent the
1922/// semantic form of the initializer, where the initializations of all
1923/// subobjects are made explicit with nested InitListExpr nodes and
1924/// C99 designators have been eliminated by placing the designated
1925/// initializations into the subobject they initialize. Additionally,
1926/// any "holes" in the initialization, where no initializer has been
1927/// specified for a particular subobject, will be replaced with
1928/// implicitly-generated ImplicitValueInitExpr expressions that
1929/// value-initialize the subobjects. Note, however, that the
1930/// initializer lists may still have fewer initializers than there are
1931/// elements to initialize within the object.
1932///
1933/// Given the semantic form of the initializer list, one can retrieve
1934/// the original syntactic form of that initializer list (if it
1935/// exists) using getSyntacticForm(). Since many initializer lists
1936/// have the same syntactic and semantic forms, getSyntacticForm() may
1937/// return NULL, indicating that the current initializer list also
1938/// serves as its syntactic form.
1939class InitListExpr : public Expr {
1940  // FIXME: Eliminate this vector in favor of ASTContext allocation
1941  std::vector<Stmt *> InitExprs;
1942  SourceLocation LBraceLoc, RBraceLoc;
1943
1944  /// Contains the initializer list that describes the syntactic form
1945  /// written in the source code.
1946  InitListExpr *SyntacticForm;
1947
1948  /// If this initializer list initializes a union, specifies which
1949  /// field within the union will be initialized.
1950  FieldDecl *UnionFieldInit;
1951
1952  /// Whether this initializer list originally had a GNU array-range
1953  /// designator in it. This is a temporary marker used by CodeGen.
1954  bool HadArrayRangeDesignator;
1955
1956public:
1957  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1958               SourceLocation rbraceloc);
1959
1960  /// \brief Build an empty initializer list.
1961  explicit InitListExpr(EmptyShell Empty) : Expr(InitListExprClass, Empty) { }
1962
1963  unsigned getNumInits() const { return InitExprs.size(); }
1964
1965  const Expr* getInit(unsigned Init) const {
1966    assert(Init < getNumInits() && "Initializer access out of range!");
1967    return cast_or_null<Expr>(InitExprs[Init]);
1968  }
1969
1970  Expr* getInit(unsigned Init) {
1971    assert(Init < getNumInits() && "Initializer access out of range!");
1972    return cast_or_null<Expr>(InitExprs[Init]);
1973  }
1974
1975  void setInit(unsigned Init, Expr *expr) {
1976    assert(Init < getNumInits() && "Initializer access out of range!");
1977    InitExprs[Init] = expr;
1978  }
1979
1980  /// \brief Reserve space for some number of initializers.
1981  void reserveInits(unsigned NumInits);
1982
1983  /// @brief Specify the number of initializers
1984  ///
1985  /// If there are more than @p NumInits initializers, the remaining
1986  /// initializers will be destroyed. If there are fewer than @p
1987  /// NumInits initializers, NULL expressions will be added for the
1988  /// unknown initializers.
1989  void resizeInits(ASTContext &Context, unsigned NumInits);
1990
1991  /// @brief Updates the initializer at index @p Init with the new
1992  /// expression @p expr, and returns the old expression at that
1993  /// location.
1994  ///
1995  /// When @p Init is out of range for this initializer list, the
1996  /// initializer list will be extended with NULL expressions to
1997  /// accomodate the new entry.
1998  Expr *updateInit(unsigned Init, Expr *expr);
1999
2000  /// \brief If this initializes a union, specifies which field in the
2001  /// union to initialize.
2002  ///
2003  /// Typically, this field is the first named field within the
2004  /// union. However, a designated initializer can specify the
2005  /// initialization of a different field within the union.
2006  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2007  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2008
2009  // Explicit InitListExpr's originate from source code (and have valid source
2010  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2011  bool isExplicit() {
2012    return LBraceLoc.isValid() && RBraceLoc.isValid();
2013  }
2014
2015  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2016  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2017  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2018  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2019
2020  /// @brief Retrieve the initializer list that describes the
2021  /// syntactic form of the initializer.
2022  ///
2023  ///
2024  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2025  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2026
2027  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2028  void sawArrayRangeDesignator(bool ARD = true) {
2029    HadArrayRangeDesignator = ARD;
2030  }
2031
2032  virtual SourceRange getSourceRange() const {
2033    return SourceRange(LBraceLoc, RBraceLoc);
2034  }
2035  static bool classof(const Stmt *T) {
2036    return T->getStmtClass() == InitListExprClass;
2037  }
2038  static bool classof(const InitListExpr *) { return true; }
2039
2040  // Iterators
2041  virtual child_iterator child_begin();
2042  virtual child_iterator child_end();
2043
2044  typedef std::vector<Stmt *>::iterator iterator;
2045  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
2046
2047  iterator begin() { return InitExprs.begin(); }
2048  iterator end() { return InitExprs.end(); }
2049  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2050  reverse_iterator rend() { return InitExprs.rend(); }
2051};
2052
2053/// @brief Represents a C99 designated initializer expression.
2054///
2055/// A designated initializer expression (C99 6.7.8) contains one or
2056/// more designators (which can be field designators, array
2057/// designators, or GNU array-range designators) followed by an
2058/// expression that initializes the field or element(s) that the
2059/// designators refer to. For example, given:
2060///
2061/// @code
2062/// struct point {
2063///   double x;
2064///   double y;
2065/// };
2066/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2067/// @endcode
2068///
2069/// The InitListExpr contains three DesignatedInitExprs, the first of
2070/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2071/// designators, one array designator for @c [2] followed by one field
2072/// designator for @c .y. The initalization expression will be 1.0.
2073class DesignatedInitExpr : public Expr {
2074public:
2075  /// \brief Forward declaration of the Designator class.
2076  class Designator;
2077
2078private:
2079  /// The location of the '=' or ':' prior to the actual initializer
2080  /// expression.
2081  SourceLocation EqualOrColonLoc;
2082
2083  /// Whether this designated initializer used the GNU deprecated
2084  /// syntax rather than the C99 '=' syntax.
2085  bool GNUSyntax : 1;
2086
2087  /// The number of designators in this initializer expression.
2088  unsigned NumDesignators : 15;
2089
2090  /// \brief The designators in this designated initialization
2091  /// expression.
2092  Designator *Designators;
2093
2094  /// The number of subexpressions of this initializer expression,
2095  /// which contains both the initializer and any additional
2096  /// expressions used by array and array-range designators.
2097  unsigned NumSubExprs : 16;
2098
2099
2100  DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
2101                     const Designator *Designators,
2102                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2103                     Expr **IndexExprs, unsigned NumIndexExprs,
2104                     Expr *Init);
2105
2106  explicit DesignatedInitExpr(unsigned NumSubExprs)
2107    : Expr(DesignatedInitExprClass, EmptyShell()),
2108      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2109
2110public:
2111  /// A field designator, e.g., ".x".
2112  struct FieldDesignator {
2113    /// Refers to the field that is being initialized. The low bit
2114    /// of this field determines whether this is actually a pointer
2115    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2116    /// initially constructed, a field designator will store an
2117    /// IdentifierInfo*. After semantic analysis has resolved that
2118    /// name, the field designator will instead store a FieldDecl*.
2119    uintptr_t NameOrField;
2120
2121    /// The location of the '.' in the designated initializer.
2122    unsigned DotLoc;
2123
2124    /// The location of the field name in the designated initializer.
2125    unsigned FieldLoc;
2126  };
2127
2128  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2129  struct ArrayOrRangeDesignator {
2130    /// Location of the first index expression within the designated
2131    /// initializer expression's list of subexpressions.
2132    unsigned Index;
2133    /// The location of the '[' starting the array range designator.
2134    unsigned LBracketLoc;
2135    /// The location of the ellipsis separating the start and end
2136    /// indices. Only valid for GNU array-range designators.
2137    unsigned EllipsisLoc;
2138    /// The location of the ']' terminating the array range designator.
2139    unsigned RBracketLoc;
2140  };
2141
2142  /// @brief Represents a single C99 designator.
2143  ///
2144  /// @todo This class is infuriatingly similar to clang::Designator,
2145  /// but minor differences (storing indices vs. storing pointers)
2146  /// keep us from reusing it. Try harder, later, to rectify these
2147  /// differences.
2148  class Designator {
2149    /// @brief The kind of designator this describes.
2150    enum {
2151      FieldDesignator,
2152      ArrayDesignator,
2153      ArrayRangeDesignator
2154    } Kind;
2155
2156    union {
2157      /// A field designator, e.g., ".x".
2158      struct FieldDesignator Field;
2159      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2160      struct ArrayOrRangeDesignator ArrayOrRange;
2161    };
2162    friend class DesignatedInitExpr;
2163
2164  public:
2165    Designator() {}
2166
2167    /// @brief Initializes a field designator.
2168    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
2169               SourceLocation FieldLoc)
2170      : Kind(FieldDesignator) {
2171      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
2172      Field.DotLoc = DotLoc.getRawEncoding();
2173      Field.FieldLoc = FieldLoc.getRawEncoding();
2174    }
2175
2176    /// @brief Initializes an array designator.
2177    Designator(unsigned Index, SourceLocation LBracketLoc,
2178               SourceLocation RBracketLoc)
2179      : Kind(ArrayDesignator) {
2180      ArrayOrRange.Index = Index;
2181      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2182      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
2183      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2184    }
2185
2186    /// @brief Initializes a GNU array-range designator.
2187    Designator(unsigned Index, SourceLocation LBracketLoc,
2188               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
2189      : Kind(ArrayRangeDesignator) {
2190      ArrayOrRange.Index = Index;
2191      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2192      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
2193      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2194    }
2195
2196    bool isFieldDesignator() const { return Kind == FieldDesignator; }
2197    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
2198    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
2199
2200    IdentifierInfo * getFieldName();
2201
2202    FieldDecl *getField() {
2203      assert(Kind == FieldDesignator && "Only valid on a field designator");
2204      if (Field.NameOrField & 0x01)
2205        return 0;
2206      else
2207        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
2208    }
2209
2210    void setField(FieldDecl *FD) {
2211      assert(Kind == FieldDesignator && "Only valid on a field designator");
2212      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
2213    }
2214
2215    SourceLocation getDotLoc() const {
2216      assert(Kind == FieldDesignator && "Only valid on a field designator");
2217      return SourceLocation::getFromRawEncoding(Field.DotLoc);
2218    }
2219
2220    SourceLocation getFieldLoc() const {
2221      assert(Kind == FieldDesignator && "Only valid on a field designator");
2222      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
2223    }
2224
2225    SourceLocation getLBracketLoc() const {
2226      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2227             "Only valid on an array or array-range designator");
2228      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
2229    }
2230
2231    SourceLocation getRBracketLoc() const {
2232      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2233             "Only valid on an array or array-range designator");
2234      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
2235    }
2236
2237    SourceLocation getEllipsisLoc() const {
2238      assert(Kind == ArrayRangeDesignator &&
2239             "Only valid on an array-range designator");
2240      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
2241    }
2242
2243    unsigned getFirstExprIndex() const {
2244      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2245             "Only valid on an array or array-range designator");
2246      return ArrayOrRange.Index;
2247    }
2248
2249    SourceLocation getStartLocation() const {
2250      if (Kind == FieldDesignator)
2251        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
2252      else
2253        return getLBracketLoc();
2254    }
2255  };
2256
2257  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
2258                                    unsigned NumDesignators,
2259                                    Expr **IndexExprs, unsigned NumIndexExprs,
2260                                    SourceLocation EqualOrColonLoc,
2261                                    bool GNUSyntax, Expr *Init);
2262
2263  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
2264
2265  /// @brief Returns the number of designators in this initializer.
2266  unsigned size() const { return NumDesignators; }
2267
2268  // Iterator access to the designators.
2269  typedef Designator* designators_iterator;
2270  designators_iterator designators_begin() { return Designators; }
2271  designators_iterator designators_end() {
2272    return Designators + NumDesignators;
2273  }
2274
2275  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
2276
2277  void setDesignators(const Designator *Desigs, unsigned NumDesigs);
2278
2279  Expr *getArrayIndex(const Designator& D);
2280  Expr *getArrayRangeStart(const Designator& D);
2281  Expr *getArrayRangeEnd(const Designator& D);
2282
2283  /// @brief Retrieve the location of the '=' that precedes the
2284  /// initializer value itself, if present.
2285  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
2286  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
2287
2288  /// @brief Determines whether this designated initializer used the
2289  /// deprecated GNU syntax for designated initializers.
2290  bool usesGNUSyntax() const { return GNUSyntax; }
2291  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
2292
2293  /// @brief Retrieve the initializer value.
2294  Expr *getInit() const {
2295    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
2296  }
2297
2298  void setInit(Expr *init) {
2299    *child_begin() = init;
2300  }
2301
2302  /// \brief Retrieve the total number of subexpressions in this
2303  /// designated initializer expression, including the actual
2304  /// initialized value and any expressions that occur within array
2305  /// and array-range designators.
2306  unsigned getNumSubExprs() const { return NumSubExprs; }
2307
2308  Expr *getSubExpr(unsigned Idx) {
2309    assert(Idx < NumSubExprs && "Subscript out of range");
2310    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2311    Ptr += sizeof(DesignatedInitExpr);
2312    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
2313  }
2314
2315  void setSubExpr(unsigned Idx, Expr *E) {
2316    assert(Idx < NumSubExprs && "Subscript out of range");
2317    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2318    Ptr += sizeof(DesignatedInitExpr);
2319    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
2320  }
2321
2322  /// \brief Replaces the designator at index @p Idx with the series
2323  /// of designators in [First, Last).
2324  void ExpandDesignator(unsigned Idx, const Designator *First,
2325                        const Designator *Last);
2326
2327  virtual SourceRange getSourceRange() const;
2328
2329  virtual void Destroy(ASTContext &C);
2330
2331  static bool classof(const Stmt *T) {
2332    return T->getStmtClass() == DesignatedInitExprClass;
2333  }
2334  static bool classof(const DesignatedInitExpr *) { return true; }
2335
2336  // Iterators
2337  virtual child_iterator child_begin();
2338  virtual child_iterator child_end();
2339};
2340
2341/// \brief Represents an implicitly-generated value initialization of
2342/// an object of a given type.
2343///
2344/// Implicit value initializations occur within semantic initializer
2345/// list expressions (InitListExpr) as placeholders for subobject
2346/// initializations not explicitly specified by the user.
2347///
2348/// \see InitListExpr
2349class ImplicitValueInitExpr : public Expr {
2350public:
2351  explicit ImplicitValueInitExpr(QualType ty)
2352    : Expr(ImplicitValueInitExprClass, ty) { }
2353
2354  /// \brief Construct an empty implicit value initialization.
2355  explicit ImplicitValueInitExpr(EmptyShell Empty)
2356    : Expr(ImplicitValueInitExprClass, Empty) { }
2357
2358  static bool classof(const Stmt *T) {
2359    return T->getStmtClass() == ImplicitValueInitExprClass;
2360  }
2361  static bool classof(const ImplicitValueInitExpr *) { return true; }
2362
2363  virtual SourceRange getSourceRange() const {
2364    return SourceRange();
2365  }
2366
2367  ImplicitValueInitExpr *Clone(ASTContext &C) const;
2368
2369  // Iterators
2370  virtual child_iterator child_begin();
2371  virtual child_iterator child_end();
2372};
2373
2374//===----------------------------------------------------------------------===//
2375// Clang Extensions
2376//===----------------------------------------------------------------------===//
2377
2378
2379/// ExtVectorElementExpr - This represents access to specific elements of a
2380/// vector, and may occur on the left hand side or right hand side.  For example
2381/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
2382///
2383/// Note that the base may have either vector or pointer to vector type, just
2384/// like a struct field reference.
2385///
2386class ExtVectorElementExpr : public Expr {
2387  Stmt *Base;
2388  IdentifierInfo *Accessor;
2389  SourceLocation AccessorLoc;
2390public:
2391  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
2392                       SourceLocation loc)
2393    : Expr(ExtVectorElementExprClass, ty),
2394      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
2395
2396  /// \brief Build an empty vector element expression.
2397  explicit ExtVectorElementExpr(EmptyShell Empty)
2398    : Expr(ExtVectorElementExprClass, Empty) { }
2399
2400  const Expr *getBase() const { return cast<Expr>(Base); }
2401  Expr *getBase() { return cast<Expr>(Base); }
2402  void setBase(Expr *E) { Base = E; }
2403
2404  IdentifierInfo &getAccessor() const { return *Accessor; }
2405  void setAccessor(IdentifierInfo *II) { Accessor = II; }
2406
2407  SourceLocation getAccessorLoc() const { return AccessorLoc; }
2408  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
2409
2410  /// getNumElements - Get the number of components being selected.
2411  unsigned getNumElements() const;
2412
2413  /// containsDuplicateElements - Return true if any element access is
2414  /// repeated.
2415  bool containsDuplicateElements() const;
2416
2417  /// getEncodedElementAccess - Encode the elements accessed into an llvm
2418  /// aggregate Constant of ConstantInt(s).
2419  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
2420
2421  virtual SourceRange getSourceRange() const {
2422    return SourceRange(getBase()->getLocStart(), AccessorLoc);
2423  }
2424
2425  /// isArrow - Return true if the base expression is a pointer to vector,
2426  /// return false if the base expression is a vector.
2427  bool isArrow() const;
2428
2429  static bool classof(const Stmt *T) {
2430    return T->getStmtClass() == ExtVectorElementExprClass;
2431  }
2432  static bool classof(const ExtVectorElementExpr *) { return true; }
2433
2434  // Iterators
2435  virtual child_iterator child_begin();
2436  virtual child_iterator child_end();
2437};
2438
2439
2440/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
2441/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
2442class BlockExpr : public Expr {
2443protected:
2444  BlockDecl *TheBlock;
2445  bool HasBlockDeclRefExprs;
2446public:
2447  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
2448    : Expr(BlockExprClass, ty),
2449      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
2450
2451  /// \brief Build an empty block expression.
2452  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
2453
2454  const BlockDecl *getBlockDecl() const { return TheBlock; }
2455  BlockDecl *getBlockDecl() { return TheBlock; }
2456  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
2457
2458  // Convenience functions for probing the underlying BlockDecl.
2459  SourceLocation getCaretLocation() const;
2460  const Stmt *getBody() const;
2461  Stmt *getBody();
2462
2463  virtual SourceRange getSourceRange() const {
2464    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
2465  }
2466
2467  /// getFunctionType - Return the underlying function type for this block.
2468  const FunctionType *getFunctionType() const;
2469
2470  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
2471  /// inside of the block that reference values outside the block.
2472  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
2473  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
2474
2475  static bool classof(const Stmt *T) {
2476    return T->getStmtClass() == BlockExprClass;
2477  }
2478  static bool classof(const BlockExpr *) { return true; }
2479
2480  // Iterators
2481  virtual child_iterator child_begin();
2482  virtual child_iterator child_end();
2483};
2484
2485/// BlockDeclRefExpr - A reference to a declared variable, function,
2486/// enum, etc.
2487class BlockDeclRefExpr : public Expr {
2488  ValueDecl *D;
2489  SourceLocation Loc;
2490  bool IsByRef : 1;
2491  bool ConstQualAdded : 1;
2492public:
2493  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
2494                   bool constAdded = false) :
2495       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef),
2496                                       ConstQualAdded(constAdded) {}
2497
2498  // \brief Build an empty reference to a declared variable in a
2499  // block.
2500  explicit BlockDeclRefExpr(EmptyShell Empty)
2501    : Expr(BlockDeclRefExprClass, Empty) { }
2502
2503  ValueDecl *getDecl() { return D; }
2504  const ValueDecl *getDecl() const { return D; }
2505  void setDecl(ValueDecl *VD) { D = VD; }
2506
2507  SourceLocation getLocation() const { return Loc; }
2508  void setLocation(SourceLocation L) { Loc = L; }
2509
2510  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
2511
2512  bool isByRef() const { return IsByRef; }
2513  void setByRef(bool BR) { IsByRef = BR; }
2514
2515  bool isConstQualAdded() const { return ConstQualAdded; }
2516  void setConstQualAdded(bool C) { ConstQualAdded = C; }
2517
2518  static bool classof(const Stmt *T) {
2519    return T->getStmtClass() == BlockDeclRefExprClass;
2520  }
2521  static bool classof(const BlockDeclRefExpr *) { return true; }
2522
2523  // Iterators
2524  virtual child_iterator child_begin();
2525  virtual child_iterator child_end();
2526};
2527
2528}  // end namespace clang
2529
2530#endif
2531