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