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