Expr.h revision 2d8b273470684a9cd47f0ce24743cc1f71ef7cbc
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/Stmt.h"
18#include "clang/AST/Type.h"
19#include "llvm/ADT/APSInt.h"
20#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/SmallVector.h"
22#include <vector>
23
24namespace clang {
25  class ASTContext;
26  class APValue;
27  class Decl;
28  class IdentifierInfo;
29  class ParmVarDecl;
30  class NamedDecl;
31  class ValueDecl;
32  class BlockDecl;
33
34/// Expr - This represents one expression.  Note that Expr's are subclasses of
35/// Stmt.  This allows an expression to be transparently used any place a Stmt
36/// is required.
37///
38class Expr : public Stmt {
39  QualType TR;
40protected:
41  Expr(StmtClass SC, QualType T) : Stmt(SC) { setType(T); }
42public:
43  QualType getType() const { return TR; }
44  void setType(QualType t) {
45    // In C++, the type of an expression is always adjusted so that it
46    // will not have reference type an expression will never have
47    // reference type (C++ [expr]p6). Use
48    // QualType::getNonReferenceType() to retrieve the non-reference
49    // type. Additionally, inspect Expr::isLvalue to determine whether
50    // an expression that is adjusted in this manner should be
51    // considered an lvalue.
52    assert((TR.isNull() || !TR->isReferenceType()) &&
53           "Expressions can't have reference type");
54
55    TR = t;
56  }
57
58  /// SourceLocation tokens are not useful in isolation - they are low level
59  /// value objects created/interpreted by SourceManager. We assume AST
60  /// clients will have a pointer to the respective SourceManager.
61  virtual SourceRange getSourceRange() const = 0;
62
63  /// getExprLoc - Return the preferred location for the arrow when diagnosing
64  /// a problem with a generic expression.
65  virtual SourceLocation getExprLoc() const { return getLocStart(); }
66
67  /// hasLocalSideEffect - Return true if this immediate expression has side
68  /// effects, not counting any sub-expressions.
69  bool hasLocalSideEffect() const;
70
71  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
72  /// incomplete type other than void. Nonarray expressions that can be lvalues:
73  ///  - name, where name must be a variable
74  ///  - e[i]
75  ///  - (e), where e must be an lvalue
76  ///  - e.name, where e must be an lvalue
77  ///  - e->name
78  ///  - *e, the type of e cannot be a function type
79  ///  - string-constant
80  ///  - reference type [C++ [expr]]
81  ///
82  enum isLvalueResult {
83    LV_Valid,
84    LV_NotObjectType,
85    LV_IncompleteVoidType,
86    LV_DuplicateVectorComponents,
87    LV_InvalidExpression
88  };
89  isLvalueResult isLvalue(ASTContext &Ctx) const;
90
91  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
92  /// does not have an incomplete type, does not have a const-qualified type,
93  /// and if it is a structure or union, does not have any member (including,
94  /// recursively, any member or element of all contained aggregates or unions)
95  /// with a const-qualified type.
96  enum isModifiableLvalueResult {
97    MLV_Valid,
98    MLV_NotObjectType,
99    MLV_IncompleteVoidType,
100    MLV_DuplicateVectorComponents,
101    MLV_InvalidExpression,
102    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
103    MLV_IncompleteType,
104    MLV_ConstQualified,
105    MLV_ArrayType,
106    MLV_NotBlockQualified,
107    MLV_ReadonlyProperty,
108    MLV_NoSetterProperty
109  };
110  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx) const;
111
112  bool isNullPointerConstant(ASTContext &Ctx) const;
113  bool isBitField();
114
115  /// getIntegerConstantExprValue() - Return the value of an integer
116  /// constant expression. The expression must be a valid integer
117  /// constant expression as determined by isIntegerConstantExpr.
118  llvm::APSInt getIntegerConstantExprValue(ASTContext &Ctx) const {
119    llvm::APSInt X;
120    bool success = isIntegerConstantExpr(X, Ctx);
121    success = success;
122    assert(success && "Illegal argument to getIntegerConstantExpr");
123    return X;
124  }
125
126  /// isIntegerConstantExpr - Return true if this expression is a valid integer
127  /// constant expression, and, if so, return its value in Result.  If not a
128  /// valid i-c-e, return false and fill in Loc (if specified) with the location
129  /// of the invalid expression.
130  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
131                             SourceLocation *Loc = 0,
132                             bool isEvaluated = true) const;
133  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
134    llvm::APSInt X;
135    return isIntegerConstantExpr(X, Ctx, Loc);
136  }
137  /// isConstantExpr - Return true if this expression is a valid constant expr.
138  bool isConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const;
139
140  /// Evaluate - Return true if this is a constant which we can fold using
141  /// any crazy technique (that has nothing to do with language standards) that
142  /// we want to.  If this function returns true, it returns the folded constant
143  /// in Result.
144  // FIXME: We should come up with a better API for the isEvaluated case.
145  bool Evaluate(APValue& Result, ASTContext &Ctx, bool *isEvaluated = 0) const;
146
147  /// isEvaluatable - Call Evaluate to see if this expression can be constant
148  /// folded, but discard the result.
149  bool isEvaluatable(ASTContext &Ctx) const;
150
151  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
152  /// must be called on an expression that constant folds to an integer.
153  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
154
155  /// hasGlobalStorage - Return true if this expression has static storage
156  /// duration.  This means that the address of this expression is a link-time
157  /// constant.
158  bool hasGlobalStorage() const;
159
160  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
161  ///  its subexpression.  If that subexpression is also a ParenExpr,
162  ///  then this method recursively returns its subexpression, and so forth.
163  ///  Otherwise, the method returns the current Expr.
164  Expr* IgnoreParens();
165
166  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
167  /// or CastExprs, returning their operand.
168  Expr *IgnoreParenCasts();
169
170  const Expr* IgnoreParens() const {
171    return const_cast<Expr*>(this)->IgnoreParens();
172  }
173  const Expr *IgnoreParenCasts() const {
174    return const_cast<Expr*>(this)->IgnoreParenCasts();
175  }
176
177  static bool classof(const Stmt *T) {
178    return T->getStmtClass() >= firstExprConstant &&
179           T->getStmtClass() <= lastExprConstant;
180  }
181  static bool classof(const Expr *) { return true; }
182
183  static inline Expr* Create(llvm::Deserializer& D, ASTContext& C) {
184    return cast<Expr>(Stmt::Create(D, C));
185  }
186};
187
188
189//===----------------------------------------------------------------------===//
190// Primary Expressions.
191//===----------------------------------------------------------------------===//
192
193/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
194/// enum, etc.
195class DeclRefExpr : public Expr {
196  NamedDecl *D;
197  SourceLocation Loc;
198
199protected:
200  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l) :
201    Expr(SC, t), D(d), Loc(l) {}
202
203public:
204  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) :
205    Expr(DeclRefExprClass, t), D(d), Loc(l) {}
206
207  NamedDecl *getDecl() { return D; }
208  const NamedDecl *getDecl() const { return D; }
209  void setDecl(NamedDecl *NewD) { D = NewD; }
210
211  SourceLocation getLocation() const { return Loc; }
212  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
213
214  static bool classof(const Stmt *T) {
215    return T->getStmtClass() == DeclRefExprClass ||
216           T->getStmtClass() == CXXConditionDeclExprClass;
217  }
218  static bool classof(const DeclRefExpr *) { return true; }
219
220  // Iterators
221  virtual child_iterator child_begin();
222  virtual child_iterator child_end();
223
224  virtual void EmitImpl(llvm::Serializer& S) const;
225  static DeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
226};
227
228/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
229class PredefinedExpr : public Expr {
230public:
231  enum IdentType {
232    Func,
233    Function,
234    PrettyFunction
235  };
236
237private:
238  SourceLocation Loc;
239  IdentType Type;
240public:
241  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
242    : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {}
243
244  IdentType getIdentType() const { return Type; }
245
246  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
247
248  static bool classof(const Stmt *T) {
249    return T->getStmtClass() == PredefinedExprClass;
250  }
251  static bool classof(const PredefinedExpr *) { return true; }
252
253  // Iterators
254  virtual child_iterator child_begin();
255  virtual child_iterator child_end();
256
257  virtual void EmitImpl(llvm::Serializer& S) const;
258  static PredefinedExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
259};
260
261class IntegerLiteral : public Expr {
262  llvm::APInt Value;
263  SourceLocation Loc;
264public:
265  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
266  // or UnsignedLongLongTy
267  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
268    : Expr(IntegerLiteralClass, type), Value(V), Loc(l) {
269    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
270  }
271  const llvm::APInt &getValue() const { return Value; }
272  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
273
274  static bool classof(const Stmt *T) {
275    return T->getStmtClass() == IntegerLiteralClass;
276  }
277  static bool classof(const IntegerLiteral *) { return true; }
278
279  // Iterators
280  virtual child_iterator child_begin();
281  virtual child_iterator child_end();
282
283  virtual void EmitImpl(llvm::Serializer& S) const;
284  static IntegerLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
285};
286
287class CharacterLiteral : public Expr {
288  unsigned Value;
289  SourceLocation Loc;
290  bool IsWide;
291public:
292  // type should be IntTy
293  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
294    : Expr(CharacterLiteralClass, type), Value(value), Loc(l), IsWide(iswide) {
295  }
296  SourceLocation getLoc() const { return Loc; }
297  bool isWide() const { return IsWide; }
298
299  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
300
301  unsigned getValue() const { return Value; }
302
303  static bool classof(const Stmt *T) {
304    return T->getStmtClass() == CharacterLiteralClass;
305  }
306  static bool classof(const CharacterLiteral *) { return true; }
307
308  // Iterators
309  virtual child_iterator child_begin();
310  virtual child_iterator child_end();
311
312  virtual void EmitImpl(llvm::Serializer& S) const;
313  static CharacterLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
314};
315
316class FloatingLiteral : public Expr {
317  llvm::APFloat Value;
318  bool IsExact : 1;
319  SourceLocation Loc;
320public:
321  FloatingLiteral(const llvm::APFloat &V, bool* isexact,
322                  QualType Type, SourceLocation L)
323    : Expr(FloatingLiteralClass, Type), Value(V), IsExact(*isexact), Loc(L) {}
324
325  const llvm::APFloat &getValue() const { return Value; }
326
327  bool isExact() const { return IsExact; }
328
329  /// getValueAsApproximateDouble - This returns the value as an inaccurate
330  /// double.  Note that this may cause loss of precision, but is useful for
331  /// debugging dumps, etc.
332  double getValueAsApproximateDouble() const;
333
334  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
335
336  static bool classof(const Stmt *T) {
337    return T->getStmtClass() == FloatingLiteralClass;
338  }
339  static bool classof(const FloatingLiteral *) { return true; }
340
341  // Iterators
342  virtual child_iterator child_begin();
343  virtual child_iterator child_end();
344
345  virtual void EmitImpl(llvm::Serializer& S) const;
346  static FloatingLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
347};
348
349/// ImaginaryLiteral - We support imaginary integer and floating point literals,
350/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
351/// IntegerLiteral classes.  Instances of this class always have a Complex type
352/// whose element type matches the subexpression.
353///
354class ImaginaryLiteral : public Expr {
355  Stmt *Val;
356public:
357  ImaginaryLiteral(Expr *val, QualType Ty)
358    : Expr(ImaginaryLiteralClass, Ty), Val(val) {}
359
360  const Expr *getSubExpr() const { return cast<Expr>(Val); }
361  Expr *getSubExpr() { return cast<Expr>(Val); }
362
363  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
364  static bool classof(const Stmt *T) {
365    return T->getStmtClass() == ImaginaryLiteralClass;
366  }
367  static bool classof(const ImaginaryLiteral *) { return true; }
368
369  // Iterators
370  virtual child_iterator child_begin();
371  virtual child_iterator child_end();
372
373  virtual void EmitImpl(llvm::Serializer& S) const;
374  static ImaginaryLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
375};
376
377/// StringLiteral - This represents a string literal expression, e.g. "foo"
378/// or L"bar" (wide strings).  The actual string is returned by getStrData()
379/// is NOT null-terminated, and the length of the string is determined by
380/// calling getByteLength().  The C type for a string is always a
381/// ConstantArrayType.
382class StringLiteral : public Expr {
383  const char *StrData;
384  unsigned ByteLength;
385  bool IsWide;
386  // if the StringLiteral was composed using token pasting, both locations
387  // are needed. If not (the common case), firstTokLoc == lastTokLoc.
388  // FIXME: if space becomes an issue, we should create a sub-class.
389  SourceLocation firstTokLoc, lastTokLoc;
390public:
391  StringLiteral(const char *strData, unsigned byteLength, bool Wide,
392                QualType t, SourceLocation b, SourceLocation e);
393  virtual ~StringLiteral();
394
395  const char *getStrData() const { return StrData; }
396  unsigned getByteLength() const { return ByteLength; }
397  bool isWide() const { return IsWide; }
398
399  virtual SourceRange getSourceRange() const {
400    return SourceRange(firstTokLoc,lastTokLoc);
401  }
402  static bool classof(const Stmt *T) {
403    return T->getStmtClass() == StringLiteralClass;
404  }
405  static bool classof(const StringLiteral *) { return true; }
406
407  // Iterators
408  virtual child_iterator child_begin();
409  virtual child_iterator child_end();
410
411  virtual void EmitImpl(llvm::Serializer& S) const;
412  static StringLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
413};
414
415/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
416/// AST node is only formed if full location information is requested.
417class ParenExpr : public Expr {
418  SourceLocation L, R;
419  Stmt *Val;
420public:
421  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
422    : Expr(ParenExprClass, val->getType()), L(l), R(r), Val(val) {}
423
424  const Expr *getSubExpr() const { return cast<Expr>(Val); }
425  Expr *getSubExpr() { return cast<Expr>(Val); }
426  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
427
428  static bool classof(const Stmt *T) {
429    return T->getStmtClass() == ParenExprClass;
430  }
431  static bool classof(const ParenExpr *) { return true; }
432
433  // Iterators
434  virtual child_iterator child_begin();
435  virtual child_iterator child_end();
436
437  virtual void EmitImpl(llvm::Serializer& S) const;
438  static ParenExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
439};
440
441
442/// UnaryOperator - This represents the unary-expression's (except sizeof and
443/// alignof), the postinc/postdec operators from postfix-expression, and various
444/// extensions.
445///
446/// Notes on various nodes:
447///
448/// Real/Imag - These return the real/imag part of a complex operand.  If
449///   applied to a non-complex value, the former returns its operand and the
450///   later returns zero in the type of the operand.
451///
452/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
453///   subexpression is a compound literal with the various MemberExpr and
454///   ArraySubscriptExpr's applied to it.
455///
456class UnaryOperator : public Expr {
457public:
458  // Note that additions to this should also update the StmtVisitor class.
459  enum Opcode {
460    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
461    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
462    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
463    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
464    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
465    Real, Imag,       // "__real expr"/"__imag expr" Extension.
466    Extension,        // __extension__ marker.
467    OffsetOf          // __builtin_offsetof
468  };
469private:
470  Stmt *Val;
471  Opcode Opc;
472  SourceLocation Loc;
473public:
474
475  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
476    : Expr(UnaryOperatorClass, type), Val(input), Opc(opc), Loc(l) {}
477
478  Opcode getOpcode() const { return Opc; }
479  Expr *getSubExpr() const { return cast<Expr>(Val); }
480
481  /// getOperatorLoc - Return the location of the operator.
482  SourceLocation getOperatorLoc() const { return Loc; }
483
484  /// isPostfix - Return true if this is a postfix operation, like x++.
485  static bool isPostfix(Opcode Op);
486
487  /// isPostfix - Return true if this is a prefix operation, like --x.
488  static bool isPrefix(Opcode Op);
489
490  bool isPrefix() const { return isPrefix(Opc); }
491  bool isPostfix() const { return isPostfix(Opc); }
492  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
493  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
494  bool isOffsetOfOp() const { return Opc == OffsetOf; }
495  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
496
497  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
498  /// corresponds to, e.g. "sizeof" or "[pre]++"
499  static const char *getOpcodeStr(Opcode Op);
500
501  virtual SourceRange getSourceRange() const {
502    if (isPostfix())
503      return SourceRange(Val->getLocStart(), Loc);
504    else
505      return SourceRange(Loc, Val->getLocEnd());
506  }
507  virtual SourceLocation getExprLoc() const { return Loc; }
508
509  static bool classof(const Stmt *T) {
510    return T->getStmtClass() == UnaryOperatorClass;
511  }
512  static bool classof(const UnaryOperator *) { return true; }
513
514  int64_t evaluateOffsetOf(ASTContext& C) const;
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 UnaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
522};
523
524/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
525/// types and expressions.
526class SizeOfAlignOfExpr : public Expr {
527  bool isSizeof : 1;  // true if sizeof, false if alignof.
528  bool isType : 1;    // true if operand is a type, false if an expression
529  void *Argument;
530  SourceLocation OpLoc, RParenLoc;
531public:
532  SizeOfAlignOfExpr(bool issizeof, bool istype, void *argument,
533                    QualType resultType, SourceLocation op,
534                    SourceLocation rp) :
535    Expr(SizeOfAlignOfExprClass, resultType),
536    isSizeof(issizeof), isType(istype), Argument(argument),
537    OpLoc(op), RParenLoc(rp) {}
538
539  virtual void Destroy(ASTContext& C);
540
541  bool isSizeOf() const { return isSizeof; }
542  bool isArgumentType() const { return isType; }
543  QualType getArgumentType() const {
544    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
545    return QualType::getFromOpaquePtr(Argument);
546  }
547  Expr* getArgumentExpr() const {
548    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
549    return (Expr *)Argument;
550  }
551  /// Gets the argument type, or the type of the argument expression, whichever
552  /// is appropriate.
553  QualType getTypeOfArgument() const {
554    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
555  }
556
557  SourceLocation getOperatorLoc() const { return OpLoc; }
558
559  virtual SourceRange getSourceRange() const {
560    return SourceRange(OpLoc, RParenLoc);
561  }
562
563  static bool classof(const Stmt *T) {
564    return T->getStmtClass() == SizeOfAlignOfExprClass;
565  }
566  static bool classof(const SizeOfAlignOfExpr *) { return true; }
567
568  // Iterators
569  virtual child_iterator child_begin();
570  virtual child_iterator child_end();
571
572  virtual void EmitImpl(llvm::Serializer& S) const;
573  static SizeOfAlignOfExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
574};
575
576//===----------------------------------------------------------------------===//
577// Postfix Operators.
578//===----------------------------------------------------------------------===//
579
580/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
581class ArraySubscriptExpr : public Expr {
582  enum { LHS, RHS, END_EXPR=2 };
583  Stmt* SubExprs[END_EXPR];
584  SourceLocation RBracketLoc;
585public:
586  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
587                     SourceLocation rbracketloc)
588  : Expr(ArraySubscriptExprClass, t), RBracketLoc(rbracketloc) {
589    SubExprs[LHS] = lhs;
590    SubExprs[RHS] = rhs;
591  }
592
593  /// An array access can be written A[4] or 4[A] (both are equivalent).
594  /// - getBase() and getIdx() always present the normalized view: A[4].
595  ///    In this case getBase() returns "A" and getIdx() returns "4".
596  /// - getLHS() and getRHS() present the syntactic view. e.g. for
597  ///    4[A] getLHS() returns "4".
598  /// Note: Because vector element access is also written A[4] we must
599  /// predicate the format conversion in getBase and getIdx only on the
600  /// the type of the RHS, as it is possible for the LHS to be a vector of
601  /// integer type
602  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
603  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
604
605  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
606  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
607
608  Expr *getBase() {
609    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
610  }
611
612  const Expr *getBase() const {
613    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
614  }
615
616  Expr *getIdx() {
617    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
618  }
619
620  const Expr *getIdx() const {
621    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
622  }
623
624  virtual SourceRange getSourceRange() const {
625    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
626  }
627
628  virtual SourceLocation getExprLoc() const { return RBracketLoc; }
629
630  static bool classof(const Stmt *T) {
631    return T->getStmtClass() == ArraySubscriptExprClass;
632  }
633  static bool classof(const ArraySubscriptExpr *) { return true; }
634
635  // Iterators
636  virtual child_iterator child_begin();
637  virtual child_iterator child_end();
638
639  virtual void EmitImpl(llvm::Serializer& S) const;
640  static ArraySubscriptExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
641};
642
643
644/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
645/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
646/// while its subclasses may represent alternative syntax that (semantically)
647/// results in a function call. For example, CXXOperatorCallExpr is
648/// a subclass for overloaded operator calls that use operator syntax, e.g.,
649/// "str1 + str2" to resolve to a function call.
650class CallExpr : public Expr {
651  enum { FN=0, ARGS_START=1 };
652  Stmt **SubExprs;
653  unsigned NumArgs;
654  SourceLocation RParenLoc;
655
656  // This version of the ctor is for deserialization.
657  CallExpr(StmtClass SC, Stmt** subexprs, unsigned numargs, QualType t,
658           SourceLocation rparenloc)
659  : Expr(SC,t), SubExprs(subexprs),
660    NumArgs(numargs), RParenLoc(rparenloc) {}
661
662protected:
663  // This version of the constructor is for derived classes.
664  CallExpr(StmtClass SC, Expr *fn, Expr **args, unsigned numargs, QualType t,
665           SourceLocation rparenloc);
666
667public:
668  CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
669           SourceLocation rparenloc);
670  ~CallExpr() {
671    delete [] SubExprs;
672  }
673
674  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
675  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
676  void setCallee(Expr *F) { SubExprs[FN] = F; }
677
678  /// getNumArgs - Return the number of actual arguments to this call.
679  ///
680  unsigned getNumArgs() const { return NumArgs; }
681
682  /// getArg - Return the specified argument.
683  Expr *getArg(unsigned Arg) {
684    assert(Arg < NumArgs && "Arg access out of range!");
685    return cast<Expr>(SubExprs[Arg+ARGS_START]);
686  }
687  const Expr *getArg(unsigned Arg) const {
688    assert(Arg < NumArgs && "Arg access out of range!");
689    return cast<Expr>(SubExprs[Arg+ARGS_START]);
690  }
691  /// setArg - Set the specified argument.
692  void setArg(unsigned Arg, Expr *ArgExpr) {
693    assert(Arg < NumArgs && "Arg access out of range!");
694    SubExprs[Arg+ARGS_START] = ArgExpr;
695  }
696
697  /// setNumArgs - This changes the number of arguments present in this call.
698  /// Any orphaned expressions are deleted by this, and any new operands are set
699  /// to null.
700  void setNumArgs(unsigned NumArgs);
701
702  typedef ExprIterator arg_iterator;
703  typedef ConstExprIterator const_arg_iterator;
704
705  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
706  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
707  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
708  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
709
710  /// getNumCommas - Return the number of commas that must have been present in
711  /// this function call.
712  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
713
714  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
715  /// not, return 0.
716  unsigned isBuiltinCall() const;
717
718  SourceLocation getRParenLoc() const { return RParenLoc; }
719
720  virtual SourceRange getSourceRange() const {
721    return SourceRange(getCallee()->getLocStart(), RParenLoc);
722  }
723
724  static bool classof(const Stmt *T) {
725    return T->getStmtClass() == CallExprClass ||
726           T->getStmtClass() == CXXOperatorCallExprClass;
727  }
728  static bool classof(const CallExpr *) { return true; }
729
730  // Iterators
731  virtual child_iterator child_begin();
732  virtual child_iterator child_end();
733
734  virtual void EmitImpl(llvm::Serializer& S) const;
735  static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C,
736                              StmtClass SC);
737};
738
739/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.
740///
741class MemberExpr : public Expr {
742  Stmt *Base;
743  FieldDecl *MemberDecl;
744  SourceLocation MemberLoc;
745  bool IsArrow;      // True if this is "X->F", false if this is "X.F".
746public:
747  MemberExpr(Expr *base, bool isarrow, FieldDecl *memberdecl, SourceLocation l,
748             QualType ty)
749    : Expr(MemberExprClass, ty),
750      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
751
752  Expr *getBase() const { return cast<Expr>(Base); }
753  FieldDecl *getMemberDecl() const { return MemberDecl; }
754  bool isArrow() const { return IsArrow; }
755
756  virtual SourceRange getSourceRange() const {
757    return SourceRange(getBase()->getLocStart(), MemberLoc);
758  }
759
760  virtual SourceLocation getExprLoc() const { return MemberLoc; }
761
762  static bool classof(const Stmt *T) {
763    return T->getStmtClass() == MemberExprClass;
764  }
765  static bool classof(const MemberExpr *) { return true; }
766
767  // Iterators
768  virtual child_iterator child_begin();
769  virtual child_iterator child_end();
770
771  virtual void EmitImpl(llvm::Serializer& S) const;
772  static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
773};
774
775/// CompoundLiteralExpr - [C99 6.5.2.5]
776///
777class CompoundLiteralExpr : public Expr {
778  /// LParenLoc - If non-null, this is the location of the left paren in a
779  /// compound literal like "(int){4}".  This can be null if this is a
780  /// synthesized compound expression.
781  SourceLocation LParenLoc;
782  Stmt *Init;
783  bool FileScope;
784public:
785  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
786                      bool fileScope)
787    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
788      FileScope(fileScope) {}
789
790  const Expr *getInitializer() const { return cast<Expr>(Init); }
791  Expr *getInitializer() { return cast<Expr>(Init); }
792
793  bool isFileScope() const { return FileScope; }
794
795  SourceLocation getLParenLoc() const { return LParenLoc; }
796
797  virtual SourceRange getSourceRange() const {
798    // FIXME: Init should never be null.
799    if (!Init)
800      return SourceRange();
801    if (LParenLoc.isInvalid())
802      return Init->getSourceRange();
803    return SourceRange(LParenLoc, Init->getLocEnd());
804  }
805
806  static bool classof(const Stmt *T) {
807    return T->getStmtClass() == CompoundLiteralExprClass;
808  }
809  static bool classof(const CompoundLiteralExpr *) { return true; }
810
811  // Iterators
812  virtual child_iterator child_begin();
813  virtual child_iterator child_end();
814
815  virtual void EmitImpl(llvm::Serializer& S) const;
816  static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
817};
818
819/// CastExpr - Base class for type casts, including both implicit
820/// casts (ImplicitCastExpr) and explicit casts that have some
821/// representation in the source code (ExplicitCastExpr's derived
822/// classes).
823class CastExpr : public Expr {
824  Stmt *Op;
825protected:
826  CastExpr(StmtClass SC, QualType ty, Expr *op) :
827    Expr(SC, ty), Op(op) {}
828
829public:
830  Expr *getSubExpr() { return cast<Expr>(Op); }
831  const Expr *getSubExpr() const { return cast<Expr>(Op); }
832
833  static bool classof(const Stmt *T) {
834    StmtClass SC = T->getStmtClass();
835    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
836      return true;
837
838    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
839      return true;
840
841    return false;
842  }
843  static bool classof(const CastExpr *) { return true; }
844
845  // Iterators
846  virtual child_iterator child_begin();
847  virtual child_iterator child_end();
848};
849
850/// ImplicitCastExpr - Allows us to explicitly represent implicit type
851/// conversions, which have no direct representation in the original
852/// source code. For example: converting T[]->T*, void f()->void
853/// (*f)(), float->double, short->int, etc.
854///
855/// In C, implicit casts always produce rvalues. However, in C++, an
856/// implicit cast whose result is being bound to a reference will be
857/// an lvalue. For example:
858///
859/// @code
860/// class Base { };
861/// class Derived : public Base { };
862/// void f(Derived d) {
863///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
864/// }
865/// @endcode
866class ImplicitCastExpr : public CastExpr {
867  /// LvalueCast - Whether this cast produces an lvalue.
868  bool LvalueCast;
869
870public:
871  ImplicitCastExpr(QualType ty, Expr *op, bool Lvalue) :
872    CastExpr(ImplicitCastExprClass, ty, op), LvalueCast(Lvalue) {}
873
874  virtual SourceRange getSourceRange() const {
875    return getSubExpr()->getSourceRange();
876  }
877
878  /// isLvalueCast - Whether this cast produces an lvalue.
879  bool isLvalueCast() const { return LvalueCast; }
880
881  /// setLvalueCast - Set whether this cast produces an lvalue.
882  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
883
884  static bool classof(const Stmt *T) {
885    return T->getStmtClass() == ImplicitCastExprClass;
886  }
887  static bool classof(const ImplicitCastExpr *) { return true; }
888
889  virtual void EmitImpl(llvm::Serializer& S) const;
890  static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
891};
892
893/// ExplicitCastExpr - An explicit cast written in the source
894/// code.
895///
896/// This class is effectively an abstract class, because it provides
897/// the basic representation of an explicitly-written cast without
898/// specifying which kind of cast (C cast, functional cast, static
899/// cast, etc.) was written; specific derived classes represent the
900/// particular style of cast and its location information.
901///
902/// Unlike implicit casts, explicit cast nodes have two different
903/// types: the type that was written into the source code, and the
904/// actual type of the expression as determined by semantic
905/// analysis. These types may differ slightly. For example, in C++ one
906/// can cast to a reference type, which indicates that the resulting
907/// expression will be an lvalue. The reference type, however, will
908/// not be used as the type of the expression.
909class ExplicitCastExpr : public CastExpr {
910  /// TypeAsWritten - The type that this expression is casting to, as
911  /// written in the source code.
912  QualType TypeAsWritten;
913
914protected:
915  ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy)
916    : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {}
917
918public:
919  /// getTypeAsWritten - Returns the type that this expression is
920  /// casting to, as written in the source code.
921  QualType getTypeAsWritten() const { return TypeAsWritten; }
922
923  static bool classof(const Stmt *T) {
924    StmtClass SC = T->getStmtClass();
925    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
926      return true;
927    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
928      return true;
929
930    return false;
931  }
932  static bool classof(const ExplicitCastExpr *) { return true; }
933};
934
935/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
936/// cast in C++ (C++ [expr.cast]), which uses the syntax
937/// (Type)expr. For example: @c (int)f.
938class CStyleCastExpr : public ExplicitCastExpr {
939  SourceLocation LPLoc; // the location of the left paren
940  SourceLocation RPLoc; // the location of the right paren
941public:
942  CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy,
943                    SourceLocation l, SourceLocation r) :
944    ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy),
945    LPLoc(l), RPLoc(r) {}
946
947  SourceLocation getLParenLoc() const { return LPLoc; }
948  SourceLocation getRParenLoc() const { return RPLoc; }
949
950  virtual SourceRange getSourceRange() const {
951    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
952  }
953  static bool classof(const Stmt *T) {
954    return T->getStmtClass() == CStyleCastExprClass;
955  }
956  static bool classof(const CStyleCastExpr *) { return true; }
957
958  virtual void EmitImpl(llvm::Serializer& S) const;
959  static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
960};
961
962class BinaryOperator : public Expr {
963public:
964  enum Opcode {
965    // Operators listed in order of precedence.
966    // Note that additions to this should also update the StmtVisitor class.
967    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
968    Add, Sub,         // [C99 6.5.6] Additive operators.
969    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
970    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
971    EQ, NE,           // [C99 6.5.9] Equality operators.
972    And,              // [C99 6.5.10] Bitwise AND operator.
973    Xor,              // [C99 6.5.11] Bitwise XOR operator.
974    Or,               // [C99 6.5.12] Bitwise OR operator.
975    LAnd,             // [C99 6.5.13] Logical AND operator.
976    LOr,              // [C99 6.5.14] Logical OR operator.
977    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
978    DivAssign, RemAssign,
979    AddAssign, SubAssign,
980    ShlAssign, ShrAssign,
981    AndAssign, XorAssign,
982    OrAssign,
983    Comma             // [C99 6.5.17] Comma operator.
984  };
985private:
986  enum { LHS, RHS, END_EXPR };
987  Stmt* SubExprs[END_EXPR];
988  Opcode Opc;
989  SourceLocation OpLoc;
990public:
991
992  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
993                 SourceLocation opLoc)
994    : Expr(BinaryOperatorClass, ResTy), Opc(opc), OpLoc(opLoc) {
995    SubExprs[LHS] = lhs;
996    SubExprs[RHS] = rhs;
997    assert(!isCompoundAssignmentOp() &&
998           "Use ArithAssignBinaryOperator for compound assignments");
999  }
1000
1001  SourceLocation getOperatorLoc() const { return OpLoc; }
1002  Opcode getOpcode() const { return Opc; }
1003  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1004  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1005  virtual SourceRange getSourceRange() const {
1006    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1007  }
1008
1009  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1010  /// corresponds to, e.g. "<<=".
1011  static const char *getOpcodeStr(Opcode Op);
1012
1013  /// predicates to categorize the respective opcodes.
1014  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1015  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1016  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
1017  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
1018
1019  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1020  bool isRelationalOp() const { return isRelationalOp(Opc); }
1021
1022  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1023  bool isEqualityOp() const { return isEqualityOp(Opc); }
1024
1025  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1026  bool isLogicalOp() const { return isLogicalOp(Opc); }
1027
1028  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1029  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1030  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1031
1032  static bool classof(const Stmt *S) {
1033    return S->getStmtClass() == BinaryOperatorClass ||
1034           S->getStmtClass() == CompoundAssignOperatorClass;
1035  }
1036  static bool classof(const BinaryOperator *) { return true; }
1037
1038  // Iterators
1039  virtual child_iterator child_begin();
1040  virtual child_iterator child_end();
1041
1042  virtual void EmitImpl(llvm::Serializer& S) const;
1043  static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1044
1045protected:
1046  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1047                 SourceLocation oploc, bool dead)
1048    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
1049    SubExprs[LHS] = lhs;
1050    SubExprs[RHS] = rhs;
1051  }
1052};
1053
1054/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1055/// track of the type the operation is performed in.  Due to the semantics of
1056/// these operators, the operands are promoted, the aritmetic performed, an
1057/// implicit conversion back to the result type done, then the assignment takes
1058/// place.  This captures the intermediate type which the computation is done
1059/// in.
1060class CompoundAssignOperator : public BinaryOperator {
1061  QualType ComputationType;
1062public:
1063  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1064                         QualType ResType, QualType CompType,
1065                         SourceLocation OpLoc)
1066    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1067      ComputationType(CompType) {
1068    assert(isCompoundAssignmentOp() &&
1069           "Only should be used for compound assignments");
1070  }
1071
1072  QualType getComputationType() const { return ComputationType; }
1073
1074  static bool classof(const CompoundAssignOperator *) { return true; }
1075  static bool classof(const Stmt *S) {
1076    return S->getStmtClass() == CompoundAssignOperatorClass;
1077  }
1078
1079  virtual void EmitImpl(llvm::Serializer& S) const;
1080  static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D,
1081                                            ASTContext& C);
1082};
1083
1084/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1085/// GNU "missing LHS" extension is in use.
1086///
1087class ConditionalOperator : public Expr {
1088  enum { COND, LHS, RHS, END_EXPR };
1089  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1090public:
1091  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1092    : Expr(ConditionalOperatorClass, t) {
1093    SubExprs[COND] = cond;
1094    SubExprs[LHS] = lhs;
1095    SubExprs[RHS] = rhs;
1096  }
1097
1098  // getCond - Return the expression representing the condition for
1099  //  the ?: operator.
1100  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1101
1102  // getTrueExpr - Return the subexpression representing the value of the ?:
1103  //  expression if the condition evaluates to true.  In most cases this value
1104  //  will be the same as getLHS() except a GCC extension allows the left
1105  //  subexpression to be omitted, and instead of the condition be returned.
1106  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1107  //  is only evaluated once.
1108  Expr *getTrueExpr() const {
1109    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1110  }
1111
1112  // getTrueExpr - Return the subexpression representing the value of the ?:
1113  // expression if the condition evaluates to false. This is the same as getRHS.
1114  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1115
1116  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1117  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1118
1119  virtual SourceRange getSourceRange() const {
1120    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1121  }
1122  static bool classof(const Stmt *T) {
1123    return T->getStmtClass() == ConditionalOperatorClass;
1124  }
1125  static bool classof(const ConditionalOperator *) { return true; }
1126
1127  // Iterators
1128  virtual child_iterator child_begin();
1129  virtual child_iterator child_end();
1130
1131  virtual void EmitImpl(llvm::Serializer& S) const;
1132  static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1133};
1134
1135/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1136class AddrLabelExpr : public Expr {
1137  SourceLocation AmpAmpLoc, LabelLoc;
1138  LabelStmt *Label;
1139public:
1140  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1141                QualType t)
1142    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1143
1144  virtual SourceRange getSourceRange() const {
1145    return SourceRange(AmpAmpLoc, LabelLoc);
1146  }
1147
1148  LabelStmt *getLabel() const { return Label; }
1149
1150  static bool classof(const Stmt *T) {
1151    return T->getStmtClass() == AddrLabelExprClass;
1152  }
1153  static bool classof(const AddrLabelExpr *) { return true; }
1154
1155  // Iterators
1156  virtual child_iterator child_begin();
1157  virtual child_iterator child_end();
1158
1159  virtual void EmitImpl(llvm::Serializer& S) const;
1160  static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1161};
1162
1163/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1164/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1165/// takes the value of the last subexpression.
1166class StmtExpr : public Expr {
1167  Stmt *SubStmt;
1168  SourceLocation LParenLoc, RParenLoc;
1169public:
1170  StmtExpr(CompoundStmt *substmt, QualType T,
1171           SourceLocation lp, SourceLocation rp) :
1172    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1173
1174  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1175  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1176
1177  virtual SourceRange getSourceRange() const {
1178    return SourceRange(LParenLoc, RParenLoc);
1179  }
1180
1181  static bool classof(const Stmt *T) {
1182    return T->getStmtClass() == StmtExprClass;
1183  }
1184  static bool classof(const StmtExpr *) { return true; }
1185
1186  // Iterators
1187  virtual child_iterator child_begin();
1188  virtual child_iterator child_end();
1189
1190  virtual void EmitImpl(llvm::Serializer& S) const;
1191  static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1192};
1193
1194/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p.
1195/// This AST node represents a function that returns 1 if two *types* (not
1196/// expressions) are compatible. The result of this built-in function can be
1197/// used in integer constant expressions.
1198class TypesCompatibleExpr : public Expr {
1199  QualType Type1;
1200  QualType Type2;
1201  SourceLocation BuiltinLoc, RParenLoc;
1202public:
1203  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1204                      QualType t1, QualType t2, SourceLocation RP) :
1205    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1206    BuiltinLoc(BLoc), RParenLoc(RP) {}
1207
1208  QualType getArgType1() const { return Type1; }
1209  QualType getArgType2() const { return Type2; }
1210
1211  virtual SourceRange getSourceRange() const {
1212    return SourceRange(BuiltinLoc, RParenLoc);
1213  }
1214  static bool classof(const Stmt *T) {
1215    return T->getStmtClass() == TypesCompatibleExprClass;
1216  }
1217  static bool classof(const TypesCompatibleExpr *) { return true; }
1218
1219  // Iterators
1220  virtual child_iterator child_begin();
1221  virtual child_iterator child_end();
1222
1223  virtual void EmitImpl(llvm::Serializer& S) const;
1224  static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1225};
1226
1227/// ShuffleVectorExpr - clang-specific builtin-in function
1228/// __builtin_shufflevector.
1229/// This AST node represents a operator that does a constant
1230/// shuffle, similar to LLVM's shufflevector instruction. It takes
1231/// two vectors and a variable number of constant indices,
1232/// and returns the appropriately shuffled vector.
1233class ShuffleVectorExpr : public Expr {
1234  SourceLocation BuiltinLoc, RParenLoc;
1235
1236  // SubExprs - the list of values passed to the __builtin_shufflevector
1237  // function. The first two are vectors, and the rest are constant
1238  // indices.  The number of values in this list is always
1239  // 2+the number of indices in the vector type.
1240  Stmt **SubExprs;
1241  unsigned NumExprs;
1242
1243public:
1244  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1245                    QualType Type, SourceLocation BLoc,
1246                    SourceLocation RP) :
1247    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1248    RParenLoc(RP), NumExprs(nexpr) {
1249
1250    SubExprs = new Stmt*[nexpr];
1251    for (unsigned i = 0; i < nexpr; i++)
1252      SubExprs[i] = args[i];
1253  }
1254
1255  virtual SourceRange getSourceRange() const {
1256    return SourceRange(BuiltinLoc, RParenLoc);
1257  }
1258  static bool classof(const Stmt *T) {
1259    return T->getStmtClass() == ShuffleVectorExprClass;
1260  }
1261  static bool classof(const ShuffleVectorExpr *) { return true; }
1262
1263  ~ShuffleVectorExpr() {
1264    delete [] SubExprs;
1265  }
1266
1267  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1268  /// constant expression, the actual arguments passed in, and the function
1269  /// pointers.
1270  unsigned getNumSubExprs() const { return NumExprs; }
1271
1272  /// getExpr - Return the Expr at the specified index.
1273  Expr *getExpr(unsigned Index) {
1274    assert((Index < NumExprs) && "Arg access out of range!");
1275    return cast<Expr>(SubExprs[Index]);
1276  }
1277  const Expr *getExpr(unsigned Index) const {
1278    assert((Index < NumExprs) && "Arg access out of range!");
1279    return cast<Expr>(SubExprs[Index]);
1280  }
1281
1282  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1283    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1284    return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue();
1285  }
1286
1287  // Iterators
1288  virtual child_iterator child_begin();
1289  virtual child_iterator child_end();
1290
1291  virtual void EmitImpl(llvm::Serializer& S) const;
1292  static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1293};
1294
1295/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1296/// This AST node is similar to the conditional operator (?:) in C, with
1297/// the following exceptions:
1298/// - the test expression must be a constant expression.
1299/// - the expression returned has it's type unaltered by promotion rules.
1300/// - does not evaluate the expression that was not chosen.
1301class ChooseExpr : public Expr {
1302  enum { COND, LHS, RHS, END_EXPR };
1303  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1304  SourceLocation BuiltinLoc, RParenLoc;
1305public:
1306  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1307             SourceLocation RP)
1308    : Expr(ChooseExprClass, t),
1309      BuiltinLoc(BLoc), RParenLoc(RP) {
1310      SubExprs[COND] = cond;
1311      SubExprs[LHS] = lhs;
1312      SubExprs[RHS] = rhs;
1313    }
1314
1315  /// isConditionTrue - Return true if the condition is true.  This is always
1316  /// statically knowable for a well-formed choosexpr.
1317  bool isConditionTrue(ASTContext &C) const;
1318
1319  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1320  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1321  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1322
1323  virtual SourceRange getSourceRange() const {
1324    return SourceRange(BuiltinLoc, RParenLoc);
1325  }
1326  static bool classof(const Stmt *T) {
1327    return T->getStmtClass() == ChooseExprClass;
1328  }
1329  static bool classof(const ChooseExpr *) { return true; }
1330
1331  // Iterators
1332  virtual child_iterator child_begin();
1333  virtual child_iterator child_end();
1334
1335  virtual void EmitImpl(llvm::Serializer& S) const;
1336  static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1337};
1338
1339/// GNUNullExpr - Implements the GNU __null extension, which is a name
1340/// for a null pointer constant that has integral type (e.g., int or
1341/// long) and is the same size and alignment as a pointer. The __null
1342/// extension is typically only used by system headers, which define
1343/// NULL as __null in C++ rather than using 0 (which is an integer
1344/// that may not match the size of a pointer).
1345class GNUNullExpr : public Expr {
1346  /// TokenLoc - The location of the __null keyword.
1347  SourceLocation TokenLoc;
1348
1349public:
1350  GNUNullExpr(QualType Ty, SourceLocation Loc)
1351    : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { }
1352
1353  /// getTokenLocation - The location of the __null token.
1354  SourceLocation getTokenLocation() const { return TokenLoc; }
1355
1356  virtual SourceRange getSourceRange() const {
1357    return SourceRange(TokenLoc);
1358  }
1359  static bool classof(const Stmt *T) {
1360    return T->getStmtClass() == GNUNullExprClass;
1361  }
1362  static bool classof(const GNUNullExpr *) { return true; }
1363
1364  // Iterators
1365  virtual child_iterator child_begin();
1366  virtual child_iterator child_end();
1367
1368  virtual void EmitImpl(llvm::Serializer& S) const;
1369  static GNUNullExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1370};
1371
1372/// OverloadExpr - Clang builtin function __builtin_overload.
1373/// This AST node provides a way to overload functions in C.
1374///
1375/// The first argument is required to be a constant expression, for the number
1376/// of arguments passed to each candidate function.
1377///
1378/// The next N arguments, where N is the value of the constant expression,
1379/// are the values to be passed as arguments.
1380///
1381/// The rest of the arguments are values of pointer to function type, which
1382/// are the candidate functions for overloading.
1383///
1384/// The result is a equivalent to a CallExpr taking N arguments to the
1385/// candidate function whose parameter types match the types of the N arguments.
1386///
1387/// example: float Z = __builtin_overload(2, X, Y, modf, mod, modl);
1388/// If X and Y are long doubles, Z will assigned the result of modl(X, Y);
1389/// If X and Y are floats, Z will be assigned the result of modf(X, Y);
1390class OverloadExpr : public Expr {
1391  // SubExprs - the list of values passed to the __builtin_overload function.
1392  // SubExpr[0] is a constant expression
1393  // SubExpr[1-N] are the parameters to pass to the matching function call
1394  // SubExpr[N-...] are the candidate functions, of type pointer to function.
1395  Stmt **SubExprs;
1396
1397  // NumExprs - the size of the SubExprs array
1398  unsigned NumExprs;
1399
1400  // The index of the matching candidate function
1401  unsigned FnIndex;
1402
1403  SourceLocation BuiltinLoc;
1404  SourceLocation RParenLoc;
1405public:
1406  OverloadExpr(Expr **args, unsigned nexprs, unsigned idx, QualType t,
1407               SourceLocation bloc, SourceLocation rploc)
1408    : Expr(OverloadExprClass, t), NumExprs(nexprs), FnIndex(idx),
1409      BuiltinLoc(bloc), RParenLoc(rploc) {
1410    SubExprs = new Stmt*[nexprs];
1411    for (unsigned i = 0; i != nexprs; ++i)
1412      SubExprs[i] = args[i];
1413  }
1414  ~OverloadExpr() {
1415    delete [] SubExprs;
1416  }
1417
1418  /// arg_begin - Return a pointer to the list of arguments that will be passed
1419  /// to the matching candidate function, skipping over the initial constant
1420  /// expression.
1421  typedef ConstExprIterator const_arg_iterator;
1422  const_arg_iterator arg_begin() const { return &SubExprs[0]+1; }
1423  const_arg_iterator arg_end(ASTContext& Ctx) const {
1424    return &SubExprs[0]+1+getNumArgs(Ctx);
1425  }
1426
1427  /// getNumArgs - Return the number of arguments to pass to the candidate
1428  /// functions.
1429  unsigned getNumArgs(ASTContext &Ctx) const {
1430    return getExpr(0)->getIntegerConstantExprValue(Ctx).getZExtValue();
1431  }
1432
1433  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1434  /// constant expression, the actual arguments passed in, and the function
1435  /// pointers.
1436  unsigned getNumSubExprs() const { return NumExprs; }
1437
1438  /// getExpr - Return the Expr at the specified index.
1439  Expr *getExpr(unsigned Index) const {
1440    assert((Index < NumExprs) && "Arg access out of range!");
1441    return cast<Expr>(SubExprs[Index]);
1442  }
1443
1444  /// getFn - Return the matching candidate function for this OverloadExpr.
1445  Expr *getFn() const { return cast<Expr>(SubExprs[FnIndex]); }
1446
1447  virtual SourceRange getSourceRange() const {
1448    return SourceRange(BuiltinLoc, RParenLoc);
1449  }
1450  static bool classof(const Stmt *T) {
1451    return T->getStmtClass() == OverloadExprClass;
1452  }
1453  static bool classof(const OverloadExpr *) { return true; }
1454
1455  // Iterators
1456  virtual child_iterator child_begin();
1457  virtual child_iterator child_end();
1458
1459  virtual void EmitImpl(llvm::Serializer& S) const;
1460  static OverloadExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1461};
1462
1463/// VAArgExpr, used for the builtin function __builtin_va_start.
1464class VAArgExpr : public Expr {
1465  Stmt *Val;
1466  SourceLocation BuiltinLoc, RParenLoc;
1467public:
1468  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1469    : Expr(VAArgExprClass, t),
1470      Val(e),
1471      BuiltinLoc(BLoc),
1472      RParenLoc(RPLoc) { }
1473
1474  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1475  Expr *getSubExpr() { return cast<Expr>(Val); }
1476  virtual SourceRange getSourceRange() const {
1477    return SourceRange(BuiltinLoc, RParenLoc);
1478  }
1479  static bool classof(const Stmt *T) {
1480    return T->getStmtClass() == VAArgExprClass;
1481  }
1482  static bool classof(const VAArgExpr *) { return true; }
1483
1484  // Iterators
1485  virtual child_iterator child_begin();
1486  virtual child_iterator child_end();
1487
1488  virtual void EmitImpl(llvm::Serializer& S) const;
1489  static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1490};
1491
1492/// InitListExpr - used for struct and array initializers, such as:
1493///    struct foo x = { 1, { 2, 3 } };
1494///
1495/// Because C is somewhat loose with braces, the AST does not necessarily
1496/// directly model the C source.  Instead, the semantic analyzer aims to make
1497/// the InitListExprs match up with the type of the decl being initialized.  We
1498/// have the following exceptions:
1499///
1500///  1. Elements at the end of the list may be dropped from the initializer.
1501///     These elements are defined to be initialized to zero.  For example:
1502///         int x[20] = { 1 };
1503///  2. Initializers may have excess initializers which are to be ignored by the
1504///     compiler.  For example:
1505///         int x[1] = { 1, 2 };
1506///  3. Redundant InitListExprs may be present around scalar elements.  These
1507///     always have a single element whose type is the same as the InitListExpr.
1508///     this can only happen for Type::isScalarType() types.
1509///         int x = { 1 };  int y[2] = { {1}, {2} };
1510///
1511class InitListExpr : public Expr {
1512  std::vector<Stmt *> InitExprs;
1513  SourceLocation LBraceLoc, RBraceLoc;
1514
1515  /// HadDesignators - Return true if there were any designators in this
1516  /// init list expr.  FIXME: this should be replaced by storing the designators
1517  /// somehow and updating codegen.
1518  bool HadDesignators;
1519public:
1520  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1521               SourceLocation rbraceloc, bool HadDesignators);
1522
1523  unsigned getNumInits() const { return InitExprs.size(); }
1524  bool hadDesignators() const { return HadDesignators; }
1525
1526  const Expr* getInit(unsigned Init) const {
1527    assert(Init < getNumInits() && "Initializer access out of range!");
1528    return cast<Expr>(InitExprs[Init]);
1529  }
1530
1531  Expr* getInit(unsigned Init) {
1532    assert(Init < getNumInits() && "Initializer access out of range!");
1533    return cast<Expr>(InitExprs[Init]);
1534  }
1535
1536  void setInit(unsigned Init, Expr *expr) {
1537    assert(Init < getNumInits() && "Initializer access out of range!");
1538    InitExprs[Init] = expr;
1539  }
1540
1541  // Dynamic removal/addition (for constructing implicit InitExpr's).
1542  void removeInit(unsigned Init) {
1543    InitExprs.erase(InitExprs.begin()+Init);
1544  }
1545  void addInit(unsigned Init, Expr *expr) {
1546    InitExprs.insert(InitExprs.begin()+Init, expr);
1547  }
1548
1549  // Explicit InitListExpr's originate from source code (and have valid source
1550  // locations). Implicit InitListExpr's are created by the semantic analyzer.
1551  bool isExplicit() {
1552    return LBraceLoc.isValid() && RBraceLoc.isValid();
1553  }
1554
1555  virtual SourceRange getSourceRange() const {
1556    return SourceRange(LBraceLoc, RBraceLoc);
1557  }
1558  static bool classof(const Stmt *T) {
1559    return T->getStmtClass() == InitListExprClass;
1560  }
1561  static bool classof(const InitListExpr *) { return true; }
1562
1563  // Iterators
1564  virtual child_iterator child_begin();
1565  virtual child_iterator child_end();
1566
1567  typedef std::vector<Stmt *>::iterator iterator;
1568  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
1569
1570  iterator begin() { return InitExprs.begin(); }
1571  iterator end() { return InitExprs.end(); }
1572  reverse_iterator rbegin() { return InitExprs.rbegin(); }
1573  reverse_iterator rend() { return InitExprs.rend(); }
1574
1575  // Serailization.
1576  virtual void EmitImpl(llvm::Serializer& S) const;
1577  static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1578
1579private:
1580  // Used by serializer.
1581  InitListExpr() : Expr(InitListExprClass, QualType()) {}
1582};
1583
1584//===----------------------------------------------------------------------===//
1585// Clang Extensions
1586//===----------------------------------------------------------------------===//
1587
1588
1589/// ExtVectorElementExpr - This represents access to specific elements of a
1590/// vector, and may occur on the left hand side or right hand side.  For example
1591/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
1592///
1593class ExtVectorElementExpr : public Expr {
1594  Stmt *Base;
1595  IdentifierInfo &Accessor;
1596  SourceLocation AccessorLoc;
1597public:
1598  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
1599                       SourceLocation loc)
1600    : Expr(ExtVectorElementExprClass, ty),
1601      Base(base), Accessor(accessor), AccessorLoc(loc) {}
1602
1603  const Expr *getBase() const { return cast<Expr>(Base); }
1604  Expr *getBase() { return cast<Expr>(Base); }
1605
1606  IdentifierInfo &getAccessor() const { return Accessor; }
1607
1608  /// getNumElements - Get the number of components being selected.
1609  unsigned getNumElements() const;
1610
1611  /// containsDuplicateElements - Return true if any element access is
1612  /// repeated.
1613  bool containsDuplicateElements() const;
1614
1615  /// getEncodedElementAccess - Encode the elements accessed into an llvm
1616  /// aggregate Constant of ConstantInt(s).
1617  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
1618
1619  virtual SourceRange getSourceRange() const {
1620    return SourceRange(getBase()->getLocStart(), AccessorLoc);
1621  }
1622
1623  static bool classof(const Stmt *T) {
1624    return T->getStmtClass() == ExtVectorElementExprClass;
1625  }
1626  static bool classof(const ExtVectorElementExpr *) { return true; }
1627
1628  // Iterators
1629  virtual child_iterator child_begin();
1630  virtual child_iterator child_end();
1631
1632  virtual void EmitImpl(llvm::Serializer& S) const;
1633  static ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1634};
1635
1636
1637/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
1638/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1639class BlockExpr : public Expr {
1640protected:
1641  BlockDecl *TheBlock;
1642public:
1643  BlockExpr(BlockDecl *BD, QualType ty) : Expr(BlockExprClass, ty),
1644            TheBlock(BD) {}
1645
1646  BlockDecl *getBlockDecl() { return TheBlock; }
1647
1648  // Convenience functions for probing the underlying BlockDecl.
1649  SourceLocation getCaretLocation() const;
1650  const Stmt *getBody() const;
1651  Stmt *getBody();
1652
1653  virtual SourceRange getSourceRange() const {
1654    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
1655  }
1656
1657  /// getFunctionType - Return the underlying function type for this block.
1658  const FunctionType *getFunctionType() const;
1659
1660  static bool classof(const Stmt *T) {
1661    return T->getStmtClass() == BlockExprClass;
1662  }
1663  static bool classof(const BlockExpr *) { return true; }
1664
1665  // Iterators
1666  virtual child_iterator child_begin();
1667  virtual child_iterator child_end();
1668
1669  virtual void EmitImpl(llvm::Serializer& S) const;
1670  static BlockExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1671};
1672
1673/// BlockDeclRefExpr - A reference to a declared variable, function,
1674/// enum, etc.
1675class BlockDeclRefExpr : public Expr {
1676  ValueDecl *D;
1677  SourceLocation Loc;
1678  bool IsByRef;
1679public:
1680  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef) :
1681       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef) {}
1682
1683  ValueDecl *getDecl() { return D; }
1684  const ValueDecl *getDecl() const { return D; }
1685  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
1686
1687  bool isByRef() const { return IsByRef; }
1688
1689  static bool classof(const Stmt *T) {
1690    return T->getStmtClass() == BlockDeclRefExprClass;
1691  }
1692  static bool classof(const BlockDeclRefExpr *) { return true; }
1693
1694  // Iterators
1695  virtual child_iterator child_begin();
1696  virtual child_iterator child_end();
1697
1698  virtual void EmitImpl(llvm::Serializer& S) const;
1699  static BlockDeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1700};
1701
1702}  // end namespace clang
1703
1704#endif
1705