Expr.h revision 83ddad3ab513f5d73698cf9fbeb4ed3f011bc3b9
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 getLocation() 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    /// CK_NullToMemberPointer - Null pointer to member pointer.
1187    CK_NullToMemberPointer,
1188
1189    /// CK_BaseToDerivedMemberPointer - Member pointer in base class to
1190    /// member pointer in derived class.
1191    CK_BaseToDerivedMemberPointer,
1192
1193    /// CK_UserDefinedConversion - Conversion using a user defined type
1194    /// conversion function.
1195    CK_UserDefinedConversion
1196  };
1197
1198  struct CastInfo {
1199    const CastKind Kind;
1200
1201    // FIXME: This should assert that the CastKind does not require extra
1202    // information.
1203    CastInfo(CastKind Kind)
1204      : Kind(Kind) { }
1205  };
1206
1207private:
1208  CastKind Kind;
1209  Stmt *Op;
1210protected:
1211  CastExpr(StmtClass SC, QualType ty, const CastInfo &info, Expr *op) :
1212    Expr(SC, ty,
1213         // Cast expressions are type-dependent if the type is
1214         // dependent (C++ [temp.dep.expr]p3).
1215         ty->isDependentType(),
1216         // Cast expressions are value-dependent if the type is
1217         // dependent or if the subexpression is value-dependent.
1218         ty->isDependentType() || (op && op->isValueDependent())),
1219    Kind(info.Kind), Op(op) {}
1220
1221  /// \brief Construct an empty cast.
1222  CastExpr(StmtClass SC, EmptyShell Empty)
1223    : Expr(SC, Empty) { }
1224
1225public:
1226  CastKind getCastKind() const { return Kind; }
1227  void setCastKind(CastKind K) { Kind = K; }
1228
1229  Expr *getSubExpr() { return cast<Expr>(Op); }
1230  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1231  void setSubExpr(Expr *E) { Op = E; }
1232
1233  static bool classof(const Stmt *T) {
1234    StmtClass SC = T->getStmtClass();
1235    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1236      return true;
1237
1238    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
1239      return true;
1240
1241    return false;
1242  }
1243  static bool classof(const CastExpr *) { return true; }
1244
1245  // Iterators
1246  virtual child_iterator child_begin();
1247  virtual child_iterator child_end();
1248};
1249
1250/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1251/// conversions, which have no direct representation in the original
1252/// source code. For example: converting T[]->T*, void f()->void
1253/// (*f)(), float->double, short->int, etc.
1254///
1255/// In C, implicit casts always produce rvalues. However, in C++, an
1256/// implicit cast whose result is being bound to a reference will be
1257/// an lvalue. For example:
1258///
1259/// @code
1260/// class Base { };
1261/// class Derived : public Base { };
1262/// void f(Derived d) {
1263///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1264/// }
1265/// @endcode
1266class ImplicitCastExpr : public CastExpr {
1267  /// LvalueCast - Whether this cast produces an lvalue.
1268  bool LvalueCast;
1269
1270public:
1271  ImplicitCastExpr(QualType ty, const CastInfo &info, Expr *op, bool Lvalue) :
1272    CastExpr(ImplicitCastExprClass, ty, info, op), LvalueCast(Lvalue) { }
1273
1274  /// \brief Construct an empty implicit cast.
1275  explicit ImplicitCastExpr(EmptyShell Shell)
1276    : CastExpr(ImplicitCastExprClass, Shell) { }
1277
1278
1279  virtual SourceRange getSourceRange() const {
1280    return getSubExpr()->getSourceRange();
1281  }
1282
1283  /// isLvalueCast - Whether this cast produces an lvalue.
1284  bool isLvalueCast() const { return LvalueCast; }
1285
1286  /// setLvalueCast - Set whether this cast produces an lvalue.
1287  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1288
1289  static bool classof(const Stmt *T) {
1290    return T->getStmtClass() == ImplicitCastExprClass;
1291  }
1292  static bool classof(const ImplicitCastExpr *) { return true; }
1293};
1294
1295/// ExplicitCastExpr - An explicit cast written in the source
1296/// code.
1297///
1298/// This class is effectively an abstract class, because it provides
1299/// the basic representation of an explicitly-written cast without
1300/// specifying which kind of cast (C cast, functional cast, static
1301/// cast, etc.) was written; specific derived classes represent the
1302/// particular style of cast and its location information.
1303///
1304/// Unlike implicit casts, explicit cast nodes have two different
1305/// types: the type that was written into the source code, and the
1306/// actual type of the expression as determined by semantic
1307/// analysis. These types may differ slightly. For example, in C++ one
1308/// can cast to a reference type, which indicates that the resulting
1309/// expression will be an lvalue. The reference type, however, will
1310/// not be used as the type of the expression.
1311class ExplicitCastExpr : public CastExpr {
1312  /// TypeAsWritten - The type that this expression is casting to, as
1313  /// written in the source code.
1314  QualType TypeAsWritten;
1315
1316protected:
1317  ExplicitCastExpr(StmtClass SC, QualType exprTy, const CastInfo &info,
1318                   Expr *op, QualType writtenTy)
1319    : CastExpr(SC, exprTy, info, op), TypeAsWritten(writtenTy) {}
1320
1321  /// \brief Construct an empty explicit cast.
1322  ExplicitCastExpr(StmtClass SC, EmptyShell Shell)
1323    : CastExpr(SC, Shell) { }
1324
1325public:
1326  /// getTypeAsWritten - Returns the type that this expression is
1327  /// casting to, as written in the source code.
1328  QualType getTypeAsWritten() const { return TypeAsWritten; }
1329  void setTypeAsWritten(QualType T) { TypeAsWritten = T; }
1330
1331  static bool classof(const Stmt *T) {
1332    StmtClass SC = T->getStmtClass();
1333    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
1334      return true;
1335    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1336      return true;
1337
1338    return false;
1339  }
1340  static bool classof(const ExplicitCastExpr *) { return true; }
1341};
1342
1343/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1344/// cast in C++ (C++ [expr.cast]), which uses the syntax
1345/// (Type)expr. For example: @c (int)f.
1346class CStyleCastExpr : public ExplicitCastExpr {
1347  SourceLocation LPLoc; // the location of the left paren
1348  SourceLocation RPLoc; // the location of the right paren
1349public:
1350  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op, QualType writtenTy,
1351                    SourceLocation l, SourceLocation r) :
1352    ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, writtenTy),
1353    LPLoc(l), RPLoc(r) {}
1354
1355  /// \brief Construct an empty C-style explicit cast.
1356  explicit CStyleCastExpr(EmptyShell Shell)
1357    : ExplicitCastExpr(CStyleCastExprClass, Shell) { }
1358
1359  SourceLocation getLParenLoc() const { return LPLoc; }
1360  void setLParenLoc(SourceLocation L) { LPLoc = L; }
1361
1362  SourceLocation getRParenLoc() const { return RPLoc; }
1363  void setRParenLoc(SourceLocation L) { RPLoc = L; }
1364
1365  virtual SourceRange getSourceRange() const {
1366    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1367  }
1368  static bool classof(const Stmt *T) {
1369    return T->getStmtClass() == CStyleCastExprClass;
1370  }
1371  static bool classof(const CStyleCastExpr *) { return true; }
1372};
1373
1374/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
1375///
1376/// This expression node kind describes a builtin binary operation,
1377/// such as "x + y" for integer values "x" and "y". The operands will
1378/// already have been converted to appropriate types (e.g., by
1379/// performing promotions or conversions).
1380///
1381/// In C++, where operators may be overloaded, a different kind of
1382/// expression node (CXXOperatorCallExpr) is used to express the
1383/// invocation of an overloaded operator with operator syntax. Within
1384/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
1385/// used to store an expression "x + y" depends on the subexpressions
1386/// for x and y. If neither x or y is type-dependent, and the "+"
1387/// operator resolves to a built-in operation, BinaryOperator will be
1388/// used to express the computation (x and y may still be
1389/// value-dependent). If either x or y is type-dependent, or if the
1390/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
1391/// be used to express the computation.
1392class BinaryOperator : public Expr {
1393public:
1394  enum Opcode {
1395    // Operators listed in order of precedence.
1396    // Note that additions to this should also update the StmtVisitor class.
1397    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1398    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1399    Add, Sub,         // [C99 6.5.6] Additive operators.
1400    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1401    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1402    EQ, NE,           // [C99 6.5.9] Equality operators.
1403    And,              // [C99 6.5.10] Bitwise AND operator.
1404    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1405    Or,               // [C99 6.5.12] Bitwise OR operator.
1406    LAnd,             // [C99 6.5.13] Logical AND operator.
1407    LOr,              // [C99 6.5.14] Logical OR operator.
1408    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1409    DivAssign, RemAssign,
1410    AddAssign, SubAssign,
1411    ShlAssign, ShrAssign,
1412    AndAssign, XorAssign,
1413    OrAssign,
1414    Comma             // [C99 6.5.17] Comma operator.
1415  };
1416private:
1417  enum { LHS, RHS, END_EXPR };
1418  Stmt* SubExprs[END_EXPR];
1419  Opcode Opc;
1420  SourceLocation OpLoc;
1421public:
1422
1423  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1424                 SourceLocation opLoc)
1425    : Expr(BinaryOperatorClass, ResTy,
1426           lhs->isTypeDependent() || rhs->isTypeDependent(),
1427           lhs->isValueDependent() || rhs->isValueDependent()),
1428      Opc(opc), OpLoc(opLoc) {
1429    SubExprs[LHS] = lhs;
1430    SubExprs[RHS] = rhs;
1431    assert(!isCompoundAssignmentOp() &&
1432           "Use ArithAssignBinaryOperator for compound assignments");
1433  }
1434
1435  /// \brief Construct an empty binary operator.
1436  explicit BinaryOperator(EmptyShell Empty)
1437    : Expr(BinaryOperatorClass, Empty), Opc(Comma) { }
1438
1439  SourceLocation getOperatorLoc() const { return OpLoc; }
1440  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1441
1442  Opcode getOpcode() const { return Opc; }
1443  void setOpcode(Opcode O) { Opc = O; }
1444
1445  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1446  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1447  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1448  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1449
1450  virtual SourceRange getSourceRange() const {
1451    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1452  }
1453
1454  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1455  /// corresponds to, e.g. "<<=".
1456  static const char *getOpcodeStr(Opcode Op);
1457
1458  /// \brief Retrieve the binary opcode that corresponds to the given
1459  /// overloaded operator.
1460  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
1461
1462  /// \brief Retrieve the overloaded operator kind that corresponds to
1463  /// the given binary opcode.
1464  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1465
1466  /// predicates to categorize the respective opcodes.
1467  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1468  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1469  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
1470  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
1471
1472  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1473  bool isRelationalOp() const { return isRelationalOp(Opc); }
1474
1475  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1476  bool isEqualityOp() const { return isEqualityOp(Opc); }
1477
1478  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1479  bool isLogicalOp() const { return isLogicalOp(Opc); }
1480
1481  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1482  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1483  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1484
1485  static bool classof(const Stmt *S) {
1486    return S->getStmtClass() == BinaryOperatorClass ||
1487           S->getStmtClass() == CompoundAssignOperatorClass;
1488  }
1489  static bool classof(const BinaryOperator *) { return true; }
1490
1491  // Iterators
1492  virtual child_iterator child_begin();
1493  virtual child_iterator child_end();
1494
1495protected:
1496  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1497                 SourceLocation oploc, bool dead)
1498    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
1499    SubExprs[LHS] = lhs;
1500    SubExprs[RHS] = rhs;
1501  }
1502
1503  BinaryOperator(StmtClass SC, EmptyShell Empty)
1504    : Expr(SC, Empty), Opc(MulAssign) { }
1505};
1506
1507/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1508/// track of the type the operation is performed in.  Due to the semantics of
1509/// these operators, the operands are promoted, the aritmetic performed, an
1510/// implicit conversion back to the result type done, then the assignment takes
1511/// place.  This captures the intermediate type which the computation is done
1512/// in.
1513class CompoundAssignOperator : public BinaryOperator {
1514  QualType ComputationLHSType;
1515  QualType ComputationResultType;
1516public:
1517  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1518                         QualType ResType, QualType CompLHSType,
1519                         QualType CompResultType,
1520                         SourceLocation OpLoc)
1521    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1522      ComputationLHSType(CompLHSType),
1523      ComputationResultType(CompResultType) {
1524    assert(isCompoundAssignmentOp() &&
1525           "Only should be used for compound assignments");
1526  }
1527
1528  /// \brief Build an empty compound assignment operator expression.
1529  explicit CompoundAssignOperator(EmptyShell Empty)
1530    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
1531
1532  // The two computation types are the type the LHS is converted
1533  // to for the computation and the type of the result; the two are
1534  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
1535  QualType getComputationLHSType() const { return ComputationLHSType; }
1536  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
1537
1538  QualType getComputationResultType() const { return ComputationResultType; }
1539  void setComputationResultType(QualType T) { ComputationResultType = T; }
1540
1541  static bool classof(const CompoundAssignOperator *) { return true; }
1542  static bool classof(const Stmt *S) {
1543    return S->getStmtClass() == CompoundAssignOperatorClass;
1544  }
1545};
1546
1547/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1548/// GNU "missing LHS" extension is in use.
1549///
1550class ConditionalOperator : public Expr {
1551  enum { COND, LHS, RHS, END_EXPR };
1552  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1553  SourceLocation QuestionLoc, ColonLoc;
1554public:
1555  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
1556                      SourceLocation CLoc, Expr *rhs, QualType t)
1557    : Expr(ConditionalOperatorClass, t,
1558           // FIXME: the type of the conditional operator doesn't
1559           // depend on the type of the conditional, but the standard
1560           // seems to imply that it could. File a bug!
1561           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
1562           (cond->isValueDependent() ||
1563            (lhs && lhs->isValueDependent()) ||
1564            (rhs && rhs->isValueDependent()))),
1565      QuestionLoc(QLoc),
1566      ColonLoc(CLoc) {
1567    SubExprs[COND] = cond;
1568    SubExprs[LHS] = lhs;
1569    SubExprs[RHS] = rhs;
1570  }
1571
1572  /// \brief Build an empty conditional operator.
1573  explicit ConditionalOperator(EmptyShell Empty)
1574    : Expr(ConditionalOperatorClass, Empty) { }
1575
1576  // getCond - Return the expression representing the condition for
1577  //  the ?: operator.
1578  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1579  void setCond(Expr *E) { SubExprs[COND] = E; }
1580
1581  // getTrueExpr - Return the subexpression representing the value of the ?:
1582  //  expression if the condition evaluates to true.  In most cases this value
1583  //  will be the same as getLHS() except a GCC extension allows the left
1584  //  subexpression to be omitted, and instead of the condition be returned.
1585  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1586  //  is only evaluated once.
1587  Expr *getTrueExpr() const {
1588    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1589  }
1590
1591  // getTrueExpr - Return the subexpression representing the value of the ?:
1592  // expression if the condition evaluates to false. This is the same as getRHS.
1593  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1594
1595  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1596  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1597
1598  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1599  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1600
1601  SourceLocation getQuestionLoc() const { return QuestionLoc; }
1602  void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
1603
1604  SourceLocation getColonLoc() const { return ColonLoc; }
1605  void setColonLoc(SourceLocation L) { ColonLoc = L; }
1606
1607  virtual SourceRange getSourceRange() const {
1608    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1609  }
1610  static bool classof(const Stmt *T) {
1611    return T->getStmtClass() == ConditionalOperatorClass;
1612  }
1613  static bool classof(const ConditionalOperator *) { return true; }
1614
1615  // Iterators
1616  virtual child_iterator child_begin();
1617  virtual child_iterator child_end();
1618};
1619
1620/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1621class AddrLabelExpr : public Expr {
1622  SourceLocation AmpAmpLoc, LabelLoc;
1623  LabelStmt *Label;
1624public:
1625  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1626                QualType t)
1627    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1628
1629  /// \brief Build an empty address of a label expression.
1630  explicit AddrLabelExpr(EmptyShell Empty)
1631    : Expr(AddrLabelExprClass, Empty) { }
1632
1633  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
1634  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
1635  SourceLocation getLabelLoc() const { return LabelLoc; }
1636  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
1637
1638  virtual SourceRange getSourceRange() const {
1639    return SourceRange(AmpAmpLoc, LabelLoc);
1640  }
1641
1642  LabelStmt *getLabel() const { return Label; }
1643  void setLabel(LabelStmt *S) { Label = S; }
1644
1645  static bool classof(const Stmt *T) {
1646    return T->getStmtClass() == AddrLabelExprClass;
1647  }
1648  static bool classof(const AddrLabelExpr *) { return true; }
1649
1650  // Iterators
1651  virtual child_iterator child_begin();
1652  virtual child_iterator child_end();
1653};
1654
1655/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1656/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1657/// takes the value of the last subexpression.
1658class StmtExpr : public Expr {
1659  Stmt *SubStmt;
1660  SourceLocation LParenLoc, RParenLoc;
1661public:
1662  StmtExpr(CompoundStmt *substmt, QualType T,
1663           SourceLocation lp, SourceLocation rp) :
1664    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1665
1666  /// \brief Build an empty statement expression.
1667  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
1668
1669  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1670  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1671  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
1672
1673  virtual SourceRange getSourceRange() const {
1674    return SourceRange(LParenLoc, RParenLoc);
1675  }
1676
1677  SourceLocation getLParenLoc() const { return LParenLoc; }
1678  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1679  SourceLocation getRParenLoc() const { return RParenLoc; }
1680  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1681
1682  static bool classof(const Stmt *T) {
1683    return T->getStmtClass() == StmtExprClass;
1684  }
1685  static bool classof(const StmtExpr *) { return true; }
1686
1687  // Iterators
1688  virtual child_iterator child_begin();
1689  virtual child_iterator child_end();
1690};
1691
1692/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
1693/// This AST node represents a function that returns 1 if two *types* (not
1694/// expressions) are compatible. The result of this built-in function can be
1695/// used in integer constant expressions.
1696class TypesCompatibleExpr : public Expr {
1697  QualType Type1;
1698  QualType Type2;
1699  SourceLocation BuiltinLoc, RParenLoc;
1700public:
1701  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1702                      QualType t1, QualType t2, SourceLocation RP) :
1703    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1704    BuiltinLoc(BLoc), RParenLoc(RP) {}
1705
1706  /// \brief Build an empty __builtin_type_compatible_p expression.
1707  explicit TypesCompatibleExpr(EmptyShell Empty)
1708    : Expr(TypesCompatibleExprClass, Empty) { }
1709
1710  QualType getArgType1() const { return Type1; }
1711  void setArgType1(QualType T) { Type1 = T; }
1712  QualType getArgType2() const { return Type2; }
1713  void setArgType2(QualType T) { Type2 = T; }
1714
1715  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1716  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1717
1718  SourceLocation getRParenLoc() const { return RParenLoc; }
1719  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1720
1721  virtual SourceRange getSourceRange() const {
1722    return SourceRange(BuiltinLoc, RParenLoc);
1723  }
1724  static bool classof(const Stmt *T) {
1725    return T->getStmtClass() == TypesCompatibleExprClass;
1726  }
1727  static bool classof(const TypesCompatibleExpr *) { return true; }
1728
1729  // Iterators
1730  virtual child_iterator child_begin();
1731  virtual child_iterator child_end();
1732};
1733
1734/// ShuffleVectorExpr - clang-specific builtin-in function
1735/// __builtin_shufflevector.
1736/// This AST node represents a operator that does a constant
1737/// shuffle, similar to LLVM's shufflevector instruction. It takes
1738/// two vectors and a variable number of constant indices,
1739/// and returns the appropriately shuffled vector.
1740class ShuffleVectorExpr : public Expr {
1741  SourceLocation BuiltinLoc, RParenLoc;
1742
1743  // SubExprs - the list of values passed to the __builtin_shufflevector
1744  // function. The first two are vectors, and the rest are constant
1745  // indices.  The number of values in this list is always
1746  // 2+the number of indices in the vector type.
1747  Stmt **SubExprs;
1748  unsigned NumExprs;
1749
1750protected:
1751  virtual void DoDestroy(ASTContext &C);
1752
1753public:
1754  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
1755                    QualType Type, SourceLocation BLoc,
1756                    SourceLocation RP) :
1757    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1758    RParenLoc(RP), NumExprs(nexpr) {
1759
1760    SubExprs = new (C) Stmt*[nexpr];
1761    for (unsigned i = 0; i < nexpr; i++)
1762      SubExprs[i] = args[i];
1763  }
1764
1765  /// \brief Build an empty vector-shuffle expression.
1766  explicit ShuffleVectorExpr(EmptyShell Empty)
1767    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
1768
1769  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1770  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1771
1772  SourceLocation getRParenLoc() const { return RParenLoc; }
1773  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1774
1775  virtual SourceRange getSourceRange() const {
1776    return SourceRange(BuiltinLoc, RParenLoc);
1777  }
1778  static bool classof(const Stmt *T) {
1779    return T->getStmtClass() == ShuffleVectorExprClass;
1780  }
1781  static bool classof(const ShuffleVectorExpr *) { return true; }
1782
1783  ~ShuffleVectorExpr() {}
1784
1785  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1786  /// constant expression, the actual arguments passed in, and the function
1787  /// pointers.
1788  unsigned getNumSubExprs() const { return NumExprs; }
1789
1790  /// getExpr - Return the Expr at the specified index.
1791  Expr *getExpr(unsigned Index) {
1792    assert((Index < NumExprs) && "Arg access out of range!");
1793    return cast<Expr>(SubExprs[Index]);
1794  }
1795  const Expr *getExpr(unsigned Index) const {
1796    assert((Index < NumExprs) && "Arg access out of range!");
1797    return cast<Expr>(SubExprs[Index]);
1798  }
1799
1800  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
1801
1802  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1803    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1804    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
1805  }
1806
1807  // Iterators
1808  virtual child_iterator child_begin();
1809  virtual child_iterator child_end();
1810};
1811
1812/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1813/// This AST node is similar to the conditional operator (?:) in C, with
1814/// the following exceptions:
1815/// - the test expression must be a integer constant expression.
1816/// - the expression returned acts like the chosen subexpression in every
1817///   visible way: the type is the same as that of the chosen subexpression,
1818///   and all predicates (whether it's an l-value, whether it's an integer
1819///   constant expression, etc.) return the same result as for the chosen
1820///   sub-expression.
1821class ChooseExpr : public Expr {
1822  enum { COND, LHS, RHS, END_EXPR };
1823  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1824  SourceLocation BuiltinLoc, RParenLoc;
1825public:
1826  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1827             SourceLocation RP)
1828    : Expr(ChooseExprClass, t),
1829      BuiltinLoc(BLoc), RParenLoc(RP) {
1830      SubExprs[COND] = cond;
1831      SubExprs[LHS] = lhs;
1832      SubExprs[RHS] = rhs;
1833    }
1834
1835  /// \brief Build an empty __builtin_choose_expr.
1836  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
1837
1838  /// isConditionTrue - Return whether the condition is true (i.e. not
1839  /// equal to zero).
1840  bool isConditionTrue(ASTContext &C) const;
1841
1842  /// getChosenSubExpr - Return the subexpression chosen according to the
1843  /// condition.
1844  Expr *getChosenSubExpr(ASTContext &C) const {
1845    return isConditionTrue(C) ? getLHS() : getRHS();
1846  }
1847
1848  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1849  void setCond(Expr *E) { SubExprs[COND] = E; }
1850  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1851  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1852  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1853  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1854
1855  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1856  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1857
1858  SourceLocation getRParenLoc() const { return RParenLoc; }
1859  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1860
1861  virtual SourceRange getSourceRange() const {
1862    return SourceRange(BuiltinLoc, RParenLoc);
1863  }
1864  static bool classof(const Stmt *T) {
1865    return T->getStmtClass() == ChooseExprClass;
1866  }
1867  static bool classof(const ChooseExpr *) { return true; }
1868
1869  // Iterators
1870  virtual child_iterator child_begin();
1871  virtual child_iterator child_end();
1872};
1873
1874/// GNUNullExpr - Implements the GNU __null extension, which is a name
1875/// for a null pointer constant that has integral type (e.g., int or
1876/// long) and is the same size and alignment as a pointer. The __null
1877/// extension is typically only used by system headers, which define
1878/// NULL as __null in C++ rather than using 0 (which is an integer
1879/// that may not match the size of a pointer).
1880class GNUNullExpr : public Expr {
1881  /// TokenLoc - The location of the __null keyword.
1882  SourceLocation TokenLoc;
1883
1884public:
1885  GNUNullExpr(QualType Ty, SourceLocation Loc)
1886    : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { }
1887
1888  /// \brief Build an empty GNU __null expression.
1889  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
1890
1891  /// getTokenLocation - The location of the __null token.
1892  SourceLocation getTokenLocation() const { return TokenLoc; }
1893  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
1894
1895  virtual SourceRange getSourceRange() const {
1896    return SourceRange(TokenLoc);
1897  }
1898  static bool classof(const Stmt *T) {
1899    return T->getStmtClass() == GNUNullExprClass;
1900  }
1901  static bool classof(const GNUNullExpr *) { return true; }
1902
1903  // Iterators
1904  virtual child_iterator child_begin();
1905  virtual child_iterator child_end();
1906};
1907
1908/// VAArgExpr, used for the builtin function __builtin_va_start.
1909class VAArgExpr : public Expr {
1910  Stmt *Val;
1911  SourceLocation BuiltinLoc, RParenLoc;
1912public:
1913  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1914    : Expr(VAArgExprClass, t),
1915      Val(e),
1916      BuiltinLoc(BLoc),
1917      RParenLoc(RPLoc) { }
1918
1919  /// \brief Create an empty __builtin_va_start expression.
1920  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
1921
1922  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1923  Expr *getSubExpr() { return cast<Expr>(Val); }
1924  void setSubExpr(Expr *E) { Val = E; }
1925
1926  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
1927  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
1928
1929  SourceLocation getRParenLoc() const { return RParenLoc; }
1930  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1931
1932  virtual SourceRange getSourceRange() const {
1933    return SourceRange(BuiltinLoc, RParenLoc);
1934  }
1935  static bool classof(const Stmt *T) {
1936    return T->getStmtClass() == VAArgExprClass;
1937  }
1938  static bool classof(const VAArgExpr *) { return true; }
1939
1940  // Iterators
1941  virtual child_iterator child_begin();
1942  virtual child_iterator child_end();
1943};
1944
1945/// @brief Describes an C or C++ initializer list.
1946///
1947/// InitListExpr describes an initializer list, which can be used to
1948/// initialize objects of different types, including
1949/// struct/class/union types, arrays, and vectors. For example:
1950///
1951/// @code
1952/// struct foo x = { 1, { 2, 3 } };
1953/// @endcode
1954///
1955/// Prior to semantic analysis, an initializer list will represent the
1956/// initializer list as written by the user, but will have the
1957/// placeholder type "void". This initializer list is called the
1958/// syntactic form of the initializer, and may contain C99 designated
1959/// initializers (represented as DesignatedInitExprs), initializations
1960/// of subobject members without explicit braces, and so on. Clients
1961/// interested in the original syntax of the initializer list should
1962/// use the syntactic form of the initializer list.
1963///
1964/// After semantic analysis, the initializer list will represent the
1965/// semantic form of the initializer, where the initializations of all
1966/// subobjects are made explicit with nested InitListExpr nodes and
1967/// C99 designators have been eliminated by placing the designated
1968/// initializations into the subobject they initialize. Additionally,
1969/// any "holes" in the initialization, where no initializer has been
1970/// specified for a particular subobject, will be replaced with
1971/// implicitly-generated ImplicitValueInitExpr expressions that
1972/// value-initialize the subobjects. Note, however, that the
1973/// initializer lists may still have fewer initializers than there are
1974/// elements to initialize within the object.
1975///
1976/// Given the semantic form of the initializer list, one can retrieve
1977/// the original syntactic form of that initializer list (if it
1978/// exists) using getSyntacticForm(). Since many initializer lists
1979/// have the same syntactic and semantic forms, getSyntacticForm() may
1980/// return NULL, indicating that the current initializer list also
1981/// serves as its syntactic form.
1982class InitListExpr : public Expr {
1983  // FIXME: Eliminate this vector in favor of ASTContext allocation
1984  std::vector<Stmt *> InitExprs;
1985  SourceLocation LBraceLoc, RBraceLoc;
1986
1987  /// Contains the initializer list that describes the syntactic form
1988  /// written in the source code.
1989  InitListExpr *SyntacticForm;
1990
1991  /// If this initializer list initializes a union, specifies which
1992  /// field within the union will be initialized.
1993  FieldDecl *UnionFieldInit;
1994
1995  /// Whether this initializer list originally had a GNU array-range
1996  /// designator in it. This is a temporary marker used by CodeGen.
1997  bool HadArrayRangeDesignator;
1998
1999public:
2000  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
2001               SourceLocation rbraceloc);
2002
2003  /// \brief Build an empty initializer list.
2004  explicit InitListExpr(EmptyShell Empty) : Expr(InitListExprClass, Empty) { }
2005
2006  unsigned getNumInits() const { return InitExprs.size(); }
2007
2008  const Expr* getInit(unsigned Init) const {
2009    assert(Init < getNumInits() && "Initializer access out of range!");
2010    return cast_or_null<Expr>(InitExprs[Init]);
2011  }
2012
2013  Expr* getInit(unsigned Init) {
2014    assert(Init < getNumInits() && "Initializer access out of range!");
2015    return cast_or_null<Expr>(InitExprs[Init]);
2016  }
2017
2018  void setInit(unsigned Init, Expr *expr) {
2019    assert(Init < getNumInits() && "Initializer access out of range!");
2020    InitExprs[Init] = expr;
2021  }
2022
2023  /// \brief Reserve space for some number of initializers.
2024  void reserveInits(unsigned NumInits);
2025
2026  /// @brief Specify the number of initializers
2027  ///
2028  /// If there are more than @p NumInits initializers, the remaining
2029  /// initializers will be destroyed. If there are fewer than @p
2030  /// NumInits initializers, NULL expressions will be added for the
2031  /// unknown initializers.
2032  void resizeInits(ASTContext &Context, unsigned NumInits);
2033
2034  /// @brief Updates the initializer at index @p Init with the new
2035  /// expression @p expr, and returns the old expression at that
2036  /// location.
2037  ///
2038  /// When @p Init is out of range for this initializer list, the
2039  /// initializer list will be extended with NULL expressions to
2040  /// accomodate the new entry.
2041  Expr *updateInit(unsigned Init, Expr *expr);
2042
2043  /// \brief If this initializes a union, specifies which field in the
2044  /// union to initialize.
2045  ///
2046  /// Typically, this field is the first named field within the
2047  /// union. However, a designated initializer can specify the
2048  /// initialization of a different field within the union.
2049  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2050  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2051
2052  // Explicit InitListExpr's originate from source code (and have valid source
2053  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2054  bool isExplicit() {
2055    return LBraceLoc.isValid() && RBraceLoc.isValid();
2056  }
2057
2058  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2059  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2060  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2061  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2062
2063  /// @brief Retrieve the initializer list that describes the
2064  /// syntactic form of the initializer.
2065  ///
2066  ///
2067  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2068  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2069
2070  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2071  void sawArrayRangeDesignator(bool ARD = true) {
2072    HadArrayRangeDesignator = ARD;
2073  }
2074
2075  virtual SourceRange getSourceRange() const {
2076    return SourceRange(LBraceLoc, RBraceLoc);
2077  }
2078  static bool classof(const Stmt *T) {
2079    return T->getStmtClass() == InitListExprClass;
2080  }
2081  static bool classof(const InitListExpr *) { return true; }
2082
2083  // Iterators
2084  virtual child_iterator child_begin();
2085  virtual child_iterator child_end();
2086
2087  typedef std::vector<Stmt *>::iterator iterator;
2088  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
2089
2090  iterator begin() { return InitExprs.begin(); }
2091  iterator end() { return InitExprs.end(); }
2092  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2093  reverse_iterator rend() { return InitExprs.rend(); }
2094};
2095
2096/// @brief Represents a C99 designated initializer expression.
2097///
2098/// A designated initializer expression (C99 6.7.8) contains one or
2099/// more designators (which can be field designators, array
2100/// designators, or GNU array-range designators) followed by an
2101/// expression that initializes the field or element(s) that the
2102/// designators refer to. For example, given:
2103///
2104/// @code
2105/// struct point {
2106///   double x;
2107///   double y;
2108/// };
2109/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2110/// @endcode
2111///
2112/// The InitListExpr contains three DesignatedInitExprs, the first of
2113/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2114/// designators, one array designator for @c [2] followed by one field
2115/// designator for @c .y. The initalization expression will be 1.0.
2116class DesignatedInitExpr : public Expr {
2117public:
2118  /// \brief Forward declaration of the Designator class.
2119  class Designator;
2120
2121private:
2122  /// The location of the '=' or ':' prior to the actual initializer
2123  /// expression.
2124  SourceLocation EqualOrColonLoc;
2125
2126  /// Whether this designated initializer used the GNU deprecated
2127  /// syntax rather than the C99 '=' syntax.
2128  bool GNUSyntax : 1;
2129
2130  /// The number of designators in this initializer expression.
2131  unsigned NumDesignators : 15;
2132
2133  /// \brief The designators in this designated initialization
2134  /// expression.
2135  Designator *Designators;
2136
2137  /// The number of subexpressions of this initializer expression,
2138  /// which contains both the initializer and any additional
2139  /// expressions used by array and array-range designators.
2140  unsigned NumSubExprs : 16;
2141
2142
2143  DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
2144                     const Designator *Designators,
2145                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2146                     Expr **IndexExprs, unsigned NumIndexExprs,
2147                     Expr *Init);
2148
2149  explicit DesignatedInitExpr(unsigned NumSubExprs)
2150    : Expr(DesignatedInitExprClass, EmptyShell()),
2151      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2152
2153protected:
2154  virtual void DoDestroy(ASTContext &C);
2155
2156public:
2157  /// A field designator, e.g., ".x".
2158  struct FieldDesignator {
2159    /// Refers to the field that is being initialized. The low bit
2160    /// of this field determines whether this is actually a pointer
2161    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2162    /// initially constructed, a field designator will store an
2163    /// IdentifierInfo*. After semantic analysis has resolved that
2164    /// name, the field designator will instead store a FieldDecl*.
2165    uintptr_t NameOrField;
2166
2167    /// The location of the '.' in the designated initializer.
2168    unsigned DotLoc;
2169
2170    /// The location of the field name in the designated initializer.
2171    unsigned FieldLoc;
2172  };
2173
2174  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2175  struct ArrayOrRangeDesignator {
2176    /// Location of the first index expression within the designated
2177    /// initializer expression's list of subexpressions.
2178    unsigned Index;
2179    /// The location of the '[' starting the array range designator.
2180    unsigned LBracketLoc;
2181    /// The location of the ellipsis separating the start and end
2182    /// indices. Only valid for GNU array-range designators.
2183    unsigned EllipsisLoc;
2184    /// The location of the ']' terminating the array range designator.
2185    unsigned RBracketLoc;
2186  };
2187
2188  /// @brief Represents a single C99 designator.
2189  ///
2190  /// @todo This class is infuriatingly similar to clang::Designator,
2191  /// but minor differences (storing indices vs. storing pointers)
2192  /// keep us from reusing it. Try harder, later, to rectify these
2193  /// differences.
2194  class Designator {
2195    /// @brief The kind of designator this describes.
2196    enum {
2197      FieldDesignator,
2198      ArrayDesignator,
2199      ArrayRangeDesignator
2200    } Kind;
2201
2202    union {
2203      /// A field designator, e.g., ".x".
2204      struct FieldDesignator Field;
2205      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2206      struct ArrayOrRangeDesignator ArrayOrRange;
2207    };
2208    friend class DesignatedInitExpr;
2209
2210  public:
2211    Designator() {}
2212
2213    /// @brief Initializes a field designator.
2214    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
2215               SourceLocation FieldLoc)
2216      : Kind(FieldDesignator) {
2217      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
2218      Field.DotLoc = DotLoc.getRawEncoding();
2219      Field.FieldLoc = FieldLoc.getRawEncoding();
2220    }
2221
2222    /// @brief Initializes an array designator.
2223    Designator(unsigned Index, SourceLocation LBracketLoc,
2224               SourceLocation RBracketLoc)
2225      : Kind(ArrayDesignator) {
2226      ArrayOrRange.Index = Index;
2227      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2228      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
2229      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2230    }
2231
2232    /// @brief Initializes a GNU array-range designator.
2233    Designator(unsigned Index, SourceLocation LBracketLoc,
2234               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
2235      : Kind(ArrayRangeDesignator) {
2236      ArrayOrRange.Index = Index;
2237      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2238      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
2239      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2240    }
2241
2242    bool isFieldDesignator() const { return Kind == FieldDesignator; }
2243    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
2244    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
2245
2246    IdentifierInfo * getFieldName();
2247
2248    FieldDecl *getField() {
2249      assert(Kind == FieldDesignator && "Only valid on a field designator");
2250      if (Field.NameOrField & 0x01)
2251        return 0;
2252      else
2253        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
2254    }
2255
2256    void setField(FieldDecl *FD) {
2257      assert(Kind == FieldDesignator && "Only valid on a field designator");
2258      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
2259    }
2260
2261    SourceLocation getDotLoc() const {
2262      assert(Kind == FieldDesignator && "Only valid on a field designator");
2263      return SourceLocation::getFromRawEncoding(Field.DotLoc);
2264    }
2265
2266    SourceLocation getFieldLoc() const {
2267      assert(Kind == FieldDesignator && "Only valid on a field designator");
2268      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
2269    }
2270
2271    SourceLocation getLBracketLoc() const {
2272      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2273             "Only valid on an array or array-range designator");
2274      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
2275    }
2276
2277    SourceLocation getRBracketLoc() const {
2278      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2279             "Only valid on an array or array-range designator");
2280      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
2281    }
2282
2283    SourceLocation getEllipsisLoc() const {
2284      assert(Kind == ArrayRangeDesignator &&
2285             "Only valid on an array-range designator");
2286      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
2287    }
2288
2289    unsigned getFirstExprIndex() const {
2290      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2291             "Only valid on an array or array-range designator");
2292      return ArrayOrRange.Index;
2293    }
2294
2295    SourceLocation getStartLocation() const {
2296      if (Kind == FieldDesignator)
2297        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
2298      else
2299        return getLBracketLoc();
2300    }
2301  };
2302
2303  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
2304                                    unsigned NumDesignators,
2305                                    Expr **IndexExprs, unsigned NumIndexExprs,
2306                                    SourceLocation EqualOrColonLoc,
2307                                    bool GNUSyntax, Expr *Init);
2308
2309  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
2310
2311  /// @brief Returns the number of designators in this initializer.
2312  unsigned size() const { return NumDesignators; }
2313
2314  // Iterator access to the designators.
2315  typedef Designator* designators_iterator;
2316  designators_iterator designators_begin() { return Designators; }
2317  designators_iterator designators_end() {
2318    return Designators + NumDesignators;
2319  }
2320
2321  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
2322
2323  void setDesignators(const Designator *Desigs, unsigned NumDesigs);
2324
2325  Expr *getArrayIndex(const Designator& D);
2326  Expr *getArrayRangeStart(const Designator& D);
2327  Expr *getArrayRangeEnd(const Designator& D);
2328
2329  /// @brief Retrieve the location of the '=' that precedes the
2330  /// initializer value itself, if present.
2331  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
2332  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
2333
2334  /// @brief Determines whether this designated initializer used the
2335  /// deprecated GNU syntax for designated initializers.
2336  bool usesGNUSyntax() const { return GNUSyntax; }
2337  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
2338
2339  /// @brief Retrieve the initializer value.
2340  Expr *getInit() const {
2341    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
2342  }
2343
2344  void setInit(Expr *init) {
2345    *child_begin() = init;
2346  }
2347
2348  /// \brief Retrieve the total number of subexpressions in this
2349  /// designated initializer expression, including the actual
2350  /// initialized value and any expressions that occur within array
2351  /// and array-range designators.
2352  unsigned getNumSubExprs() const { return NumSubExprs; }
2353
2354  Expr *getSubExpr(unsigned Idx) {
2355    assert(Idx < NumSubExprs && "Subscript out of range");
2356    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2357    Ptr += sizeof(DesignatedInitExpr);
2358    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
2359  }
2360
2361  void setSubExpr(unsigned Idx, Expr *E) {
2362    assert(Idx < NumSubExprs && "Subscript out of range");
2363    char* Ptr = static_cast<char*>(static_cast<void *>(this));
2364    Ptr += sizeof(DesignatedInitExpr);
2365    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
2366  }
2367
2368  /// \brief Replaces the designator at index @p Idx with the series
2369  /// of designators in [First, Last).
2370  void ExpandDesignator(unsigned Idx, const Designator *First,
2371                        const Designator *Last);
2372
2373  virtual SourceRange getSourceRange() const;
2374
2375  static bool classof(const Stmt *T) {
2376    return T->getStmtClass() == DesignatedInitExprClass;
2377  }
2378  static bool classof(const DesignatedInitExpr *) { return true; }
2379
2380  // Iterators
2381  virtual child_iterator child_begin();
2382  virtual child_iterator child_end();
2383};
2384
2385/// \brief Represents an implicitly-generated value initialization of
2386/// an object of a given type.
2387///
2388/// Implicit value initializations occur within semantic initializer
2389/// list expressions (InitListExpr) as placeholders for subobject
2390/// initializations not explicitly specified by the user.
2391///
2392/// \see InitListExpr
2393class ImplicitValueInitExpr : public Expr {
2394public:
2395  explicit ImplicitValueInitExpr(QualType ty)
2396    : Expr(ImplicitValueInitExprClass, ty) { }
2397
2398  /// \brief Construct an empty implicit value initialization.
2399  explicit ImplicitValueInitExpr(EmptyShell Empty)
2400    : Expr(ImplicitValueInitExprClass, Empty) { }
2401
2402  static bool classof(const Stmt *T) {
2403    return T->getStmtClass() == ImplicitValueInitExprClass;
2404  }
2405  static bool classof(const ImplicitValueInitExpr *) { return true; }
2406
2407  virtual SourceRange getSourceRange() const {
2408    return SourceRange();
2409  }
2410
2411  // Iterators
2412  virtual child_iterator child_begin();
2413  virtual child_iterator child_end();
2414};
2415
2416
2417class ParenListExpr : public Expr {
2418  Stmt **Exprs;
2419  unsigned NumExprs;
2420  SourceLocation LParenLoc, RParenLoc;
2421
2422protected:
2423  virtual void DoDestroy(ASTContext& C);
2424
2425public:
2426  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
2427                unsigned numexprs, SourceLocation rparenloc);
2428
2429  ~ParenListExpr() {}
2430
2431  /// \brief Build an empty paren list.
2432  //explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
2433
2434  unsigned getNumExprs() const { return NumExprs; }
2435
2436  const Expr* getExpr(unsigned Init) const {
2437    assert(Init < getNumExprs() && "Initializer access out of range!");
2438    return cast_or_null<Expr>(Exprs[Init]);
2439  }
2440
2441  Expr* getExpr(unsigned Init) {
2442    assert(Init < getNumExprs() && "Initializer access out of range!");
2443    return cast_or_null<Expr>(Exprs[Init]);
2444  }
2445
2446  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
2447
2448  SourceLocation getLParenLoc() const { return LParenLoc; }
2449  SourceLocation getRParenLoc() const { return RParenLoc; }
2450
2451  virtual SourceRange getSourceRange() const {
2452    return SourceRange(LParenLoc, RParenLoc);
2453  }
2454  static bool classof(const Stmt *T) {
2455    return T->getStmtClass() == ParenListExprClass;
2456  }
2457  static bool classof(const ParenListExpr *) { return true; }
2458
2459  // Iterators
2460  virtual child_iterator child_begin();
2461  virtual child_iterator child_end();
2462};
2463
2464
2465//===----------------------------------------------------------------------===//
2466// Clang Extensions
2467//===----------------------------------------------------------------------===//
2468
2469
2470/// ExtVectorElementExpr - This represents access to specific elements of a
2471/// vector, and may occur on the left hand side or right hand side.  For example
2472/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
2473///
2474/// Note that the base may have either vector or pointer to vector type, just
2475/// like a struct field reference.
2476///
2477class ExtVectorElementExpr : public Expr {
2478  Stmt *Base;
2479  IdentifierInfo *Accessor;
2480  SourceLocation AccessorLoc;
2481public:
2482  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
2483                       SourceLocation loc)
2484    : Expr(ExtVectorElementExprClass, ty),
2485      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
2486
2487  /// \brief Build an empty vector element expression.
2488  explicit ExtVectorElementExpr(EmptyShell Empty)
2489    : Expr(ExtVectorElementExprClass, Empty) { }
2490
2491  const Expr *getBase() const { return cast<Expr>(Base); }
2492  Expr *getBase() { return cast<Expr>(Base); }
2493  void setBase(Expr *E) { Base = E; }
2494
2495  IdentifierInfo &getAccessor() const { return *Accessor; }
2496  void setAccessor(IdentifierInfo *II) { Accessor = II; }
2497
2498  SourceLocation getAccessorLoc() const { return AccessorLoc; }
2499  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
2500
2501  /// getNumElements - Get the number of components being selected.
2502  unsigned getNumElements() const;
2503
2504  /// containsDuplicateElements - Return true if any element access is
2505  /// repeated.
2506  bool containsDuplicateElements() const;
2507
2508  /// getEncodedElementAccess - Encode the elements accessed into an llvm
2509  /// aggregate Constant of ConstantInt(s).
2510  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
2511
2512  virtual SourceRange getSourceRange() const {
2513    return SourceRange(getBase()->getLocStart(), AccessorLoc);
2514  }
2515
2516  /// isArrow - Return true if the base expression is a pointer to vector,
2517  /// return false if the base expression is a vector.
2518  bool isArrow() const;
2519
2520  static bool classof(const Stmt *T) {
2521    return T->getStmtClass() == ExtVectorElementExprClass;
2522  }
2523  static bool classof(const ExtVectorElementExpr *) { return true; }
2524
2525  // Iterators
2526  virtual child_iterator child_begin();
2527  virtual child_iterator child_end();
2528};
2529
2530
2531/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
2532/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
2533class BlockExpr : public Expr {
2534protected:
2535  BlockDecl *TheBlock;
2536  bool HasBlockDeclRefExprs;
2537public:
2538  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
2539    : Expr(BlockExprClass, ty),
2540      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
2541
2542  /// \brief Build an empty block expression.
2543  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
2544
2545  const BlockDecl *getBlockDecl() const { return TheBlock; }
2546  BlockDecl *getBlockDecl() { return TheBlock; }
2547  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
2548
2549  // Convenience functions for probing the underlying BlockDecl.
2550  SourceLocation getCaretLocation() const;
2551  const Stmt *getBody() const;
2552  Stmt *getBody();
2553
2554  virtual SourceRange getSourceRange() const {
2555    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
2556  }
2557
2558  /// getFunctionType - Return the underlying function type for this block.
2559  const FunctionType *getFunctionType() const;
2560
2561  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
2562  /// inside of the block that reference values outside the block.
2563  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
2564  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
2565
2566  static bool classof(const Stmt *T) {
2567    return T->getStmtClass() == BlockExprClass;
2568  }
2569  static bool classof(const BlockExpr *) { return true; }
2570
2571  // Iterators
2572  virtual child_iterator child_begin();
2573  virtual child_iterator child_end();
2574};
2575
2576/// BlockDeclRefExpr - A reference to a declared variable, function,
2577/// enum, etc.
2578class BlockDeclRefExpr : public Expr {
2579  ValueDecl *D;
2580  SourceLocation Loc;
2581  bool IsByRef : 1;
2582  bool ConstQualAdded : 1;
2583public:
2584  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
2585                   bool constAdded = false) :
2586       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef),
2587                                       ConstQualAdded(constAdded) {}
2588
2589  // \brief Build an empty reference to a declared variable in a
2590  // block.
2591  explicit BlockDeclRefExpr(EmptyShell Empty)
2592    : Expr(BlockDeclRefExprClass, Empty) { }
2593
2594  ValueDecl *getDecl() { return D; }
2595  const ValueDecl *getDecl() const { return D; }
2596  void setDecl(ValueDecl *VD) { D = VD; }
2597
2598  SourceLocation getLocation() const { return Loc; }
2599  void setLocation(SourceLocation L) { Loc = L; }
2600
2601  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
2602
2603  bool isByRef() const { return IsByRef; }
2604  void setByRef(bool BR) { IsByRef = BR; }
2605
2606  bool isConstQualAdded() const { return ConstQualAdded; }
2607  void setConstQualAdded(bool C) { ConstQualAdded = C; }
2608
2609  static bool classof(const Stmt *T) {
2610    return T->getStmtClass() == BlockDeclRefExprClass;
2611  }
2612  static bool classof(const BlockDeclRefExpr *) { return true; }
2613
2614  // Iterators
2615  virtual child_iterator child_begin();
2616  virtual child_iterator child_end();
2617};
2618
2619}  // end namespace clang
2620
2621#endif
2622