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