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