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