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