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