Expr.h revision fc89c31a329eb6b36c6dbd8b7cb945d1a831650e
16f56ab789cb470620554d624c37f488285b3b04eDan Albert//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
26f56ab789cb470620554d624c37f488285b3b04eDan Albert//
36f56ab789cb470620554d624c37f488285b3b04eDan Albert//                     The LLVM Compiler Infrastructure
46f56ab789cb470620554d624c37f488285b3b04eDan Albert//
56f56ab789cb470620554d624c37f488285b3b04eDan Albert// This file is distributed under the University of Illinois Open Source
66f56ab789cb470620554d624c37f488285b3b04eDan Albert// License. See LICENSE.TXT for details.
76f56ab789cb470620554d624c37f488285b3b04eDan Albert//
86f56ab789cb470620554d624c37f488285b3b04eDan Albert//===----------------------------------------------------------------------===//
96f56ab789cb470620554d624c37f488285b3b04eDan Albert//
106f56ab789cb470620554d624c37f488285b3b04eDan Albert//  This file defines the Expr interface and subclasses.
116f56ab789cb470620554d624c37f488285b3b04eDan Albert//
126f56ab789cb470620554d624c37f488285b3b04eDan Albert//===----------------------------------------------------------------------===//
136f56ab789cb470620554d624c37f488285b3b04eDan Albert
146f56ab789cb470620554d624c37f488285b3b04eDan Albert#ifndef LLVM_CLANG_AST_EXPR_H
156f56ab789cb470620554d624c37f488285b3b04eDan Albert#define LLVM_CLANG_AST_EXPR_H
166f56ab789cb470620554d624c37f488285b3b04eDan Albert
176f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "clang/AST/APValue.h"
186f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "clang/AST/Stmt.h"
196f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "clang/AST/Type.h"
206f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "clang/AST/DeclAccessPair.h"
216f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "clang/AST/ASTVector.h"
226f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "clang/AST/UsuallyTinyPtrVector.h"
236f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "llvm/ADT/APSInt.h"
246f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "llvm/ADT/APFloat.h"
256f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "llvm/ADT/SmallVector.h"
266f56ab789cb470620554d624c37f488285b3b04eDan Albert#include "llvm/ADT/StringRef.h"
276f56ab789cb470620554d624c37f488285b3b04eDan Albert#include <vector>
286f56ab789cb470620554d624c37f488285b3b04eDan Albert
296f56ab789cb470620554d624c37f488285b3b04eDan Albertnamespace clang {
306f56ab789cb470620554d624c37f488285b3b04eDan Albert  class ASTContext;
316f56ab789cb470620554d624c37f488285b3b04eDan Albert  class APValue;
326f56ab789cb470620554d624c37f488285b3b04eDan Albert  class Decl;
336f56ab789cb470620554d624c37f488285b3b04eDan Albert  class IdentifierInfo;
346f56ab789cb470620554d624c37f488285b3b04eDan Albert  class ParmVarDecl;
356f56ab789cb470620554d624c37f488285b3b04eDan Albert  class NamedDecl;
366f56ab789cb470620554d624c37f488285b3b04eDan Albert  class ValueDecl;
376f56ab789cb470620554d624c37f488285b3b04eDan Albert  class BlockDecl;
386f56ab789cb470620554d624c37f488285b3b04eDan Albert  class CXXBaseSpecifier;
396f56ab789cb470620554d624c37f488285b3b04eDan Albert  class CXXOperatorCallExpr;
406f56ab789cb470620554d624c37f488285b3b04eDan Albert  class CXXMemberCallExpr;
416f56ab789cb470620554d624c37f488285b3b04eDan Albert  class TemplateArgumentLoc;
426f56ab789cb470620554d624c37f488285b3b04eDan Albert  class TemplateArgumentListInfo;
436f56ab789cb470620554d624c37f488285b3b04eDan Albert
446f56ab789cb470620554d624c37f488285b3b04eDan Albert/// \brief A simple array of base specifiers.
456f56ab789cb470620554d624c37f488285b3b04eDan Alberttypedef UsuallyTinyPtrVector<const CXXBaseSpecifier> CXXBaseSpecifierArray;
466f56ab789cb470620554d624c37f488285b3b04eDan Albert
476f56ab789cb470620554d624c37f488285b3b04eDan Albert/// Expr - This represents one expression.  Note that Expr's are subclasses of
486f56ab789cb470620554d624c37f488285b3b04eDan Albert/// Stmt.  This allows an expression to be transparently used any place a Stmt
496f56ab789cb470620554d624c37f488285b3b04eDan Albert/// is required.
506f56ab789cb470620554d624c37f488285b3b04eDan Albert///
516f56ab789cb470620554d624c37f488285b3b04eDan Albertclass Expr : public Stmt {
526f56ab789cb470620554d624c37f488285b3b04eDan Albert  QualType TR;
536f56ab789cb470620554d624c37f488285b3b04eDan Albert
546f56ab789cb470620554d624c37f488285b3b04eDan Albertprotected:
556f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// TypeDependent - Whether this expression is type-dependent
566f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// (C++ [temp.dep.expr]).
576f56ab789cb470620554d624c37f488285b3b04eDan Albert  bool TypeDependent : 1;
586f56ab789cb470620554d624c37f488285b3b04eDan Albert
596f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// ValueDependent - Whether this expression is value-dependent
606f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// (C++ [temp.dep.constexpr]).
616f56ab789cb470620554d624c37f488285b3b04eDan Albert  bool ValueDependent : 1;
626f56ab789cb470620554d624c37f488285b3b04eDan Albert
636f56ab789cb470620554d624c37f488285b3b04eDan Albert  Expr(StmtClass SC, QualType T, bool TD, bool VD)
646f56ab789cb470620554d624c37f488285b3b04eDan Albert    : Stmt(SC), TypeDependent(TD), ValueDependent(VD) {
656f56ab789cb470620554d624c37f488285b3b04eDan Albert    setType(T);
666f56ab789cb470620554d624c37f488285b3b04eDan Albert  }
676f56ab789cb470620554d624c37f488285b3b04eDan Albert
686f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// \brief Construct an empty expression.
696f56ab789cb470620554d624c37f488285b3b04eDan Albert  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
706f56ab789cb470620554d624c37f488285b3b04eDan Albert
716f56ab789cb470620554d624c37f488285b3b04eDan Albertpublic:
726f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// \brief Increases the reference count for this expression.
736f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///
746f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// Invoke the Retain() operation when this expression
756f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// is being shared by another owner.
766f56ab789cb470620554d624c37f488285b3b04eDan Albert  Expr *Retain() {
776f56ab789cb470620554d624c37f488285b3b04eDan Albert    Stmt::Retain();
786f56ab789cb470620554d624c37f488285b3b04eDan Albert    return this;
796f56ab789cb470620554d624c37f488285b3b04eDan Albert  }
806f56ab789cb470620554d624c37f488285b3b04eDan Albert
816f56ab789cb470620554d624c37f488285b3b04eDan Albert  QualType getType() const { return TR; }
826f56ab789cb470620554d624c37f488285b3b04eDan Albert  void setType(QualType t) {
836f56ab789cb470620554d624c37f488285b3b04eDan Albert    // In C++, the type of an expression is always adjusted so that it
846f56ab789cb470620554d624c37f488285b3b04eDan Albert    // will not have reference type an expression will never have
856f56ab789cb470620554d624c37f488285b3b04eDan Albert    // reference type (C++ [expr]p6). Use
866f56ab789cb470620554d624c37f488285b3b04eDan Albert    // QualType::getNonReferenceType() to retrieve the non-reference
876f56ab789cb470620554d624c37f488285b3b04eDan Albert    // type. Additionally, inspect Expr::isLvalue to determine whether
886f56ab789cb470620554d624c37f488285b3b04eDan Albert    // an expression that is adjusted in this manner should be
896f56ab789cb470620554d624c37f488285b3b04eDan Albert    // considered an lvalue.
906f56ab789cb470620554d624c37f488285b3b04eDan Albert    assert((t.isNull() || !t->isReferenceType()) &&
916f56ab789cb470620554d624c37f488285b3b04eDan Albert           "Expressions can't have reference type");
926f56ab789cb470620554d624c37f488285b3b04eDan Albert
936f56ab789cb470620554d624c37f488285b3b04eDan Albert    TR = t;
946f56ab789cb470620554d624c37f488285b3b04eDan Albert  }
956f56ab789cb470620554d624c37f488285b3b04eDan Albert
966f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// isValueDependent - Determines whether this expression is
976f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
986f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// array bound of "Chars" in the following example is
996f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// value-dependent.
1006f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// @code
1016f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// template<int Size, char (&Chars)[Size]> struct meta_string;
1026f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// @endcode
1036f56ab789cb470620554d624c37f488285b3b04eDan Albert  bool isValueDependent() const { return ValueDependent; }
1046f56ab789cb470620554d624c37f488285b3b04eDan Albert
1056f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// \brief Set whether this expression is value-dependent or not.
1066f56ab789cb470620554d624c37f488285b3b04eDan Albert  void setValueDependent(bool VD) { ValueDependent = VD; }
1076f56ab789cb470620554d624c37f488285b3b04eDan Albert
1086f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// isTypeDependent - Determines whether this expression is
1096f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// type-dependent (C++ [temp.dep.expr]), which means that its type
1106f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// could change from one template instantiation to the next. For
1116f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// example, the expressions "x" and "x + y" are type-dependent in
1126f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// the following code, but "y" is not type-dependent:
1136f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// @code
1146f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// template<typename T>
1156f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// void add(T x, int y) {
1166f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///   x + y;
1176f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// }
1186f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// @endcode
1196f56ab789cb470620554d624c37f488285b3b04eDan Albert  bool isTypeDependent() const { return TypeDependent; }
1206f56ab789cb470620554d624c37f488285b3b04eDan Albert
1216f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// \brief Set whether this expression is type-dependent or not.
1226f56ab789cb470620554d624c37f488285b3b04eDan Albert  void setTypeDependent(bool TD) { TypeDependent = TD; }
1236f56ab789cb470620554d624c37f488285b3b04eDan Albert
1246f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// SourceLocation tokens are not useful in isolation - they are low level
1256f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// value objects created/interpreted by SourceManager. We assume AST
1266f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// clients will have a pointer to the respective SourceManager.
1276f56ab789cb470620554d624c37f488285b3b04eDan Albert  virtual SourceRange getSourceRange() const = 0;
1286f56ab789cb470620554d624c37f488285b3b04eDan Albert
1296f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// getExprLoc - Return the preferred location for the arrow when diagnosing
1306f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// a problem with a generic expression.
1316f56ab789cb470620554d624c37f488285b3b04eDan Albert  virtual SourceLocation getExprLoc() const { return getLocStart(); }
1326f56ab789cb470620554d624c37f488285b3b04eDan Albert
1336f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// isUnusedResultAWarning - Return true if this immediate expression should
1346f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
1356f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// with location to warn on and the source range[s] to report with the
1366f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// warning.
1376f56ab789cb470620554d624c37f488285b3b04eDan Albert  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1386f56ab789cb470620554d624c37f488285b3b04eDan Albert                              SourceRange &R2, ASTContext &Ctx) const;
1396f56ab789cb470620554d624c37f488285b3b04eDan Albert
1406f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
1416f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// incomplete type other than void. Nonarray expressions that can be lvalues:
1426f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - name, where name must be a variable
1436f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - e[i]
1446f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - (e), where e must be an lvalue
1456f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - e.name, where e must be an lvalue
1466f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - e->name
1476f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - *e, the type of e cannot be a function type
1486f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - string-constant
1496f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - reference type [C++ [expr]]
1506f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///  - b ? x : y, where x and y are lvalues of suitable types [C++]
1516f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///
1526f56ab789cb470620554d624c37f488285b3b04eDan Albert  enum isLvalueResult {
1536f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_Valid,
1546f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_NotObjectType,
1556f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_IncompleteVoidType,
1566f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_DuplicateVectorComponents,
1576f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_InvalidExpression,
1586f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_MemberFunction,
1596f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_SubObjCPropertySetting,
1606f56ab789cb470620554d624c37f488285b3b04eDan Albert    LV_ClassTemporary
1616f56ab789cb470620554d624c37f488285b3b04eDan Albert  };
1626f56ab789cb470620554d624c37f488285b3b04eDan Albert  isLvalueResult isLvalue(ASTContext &Ctx) const;
1636f56ab789cb470620554d624c37f488285b3b04eDan Albert
1646f56ab789cb470620554d624c37f488285b3b04eDan Albert  // Same as above, but excluding checks for non-object and void types in C
1656f56ab789cb470620554d624c37f488285b3b04eDan Albert  isLvalueResult isLvalueInternal(ASTContext &Ctx) const;
1666f56ab789cb470620554d624c37f488285b3b04eDan Albert
1676f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
1686f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// does not have an incomplete type, does not have a const-qualified type,
1696f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// and if it is a structure or union, does not have any member (including,
1706f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// recursively, any member or element of all contained aggregates or unions)
1716f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// with a const-qualified type.
1726f56ab789cb470620554d624c37f488285b3b04eDan Albert  ///
1736f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// \param Loc [in] [out] - A source location which *may* be filled
1746f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// in with the location of the expression making this a
1756f56ab789cb470620554d624c37f488285b3b04eDan Albert  /// non-modifiable lvalue, if specified.
1766f56ab789cb470620554d624c37f488285b3b04eDan Albert  enum isModifiableLvalueResult {
1776f56ab789cb470620554d624c37f488285b3b04eDan Albert    MLV_Valid,
1786f56ab789cb470620554d624c37f488285b3b04eDan Albert    MLV_NotObjectType,
1796f56ab789cb470620554d624c37f488285b3b04eDan Albert    MLV_IncompleteVoidType,
180    MLV_DuplicateVectorComponents,
181    MLV_InvalidExpression,
182    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
183    MLV_IncompleteType,
184    MLV_ConstQualified,
185    MLV_ArrayType,
186    MLV_NotBlockQualified,
187    MLV_ReadonlyProperty,
188    MLV_NoSetterProperty,
189    MLV_MemberFunction,
190    MLV_SubObjCPropertySetting,
191    MLV_ClassTemporary
192  };
193  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
194                                              SourceLocation *Loc = 0) const;
195
196  /// \brief If this expression refers to a bit-field, retrieve the
197  /// declaration of that bit-field.
198  FieldDecl *getBitField();
199
200  const FieldDecl *getBitField() const {
201    return const_cast<Expr*>(this)->getBitField();
202  }
203
204  /// \brief Returns whether this expression refers to a vector element.
205  bool refersToVectorElement() const;
206
207  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
208  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
209  /// but also int expressions which are produced by things like comparisons in
210  /// C.
211  bool isKnownToHaveBooleanValue() const;
212
213  /// isIntegerConstantExpr - Return true if this expression is a valid integer
214  /// constant expression, and, if so, return its value in Result.  If not a
215  /// valid i-c-e, return false and fill in Loc (if specified) with the location
216  /// of the invalid expression.
217  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
218                             SourceLocation *Loc = 0,
219                             bool isEvaluated = true) const;
220  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
221    llvm::APSInt X;
222    return isIntegerConstantExpr(X, Ctx, Loc);
223  }
224  /// isConstantInitializer - Returns true if this expression is a constant
225  /// initializer, which can be emitted at compile-time.
226  bool isConstantInitializer(ASTContext &Ctx) const;
227
228  /// EvalResult is a struct with detailed info about an evaluated expression.
229  struct EvalResult {
230    /// Val - This is the value the expression can be folded to.
231    APValue Val;
232
233    /// HasSideEffects - Whether the evaluated expression has side effects.
234    /// For example, (f() && 0) can be folded, but it still has side effects.
235    bool HasSideEffects;
236
237    /// Diag - If the expression is unfoldable, then Diag contains a note
238    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
239    /// position for the error, and DiagExpr is the expression that caused
240    /// the error.
241    /// If the expression is foldable, but not an integer constant expression,
242    /// Diag contains a note diagnostic that describes why it isn't an integer
243    /// constant expression. If the expression *is* an integer constant
244    /// expression, then Diag will be zero.
245    unsigned Diag;
246    const Expr *DiagExpr;
247    SourceLocation DiagLoc;
248
249    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
250  };
251
252  /// Evaluate - Return true if this is a constant which we can fold using
253  /// any crazy technique (that has nothing to do with language standards) that
254  /// we want to.  If this function returns true, it returns the folded constant
255  /// in Result.
256  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
257
258  /// EvaluateAsAny - The same as Evaluate, except that it also succeeds on
259  /// stack based objects.
260  bool EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const;
261
262  /// EvaluateAsBooleanCondition - Return true if this is a constant
263  /// which we we can fold and convert to a boolean condition using
264  /// any crazy technique that we want to.
265  bool EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const;
266
267  /// isEvaluatable - Call Evaluate to see if this expression can be constant
268  /// folded, but discard the result.
269  bool isEvaluatable(ASTContext &Ctx) const;
270
271  /// HasSideEffects - This routine returns true for all those expressions
272  /// which must be evaluated each time and must not be optimization away
273  /// or evaluated at compile time. Example is a function call, volatile
274  /// variable read.
275  bool HasSideEffects(ASTContext &Ctx) const;
276
277  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
278  /// must be called on an expression that constant folds to an integer.
279  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
280
281  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
282  /// with link time known address.
283  bool EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const;
284
285  /// EvaluateAsAnyLValue - The same as EvaluateAsLValue, except that it
286  /// also succeeds on stack based, immutable address lvalues.
287  bool EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const;
288
289  /// \brief Enumeration used to describe how \c isNullPointerConstant()
290  /// should cope with value-dependent expressions.
291  enum NullPointerConstantValueDependence {
292    /// \brief Specifies that the expression should never be value-dependent.
293    NPC_NeverValueDependent = 0,
294
295    /// \brief Specifies that a value-dependent expression of integral or
296    /// dependent type should be considered a null pointer constant.
297    NPC_ValueDependentIsNull,
298
299    /// \brief Specifies that a value-dependent expression should be considered
300    /// to never be a null pointer constant.
301    NPC_ValueDependentIsNotNull
302  };
303
304  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
305  /// integer constant expression with the value zero, or if this is one that is
306  /// cast to void*.
307  bool isNullPointerConstant(ASTContext &Ctx,
308                             NullPointerConstantValueDependence NPC) const;
309
310  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
311  /// write barrier.
312  bool isOBJCGCCandidate(ASTContext &Ctx) const;
313
314  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
315  ///  its subexpression.  If that subexpression is also a ParenExpr,
316  ///  then this method recursively returns its subexpression, and so forth.
317  ///  Otherwise, the method returns the current Expr.
318  Expr *IgnoreParens();
319
320  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
321  /// or CastExprs, returning their operand.
322  Expr *IgnoreParenCasts();
323
324  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
325  /// value (including ptr->int casts of the same size).  Strip off any
326  /// ParenExpr or CastExprs, returning their operand.
327  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
328
329  /// \brief Determine whether this expression is a default function argument.
330  ///
331  /// Default arguments are implicitly generated in the abstract syntax tree
332  /// by semantic analysis for function calls, object constructions, etc. in
333  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
334  /// this routine also looks through any implicit casts to determine whether
335  /// the expression is a default argument.
336  bool isDefaultArgument() const;
337
338  /// \brief Determine whether this expression directly creates a
339  /// temporary object (of class type).
340  bool isTemporaryObject() const { return getTemporaryObject() != 0; }
341
342  /// \brief If this expression directly creates a temporary object of
343  /// class type, return the expression that actually constructs that
344  /// temporary object.
345  const Expr *getTemporaryObject() const;
346
347  const Expr *IgnoreParens() const {
348    return const_cast<Expr*>(this)->IgnoreParens();
349  }
350  const Expr *IgnoreParenCasts() const {
351    return const_cast<Expr*>(this)->IgnoreParenCasts();
352  }
353  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
354    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
355  }
356
357  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
358  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
359
360  static bool classof(const Stmt *T) {
361    return T->getStmtClass() >= firstExprConstant &&
362           T->getStmtClass() <= lastExprConstant;
363  }
364  static bool classof(const Expr *) { return true; }
365};
366
367
368//===----------------------------------------------------------------------===//
369// Primary Expressions.
370//===----------------------------------------------------------------------===//
371
372/// \brief Represents the qualifier that may precede a C++ name, e.g., the
373/// "std::" in "std::sort".
374struct NameQualifier {
375  /// \brief The nested name specifier.
376  NestedNameSpecifier *NNS;
377
378  /// \brief The source range covered by the nested name specifier.
379  SourceRange Range;
380};
381
382/// \brief Represents an explicit template argument list in C++, e.g.,
383/// the "<int>" in "sort<int>".
384struct ExplicitTemplateArgumentList {
385  /// \brief The source location of the left angle bracket ('<');
386  SourceLocation LAngleLoc;
387
388  /// \brief The source location of the right angle bracket ('>');
389  SourceLocation RAngleLoc;
390
391  /// \brief The number of template arguments in TemplateArgs.
392  /// The actual template arguments (if any) are stored after the
393  /// ExplicitTemplateArgumentList structure.
394  unsigned NumTemplateArgs;
395
396  /// \brief Retrieve the template arguments
397  TemplateArgumentLoc *getTemplateArgs() {
398    return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
399  }
400
401  /// \brief Retrieve the template arguments
402  const TemplateArgumentLoc *getTemplateArgs() const {
403    return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
404  }
405
406  void initializeFrom(const TemplateArgumentListInfo &List);
407  void copyInto(TemplateArgumentListInfo &List) const;
408  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
409};
410
411/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
412/// enum, etc.
413class DeclRefExpr : public Expr {
414  enum {
415    // Flag on DecoratedD that specifies when this declaration reference
416    // expression has a C++ nested-name-specifier.
417    HasQualifierFlag = 0x01,
418    // Flag on DecoratedD that specifies when this declaration reference
419    // expression has an explicit C++ template argument list.
420    HasExplicitTemplateArgumentListFlag = 0x02
421  };
422
423  // DecoratedD - The declaration that we are referencing, plus two bits to
424  // indicate whether (1) the declaration's name was explicitly qualified and
425  // (2) the declaration's name was followed by an explicit template
426  // argument list.
427  llvm::PointerIntPair<ValueDecl *, 2> DecoratedD;
428
429  // Loc - The location of the declaration name itself.
430  SourceLocation Loc;
431
432  /// \brief Retrieve the qualifier that preceded the declaration name, if any.
433  NameQualifier *getNameQualifier() {
434    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
435      return 0;
436
437    return reinterpret_cast<NameQualifier *> (this + 1);
438  }
439
440  /// \brief Retrieve the qualifier that preceded the member name, if any.
441  const NameQualifier *getNameQualifier() const {
442    return const_cast<DeclRefExpr *>(this)->getNameQualifier();
443  }
444
445  /// \brief Retrieve the explicit template argument list that followed the
446  /// member template name, if any.
447  ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() {
448    if ((DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag) == 0)
449      return 0;
450
451    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
452      return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
453
454    return reinterpret_cast<ExplicitTemplateArgumentList *>(
455                                                      getNameQualifier() + 1);
456  }
457
458  /// \brief Retrieve the explicit template argument list that followed the
459  /// member template name, if any.
460  const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const {
461    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgumentList();
462  }
463
464  DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
465              ValueDecl *D, SourceLocation NameLoc,
466              const TemplateArgumentListInfo *TemplateArgs,
467              QualType T);
468
469protected:
470  /// \brief Computes the type- and value-dependence flags for this
471  /// declaration reference expression.
472  void computeDependence();
473
474  DeclRefExpr(StmtClass SC, ValueDecl *d, QualType t, SourceLocation l) :
475    Expr(SC, t, false, false), DecoratedD(d, 0), Loc(l) {
476    computeDependence();
477  }
478
479public:
480  DeclRefExpr(ValueDecl *d, QualType t, SourceLocation l) :
481    Expr(DeclRefExprClass, t, false, false), DecoratedD(d, 0), Loc(l) {
482    computeDependence();
483  }
484
485  /// \brief Construct an empty declaration reference expression.
486  explicit DeclRefExpr(EmptyShell Empty)
487    : Expr(DeclRefExprClass, Empty) { }
488
489  static DeclRefExpr *Create(ASTContext &Context,
490                             NestedNameSpecifier *Qualifier,
491                             SourceRange QualifierRange,
492                             ValueDecl *D,
493                             SourceLocation NameLoc,
494                             QualType T,
495                             const TemplateArgumentListInfo *TemplateArgs = 0);
496
497  ValueDecl *getDecl() { return DecoratedD.getPointer(); }
498  const ValueDecl *getDecl() const { return DecoratedD.getPointer(); }
499  void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); }
500
501  SourceLocation getLocation() const { return Loc; }
502  void setLocation(SourceLocation L) { Loc = L; }
503  virtual SourceRange getSourceRange() const;
504
505  /// \brief Determine whether this declaration reference was preceded by a
506  /// C++ nested-name-specifier, e.g., \c N::foo.
507  bool hasQualifier() const { return DecoratedD.getInt() & HasQualifierFlag; }
508
509  /// \brief If the name was qualified, retrieves the source range of
510  /// the nested-name-specifier that precedes the name. Otherwise,
511  /// returns an empty source range.
512  SourceRange getQualifierRange() const {
513    if (!hasQualifier())
514      return SourceRange();
515
516    return getNameQualifier()->Range;
517  }
518
519  /// \brief If the name was qualified, retrieves the nested-name-specifier
520  /// that precedes the name. Otherwise, returns NULL.
521  NestedNameSpecifier *getQualifier() const {
522    if (!hasQualifier())
523      return 0;
524
525    return getNameQualifier()->NNS;
526  }
527
528  /// \brief Determines whether this member expression actually had a C++
529  /// template argument list explicitly specified, e.g., x.f<int>.
530  bool hasExplicitTemplateArgumentList() const {
531    return DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag;
532  }
533
534  /// \brief Copies the template arguments (if present) into the given
535  /// structure.
536  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
537    if (hasExplicitTemplateArgumentList())
538      getExplicitTemplateArgumentList()->copyInto(List);
539  }
540
541  /// \brief Retrieve the location of the left angle bracket following the
542  /// member name ('<'), if any.
543  SourceLocation getLAngleLoc() const {
544    if (!hasExplicitTemplateArgumentList())
545      return SourceLocation();
546
547    return getExplicitTemplateArgumentList()->LAngleLoc;
548  }
549
550  /// \brief Retrieve the template arguments provided as part of this
551  /// template-id.
552  const TemplateArgumentLoc *getTemplateArgs() const {
553    if (!hasExplicitTemplateArgumentList())
554      return 0;
555
556    return getExplicitTemplateArgumentList()->getTemplateArgs();
557  }
558
559  /// \brief Retrieve the number of template arguments provided as part of this
560  /// template-id.
561  unsigned getNumTemplateArgs() const {
562    if (!hasExplicitTemplateArgumentList())
563      return 0;
564
565    return getExplicitTemplateArgumentList()->NumTemplateArgs;
566  }
567
568  /// \brief Retrieve the location of the right angle bracket following the
569  /// template arguments ('>').
570  SourceLocation getRAngleLoc() const {
571    if (!hasExplicitTemplateArgumentList())
572      return SourceLocation();
573
574    return getExplicitTemplateArgumentList()->RAngleLoc;
575  }
576
577  static bool classof(const Stmt *T) {
578    return T->getStmtClass() == DeclRefExprClass;
579  }
580  static bool classof(const DeclRefExpr *) { return true; }
581
582  // Iterators
583  virtual child_iterator child_begin();
584  virtual child_iterator child_end();
585};
586
587/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
588class PredefinedExpr : public Expr {
589public:
590  enum IdentType {
591    Func,
592    Function,
593    PrettyFunction,
594    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
595    /// 'virtual' keyword is omitted for virtual member functions.
596    PrettyFunctionNoVirtual
597  };
598
599private:
600  SourceLocation Loc;
601  IdentType Type;
602public:
603  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
604    : Expr(PredefinedExprClass, type, type->isDependentType(),
605           type->isDependentType()), Loc(l), Type(IT) {}
606
607  /// \brief Construct an empty predefined expression.
608  explicit PredefinedExpr(EmptyShell Empty)
609    : Expr(PredefinedExprClass, Empty) { }
610
611  IdentType getIdentType() const { return Type; }
612  void setIdentType(IdentType IT) { Type = IT; }
613
614  SourceLocation getLocation() const { return Loc; }
615  void setLocation(SourceLocation L) { Loc = L; }
616
617  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
618
619  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
620
621  static bool classof(const Stmt *T) {
622    return T->getStmtClass() == PredefinedExprClass;
623  }
624  static bool classof(const PredefinedExpr *) { return true; }
625
626  // Iterators
627  virtual child_iterator child_begin();
628  virtual child_iterator child_end();
629};
630
631class IntegerLiteral : public Expr {
632  llvm::APInt Value;
633  SourceLocation Loc;
634public:
635  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
636  // or UnsignedLongLongTy
637  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
638    : Expr(IntegerLiteralClass, type, false, false), Value(V), Loc(l) {
639    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
640  }
641
642  /// \brief Construct an empty integer literal.
643  explicit IntegerLiteral(EmptyShell Empty)
644    : Expr(IntegerLiteralClass, Empty) { }
645
646  const llvm::APInt &getValue() const { return Value; }
647  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
648
649  /// \brief Retrieve the location of the literal.
650  SourceLocation getLocation() const { return Loc; }
651
652  void setValue(const llvm::APInt &Val) { Value = Val; }
653  void setLocation(SourceLocation Location) { Loc = Location; }
654
655  static bool classof(const Stmt *T) {
656    return T->getStmtClass() == IntegerLiteralClass;
657  }
658  static bool classof(const IntegerLiteral *) { return true; }
659
660  // Iterators
661  virtual child_iterator child_begin();
662  virtual child_iterator child_end();
663};
664
665class CharacterLiteral : public Expr {
666  unsigned Value;
667  SourceLocation Loc;
668  bool IsWide;
669public:
670  // type should be IntTy
671  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
672    : Expr(CharacterLiteralClass, type, false, false), Value(value), Loc(l),
673      IsWide(iswide) {
674  }
675
676  /// \brief Construct an empty character literal.
677  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
678
679  SourceLocation getLocation() const { return Loc; }
680  bool isWide() const { return IsWide; }
681
682  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
683
684  unsigned getValue() const { return Value; }
685
686  void setLocation(SourceLocation Location) { Loc = Location; }
687  void setWide(bool W) { IsWide = W; }
688  void setValue(unsigned Val) { Value = Val; }
689
690  static bool classof(const Stmt *T) {
691    return T->getStmtClass() == CharacterLiteralClass;
692  }
693  static bool classof(const CharacterLiteral *) { return true; }
694
695  // Iterators
696  virtual child_iterator child_begin();
697  virtual child_iterator child_end();
698};
699
700class FloatingLiteral : public Expr {
701  llvm::APFloat Value;
702  bool IsExact : 1;
703  SourceLocation Loc;
704public:
705  FloatingLiteral(const llvm::APFloat &V, bool isexact,
706                  QualType Type, SourceLocation L)
707    : Expr(FloatingLiteralClass, Type, false, false), Value(V),
708      IsExact(isexact), Loc(L) {}
709
710  /// \brief Construct an empty floating-point literal.
711  explicit FloatingLiteral(EmptyShell Empty)
712    : Expr(FloatingLiteralClass, Empty), Value(0.0) { }
713
714  const llvm::APFloat &getValue() const { return Value; }
715  void setValue(const llvm::APFloat &Val) { Value = Val; }
716
717  bool isExact() const { return IsExact; }
718  void setExact(bool E) { IsExact = E; }
719
720  /// getValueAsApproximateDouble - This returns the value as an inaccurate
721  /// double.  Note that this may cause loss of precision, but is useful for
722  /// debugging dumps, etc.
723  double getValueAsApproximateDouble() const;
724
725  SourceLocation getLocation() const { return Loc; }
726  void setLocation(SourceLocation L) { Loc = L; }
727
728  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
729
730  static bool classof(const Stmt *T) {
731    return T->getStmtClass() == FloatingLiteralClass;
732  }
733  static bool classof(const FloatingLiteral *) { return true; }
734
735  // Iterators
736  virtual child_iterator child_begin();
737  virtual child_iterator child_end();
738};
739
740/// ImaginaryLiteral - We support imaginary integer and floating point literals,
741/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
742/// IntegerLiteral classes.  Instances of this class always have a Complex type
743/// whose element type matches the subexpression.
744///
745class ImaginaryLiteral : public Expr {
746  Stmt *Val;
747public:
748  ImaginaryLiteral(Expr *val, QualType Ty)
749    : Expr(ImaginaryLiteralClass, Ty, false, false), Val(val) {}
750
751  /// \brief Build an empty imaginary literal.
752  explicit ImaginaryLiteral(EmptyShell Empty)
753    : Expr(ImaginaryLiteralClass, Empty) { }
754
755  const Expr *getSubExpr() const { return cast<Expr>(Val); }
756  Expr *getSubExpr() { return cast<Expr>(Val); }
757  void setSubExpr(Expr *E) { Val = E; }
758
759  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
760  static bool classof(const Stmt *T) {
761    return T->getStmtClass() == ImaginaryLiteralClass;
762  }
763  static bool classof(const ImaginaryLiteral *) { return true; }
764
765  // Iterators
766  virtual child_iterator child_begin();
767  virtual child_iterator child_end();
768};
769
770/// StringLiteral - This represents a string literal expression, e.g. "foo"
771/// or L"bar" (wide strings).  The actual string is returned by getStrData()
772/// is NOT null-terminated, and the length of the string is determined by
773/// calling getByteLength().  The C type for a string is always a
774/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
775/// not.
776///
777/// Note that strings in C can be formed by concatenation of multiple string
778/// literal pptokens in translation phase #6.  This keeps track of the locations
779/// of each of these pieces.
780///
781/// Strings in C can also be truncated and extended by assigning into arrays,
782/// e.g. with constructs like:
783///   char X[2] = "foobar";
784/// In this case, getByteLength() will return 6, but the string literal will
785/// have type "char[2]".
786class StringLiteral : public Expr {
787  const char *StrData;
788  unsigned ByteLength;
789  bool IsWide;
790  unsigned NumConcatenated;
791  SourceLocation TokLocs[1];
792
793  StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, false, false) {}
794
795protected:
796  virtual void DoDestroy(ASTContext &C);
797
798public:
799  /// This is the "fully general" constructor that allows representation of
800  /// strings formed from multiple concatenated tokens.
801  static StringLiteral *Create(ASTContext &C, const char *StrData,
802                               unsigned ByteLength, bool Wide, QualType Ty,
803                               const SourceLocation *Loc, unsigned NumStrs);
804
805  /// Simple constructor for string literals made from one token.
806  static StringLiteral *Create(ASTContext &C, const char *StrData,
807                               unsigned ByteLength,
808                               bool Wide, QualType Ty, SourceLocation Loc) {
809    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
810  }
811
812  /// \brief Construct an empty string literal.
813  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
814
815  llvm::StringRef getString() const {
816    return llvm::StringRef(StrData, ByteLength);
817  }
818  // FIXME: These are deprecated, replace with StringRef.
819  const char *getStrData() const { return StrData; }
820  unsigned getByteLength() const { return ByteLength; }
821
822  /// \brief Sets the string data to the given string data.
823  void setString(ASTContext &C, llvm::StringRef Str);
824
825  bool isWide() const { return IsWide; }
826  void setWide(bool W) { IsWide = W; }
827
828  bool containsNonAsciiOrNull() const {
829    llvm::StringRef Str = getString();
830    for (unsigned i = 0, e = Str.size(); i != e; ++i)
831      if (!isascii(Str[i]) || !Str[i])
832        return true;
833    return false;
834  }
835  /// getNumConcatenated - Get the number of string literal tokens that were
836  /// concatenated in translation phase #6 to form this string literal.
837  unsigned getNumConcatenated() const { return NumConcatenated; }
838
839  SourceLocation getStrTokenLoc(unsigned TokNum) const {
840    assert(TokNum < NumConcatenated && "Invalid tok number");
841    return TokLocs[TokNum];
842  }
843  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
844    assert(TokNum < NumConcatenated && "Invalid tok number");
845    TokLocs[TokNum] = L;
846  }
847
848  typedef const SourceLocation *tokloc_iterator;
849  tokloc_iterator tokloc_begin() const { return TokLocs; }
850  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
851
852  virtual SourceRange getSourceRange() const {
853    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
854  }
855  static bool classof(const Stmt *T) {
856    return T->getStmtClass() == StringLiteralClass;
857  }
858  static bool classof(const StringLiteral *) { return true; }
859
860  // Iterators
861  virtual child_iterator child_begin();
862  virtual child_iterator child_end();
863};
864
865/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
866/// AST node is only formed if full location information is requested.
867class ParenExpr : public Expr {
868  SourceLocation L, R;
869  Stmt *Val;
870public:
871  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
872    : Expr(ParenExprClass, val->getType(),
873           val->isTypeDependent(), val->isValueDependent()),
874      L(l), R(r), Val(val) {}
875
876  /// \brief Construct an empty parenthesized expression.
877  explicit ParenExpr(EmptyShell Empty)
878    : Expr(ParenExprClass, Empty) { }
879
880  const Expr *getSubExpr() const { return cast<Expr>(Val); }
881  Expr *getSubExpr() { return cast<Expr>(Val); }
882  void setSubExpr(Expr *E) { Val = E; }
883
884  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
885
886  /// \brief Get the location of the left parentheses '('.
887  SourceLocation getLParen() const { return L; }
888  void setLParen(SourceLocation Loc) { L = Loc; }
889
890  /// \brief Get the location of the right parentheses ')'.
891  SourceLocation getRParen() const { return R; }
892  void setRParen(SourceLocation Loc) { R = Loc; }
893
894  static bool classof(const Stmt *T) {
895    return T->getStmtClass() == ParenExprClass;
896  }
897  static bool classof(const ParenExpr *) { return true; }
898
899  // Iterators
900  virtual child_iterator child_begin();
901  virtual child_iterator child_end();
902};
903
904
905/// UnaryOperator - This represents the unary-expression's (except sizeof and
906/// alignof), the postinc/postdec operators from postfix-expression, and various
907/// extensions.
908///
909/// Notes on various nodes:
910///
911/// Real/Imag - These return the real/imag part of a complex operand.  If
912///   applied to a non-complex value, the former returns its operand and the
913///   later returns zero in the type of the operand.
914///
915/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
916///   subexpression is a compound literal with the various MemberExpr and
917///   ArraySubscriptExpr's applied to it.
918///
919class UnaryOperator : public Expr {
920public:
921  // Note that additions to this should also update the StmtVisitor class.
922  enum Opcode {
923    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
924    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
925    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
926    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
927    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
928    Real, Imag,       // "__real expr"/"__imag expr" Extension.
929    Extension,        // __extension__ marker.
930    OffsetOf          // __builtin_offsetof
931  };
932private:
933  Stmt *Val;
934  Opcode Opc;
935  SourceLocation Loc;
936public:
937
938  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
939    : Expr(UnaryOperatorClass, type,
940           input->isTypeDependent() && opc != OffsetOf,
941           input->isValueDependent()),
942      Val(input), Opc(opc), Loc(l) {}
943
944  /// \brief Build an empty unary operator.
945  explicit UnaryOperator(EmptyShell Empty)
946    : Expr(UnaryOperatorClass, Empty), Opc(AddrOf) { }
947
948  Opcode getOpcode() const { return Opc; }
949  void setOpcode(Opcode O) { Opc = O; }
950
951  Expr *getSubExpr() const { return cast<Expr>(Val); }
952  void setSubExpr(Expr *E) { Val = E; }
953
954  /// getOperatorLoc - Return the location of the operator.
955  SourceLocation getOperatorLoc() const { return Loc; }
956  void setOperatorLoc(SourceLocation L) { Loc = L; }
957
958  /// isPostfix - Return true if this is a postfix operation, like x++.
959  static bool isPostfix(Opcode Op) {
960    return Op == PostInc || Op == PostDec;
961  }
962
963  /// isPostfix - Return true if this is a prefix operation, like --x.
964  static bool isPrefix(Opcode Op) {
965    return Op == PreInc || Op == PreDec;
966  }
967
968  bool isPrefix() const { return isPrefix(Opc); }
969  bool isPostfix() const { return isPostfix(Opc); }
970  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
971  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
972  bool isOffsetOfOp() const { return Opc == OffsetOf; }
973  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
974  bool isArithmeticOp() const { return isArithmeticOp(Opc); }
975
976  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
977  /// corresponds to, e.g. "sizeof" or "[pre]++"
978  static const char *getOpcodeStr(Opcode Op);
979
980  /// \brief Retrieve the unary opcode that corresponds to the given
981  /// overloaded operator.
982  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
983
984  /// \brief Retrieve the overloaded operator kind that corresponds to
985  /// the given unary opcode.
986  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
987
988  virtual SourceRange getSourceRange() const {
989    if (isPostfix())
990      return SourceRange(Val->getLocStart(), Loc);
991    else
992      return SourceRange(Loc, Val->getLocEnd());
993  }
994  virtual SourceLocation getExprLoc() const { return Loc; }
995
996  static bool classof(const Stmt *T) {
997    return T->getStmtClass() == UnaryOperatorClass;
998  }
999  static bool classof(const UnaryOperator *) { return true; }
1000
1001  // Iterators
1002  virtual child_iterator child_begin();
1003  virtual child_iterator child_end();
1004};
1005
1006/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
1007/// types and expressions.
1008class SizeOfAlignOfExpr : public Expr {
1009  bool isSizeof : 1;  // true if sizeof, false if alignof.
1010  bool isType : 1;    // true if operand is a type, false if an expression
1011  union {
1012    TypeSourceInfo *Ty;
1013    Stmt *Ex;
1014  } Argument;
1015  SourceLocation OpLoc, RParenLoc;
1016
1017protected:
1018  virtual void DoDestroy(ASTContext& C);
1019
1020public:
1021  SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo,
1022                    QualType resultType, SourceLocation op,
1023                    SourceLocation rp) :
1024      Expr(SizeOfAlignOfExprClass, resultType,
1025           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1026           // Value-dependent if the argument is type-dependent.
1027           TInfo->getType()->isDependentType()),
1028      isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
1029    Argument.Ty = TInfo;
1030  }
1031
1032  SizeOfAlignOfExpr(bool issizeof, Expr *E,
1033                    QualType resultType, SourceLocation op,
1034                    SourceLocation rp) :
1035      Expr(SizeOfAlignOfExprClass, resultType,
1036           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1037           // Value-dependent if the argument is type-dependent.
1038           E->isTypeDependent()),
1039      isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
1040    Argument.Ex = E;
1041  }
1042
1043  /// \brief Construct an empty sizeof/alignof expression.
1044  explicit SizeOfAlignOfExpr(EmptyShell Empty)
1045    : Expr(SizeOfAlignOfExprClass, Empty) { }
1046
1047  bool isSizeOf() const { return isSizeof; }
1048  void setSizeof(bool S) { isSizeof = S; }
1049
1050  bool isArgumentType() const { return isType; }
1051  QualType getArgumentType() const {
1052    return getArgumentTypeInfo()->getType();
1053  }
1054  TypeSourceInfo *getArgumentTypeInfo() const {
1055    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1056    return Argument.Ty;
1057  }
1058  Expr *getArgumentExpr() {
1059    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1060    return static_cast<Expr*>(Argument.Ex);
1061  }
1062  const Expr *getArgumentExpr() const {
1063    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
1064  }
1065
1066  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1067  void setArgument(TypeSourceInfo *TInfo) {
1068    Argument.Ty = TInfo;
1069    isType = true;
1070  }
1071
1072  /// Gets the argument type, or the type of the argument expression, whichever
1073  /// is appropriate.
1074  QualType getTypeOfArgument() const {
1075    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1076  }
1077
1078  SourceLocation getOperatorLoc() const { return OpLoc; }
1079  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1080
1081  SourceLocation getRParenLoc() const { return RParenLoc; }
1082  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1083
1084  virtual SourceRange getSourceRange() const {
1085    return SourceRange(OpLoc, RParenLoc);
1086  }
1087
1088  static bool classof(const Stmt *T) {
1089    return T->getStmtClass() == SizeOfAlignOfExprClass;
1090  }
1091  static bool classof(const SizeOfAlignOfExpr *) { return true; }
1092
1093  // Iterators
1094  virtual child_iterator child_begin();
1095  virtual child_iterator child_end();
1096};
1097
1098//===----------------------------------------------------------------------===//
1099// Postfix Operators.
1100//===----------------------------------------------------------------------===//
1101
1102/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1103class ArraySubscriptExpr : public Expr {
1104  enum { LHS, RHS, END_EXPR=2 };
1105  Stmt* SubExprs[END_EXPR];
1106  SourceLocation RBracketLoc;
1107public:
1108  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1109                     SourceLocation rbracketloc)
1110  : Expr(ArraySubscriptExprClass, t,
1111         lhs->isTypeDependent() || rhs->isTypeDependent(),
1112         lhs->isValueDependent() || rhs->isValueDependent()),
1113    RBracketLoc(rbracketloc) {
1114    SubExprs[LHS] = lhs;
1115    SubExprs[RHS] = rhs;
1116  }
1117
1118  /// \brief Create an empty array subscript expression.
1119  explicit ArraySubscriptExpr(EmptyShell Shell)
1120    : Expr(ArraySubscriptExprClass, Shell) { }
1121
1122  /// An array access can be written A[4] or 4[A] (both are equivalent).
1123  /// - getBase() and getIdx() always present the normalized view: A[4].
1124  ///    In this case getBase() returns "A" and getIdx() returns "4".
1125  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1126  ///    4[A] getLHS() returns "4".
1127  /// Note: Because vector element access is also written A[4] we must
1128  /// predicate the format conversion in getBase and getIdx only on the
1129  /// the type of the RHS, as it is possible for the LHS to be a vector of
1130  /// integer type
1131  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1132  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1133  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1134
1135  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1136  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1137  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1138
1139  Expr *getBase() {
1140    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1141  }
1142
1143  const Expr *getBase() const {
1144    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1145  }
1146
1147  Expr *getIdx() {
1148    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1149  }
1150
1151  const Expr *getIdx() const {
1152    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1153  }
1154
1155  virtual SourceRange getSourceRange() const {
1156    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1157  }
1158
1159  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1160  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1161
1162  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1163
1164  static bool classof(const Stmt *T) {
1165    return T->getStmtClass() == ArraySubscriptExprClass;
1166  }
1167  static bool classof(const ArraySubscriptExpr *) { return true; }
1168
1169  // Iterators
1170  virtual child_iterator child_begin();
1171  virtual child_iterator child_end();
1172};
1173
1174
1175/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1176/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1177/// while its subclasses may represent alternative syntax that (semantically)
1178/// results in a function call. For example, CXXOperatorCallExpr is
1179/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1180/// "str1 + str2" to resolve to a function call.
1181class CallExpr : public Expr {
1182  enum { FN=0, ARGS_START=1 };
1183  Stmt **SubExprs;
1184  unsigned NumArgs;
1185  SourceLocation RParenLoc;
1186
1187protected:
1188  // This version of the constructor is for derived classes.
1189  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
1190           QualType t, SourceLocation rparenloc);
1191
1192  virtual void DoDestroy(ASTContext& C);
1193
1194public:
1195  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1196           SourceLocation rparenloc);
1197
1198  /// \brief Build an empty call expression.
1199  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1200
1201  ~CallExpr() {}
1202
1203  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1204  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1205  void setCallee(Expr *F) { SubExprs[FN] = F; }
1206
1207  Decl *getCalleeDecl();
1208  const Decl *getCalleeDecl() const {
1209    return const_cast<CallExpr*>(this)->getCalleeDecl();
1210  }
1211
1212  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1213  FunctionDecl *getDirectCallee();
1214  const FunctionDecl *getDirectCallee() const {
1215    return const_cast<CallExpr*>(this)->getDirectCallee();
1216  }
1217
1218  /// getNumArgs - Return the number of actual arguments to this call.
1219  ///
1220  unsigned getNumArgs() const { return NumArgs; }
1221
1222  /// getArg - Return the specified argument.
1223  Expr *getArg(unsigned Arg) {
1224    assert(Arg < NumArgs && "Arg access out of range!");
1225    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1226  }
1227  const Expr *getArg(unsigned Arg) const {
1228    assert(Arg < NumArgs && "Arg access out of range!");
1229    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1230  }
1231
1232  /// setArg - Set the specified argument.
1233  void setArg(unsigned Arg, Expr *ArgExpr) {
1234    assert(Arg < NumArgs && "Arg access out of range!");
1235    SubExprs[Arg+ARGS_START] = ArgExpr;
1236  }
1237
1238  /// setNumArgs - This changes the number of arguments present in this call.
1239  /// Any orphaned expressions are deleted by this, and any new operands are set
1240  /// to null.
1241  void setNumArgs(ASTContext& C, unsigned NumArgs);
1242
1243  typedef ExprIterator arg_iterator;
1244  typedef ConstExprIterator const_arg_iterator;
1245
1246  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
1247  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
1248  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
1249  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
1250
1251  /// getNumCommas - Return the number of commas that must have been present in
1252  /// this function call.
1253  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1254
1255  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1256  /// not, return 0.
1257  unsigned isBuiltinCall(ASTContext &Context) const;
1258
1259  /// getCallReturnType - Get the return type of the call expr. This is not
1260  /// always the type of the expr itself, if the return type is a reference
1261  /// type.
1262  QualType getCallReturnType() const;
1263
1264  SourceLocation getRParenLoc() const { return RParenLoc; }
1265  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1266
1267  virtual SourceRange getSourceRange() const {
1268    return SourceRange(getCallee()->getLocStart(), RParenLoc);
1269  }
1270
1271  static bool classof(const Stmt *T) {
1272    return T->getStmtClass() == CallExprClass ||
1273           T->getStmtClass() == CXXOperatorCallExprClass ||
1274           T->getStmtClass() == CXXMemberCallExprClass;
1275  }
1276  static bool classof(const CallExpr *) { return true; }
1277  static bool classof(const CXXOperatorCallExpr *) { return true; }
1278  static bool classof(const CXXMemberCallExpr *) { return true; }
1279
1280  // Iterators
1281  virtual child_iterator child_begin();
1282  virtual child_iterator child_end();
1283};
1284
1285/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1286///
1287class MemberExpr : public Expr {
1288  /// Extra data stored in some member expressions.
1289  struct MemberNameQualifier : public NameQualifier {
1290    DeclAccessPair FoundDecl;
1291  };
1292
1293  /// Base - the expression for the base pointer or structure references.  In
1294  /// X.F, this is "X".
1295  Stmt *Base;
1296
1297  /// MemberDecl - This is the decl being referenced by the field/member name.
1298  /// In X.F, this is the decl referenced by F.
1299  ValueDecl *MemberDecl;
1300
1301  /// MemberLoc - This is the location of the member name.
1302  SourceLocation MemberLoc;
1303
1304  /// IsArrow - True if this is "X->F", false if this is "X.F".
1305  bool IsArrow : 1;
1306
1307  /// \brief True if this member expression used a nested-name-specifier to
1308  /// refer to the member, e.g., "x->Base::f", or found its member via a using
1309  /// declaration.  When true, a MemberNameQualifier
1310  /// structure is allocated immediately after the MemberExpr.
1311  bool HasQualifierOrFoundDecl : 1;
1312
1313  /// \brief True if this member expression specified a template argument list
1314  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1315  /// structure (and its TemplateArguments) are allocated immediately after
1316  /// the MemberExpr or, if the member expression also has a qualifier, after
1317  /// the MemberNameQualifier structure.
1318  bool HasExplicitTemplateArgumentList : 1;
1319
1320  /// \brief Retrieve the qualifier that preceded the member name, if any.
1321  MemberNameQualifier *getMemberQualifier() {
1322    assert(HasQualifierOrFoundDecl);
1323    return reinterpret_cast<MemberNameQualifier *> (this + 1);
1324  }
1325
1326  /// \brief Retrieve the qualifier that preceded the member name, if any.
1327  const MemberNameQualifier *getMemberQualifier() const {
1328    return const_cast<MemberExpr *>(this)->getMemberQualifier();
1329  }
1330
1331  /// \brief Retrieve the explicit template argument list that followed the
1332  /// member template name, if any.
1333  ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() {
1334    if (!HasExplicitTemplateArgumentList)
1335      return 0;
1336
1337    if (!HasQualifierOrFoundDecl)
1338      return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
1339
1340    return reinterpret_cast<ExplicitTemplateArgumentList *>(
1341                                                      getMemberQualifier() + 1);
1342  }
1343
1344  /// \brief Retrieve the explicit template argument list that followed the
1345  /// member template name, if any.
1346  const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const {
1347    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgumentList();
1348  }
1349
1350public:
1351  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1352             SourceLocation l, QualType ty)
1353    : Expr(MemberExprClass, ty,
1354           base->isTypeDependent(), base->isValueDependent()),
1355      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow),
1356      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
1357
1358  /// \brief Build an empty member reference expression.
1359  explicit MemberExpr(EmptyShell Empty)
1360    : Expr(MemberExprClass, Empty), HasQualifierOrFoundDecl(false),
1361      HasExplicitTemplateArgumentList(false) { }
1362
1363  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
1364                            NestedNameSpecifier *qual, SourceRange qualrange,
1365                            ValueDecl *memberdecl, DeclAccessPair founddecl,
1366                            SourceLocation l,
1367                            const TemplateArgumentListInfo *targs,
1368                            QualType ty);
1369
1370  void setBase(Expr *E) { Base = E; }
1371  Expr *getBase() const { return cast<Expr>(Base); }
1372
1373  /// \brief Retrieve the member declaration to which this expression refers.
1374  ///
1375  /// The returned declaration will either be a FieldDecl or (in C++)
1376  /// a CXXMethodDecl.
1377  ValueDecl *getMemberDecl() const { return MemberDecl; }
1378  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
1379
1380  /// \brief Retrieves the declaration found by lookup.
1381  DeclAccessPair getFoundDecl() const {
1382    if (!HasQualifierOrFoundDecl)
1383      return DeclAccessPair::make(getMemberDecl(),
1384                                  getMemberDecl()->getAccess());
1385    return getMemberQualifier()->FoundDecl;
1386  }
1387
1388  /// \brief Determines whether this member expression actually had
1389  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
1390  /// x->Base::foo.
1391  bool hasQualifier() const { return getQualifier() != 0; }
1392
1393  /// \brief If the member name was qualified, retrieves the source range of
1394  /// the nested-name-specifier that precedes the member name. Otherwise,
1395  /// returns an empty source range.
1396  SourceRange getQualifierRange() const {
1397    if (!HasQualifierOrFoundDecl)
1398      return SourceRange();
1399
1400    return getMemberQualifier()->Range;
1401  }
1402
1403  /// \brief If the member name was qualified, retrieves the
1404  /// nested-name-specifier that precedes the member name. Otherwise, returns
1405  /// NULL.
1406  NestedNameSpecifier *getQualifier() const {
1407    if (!HasQualifierOrFoundDecl)
1408      return 0;
1409
1410    return getMemberQualifier()->NNS;
1411  }
1412
1413  /// \brief Determines whether this member expression actually had a C++
1414  /// template argument list explicitly specified, e.g., x.f<int>.
1415  bool hasExplicitTemplateArgumentList() const {
1416    return HasExplicitTemplateArgumentList;
1417  }
1418
1419  /// \brief Copies the template arguments (if present) into the given
1420  /// structure.
1421  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1422    if (hasExplicitTemplateArgumentList())
1423      getExplicitTemplateArgumentList()->copyInto(List);
1424  }
1425
1426  /// \brief Retrieve the location of the left angle bracket following the
1427  /// member name ('<'), if any.
1428  SourceLocation getLAngleLoc() const {
1429    if (!HasExplicitTemplateArgumentList)
1430      return SourceLocation();
1431
1432    return getExplicitTemplateArgumentList()->LAngleLoc;
1433  }
1434
1435  /// \brief Retrieve the template arguments provided as part of this
1436  /// template-id.
1437  const TemplateArgumentLoc *getTemplateArgs() const {
1438    if (!HasExplicitTemplateArgumentList)
1439      return 0;
1440
1441    return getExplicitTemplateArgumentList()->getTemplateArgs();
1442  }
1443
1444  /// \brief Retrieve the number of template arguments provided as part of this
1445  /// template-id.
1446  unsigned getNumTemplateArgs() const {
1447    if (!HasExplicitTemplateArgumentList)
1448      return 0;
1449
1450    return getExplicitTemplateArgumentList()->NumTemplateArgs;
1451  }
1452
1453  /// \brief Retrieve the location of the right angle bracket following the
1454  /// template arguments ('>').
1455  SourceLocation getRAngleLoc() const {
1456    if (!HasExplicitTemplateArgumentList)
1457      return SourceLocation();
1458
1459    return getExplicitTemplateArgumentList()->RAngleLoc;
1460  }
1461
1462  bool isArrow() const { return IsArrow; }
1463  void setArrow(bool A) { IsArrow = A; }
1464
1465  /// getMemberLoc - Return the location of the "member", in X->F, it is the
1466  /// location of 'F'.
1467  SourceLocation getMemberLoc() const { return MemberLoc; }
1468  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
1469
1470  virtual SourceRange getSourceRange() const {
1471    // If we have an implicit base (like a C++ implicit this),
1472    // make sure not to return its location
1473    SourceLocation EndLoc = MemberLoc;
1474    if (HasExplicitTemplateArgumentList)
1475      EndLoc = getRAngleLoc();
1476
1477    SourceLocation BaseLoc = getBase()->getLocStart();
1478    if (BaseLoc.isInvalid())
1479      return SourceRange(MemberLoc, EndLoc);
1480    return SourceRange(BaseLoc, EndLoc);
1481  }
1482
1483  virtual SourceLocation getExprLoc() const { return MemberLoc; }
1484
1485  static bool classof(const Stmt *T) {
1486    return T->getStmtClass() == MemberExprClass;
1487  }
1488  static bool classof(const MemberExpr *) { return true; }
1489
1490  // Iterators
1491  virtual child_iterator child_begin();
1492  virtual child_iterator child_end();
1493};
1494
1495/// CompoundLiteralExpr - [C99 6.5.2.5]
1496///
1497class CompoundLiteralExpr : public Expr {
1498  /// LParenLoc - If non-null, this is the location of the left paren in a
1499  /// compound literal like "(int){4}".  This can be null if this is a
1500  /// synthesized compound expression.
1501  SourceLocation LParenLoc;
1502
1503  /// The type as written.  This can be an incomplete array type, in
1504  /// which case the actual expression type will be different.
1505  TypeSourceInfo *TInfo;
1506  Stmt *Init;
1507  bool FileScope;
1508public:
1509  // FIXME: Can compound literals be value-dependent?
1510  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
1511                      QualType T, Expr *init, bool fileScope)
1512    : Expr(CompoundLiteralExprClass, T,
1513           tinfo->getType()->isDependentType(), false),
1514      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
1515
1516  /// \brief Construct an empty compound literal.
1517  explicit CompoundLiteralExpr(EmptyShell Empty)
1518    : Expr(CompoundLiteralExprClass, Empty) { }
1519
1520  const Expr *getInitializer() const { return cast<Expr>(Init); }
1521  Expr *getInitializer() { return cast<Expr>(Init); }
1522  void setInitializer(Expr *E) { Init = E; }
1523
1524  bool isFileScope() const { return FileScope; }
1525  void setFileScope(bool FS) { FileScope = FS; }
1526
1527  SourceLocation getLParenLoc() const { return LParenLoc; }
1528  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1529
1530  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
1531  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
1532
1533  virtual SourceRange getSourceRange() const {
1534    // FIXME: Init should never be null.
1535    if (!Init)
1536      return SourceRange();
1537    if (LParenLoc.isInvalid())
1538      return Init->getSourceRange();
1539    return SourceRange(LParenLoc, Init->getLocEnd());
1540  }
1541
1542  static bool classof(const Stmt *T) {
1543    return T->getStmtClass() == CompoundLiteralExprClass;
1544  }
1545  static bool classof(const CompoundLiteralExpr *) { return true; }
1546
1547  // Iterators
1548  virtual child_iterator child_begin();
1549  virtual child_iterator child_end();
1550};
1551
1552/// CastExpr - Base class for type casts, including both implicit
1553/// casts (ImplicitCastExpr) and explicit casts that have some
1554/// representation in the source code (ExplicitCastExpr's derived
1555/// classes).
1556class CastExpr : public Expr {
1557public:
1558  /// CastKind - the kind of cast this represents.
1559  enum CastKind {
1560    /// CK_Unknown - Unknown cast kind.
1561    /// FIXME: The goal is to get rid of this and make all casts have a
1562    /// kind so that the AST client doesn't have to try to figure out what's
1563    /// going on.
1564    CK_Unknown,
1565
1566    /// CK_BitCast - Used for reinterpret_cast.
1567    CK_BitCast,
1568
1569    /// CK_NoOp - Used for const_cast.
1570    CK_NoOp,
1571
1572    /// CK_BaseToDerived - Base to derived class casts.
1573    CK_BaseToDerived,
1574
1575    /// CK_DerivedToBase - Derived to base class casts.
1576    CK_DerivedToBase,
1577
1578    /// CK_UncheckedDerivedToBase - Derived to base class casts that
1579    /// assume that the derived pointer is not null.
1580    CK_UncheckedDerivedToBase,
1581
1582    /// CK_Dynamic - Dynamic cast.
1583    CK_Dynamic,
1584
1585    /// CK_ToUnion - Cast to union (GCC extension).
1586    CK_ToUnion,
1587
1588    /// CK_ArrayToPointerDecay - Array to pointer decay.
1589    CK_ArrayToPointerDecay,
1590
1591    // CK_FunctionToPointerDecay - Function to pointer decay.
1592    CK_FunctionToPointerDecay,
1593
1594    /// CK_NullToMemberPointer - Null pointer to member pointer.
1595    CK_NullToMemberPointer,
1596
1597    /// CK_BaseToDerivedMemberPointer - Member pointer in base class to
1598    /// member pointer in derived class.
1599    CK_BaseToDerivedMemberPointer,
1600
1601    /// CK_DerivedToBaseMemberPointer - Member pointer in derived class to
1602    /// member pointer in base class.
1603    CK_DerivedToBaseMemberPointer,
1604
1605    /// CK_UserDefinedConversion - Conversion using a user defined type
1606    /// conversion function.
1607    CK_UserDefinedConversion,
1608
1609    /// CK_ConstructorConversion - Conversion by constructor
1610    CK_ConstructorConversion,
1611
1612    /// CK_IntegralToPointer - Integral to pointer
1613    CK_IntegralToPointer,
1614
1615    /// CK_PointerToIntegral - Pointer to integral
1616    CK_PointerToIntegral,
1617
1618    /// CK_ToVoid - Cast to void.
1619    CK_ToVoid,
1620
1621    /// CK_VectorSplat - Casting from an integer/floating type to an extended
1622    /// vector type with the same element type as the src type. Splats the
1623    /// src expression into the destination expression.
1624    CK_VectorSplat,
1625
1626    /// CK_IntegralCast - Casting between integral types of different size.
1627    CK_IntegralCast,
1628
1629    /// CK_IntegralToFloating - Integral to floating point.
1630    CK_IntegralToFloating,
1631
1632    /// CK_FloatingToIntegral - Floating point to integral.
1633    CK_FloatingToIntegral,
1634
1635    /// CK_FloatingCast - Casting between floating types of different size.
1636    CK_FloatingCast,
1637
1638    /// CK_MemberPointerToBoolean - Member pointer to boolean
1639    CK_MemberPointerToBoolean,
1640
1641    /// CK_AnyPointerToObjCPointerCast - Casting any pointer to objective-c
1642    /// pointer
1643    CK_AnyPointerToObjCPointerCast,
1644    /// CK_AnyPointerToBlockPointerCast - Casting any pointer to block
1645    /// pointer
1646    CK_AnyPointerToBlockPointerCast
1647
1648  };
1649
1650private:
1651  CastKind Kind;
1652  Stmt *Op;
1653
1654  /// BasePath - For derived-to-base and base-to-derived casts, the base array
1655  /// contains the inheritance path.
1656  CXXBaseSpecifierArray BasePath;
1657
1658  void CheckBasePath() const {
1659#ifndef NDEBUG
1660    switch (getCastKind()) {
1661    case CK_DerivedToBase:
1662    case CK_UncheckedDerivedToBase:
1663    case CK_DerivedToBaseMemberPointer:
1664    case CK_BaseToDerived:
1665    case CK_BaseToDerivedMemberPointer:
1666      assert(!BasePath.empty() && "Cast kind should have a base path!");
1667      break;
1668
1669    // These should not have an inheritance path.
1670    case CK_Unknown:
1671    case CK_BitCast:
1672    case CK_NoOp:
1673    case CK_Dynamic:
1674    case CK_ToUnion:
1675    case CK_ArrayToPointerDecay:
1676    case CK_FunctionToPointerDecay:
1677    case CK_NullToMemberPointer:
1678    case CK_UserDefinedConversion:
1679    case CK_ConstructorConversion:
1680    case CK_IntegralToPointer:
1681    case CK_PointerToIntegral:
1682    case CK_ToVoid:
1683    case CK_VectorSplat:
1684    case CK_IntegralCast:
1685    case CK_IntegralToFloating:
1686    case CK_FloatingToIntegral:
1687    case CK_FloatingCast:
1688    case CK_MemberPointerToBoolean:
1689    case CK_AnyPointerToObjCPointerCast:
1690    case CK_AnyPointerToBlockPointerCast:
1691      assert(BasePath.empty() && "Cast kind should not have a base path!");
1692      break;
1693    }
1694#endif
1695  }
1696
1697protected:
1698  CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op,
1699           CXXBaseSpecifierArray BasePath) :
1700    Expr(SC, ty,
1701         // Cast expressions are type-dependent if the type is
1702         // dependent (C++ [temp.dep.expr]p3).
1703         ty->isDependentType(),
1704         // Cast expressions are value-dependent if the type is
1705         // dependent or if the subexpression is value-dependent.
1706         ty->isDependentType() || (op && op->isValueDependent())),
1707    Kind(kind), Op(op), BasePath(BasePath) {
1708      CheckBasePath();
1709    }
1710
1711  /// \brief Construct an empty cast.
1712  CastExpr(StmtClass SC, EmptyShell Empty)
1713    : Expr(SC, Empty) { }
1714
1715  virtual void DoDestroy(ASTContext &C);
1716
1717public:
1718  CastKind getCastKind() const { return Kind; }
1719  void setCastKind(CastKind K) { Kind = K; }
1720  const char *getCastKindName() const;
1721
1722  Expr *getSubExpr() { return cast<Expr>(Op); }
1723  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1724  void setSubExpr(Expr *E) { Op = E; }
1725
1726  /// \brief Retrieve the cast subexpression as it was written in the source
1727  /// code, looking through any implicit casts or other intermediate nodes
1728  /// introduced by semantic analysis.
1729  Expr *getSubExprAsWritten();
1730  const Expr *getSubExprAsWritten() const {
1731    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
1732  }
1733
1734  const CXXBaseSpecifierArray& getBasePath() const { return BasePath; }
1735
1736  static bool classof(const Stmt *T) {
1737    StmtClass SC = T->getStmtClass();
1738    if (SC >= CXXStaticCastExprClass && SC <= CXXFunctionalCastExprClass)
1739      return true;
1740
1741    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
1742      return true;
1743
1744    return false;
1745  }
1746  static bool classof(const CastExpr *) { return true; }
1747
1748  // Iterators
1749  virtual child_iterator child_begin();
1750  virtual child_iterator child_end();
1751};
1752
1753/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1754/// conversions, which have no direct representation in the original
1755/// source code. For example: converting T[]->T*, void f()->void
1756/// (*f)(), float->double, short->int, etc.
1757///
1758/// In C, implicit casts always produce rvalues. However, in C++, an
1759/// implicit cast whose result is being bound to a reference will be
1760/// an lvalue. For example:
1761///
1762/// @code
1763/// class Base { };
1764/// class Derived : public Base { };
1765/// void f(Derived d) {
1766///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1767/// }
1768/// @endcode
1769class ImplicitCastExpr : public CastExpr {
1770  /// LvalueCast - Whether this cast produces an lvalue.
1771  bool LvalueCast;
1772
1773public:
1774  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
1775                   CXXBaseSpecifierArray BasePath, bool Lvalue)
1776    : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePath),
1777    LvalueCast(Lvalue) { }
1778
1779  /// \brief Construct an empty implicit cast.
1780  explicit ImplicitCastExpr(EmptyShell Shell)
1781    : CastExpr(ImplicitCastExprClass, Shell) { }
1782
1783  virtual SourceRange getSourceRange() const {
1784    return getSubExpr()->getSourceRange();
1785  }
1786
1787  /// isLvalueCast - Whether this cast produces an lvalue.
1788  bool isLvalueCast() const { return LvalueCast; }
1789
1790  /// setLvalueCast - Set whether this cast produces an lvalue.
1791  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1792
1793  static bool classof(const Stmt *T) {
1794    return T->getStmtClass() == ImplicitCastExprClass;
1795  }
1796  static bool classof(const ImplicitCastExpr *) { return true; }
1797};
1798
1799/// ExplicitCastExpr - An explicit cast written in the source
1800/// code.
1801///
1802/// This class is effectively an abstract class, because it provides
1803/// the basic representation of an explicitly-written cast without
1804/// specifying which kind of cast (C cast, functional cast, static
1805/// cast, etc.) was written; specific derived classes represent the
1806/// particular style of cast and its location information.
1807///
1808/// Unlike implicit casts, explicit cast nodes have two different
1809/// types: the type that was written into the source code, and the
1810/// actual type of the expression as determined by semantic
1811/// analysis. These types may differ slightly. For example, in C++ one
1812/// can cast to a reference type, which indicates that the resulting
1813/// expression will be an lvalue. The reference type, however, will
1814/// not be used as the type of the expression.
1815class ExplicitCastExpr : public CastExpr {
1816  /// TInfo - Source type info for the (written) type
1817  /// this expression is casting to.
1818  TypeSourceInfo *TInfo;
1819
1820protected:
1821  ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind,
1822                   Expr *op, CXXBaseSpecifierArray BasePath,
1823                   TypeSourceInfo *writtenTy)
1824    : CastExpr(SC, exprTy, kind, op, BasePath), TInfo(writtenTy) {}
1825
1826  /// \brief Construct an empty explicit cast.
1827  ExplicitCastExpr(StmtClass SC, EmptyShell Shell)
1828    : CastExpr(SC, Shell) { }
1829
1830public:
1831  /// getTypeInfoAsWritten - Returns the type source info for the type
1832  /// that this expression is casting to.
1833  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
1834  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
1835
1836  /// getTypeAsWritten - Returns the type that this expression is
1837  /// casting to, as written in the source code.
1838  QualType getTypeAsWritten() const { return TInfo->getType(); }
1839
1840  static bool classof(const Stmt *T) {
1841    StmtClass SC = T->getStmtClass();
1842    if (SC >= CStyleCastExprClass && SC <= CStyleCastExprClass)
1843      return true;
1844    if (SC >= CXXStaticCastExprClass && SC <= CXXFunctionalCastExprClass)
1845      return true;
1846
1847    return false;
1848  }
1849  static bool classof(const ExplicitCastExpr *) { return true; }
1850};
1851
1852/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1853/// cast in C++ (C++ [expr.cast]), which uses the syntax
1854/// (Type)expr. For example: @c (int)f.
1855class CStyleCastExpr : public ExplicitCastExpr {
1856  SourceLocation LPLoc; // the location of the left paren
1857  SourceLocation RPLoc; // the location of the right paren
1858public:
1859  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op,
1860                 CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy,
1861                 SourceLocation l, SourceLocation r)
1862    : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, BasePath,
1863                       writtenTy), LPLoc(l), RPLoc(r) {}
1864
1865  /// \brief Construct an empty C-style explicit cast.
1866  explicit CStyleCastExpr(EmptyShell Shell)
1867    : ExplicitCastExpr(CStyleCastExprClass, Shell) { }
1868
1869  SourceLocation getLParenLoc() const { return LPLoc; }
1870  void setLParenLoc(SourceLocation L) { LPLoc = L; }
1871
1872  SourceLocation getRParenLoc() const { return RPLoc; }
1873  void setRParenLoc(SourceLocation L) { RPLoc = L; }
1874
1875  virtual SourceRange getSourceRange() const {
1876    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1877  }
1878  static bool classof(const Stmt *T) {
1879    return T->getStmtClass() == CStyleCastExprClass;
1880  }
1881  static bool classof(const CStyleCastExpr *) { return true; }
1882};
1883
1884/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
1885///
1886/// This expression node kind describes a builtin binary operation,
1887/// such as "x + y" for integer values "x" and "y". The operands will
1888/// already have been converted to appropriate types (e.g., by
1889/// performing promotions or conversions).
1890///
1891/// In C++, where operators may be overloaded, a different kind of
1892/// expression node (CXXOperatorCallExpr) is used to express the
1893/// invocation of an overloaded operator with operator syntax. Within
1894/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
1895/// used to store an expression "x + y" depends on the subexpressions
1896/// for x and y. If neither x or y is type-dependent, and the "+"
1897/// operator resolves to a built-in operation, BinaryOperator will be
1898/// used to express the computation (x and y may still be
1899/// value-dependent). If either x or y is type-dependent, or if the
1900/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
1901/// be used to express the computation.
1902class BinaryOperator : public Expr {
1903public:
1904  enum Opcode {
1905    // Operators listed in order of precedence.
1906    // Note that additions to this should also update the StmtVisitor class.
1907    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1908    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1909    Add, Sub,         // [C99 6.5.6] Additive operators.
1910    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1911    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1912    EQ, NE,           // [C99 6.5.9] Equality operators.
1913    And,              // [C99 6.5.10] Bitwise AND operator.
1914    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1915    Or,               // [C99 6.5.12] Bitwise OR operator.
1916    LAnd,             // [C99 6.5.13] Logical AND operator.
1917    LOr,              // [C99 6.5.14] Logical OR operator.
1918    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1919    DivAssign, RemAssign,
1920    AddAssign, SubAssign,
1921    ShlAssign, ShrAssign,
1922    AndAssign, XorAssign,
1923    OrAssign,
1924    Comma             // [C99 6.5.17] Comma operator.
1925  };
1926private:
1927  enum { LHS, RHS, END_EXPR };
1928  Stmt* SubExprs[END_EXPR];
1929  Opcode Opc;
1930  SourceLocation OpLoc;
1931public:
1932
1933  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1934                 SourceLocation opLoc)
1935    : Expr(BinaryOperatorClass, ResTy,
1936           lhs->isTypeDependent() || rhs->isTypeDependent(),
1937           lhs->isValueDependent() || rhs->isValueDependent()),
1938      Opc(opc), OpLoc(opLoc) {
1939    SubExprs[LHS] = lhs;
1940    SubExprs[RHS] = rhs;
1941    assert(!isCompoundAssignmentOp() &&
1942           "Use ArithAssignBinaryOperator for compound assignments");
1943  }
1944
1945  /// \brief Construct an empty binary operator.
1946  explicit BinaryOperator(EmptyShell Empty)
1947    : Expr(BinaryOperatorClass, Empty), Opc(Comma) { }
1948
1949  SourceLocation getOperatorLoc() const { return OpLoc; }
1950  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1951
1952  Opcode getOpcode() const { return Opc; }
1953  void setOpcode(Opcode O) { Opc = O; }
1954
1955  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1956  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1957  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1958  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1959
1960  virtual SourceRange getSourceRange() const {
1961    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1962  }
1963
1964  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1965  /// corresponds to, e.g. "<<=".
1966  static const char *getOpcodeStr(Opcode Op);
1967
1968  /// \brief Retrieve the binary opcode that corresponds to the given
1969  /// overloaded operator.
1970  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
1971
1972  /// \brief Retrieve the overloaded operator kind that corresponds to
1973  /// the given binary opcode.
1974  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1975
1976  /// predicates to categorize the respective opcodes.
1977  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1978  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1979  static bool isShiftOp(Opcode Opc) { return Opc == Shl || Opc == Shr; }
1980  bool isShiftOp() const { return isShiftOp(Opc); }
1981
1982  static bool isBitwiseOp(Opcode Opc) { return Opc >= And && Opc <= Or; }
1983  bool isBitwiseOp() const { return isBitwiseOp(Opc); }
1984
1985  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1986  bool isRelationalOp() const { return isRelationalOp(Opc); }
1987
1988  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1989  bool isEqualityOp() const { return isEqualityOp(Opc); }
1990
1991  static bool isComparisonOp(Opcode Opc) { return Opc >= LT && Opc <= NE; }
1992  bool isComparisonOp() const { return isComparisonOp(Opc); }
1993
1994  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1995  bool isLogicalOp() const { return isLogicalOp(Opc); }
1996
1997  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1998  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1999  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
2000
2001  static bool classof(const Stmt *S) {
2002    return S->getStmtClass() == BinaryOperatorClass ||
2003           S->getStmtClass() == CompoundAssignOperatorClass;
2004  }
2005  static bool classof(const BinaryOperator *) { return true; }
2006
2007  // Iterators
2008  virtual child_iterator child_begin();
2009  virtual child_iterator child_end();
2010
2011protected:
2012  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2013                 SourceLocation opLoc, bool dead)
2014    : Expr(CompoundAssignOperatorClass, ResTy,
2015           lhs->isTypeDependent() || rhs->isTypeDependent(),
2016           lhs->isValueDependent() || rhs->isValueDependent()),
2017      Opc(opc), OpLoc(opLoc) {
2018    SubExprs[LHS] = lhs;
2019    SubExprs[RHS] = rhs;
2020  }
2021
2022  BinaryOperator(StmtClass SC, EmptyShell Empty)
2023    : Expr(SC, Empty), Opc(MulAssign) { }
2024};
2025
2026/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2027/// track of the type the operation is performed in.  Due to the semantics of
2028/// these operators, the operands are promoted, the aritmetic performed, an
2029/// implicit conversion back to the result type done, then the assignment takes
2030/// place.  This captures the intermediate type which the computation is done
2031/// in.
2032class CompoundAssignOperator : public BinaryOperator {
2033  QualType ComputationLHSType;
2034  QualType ComputationResultType;
2035public:
2036  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
2037                         QualType ResType, QualType CompLHSType,
2038                         QualType CompResultType,
2039                         SourceLocation OpLoc)
2040    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
2041      ComputationLHSType(CompLHSType),
2042      ComputationResultType(CompResultType) {
2043    assert(isCompoundAssignmentOp() &&
2044           "Only should be used for compound assignments");
2045  }
2046
2047  /// \brief Build an empty compound assignment operator expression.
2048  explicit CompoundAssignOperator(EmptyShell Empty)
2049    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2050
2051  // The two computation types are the type the LHS is converted
2052  // to for the computation and the type of the result; the two are
2053  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2054  QualType getComputationLHSType() const { return ComputationLHSType; }
2055  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2056
2057  QualType getComputationResultType() const { return ComputationResultType; }
2058  void setComputationResultType(QualType T) { ComputationResultType = T; }
2059
2060  static bool classof(const CompoundAssignOperator *) { return true; }
2061  static bool classof(const Stmt *S) {
2062    return S->getStmtClass() == CompoundAssignOperatorClass;
2063  }
2064};
2065
2066/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
2067/// GNU "missing LHS" extension is in use.
2068///
2069class ConditionalOperator : public Expr {
2070  enum { COND, LHS, RHS, END_EXPR };
2071  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2072  SourceLocation QuestionLoc, ColonLoc;
2073public:
2074  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2075                      SourceLocation CLoc, Expr *rhs, QualType t)
2076    : Expr(ConditionalOperatorClass, t,
2077           // FIXME: the type of the conditional operator doesn't
2078           // depend on the type of the conditional, but the standard
2079           // seems to imply that it could. File a bug!
2080           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
2081           (cond->isValueDependent() ||
2082            (lhs && lhs->isValueDependent()) ||
2083            (rhs && rhs->isValueDependent()))),
2084      QuestionLoc(QLoc),
2085      ColonLoc(CLoc) {
2086    SubExprs[COND] = cond;
2087    SubExprs[LHS] = lhs;
2088    SubExprs[RHS] = rhs;
2089  }
2090
2091  /// \brief Build an empty conditional operator.
2092  explicit ConditionalOperator(EmptyShell Empty)
2093    : Expr(ConditionalOperatorClass, Empty) { }
2094
2095  // getCond - Return the expression representing the condition for
2096  //  the ?: operator.
2097  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2098  void setCond(Expr *E) { SubExprs[COND] = E; }
2099
2100  // getTrueExpr - Return the subexpression representing the value of the ?:
2101  //  expression if the condition evaluates to true.  In most cases this value
2102  //  will be the same as getLHS() except a GCC extension allows the left
2103  //  subexpression to be omitted, and instead of the condition be returned.
2104  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
2105  //  is only evaluated once.
2106  Expr *getTrueExpr() const {
2107    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
2108  }
2109
2110  // getTrueExpr - Return the subexpression representing the value of the ?:
2111  // expression if the condition evaluates to false. This is the same as getRHS.
2112  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2113
2114  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
2115  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2116
2117  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2118  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2119
2120  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2121  void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
2122
2123  SourceLocation getColonLoc() const { return ColonLoc; }
2124  void setColonLoc(SourceLocation L) { ColonLoc = L; }
2125
2126  virtual SourceRange getSourceRange() const {
2127    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2128  }
2129  static bool classof(const Stmt *T) {
2130    return T->getStmtClass() == ConditionalOperatorClass;
2131  }
2132  static bool classof(const ConditionalOperator *) { return true; }
2133
2134  // Iterators
2135  virtual child_iterator child_begin();
2136  virtual child_iterator child_end();
2137};
2138
2139/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2140class AddrLabelExpr : public Expr {
2141  SourceLocation AmpAmpLoc, LabelLoc;
2142  LabelStmt *Label;
2143public:
2144  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
2145                QualType t)
2146    : Expr(AddrLabelExprClass, t, false, false),
2147      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2148
2149  /// \brief Build an empty address of a label expression.
2150  explicit AddrLabelExpr(EmptyShell Empty)
2151    : Expr(AddrLabelExprClass, Empty) { }
2152
2153  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2154  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2155  SourceLocation getLabelLoc() const { return LabelLoc; }
2156  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2157
2158  virtual SourceRange getSourceRange() const {
2159    return SourceRange(AmpAmpLoc, LabelLoc);
2160  }
2161
2162  LabelStmt *getLabel() const { return Label; }
2163  void setLabel(LabelStmt *S) { Label = S; }
2164
2165  static bool classof(const Stmt *T) {
2166    return T->getStmtClass() == AddrLabelExprClass;
2167  }
2168  static bool classof(const AddrLabelExpr *) { return true; }
2169
2170  // Iterators
2171  virtual child_iterator child_begin();
2172  virtual child_iterator child_end();
2173};
2174
2175/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2176/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2177/// takes the value of the last subexpression.
2178class StmtExpr : public Expr {
2179  Stmt *SubStmt;
2180  SourceLocation LParenLoc, RParenLoc;
2181public:
2182  // FIXME: Does type-dependence need to be computed differently?
2183  StmtExpr(CompoundStmt *substmt, QualType T,
2184           SourceLocation lp, SourceLocation rp) :
2185    Expr(StmtExprClass, T, T->isDependentType(), false),
2186    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2187
2188  /// \brief Build an empty statement expression.
2189  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2190
2191  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2192  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2193  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2194
2195  virtual SourceRange getSourceRange() const {
2196    return SourceRange(LParenLoc, RParenLoc);
2197  }
2198
2199  SourceLocation getLParenLoc() const { return LParenLoc; }
2200  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2201  SourceLocation getRParenLoc() const { return RParenLoc; }
2202  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2203
2204  static bool classof(const Stmt *T) {
2205    return T->getStmtClass() == StmtExprClass;
2206  }
2207  static bool classof(const StmtExpr *) { return true; }
2208
2209  // Iterators
2210  virtual child_iterator child_begin();
2211  virtual child_iterator child_end();
2212};
2213
2214/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
2215/// This AST node represents a function that returns 1 if two *types* (not
2216/// expressions) are compatible. The result of this built-in function can be
2217/// used in integer constant expressions.
2218class TypesCompatibleExpr : public Expr {
2219  QualType Type1;
2220  QualType Type2;
2221  SourceLocation BuiltinLoc, RParenLoc;
2222public:
2223  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
2224                      QualType t1, QualType t2, SourceLocation RP) :
2225    Expr(TypesCompatibleExprClass, ReturnType, false, false),
2226    Type1(t1), Type2(t2), BuiltinLoc(BLoc), RParenLoc(RP) {}
2227
2228  /// \brief Build an empty __builtin_type_compatible_p expression.
2229  explicit TypesCompatibleExpr(EmptyShell Empty)
2230    : Expr(TypesCompatibleExprClass, Empty) { }
2231
2232  QualType getArgType1() const { return Type1; }
2233  void setArgType1(QualType T) { Type1 = T; }
2234  QualType getArgType2() const { return Type2; }
2235  void setArgType2(QualType T) { Type2 = T; }
2236
2237  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2238  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2239
2240  SourceLocation getRParenLoc() const { return RParenLoc; }
2241  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2242
2243  virtual SourceRange getSourceRange() const {
2244    return SourceRange(BuiltinLoc, RParenLoc);
2245  }
2246  static bool classof(const Stmt *T) {
2247    return T->getStmtClass() == TypesCompatibleExprClass;
2248  }
2249  static bool classof(const TypesCompatibleExpr *) { return true; }
2250
2251  // Iterators
2252  virtual child_iterator child_begin();
2253  virtual child_iterator child_end();
2254};
2255
2256/// ShuffleVectorExpr - clang-specific builtin-in function
2257/// __builtin_shufflevector.
2258/// This AST node represents a operator that does a constant
2259/// shuffle, similar to LLVM's shufflevector instruction. It takes
2260/// two vectors and a variable number of constant indices,
2261/// and returns the appropriately shuffled vector.
2262class ShuffleVectorExpr : public Expr {
2263  SourceLocation BuiltinLoc, RParenLoc;
2264
2265  // SubExprs - the list of values passed to the __builtin_shufflevector
2266  // function. The first two are vectors, and the rest are constant
2267  // indices.  The number of values in this list is always
2268  // 2+the number of indices in the vector type.
2269  Stmt **SubExprs;
2270  unsigned NumExprs;
2271
2272protected:
2273  virtual void DoDestroy(ASTContext &C);
2274
2275public:
2276  // FIXME: Can a shufflevector be value-dependent?  Does type-dependence need
2277  // to be computed differently?
2278  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2279                    QualType Type, SourceLocation BLoc,
2280                    SourceLocation RP) :
2281    Expr(ShuffleVectorExprClass, Type, Type->isDependentType(), false),
2282    BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) {
2283
2284    SubExprs = new (C) Stmt*[nexpr];
2285    for (unsigned i = 0; i < nexpr; i++)
2286      SubExprs[i] = args[i];
2287  }
2288
2289  /// \brief Build an empty vector-shuffle expression.
2290  explicit ShuffleVectorExpr(EmptyShell Empty)
2291    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2292
2293  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2294  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2295
2296  SourceLocation getRParenLoc() const { return RParenLoc; }
2297  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2298
2299  virtual SourceRange getSourceRange() const {
2300    return SourceRange(BuiltinLoc, RParenLoc);
2301  }
2302  static bool classof(const Stmt *T) {
2303    return T->getStmtClass() == ShuffleVectorExprClass;
2304  }
2305  static bool classof(const ShuffleVectorExpr *) { return true; }
2306
2307  ~ShuffleVectorExpr() {}
2308
2309  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
2310  /// constant expression, the actual arguments passed in, and the function
2311  /// pointers.
2312  unsigned getNumSubExprs() const { return NumExprs; }
2313
2314  /// getExpr - Return the Expr at the specified index.
2315  Expr *getExpr(unsigned Index) {
2316    assert((Index < NumExprs) && "Arg access out of range!");
2317    return cast<Expr>(SubExprs[Index]);
2318  }
2319  const Expr *getExpr(unsigned Index) const {
2320    assert((Index < NumExprs) && "Arg access out of range!");
2321    return cast<Expr>(SubExprs[Index]);
2322  }
2323
2324  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2325
2326  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2327    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2328    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2329  }
2330
2331  // Iterators
2332  virtual child_iterator child_begin();
2333  virtual child_iterator child_end();
2334};
2335
2336/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2337/// This AST node is similar to the conditional operator (?:) in C, with
2338/// the following exceptions:
2339/// - the test expression must be a integer constant expression.
2340/// - the expression returned acts like the chosen subexpression in every
2341///   visible way: the type is the same as that of the chosen subexpression,
2342///   and all predicates (whether it's an l-value, whether it's an integer
2343///   constant expression, etc.) return the same result as for the chosen
2344///   sub-expression.
2345class ChooseExpr : public Expr {
2346  enum { COND, LHS, RHS, END_EXPR };
2347  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2348  SourceLocation BuiltinLoc, RParenLoc;
2349public:
2350  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
2351             SourceLocation RP, bool TypeDependent, bool ValueDependent)
2352    : Expr(ChooseExprClass, t, TypeDependent, ValueDependent),
2353      BuiltinLoc(BLoc), RParenLoc(RP) {
2354      SubExprs[COND] = cond;
2355      SubExprs[LHS] = lhs;
2356      SubExprs[RHS] = rhs;
2357    }
2358
2359  /// \brief Build an empty __builtin_choose_expr.
2360  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
2361
2362  /// isConditionTrue - Return whether the condition is true (i.e. not
2363  /// equal to zero).
2364  bool isConditionTrue(ASTContext &C) const;
2365
2366  /// getChosenSubExpr - Return the subexpression chosen according to the
2367  /// condition.
2368  Expr *getChosenSubExpr(ASTContext &C) const {
2369    return isConditionTrue(C) ? getLHS() : getRHS();
2370  }
2371
2372  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2373  void setCond(Expr *E) { SubExprs[COND] = E; }
2374  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2375  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2376  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2377  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2378
2379  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2380  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2381
2382  SourceLocation getRParenLoc() const { return RParenLoc; }
2383  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2384
2385  virtual SourceRange getSourceRange() const {
2386    return SourceRange(BuiltinLoc, RParenLoc);
2387  }
2388  static bool classof(const Stmt *T) {
2389    return T->getStmtClass() == ChooseExprClass;
2390  }
2391  static bool classof(const ChooseExpr *) { return true; }
2392
2393  // Iterators
2394  virtual child_iterator child_begin();
2395  virtual child_iterator child_end();
2396};
2397
2398/// GNUNullExpr - Implements the GNU __null extension, which is a name
2399/// for a null pointer constant that has integral type (e.g., int or
2400/// long) and is the same size and alignment as a pointer. The __null
2401/// extension is typically only used by system headers, which define
2402/// NULL as __null in C++ rather than using 0 (which is an integer
2403/// that may not match the size of a pointer).
2404class GNUNullExpr : public Expr {
2405  /// TokenLoc - The location of the __null keyword.
2406  SourceLocation TokenLoc;
2407
2408public:
2409  GNUNullExpr(QualType Ty, SourceLocation Loc)
2410    : Expr(GNUNullExprClass, Ty, false, false), TokenLoc(Loc) { }
2411
2412  /// \brief Build an empty GNU __null expression.
2413  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
2414
2415  /// getTokenLocation - The location of the __null token.
2416  SourceLocation getTokenLocation() const { return TokenLoc; }
2417  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
2418
2419  virtual SourceRange getSourceRange() const {
2420    return SourceRange(TokenLoc);
2421  }
2422  static bool classof(const Stmt *T) {
2423    return T->getStmtClass() == GNUNullExprClass;
2424  }
2425  static bool classof(const GNUNullExpr *) { return true; }
2426
2427  // Iterators
2428  virtual child_iterator child_begin();
2429  virtual child_iterator child_end();
2430};
2431
2432/// VAArgExpr, used for the builtin function __builtin_va_arg.
2433class VAArgExpr : public Expr {
2434  Stmt *Val;
2435  SourceLocation BuiltinLoc, RParenLoc;
2436public:
2437  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
2438    : Expr(VAArgExprClass, t, t->isDependentType(), false),
2439      Val(e),
2440      BuiltinLoc(BLoc),
2441      RParenLoc(RPLoc) { }
2442
2443  /// \brief Create an empty __builtin_va_arg expression.
2444  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
2445
2446  const Expr *getSubExpr() const { return cast<Expr>(Val); }
2447  Expr *getSubExpr() { return cast<Expr>(Val); }
2448  void setSubExpr(Expr *E) { Val = E; }
2449
2450  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2451  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2452
2453  SourceLocation getRParenLoc() const { return RParenLoc; }
2454  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2455
2456  virtual SourceRange getSourceRange() const {
2457    return SourceRange(BuiltinLoc, RParenLoc);
2458  }
2459  static bool classof(const Stmt *T) {
2460    return T->getStmtClass() == VAArgExprClass;
2461  }
2462  static bool classof(const VAArgExpr *) { return true; }
2463
2464  // Iterators
2465  virtual child_iterator child_begin();
2466  virtual child_iterator child_end();
2467};
2468
2469/// @brief Describes an C or C++ initializer list.
2470///
2471/// InitListExpr describes an initializer list, which can be used to
2472/// initialize objects of different types, including
2473/// struct/class/union types, arrays, and vectors. For example:
2474///
2475/// @code
2476/// struct foo x = { 1, { 2, 3 } };
2477/// @endcode
2478///
2479/// Prior to semantic analysis, an initializer list will represent the
2480/// initializer list as written by the user, but will have the
2481/// placeholder type "void". This initializer list is called the
2482/// syntactic form of the initializer, and may contain C99 designated
2483/// initializers (represented as DesignatedInitExprs), initializations
2484/// of subobject members without explicit braces, and so on. Clients
2485/// interested in the original syntax of the initializer list should
2486/// use the syntactic form of the initializer list.
2487///
2488/// After semantic analysis, the initializer list will represent the
2489/// semantic form of the initializer, where the initializations of all
2490/// subobjects are made explicit with nested InitListExpr nodes and
2491/// C99 designators have been eliminated by placing the designated
2492/// initializations into the subobject they initialize. Additionally,
2493/// any "holes" in the initialization, where no initializer has been
2494/// specified for a particular subobject, will be replaced with
2495/// implicitly-generated ImplicitValueInitExpr expressions that
2496/// value-initialize the subobjects. Note, however, that the
2497/// initializer lists may still have fewer initializers than there are
2498/// elements to initialize within the object.
2499///
2500/// Given the semantic form of the initializer list, one can retrieve
2501/// the original syntactic form of that initializer list (if it
2502/// exists) using getSyntacticForm(). Since many initializer lists
2503/// have the same syntactic and semantic forms, getSyntacticForm() may
2504/// return NULL, indicating that the current initializer list also
2505/// serves as its syntactic form.
2506class InitListExpr : public Expr {
2507  // FIXME: Eliminate this vector in favor of ASTContext allocation
2508  typedef ASTVector<Stmt *> InitExprsTy;
2509  InitExprsTy InitExprs;
2510  SourceLocation LBraceLoc, RBraceLoc;
2511
2512  /// Contains the initializer list that describes the syntactic form
2513  /// written in the source code.
2514  InitListExpr *SyntacticForm;
2515
2516  /// If this initializer list initializes a union, specifies which
2517  /// field within the union will be initialized.
2518  FieldDecl *UnionFieldInit;
2519
2520  /// Whether this initializer list originally had a GNU array-range
2521  /// designator in it. This is a temporary marker used by CodeGen.
2522  bool HadArrayRangeDesignator;
2523
2524public:
2525  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
2526               Expr **initexprs, unsigned numinits,
2527               SourceLocation rbraceloc);
2528
2529  /// \brief Build an empty initializer list.
2530  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
2531    : Expr(InitListExprClass, Empty), InitExprs(C) { }
2532
2533  unsigned getNumInits() const { return InitExprs.size(); }
2534
2535  const Expr* getInit(unsigned Init) const {
2536    assert(Init < getNumInits() && "Initializer access out of range!");
2537    return cast_or_null<Expr>(InitExprs[Init]);
2538  }
2539
2540  Expr* getInit(unsigned Init) {
2541    assert(Init < getNumInits() && "Initializer access out of range!");
2542    return cast_or_null<Expr>(InitExprs[Init]);
2543  }
2544
2545  void setInit(unsigned Init, Expr *expr) {
2546    assert(Init < getNumInits() && "Initializer access out of range!");
2547    InitExprs[Init] = expr;
2548  }
2549
2550  /// \brief Reserve space for some number of initializers.
2551  void reserveInits(ASTContext &C, unsigned NumInits);
2552
2553  /// @brief Specify the number of initializers
2554  ///
2555  /// If there are more than @p NumInits initializers, the remaining
2556  /// initializers will be destroyed. If there are fewer than @p
2557  /// NumInits initializers, NULL expressions will be added for the
2558  /// unknown initializers.
2559  void resizeInits(ASTContext &Context, unsigned NumInits);
2560
2561  /// @brief Updates the initializer at index @p Init with the new
2562  /// expression @p expr, and returns the old expression at that
2563  /// location.
2564  ///
2565  /// When @p Init is out of range for this initializer list, the
2566  /// initializer list will be extended with NULL expressions to
2567  /// accomodate the new entry.
2568  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
2569
2570  /// \brief If this initializes a union, specifies which field in the
2571  /// union to initialize.
2572  ///
2573  /// Typically, this field is the first named field within the
2574  /// union. However, a designated initializer can specify the
2575  /// initialization of a different field within the union.
2576  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2577  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2578
2579  // Explicit InitListExpr's originate from source code (and have valid source
2580  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2581  bool isExplicit() {
2582    return LBraceLoc.isValid() && RBraceLoc.isValid();
2583  }
2584
2585  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2586  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2587  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2588  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2589
2590  /// @brief Retrieve the initializer list that describes the
2591  /// syntactic form of the initializer.
2592  ///
2593  ///
2594  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2595  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2596
2597  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2598  void sawArrayRangeDesignator(bool ARD = true) {
2599    HadArrayRangeDesignator = ARD;
2600  }
2601
2602  virtual SourceRange getSourceRange() const {
2603    return SourceRange(LBraceLoc, RBraceLoc);
2604  }
2605  static bool classof(const Stmt *T) {
2606    return T->getStmtClass() == InitListExprClass;
2607  }
2608  static bool classof(const InitListExpr *) { return true; }
2609
2610  // Iterators
2611  virtual child_iterator child_begin();
2612  virtual child_iterator child_end();
2613
2614  typedef InitExprsTy::iterator iterator;
2615  typedef InitExprsTy::reverse_iterator reverse_iterator;
2616
2617  iterator begin() { return InitExprs.begin(); }
2618  iterator end() { return InitExprs.end(); }
2619  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2620  reverse_iterator rend() { return InitExprs.rend(); }
2621};
2622
2623/// @brief Represents a C99 designated initializer expression.
2624///
2625/// A designated initializer expression (C99 6.7.8) contains one or
2626/// more designators (which can be field designators, array
2627/// designators, or GNU array-range designators) followed by an
2628/// expression that initializes the field or element(s) that the
2629/// designators refer to. For example, given:
2630///
2631/// @code
2632/// struct point {
2633///   double x;
2634///   double y;
2635/// };
2636/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2637/// @endcode
2638///
2639/// The InitListExpr contains three DesignatedInitExprs, the first of
2640/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2641/// designators, one array designator for @c [2] followed by one field
2642/// designator for @c .y. The initalization expression will be 1.0.
2643class DesignatedInitExpr : public Expr {
2644public:
2645  /// \brief Forward declaration of the Designator class.
2646  class Designator;
2647
2648private:
2649  /// The location of the '=' or ':' prior to the actual initializer
2650  /// expression.
2651  SourceLocation EqualOrColonLoc;
2652
2653  /// Whether this designated initializer used the GNU deprecated
2654  /// syntax rather than the C99 '=' syntax.
2655  bool GNUSyntax : 1;
2656
2657  /// The number of designators in this initializer expression.
2658  unsigned NumDesignators : 15;
2659
2660  /// \brief The designators in this designated initialization
2661  /// expression.
2662  Designator *Designators;
2663
2664  /// The number of subexpressions of this initializer expression,
2665  /// which contains both the initializer and any additional
2666  /// expressions used by array and array-range designators.
2667  unsigned NumSubExprs : 16;
2668
2669
2670  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
2671                     const Designator *Designators,
2672                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2673                     Expr **IndexExprs, unsigned NumIndexExprs,
2674                     Expr *Init);
2675
2676  explicit DesignatedInitExpr(unsigned NumSubExprs)
2677    : Expr(DesignatedInitExprClass, EmptyShell()),
2678      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2679
2680protected:
2681  virtual void DoDestroy(ASTContext &C);
2682
2683  void DestroyDesignators(ASTContext &C);
2684
2685public:
2686  /// A field designator, e.g., ".x".
2687  struct FieldDesignator {
2688    /// Refers to the field that is being initialized. The low bit
2689    /// of this field determines whether this is actually a pointer
2690    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2691    /// initially constructed, a field designator will store an
2692    /// IdentifierInfo*. After semantic analysis has resolved that
2693    /// name, the field designator will instead store a FieldDecl*.
2694    uintptr_t NameOrField;
2695
2696    /// The location of the '.' in the designated initializer.
2697    unsigned DotLoc;
2698
2699    /// The location of the field name in the designated initializer.
2700    unsigned FieldLoc;
2701  };
2702
2703  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2704  struct ArrayOrRangeDesignator {
2705    /// Location of the first index expression within the designated
2706    /// initializer expression's list of subexpressions.
2707    unsigned Index;
2708    /// The location of the '[' starting the array range designator.
2709    unsigned LBracketLoc;
2710    /// The location of the ellipsis separating the start and end
2711    /// indices. Only valid for GNU array-range designators.
2712    unsigned EllipsisLoc;
2713    /// The location of the ']' terminating the array range designator.
2714    unsigned RBracketLoc;
2715  };
2716
2717  /// @brief Represents a single C99 designator.
2718  ///
2719  /// @todo This class is infuriatingly similar to clang::Designator,
2720  /// but minor differences (storing indices vs. storing pointers)
2721  /// keep us from reusing it. Try harder, later, to rectify these
2722  /// differences.
2723  class Designator {
2724    /// @brief The kind of designator this describes.
2725    enum {
2726      FieldDesignator,
2727      ArrayDesignator,
2728      ArrayRangeDesignator
2729    } Kind;
2730
2731    union {
2732      /// A field designator, e.g., ".x".
2733      struct FieldDesignator Field;
2734      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2735      struct ArrayOrRangeDesignator ArrayOrRange;
2736    };
2737    friend class DesignatedInitExpr;
2738
2739  public:
2740    Designator() {}
2741
2742    /// @brief Initializes a field designator.
2743    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
2744               SourceLocation FieldLoc)
2745      : Kind(FieldDesignator) {
2746      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
2747      Field.DotLoc = DotLoc.getRawEncoding();
2748      Field.FieldLoc = FieldLoc.getRawEncoding();
2749    }
2750
2751    /// @brief Initializes an array designator.
2752    Designator(unsigned Index, SourceLocation LBracketLoc,
2753               SourceLocation RBracketLoc)
2754      : Kind(ArrayDesignator) {
2755      ArrayOrRange.Index = Index;
2756      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2757      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
2758      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2759    }
2760
2761    /// @brief Initializes a GNU array-range designator.
2762    Designator(unsigned Index, SourceLocation LBracketLoc,
2763               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
2764      : Kind(ArrayRangeDesignator) {
2765      ArrayOrRange.Index = Index;
2766      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2767      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
2768      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2769    }
2770
2771    bool isFieldDesignator() const { return Kind == FieldDesignator; }
2772    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
2773    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
2774
2775    IdentifierInfo * getFieldName();
2776
2777    FieldDecl *getField() {
2778      assert(Kind == FieldDesignator && "Only valid on a field designator");
2779      if (Field.NameOrField & 0x01)
2780        return 0;
2781      else
2782        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
2783    }
2784
2785    void setField(FieldDecl *FD) {
2786      assert(Kind == FieldDesignator && "Only valid on a field designator");
2787      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
2788    }
2789
2790    SourceLocation getDotLoc() const {
2791      assert(Kind == FieldDesignator && "Only valid on a field designator");
2792      return SourceLocation::getFromRawEncoding(Field.DotLoc);
2793    }
2794
2795    SourceLocation getFieldLoc() const {
2796      assert(Kind == FieldDesignator && "Only valid on a field designator");
2797      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
2798    }
2799
2800    SourceLocation getLBracketLoc() const {
2801      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2802             "Only valid on an array or array-range designator");
2803      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
2804    }
2805
2806    SourceLocation getRBracketLoc() const {
2807      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2808             "Only valid on an array or array-range designator");
2809      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
2810    }
2811
2812    SourceLocation getEllipsisLoc() const {
2813      assert(Kind == ArrayRangeDesignator &&
2814             "Only valid on an array-range designator");
2815      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
2816    }
2817
2818    unsigned getFirstExprIndex() const {
2819      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2820             "Only valid on an array or array-range designator");
2821      return ArrayOrRange.Index;
2822    }
2823
2824    SourceLocation getStartLocation() const {
2825      if (Kind == FieldDesignator)
2826        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
2827      else
2828        return getLBracketLoc();
2829    }
2830  };
2831
2832  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
2833                                    unsigned NumDesignators,
2834                                    Expr **IndexExprs, unsigned NumIndexExprs,
2835                                    SourceLocation EqualOrColonLoc,
2836                                    bool GNUSyntax, Expr *Init);
2837
2838  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
2839
2840  /// @brief Returns the number of designators in this initializer.
2841  unsigned size() const { return NumDesignators; }
2842
2843  // Iterator access to the designators.
2844  typedef Designator* designators_iterator;
2845  designators_iterator designators_begin() { return Designators; }
2846  designators_iterator designators_end() {
2847    return Designators + NumDesignators;
2848  }
2849
2850  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
2851
2852  void setDesignators(ASTContext &C, const Designator *Desigs,
2853                      unsigned NumDesigs);
2854
2855  Expr *getArrayIndex(const Designator& D);
2856  Expr *getArrayRangeStart(const Designator& D);
2857  Expr *getArrayRangeEnd(const Designator& D);
2858
2859  /// @brief Retrieve the location of the '=' that precedes the
2860  /// initializer value itself, if present.
2861  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
2862  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
2863
2864  /// @brief Determines whether this designated initializer used the
2865  /// deprecated GNU syntax for designated initializers.
2866  bool usesGNUSyntax() const { return GNUSyntax; }
2867  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
2868
2869  /// @brief Retrieve the initializer value.
2870  Expr *getInit() const {
2871    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
2872  }
2873
2874  void setInit(Expr *init) {
2875    *child_begin() = init;
2876  }
2877
2878  /// \brief Retrieve the total number of subexpressions in this
2879  /// designated initializer expression, including the actual
2880  /// initialized value and any expressions that occur within array
2881  /// and array-range designators.
2882  unsigned getNumSubExprs() const { return NumSubExprs; }
2883
2884  Expr *getSubExpr(unsigned Idx) {
2885    assert(Idx < NumSubExprs && "Subscript out of range");
2886    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2887    Ptr += sizeof(DesignatedInitExpr);
2888    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
2889  }
2890
2891  void setSubExpr(unsigned Idx, Expr *E) {
2892    assert(Idx < NumSubExprs && "Subscript out of range");
2893    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2894    Ptr += sizeof(DesignatedInitExpr);
2895    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
2896  }
2897
2898  /// \brief Replaces the designator at index @p Idx with the series
2899  /// of designators in [First, Last).
2900  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
2901                        const Designator *Last);
2902
2903  virtual SourceRange getSourceRange() const;
2904
2905  static bool classof(const Stmt *T) {
2906    return T->getStmtClass() == DesignatedInitExprClass;
2907  }
2908  static bool classof(const DesignatedInitExpr *) { return true; }
2909
2910  // Iterators
2911  virtual child_iterator child_begin();
2912  virtual child_iterator child_end();
2913};
2914
2915/// \brief Represents an implicitly-generated value initialization of
2916/// an object of a given type.
2917///
2918/// Implicit value initializations occur within semantic initializer
2919/// list expressions (InitListExpr) as placeholders for subobject
2920/// initializations not explicitly specified by the user.
2921///
2922/// \see InitListExpr
2923class ImplicitValueInitExpr : public Expr {
2924public:
2925  explicit ImplicitValueInitExpr(QualType ty)
2926    : Expr(ImplicitValueInitExprClass, ty, false, false) { }
2927
2928  /// \brief Construct an empty implicit value initialization.
2929  explicit ImplicitValueInitExpr(EmptyShell Empty)
2930    : Expr(ImplicitValueInitExprClass, Empty) { }
2931
2932  static bool classof(const Stmt *T) {
2933    return T->getStmtClass() == ImplicitValueInitExprClass;
2934  }
2935  static bool classof(const ImplicitValueInitExpr *) { return true; }
2936
2937  virtual SourceRange getSourceRange() const {
2938    return SourceRange();
2939  }
2940
2941  // Iterators
2942  virtual child_iterator child_begin();
2943  virtual child_iterator child_end();
2944};
2945
2946
2947class ParenListExpr : public Expr {
2948  Stmt **Exprs;
2949  unsigned NumExprs;
2950  SourceLocation LParenLoc, RParenLoc;
2951
2952protected:
2953  virtual void DoDestroy(ASTContext& C);
2954
2955public:
2956  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
2957                unsigned numexprs, SourceLocation rparenloc);
2958
2959  ~ParenListExpr() {}
2960
2961  /// \brief Build an empty paren list.
2962  //explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
2963
2964  unsigned getNumExprs() const { return NumExprs; }
2965
2966  const Expr* getExpr(unsigned Init) const {
2967    assert(Init < getNumExprs() && "Initializer access out of range!");
2968    return cast_or_null<Expr>(Exprs[Init]);
2969  }
2970
2971  Expr* getExpr(unsigned Init) {
2972    assert(Init < getNumExprs() && "Initializer access out of range!");
2973    return cast_or_null<Expr>(Exprs[Init]);
2974  }
2975
2976  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
2977
2978  SourceLocation getLParenLoc() const { return LParenLoc; }
2979  SourceLocation getRParenLoc() const { return RParenLoc; }
2980
2981  virtual SourceRange getSourceRange() const {
2982    return SourceRange(LParenLoc, RParenLoc);
2983  }
2984  static bool classof(const Stmt *T) {
2985    return T->getStmtClass() == ParenListExprClass;
2986  }
2987  static bool classof(const ParenListExpr *) { return true; }
2988
2989  // Iterators
2990  virtual child_iterator child_begin();
2991  virtual child_iterator child_end();
2992};
2993
2994
2995//===----------------------------------------------------------------------===//
2996// Clang Extensions
2997//===----------------------------------------------------------------------===//
2998
2999
3000/// ExtVectorElementExpr - This represents access to specific elements of a
3001/// vector, and may occur on the left hand side or right hand side.  For example
3002/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3003///
3004/// Note that the base may have either vector or pointer to vector type, just
3005/// like a struct field reference.
3006///
3007class ExtVectorElementExpr : public Expr {
3008  Stmt *Base;
3009  IdentifierInfo *Accessor;
3010  SourceLocation AccessorLoc;
3011public:
3012  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
3013                       SourceLocation loc)
3014    : Expr(ExtVectorElementExprClass, ty, base->isTypeDependent(),
3015           base->isValueDependent()),
3016      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3017
3018  /// \brief Build an empty vector element expression.
3019  explicit ExtVectorElementExpr(EmptyShell Empty)
3020    : Expr(ExtVectorElementExprClass, Empty) { }
3021
3022  const Expr *getBase() const { return cast<Expr>(Base); }
3023  Expr *getBase() { return cast<Expr>(Base); }
3024  void setBase(Expr *E) { Base = E; }
3025
3026  IdentifierInfo &getAccessor() const { return *Accessor; }
3027  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3028
3029  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3030  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3031
3032  /// getNumElements - Get the number of components being selected.
3033  unsigned getNumElements() const;
3034
3035  /// containsDuplicateElements - Return true if any element access is
3036  /// repeated.
3037  bool containsDuplicateElements() const;
3038
3039  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3040  /// aggregate Constant of ConstantInt(s).
3041  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3042
3043  virtual SourceRange getSourceRange() const {
3044    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3045  }
3046
3047  /// isArrow - Return true if the base expression is a pointer to vector,
3048  /// return false if the base expression is a vector.
3049  bool isArrow() const;
3050
3051  static bool classof(const Stmt *T) {
3052    return T->getStmtClass() == ExtVectorElementExprClass;
3053  }
3054  static bool classof(const ExtVectorElementExpr *) { return true; }
3055
3056  // Iterators
3057  virtual child_iterator child_begin();
3058  virtual child_iterator child_end();
3059};
3060
3061
3062/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3063/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3064class BlockExpr : public Expr {
3065protected:
3066  BlockDecl *TheBlock;
3067  bool HasBlockDeclRefExprs;
3068public:
3069  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
3070    : Expr(BlockExprClass, ty, ty->isDependentType(), false),
3071      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
3072
3073  /// \brief Build an empty block expression.
3074  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3075
3076  const BlockDecl *getBlockDecl() const { return TheBlock; }
3077  BlockDecl *getBlockDecl() { return TheBlock; }
3078  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3079
3080  // Convenience functions for probing the underlying BlockDecl.
3081  SourceLocation getCaretLocation() const;
3082  const Stmt *getBody() const;
3083  Stmt *getBody();
3084
3085  virtual SourceRange getSourceRange() const {
3086    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3087  }
3088
3089  /// getFunctionType - Return the underlying function type for this block.
3090  const FunctionType *getFunctionType() const;
3091
3092  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
3093  /// inside of the block that reference values outside the block.
3094  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
3095  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
3096
3097  static bool classof(const Stmt *T) {
3098    return T->getStmtClass() == BlockExprClass;
3099  }
3100  static bool classof(const BlockExpr *) { return true; }
3101
3102  // Iterators
3103  virtual child_iterator child_begin();
3104  virtual child_iterator child_end();
3105};
3106
3107/// BlockDeclRefExpr - A reference to a declared variable, function,
3108/// enum, etc.
3109class BlockDeclRefExpr : public Expr {
3110  ValueDecl *D;
3111  SourceLocation Loc;
3112  bool IsByRef : 1;
3113  bool ConstQualAdded : 1;
3114public:
3115  // FIXME: Fix type/value dependence!
3116  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
3117                   bool constAdded = false)
3118  : Expr(BlockDeclRefExprClass, t, false, false), D(d), Loc(l), IsByRef(ByRef),
3119    ConstQualAdded(constAdded) {}
3120
3121  // \brief Build an empty reference to a declared variable in a
3122  // block.
3123  explicit BlockDeclRefExpr(EmptyShell Empty)
3124    : Expr(BlockDeclRefExprClass, Empty) { }
3125
3126  ValueDecl *getDecl() { return D; }
3127  const ValueDecl *getDecl() const { return D; }
3128  void setDecl(ValueDecl *VD) { D = VD; }
3129
3130  SourceLocation getLocation() const { return Loc; }
3131  void setLocation(SourceLocation L) { Loc = L; }
3132
3133  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
3134
3135  bool isByRef() const { return IsByRef; }
3136  void setByRef(bool BR) { IsByRef = BR; }
3137
3138  bool isConstQualAdded() const { return ConstQualAdded; }
3139  void setConstQualAdded(bool C) { ConstQualAdded = C; }
3140
3141  static bool classof(const Stmt *T) {
3142    return T->getStmtClass() == BlockDeclRefExprClass;
3143  }
3144  static bool classof(const BlockDeclRefExpr *) { return true; }
3145
3146  // Iterators
3147  virtual child_iterator child_begin();
3148  virtual child_iterator child_end();
3149};
3150
3151}  // end namespace clang
3152
3153#endif
3154