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