Expr.h revision 904eed3f6148758d39a2d3c88f3133274460d645
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 of
435/// types), 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    SizeOf, AlignOf,  // [C99 6.5.3.4] Sizeof (expr, not type) operator.
458    Real, Imag,       // "__real expr"/"__imag expr" Extension.
459    Extension,        // __extension__ marker.
460    OffsetOf          // __builtin_offsetof
461  };
462private:
463  Stmt *Val;
464  Opcode Opc;
465  SourceLocation Loc;
466public:
467
468  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
469    : Expr(UnaryOperatorClass, type), Val(input), Opc(opc), Loc(l) {}
470
471  Opcode getOpcode() const { return Opc; }
472  Expr *getSubExpr() const { return cast<Expr>(Val); }
473
474  /// getOperatorLoc - Return the location of the operator.
475  SourceLocation getOperatorLoc() const { return Loc; }
476
477  /// isPostfix - Return true if this is a postfix operation, like x++.
478  static bool isPostfix(Opcode Op);
479
480  /// isPostfix - Return true if this is a prefix operation, like --x.
481  static bool isPrefix(Opcode Op);
482
483  bool isPrefix() const { return isPrefix(Opc); }
484  bool isPostfix() const { return isPostfix(Opc); }
485  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
486  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
487  bool isSizeOfAlignOfOp() const { return Opc == SizeOf || Opc == AlignOf; }
488  bool isOffsetOfOp() const { return Opc == OffsetOf; }
489  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
490
491  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
492  /// corresponds to, e.g. "sizeof" or "[pre]++"
493  static const char *getOpcodeStr(Opcode Op);
494
495  virtual SourceRange getSourceRange() const {
496    if (isPostfix())
497      return SourceRange(Val->getLocStart(), Loc);
498    else
499      return SourceRange(Loc, Val->getLocEnd());
500  }
501  virtual SourceLocation getExprLoc() const { return Loc; }
502
503  static bool classof(const Stmt *T) {
504    return T->getStmtClass() == UnaryOperatorClass;
505  }
506  static bool classof(const UnaryOperator *) { return true; }
507
508  int64_t evaluateOffsetOf(ASTContext& C) const;
509
510  // Iterators
511  virtual child_iterator child_begin();
512  virtual child_iterator child_end();
513
514  virtual void EmitImpl(llvm::Serializer& S) const;
515  static UnaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
516};
517
518/// SizeOfAlignOfTypeExpr - [C99 6.5.3.4] - This is only for sizeof/alignof of
519/// *types*.  sizeof(expr) is handled by UnaryOperator.
520class SizeOfAlignOfTypeExpr : public Expr {
521  bool isSizeof;  // true if sizeof, false if alignof.
522  QualType Ty;
523  SourceLocation OpLoc, RParenLoc;
524public:
525  SizeOfAlignOfTypeExpr(bool issizeof, QualType argType, QualType resultType,
526                        SourceLocation op, SourceLocation rp) :
527    Expr(SizeOfAlignOfTypeExprClass, resultType),
528    isSizeof(issizeof), Ty(argType), OpLoc(op), RParenLoc(rp) {}
529
530  virtual void Destroy(ASTContext& C);
531
532  bool isSizeOf() const { return isSizeof; }
533  QualType getArgumentType() const { return Ty; }
534
535  SourceLocation getOperatorLoc() const { return OpLoc; }
536
537  virtual SourceRange getSourceRange() const {
538    return SourceRange(OpLoc, RParenLoc);
539  }
540
541  static bool classof(const Stmt *T) {
542    return T->getStmtClass() == SizeOfAlignOfTypeExprClass;
543  }
544  static bool classof(const SizeOfAlignOfTypeExpr *) { return true; }
545
546  // Iterators
547  virtual child_iterator child_begin();
548  virtual child_iterator child_end();
549
550  virtual void EmitImpl(llvm::Serializer& S) const;
551  static SizeOfAlignOfTypeExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
552};
553
554//===----------------------------------------------------------------------===//
555// Postfix Operators.
556//===----------------------------------------------------------------------===//
557
558/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
559class ArraySubscriptExpr : public Expr {
560  enum { LHS, RHS, END_EXPR=2 };
561  Stmt* SubExprs[END_EXPR];
562  SourceLocation RBracketLoc;
563public:
564  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
565                     SourceLocation rbracketloc)
566  : Expr(ArraySubscriptExprClass, t), RBracketLoc(rbracketloc) {
567    SubExprs[LHS] = lhs;
568    SubExprs[RHS] = rhs;
569  }
570
571  /// An array access can be written A[4] or 4[A] (both are equivalent).
572  /// - getBase() and getIdx() always present the normalized view: A[4].
573  ///    In this case getBase() returns "A" and getIdx() returns "4".
574  /// - getLHS() and getRHS() present the syntactic view. e.g. for
575  ///    4[A] getLHS() returns "4".
576  /// Note: Because vector element access is also written A[4] we must
577  /// predicate the format conversion in getBase and getIdx only on the
578  /// the type of the RHS, as it is possible for the LHS to be a vector of
579  /// integer type
580  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
581  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
582
583  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
584  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
585
586  Expr *getBase() {
587    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
588  }
589
590  const Expr *getBase() const {
591    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
592  }
593
594  Expr *getIdx() {
595    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
596  }
597
598  const Expr *getIdx() const {
599    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
600  }
601
602  virtual SourceRange getSourceRange() const {
603    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
604  }
605
606  virtual SourceLocation getExprLoc() const { return RBracketLoc; }
607
608  static bool classof(const Stmt *T) {
609    return T->getStmtClass() == ArraySubscriptExprClass;
610  }
611  static bool classof(const ArraySubscriptExpr *) { return true; }
612
613  // Iterators
614  virtual child_iterator child_begin();
615  virtual child_iterator child_end();
616
617  virtual void EmitImpl(llvm::Serializer& S) const;
618  static ArraySubscriptExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
619};
620
621
622/// CallExpr - [C99 6.5.2.2] Function Calls.
623///
624class CallExpr : public Expr {
625  enum { FN=0, ARGS_START=1 };
626  Stmt **SubExprs;
627  unsigned NumArgs;
628  SourceLocation RParenLoc;
629
630  // This version of the ctor is for deserialization.
631  CallExpr(Stmt** subexprs, unsigned numargs, QualType t,
632           SourceLocation rparenloc)
633  : Expr(CallExprClass,t), SubExprs(subexprs),
634    NumArgs(numargs), RParenLoc(rparenloc) {}
635
636public:
637  CallExpr(Expr *fn, Expr **args, unsigned numargs, QualType t,
638           SourceLocation rparenloc);
639  ~CallExpr() {
640    delete [] SubExprs;
641  }
642
643  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
644  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
645  void setCallee(Expr *F) { SubExprs[FN] = F; }
646
647  /// getNumArgs - Return the number of actual arguments to this call.
648  ///
649  unsigned getNumArgs() const { return NumArgs; }
650
651  /// getArg - Return the specified argument.
652  Expr *getArg(unsigned Arg) {
653    assert(Arg < NumArgs && "Arg access out of range!");
654    return cast<Expr>(SubExprs[Arg+ARGS_START]);
655  }
656  const Expr *getArg(unsigned Arg) const {
657    assert(Arg < NumArgs && "Arg access out of range!");
658    return cast<Expr>(SubExprs[Arg+ARGS_START]);
659  }
660  /// setArg - Set the specified argument.
661  void setArg(unsigned Arg, Expr *ArgExpr) {
662    assert(Arg < NumArgs && "Arg access out of range!");
663    SubExprs[Arg+ARGS_START] = ArgExpr;
664  }
665
666  /// setNumArgs - This changes the number of arguments present in this call.
667  /// Any orphaned expressions are deleted by this, and any new operands are set
668  /// to null.
669  void setNumArgs(unsigned NumArgs);
670
671  typedef ExprIterator arg_iterator;
672  typedef ConstExprIterator const_arg_iterator;
673
674  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
675  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
676  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
677  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
678
679  /// getNumCommas - Return the number of commas that must have been present in
680  /// this function call.
681  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
682
683  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
684  /// not, return 0.
685  unsigned isBuiltinCall() const;
686
687  SourceLocation getRParenLoc() const { return RParenLoc; }
688
689  virtual SourceRange getSourceRange() const {
690    return SourceRange(getCallee()->getLocStart(), RParenLoc);
691  }
692
693  static bool classof(const Stmt *T) {
694    return T->getStmtClass() == CallExprClass;
695  }
696  static bool classof(const CallExpr *) { return true; }
697
698  // Iterators
699  virtual child_iterator child_begin();
700  virtual child_iterator child_end();
701
702  virtual void EmitImpl(llvm::Serializer& S) const;
703  static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
704};
705
706/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.
707///
708class MemberExpr : public Expr {
709  Stmt *Base;
710  FieldDecl *MemberDecl;
711  SourceLocation MemberLoc;
712  bool IsArrow;      // True if this is "X->F", false if this is "X.F".
713public:
714  MemberExpr(Expr *base, bool isarrow, FieldDecl *memberdecl, SourceLocation l,
715             QualType ty)
716    : Expr(MemberExprClass, ty),
717      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
718
719  Expr *getBase() const { return cast<Expr>(Base); }
720  FieldDecl *getMemberDecl() const { return MemberDecl; }
721  bool isArrow() const { return IsArrow; }
722
723  virtual SourceRange getSourceRange() const {
724    return SourceRange(getBase()->getLocStart(), MemberLoc);
725  }
726
727  virtual SourceLocation getExprLoc() const { return MemberLoc; }
728
729  static bool classof(const Stmt *T) {
730    return T->getStmtClass() == MemberExprClass;
731  }
732  static bool classof(const MemberExpr *) { return true; }
733
734  // Iterators
735  virtual child_iterator child_begin();
736  virtual child_iterator child_end();
737
738  virtual void EmitImpl(llvm::Serializer& S) const;
739  static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
740};
741
742/// CompoundLiteralExpr - [C99 6.5.2.5]
743///
744class CompoundLiteralExpr : public Expr {
745  /// LParenLoc - If non-null, this is the location of the left paren in a
746  /// compound literal like "(int){4}".  This can be null if this is a
747  /// synthesized compound expression.
748  SourceLocation LParenLoc;
749  Stmt *Init;
750  bool FileScope;
751public:
752  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
753                      bool fileScope)
754    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
755      FileScope(fileScope) {}
756
757  const Expr *getInitializer() const { return cast<Expr>(Init); }
758  Expr *getInitializer() { return cast<Expr>(Init); }
759
760  bool isFileScope() const { return FileScope; }
761
762  SourceLocation getLParenLoc() const { return LParenLoc; }
763
764  virtual SourceRange getSourceRange() const {
765    // FIXME: Init should never be null.
766    if (!Init)
767      return SourceRange();
768    if (LParenLoc.isInvalid())
769      return Init->getSourceRange();
770    return SourceRange(LParenLoc, Init->getLocEnd());
771  }
772
773  static bool classof(const Stmt *T) {
774    return T->getStmtClass() == CompoundLiteralExprClass;
775  }
776  static bool classof(const CompoundLiteralExpr *) { return true; }
777
778  // Iterators
779  virtual child_iterator child_begin();
780  virtual child_iterator child_end();
781
782  virtual void EmitImpl(llvm::Serializer& S) const;
783  static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
784};
785
786/// CastExpr - Base class for type casts, including both implicit
787/// casts (ImplicitCastExpr) and explicit casts that have some
788/// representation in the source code (ExplicitCastExpr's derived
789/// classes).
790class CastExpr : public Expr {
791  Stmt *Op;
792protected:
793  CastExpr(StmtClass SC, QualType ty, Expr *op) :
794    Expr(SC, ty), Op(op) {}
795
796public:
797  Expr *getSubExpr() { return cast<Expr>(Op); }
798  const Expr *getSubExpr() const { return cast<Expr>(Op); }
799
800  static bool classof(const Stmt *T) {
801    StmtClass SC = T->getStmtClass();
802    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
803      return true;
804
805    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
806      return true;
807
808    return false;
809  }
810  static bool classof(const CastExpr *) { return true; }
811
812  // Iterators
813  virtual child_iterator child_begin();
814  virtual child_iterator child_end();
815};
816
817/// ImplicitCastExpr - Allows us to explicitly represent implicit type
818/// conversions, which have no direct representation in the original
819/// source code. For example: converting T[]->T*, void f()->void
820/// (*f)(), float->double, short->int, etc.
821///
822class ImplicitCastExpr : public CastExpr {
823public:
824  ImplicitCastExpr(QualType ty, Expr *op) :
825    CastExpr(ImplicitCastExprClass, ty, op) {}
826
827  virtual SourceRange getSourceRange() const {
828    return getSubExpr()->getSourceRange();
829  }
830
831  static bool classof(const Stmt *T) {
832    return T->getStmtClass() == ImplicitCastExprClass;
833  }
834  static bool classof(const ImplicitCastExpr *) { return true; }
835
836  virtual void EmitImpl(llvm::Serializer& S) const;
837  static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
838};
839
840/// ExplicitCastExpr - An explicit cast written in the source
841/// code.
842///
843/// This class is effectively an abstract class, because it provides
844/// the basic representation of an explicitly-written cast without
845/// specifying which kind of cast (C cast, functional cast, static
846/// cast, etc.) was written; specific derived classes represent the
847/// particular style of cast and its location information.
848///
849/// Unlike implicit casts, explicit cast nodes have two different
850/// types: the type that was written into the source code, and the
851/// actual type of the expression as determined by semantic
852/// analysis. These types may differ slightly. For example, in C++ one
853/// can cast to a reference type, which indicates that the resulting
854/// expression will be an lvalue. The reference type, however, will
855/// not be used as the type of the expression.
856class ExplicitCastExpr : public CastExpr {
857  /// TypeAsWritten - The type that this expression is casting to, as
858  /// written in the source code.
859  QualType TypeAsWritten;
860
861protected:
862  ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy)
863    : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {}
864
865public:
866  /// getTypeAsWritten - Returns the type that this expression is
867  /// casting to, as written in the source code.
868  QualType getTypeAsWritten() const { return TypeAsWritten; }
869
870  static bool classof(const Stmt *T) {
871    StmtClass SC = T->getStmtClass();
872    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
873      return true;
874    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
875      return true;
876
877    return false;
878  }
879  static bool classof(const ExplicitCastExpr *) { return true; }
880};
881
882/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
883/// cast in C++ (C++ [expr.cast]), which uses the syntax
884/// (Type)expr. For example: @c (int)f.
885class CStyleCastExpr : public ExplicitCastExpr {
886  SourceLocation LPLoc; // the location of the left paren
887  SourceLocation RPLoc; // the location of the right paren
888public:
889  CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy,
890                    SourceLocation l, SourceLocation r) :
891    ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy),
892    LPLoc(l), RPLoc(r) {}
893
894  SourceLocation getLParenLoc() const { return LPLoc; }
895  SourceLocation getRParenLoc() const { return RPLoc; }
896
897  virtual SourceRange getSourceRange() const {
898    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
899  }
900  static bool classof(const Stmt *T) {
901    return T->getStmtClass() == CStyleCastExprClass;
902  }
903  static bool classof(const CStyleCastExpr *) { return true; }
904
905  virtual void EmitImpl(llvm::Serializer& S) const;
906  static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
907};
908
909class BinaryOperator : public Expr {
910public:
911  enum Opcode {
912    // Operators listed in order of precedence.
913    // Note that additions to this should also update the StmtVisitor class.
914    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
915    Add, Sub,         // [C99 6.5.6] Additive operators.
916    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
917    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
918    EQ, NE,           // [C99 6.5.9] Equality operators.
919    And,              // [C99 6.5.10] Bitwise AND operator.
920    Xor,              // [C99 6.5.11] Bitwise XOR operator.
921    Or,               // [C99 6.5.12] Bitwise OR operator.
922    LAnd,             // [C99 6.5.13] Logical AND operator.
923    LOr,              // [C99 6.5.14] Logical OR operator.
924    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
925    DivAssign, RemAssign,
926    AddAssign, SubAssign,
927    ShlAssign, ShrAssign,
928    AndAssign, XorAssign,
929    OrAssign,
930    Comma             // [C99 6.5.17] Comma operator.
931  };
932private:
933  enum { LHS, RHS, END_EXPR };
934  Stmt* SubExprs[END_EXPR];
935  Opcode Opc;
936  SourceLocation OpLoc;
937public:
938
939  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
940                 SourceLocation opLoc)
941    : Expr(BinaryOperatorClass, ResTy), Opc(opc), OpLoc(opLoc) {
942    SubExprs[LHS] = lhs;
943    SubExprs[RHS] = rhs;
944    assert(!isCompoundAssignmentOp() &&
945           "Use ArithAssignBinaryOperator for compound assignments");
946  }
947
948  SourceLocation getOperatorLoc() const { return OpLoc; }
949  Opcode getOpcode() const { return Opc; }
950  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
951  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
952  virtual SourceRange getSourceRange() const {
953    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
954  }
955
956  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
957  /// corresponds to, e.g. "<<=".
958  static const char *getOpcodeStr(Opcode Op);
959
960  /// predicates to categorize the respective opcodes.
961  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
962  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
963  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
964  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
965
966  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
967  bool isRelationalOp() const { return isRelationalOp(Opc); }
968
969  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
970  bool isEqualityOp() const { return isEqualityOp(Opc); }
971
972  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
973  bool isLogicalOp() const { return isLogicalOp(Opc); }
974
975  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
976  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
977  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
978
979  static bool classof(const Stmt *S) {
980    return S->getStmtClass() == BinaryOperatorClass ||
981           S->getStmtClass() == CompoundAssignOperatorClass;
982  }
983  static bool classof(const BinaryOperator *) { return true; }
984
985  // Iterators
986  virtual child_iterator child_begin();
987  virtual child_iterator child_end();
988
989  virtual void EmitImpl(llvm::Serializer& S) const;
990  static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
991
992protected:
993  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
994                 SourceLocation oploc, bool dead)
995    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
996    SubExprs[LHS] = lhs;
997    SubExprs[RHS] = rhs;
998  }
999};
1000
1001/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1002/// track of the type the operation is performed in.  Due to the semantics of
1003/// these operators, the operands are promoted, the aritmetic performed, an
1004/// implicit conversion back to the result type done, then the assignment takes
1005/// place.  This captures the intermediate type which the computation is done
1006/// in.
1007class CompoundAssignOperator : public BinaryOperator {
1008  QualType ComputationType;
1009public:
1010  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1011                         QualType ResType, QualType CompType,
1012                         SourceLocation OpLoc)
1013    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1014      ComputationType(CompType) {
1015    assert(isCompoundAssignmentOp() &&
1016           "Only should be used for compound assignments");
1017  }
1018
1019  QualType getComputationType() const { return ComputationType; }
1020
1021  static bool classof(const CompoundAssignOperator *) { return true; }
1022  static bool classof(const Stmt *S) {
1023    return S->getStmtClass() == CompoundAssignOperatorClass;
1024  }
1025
1026  virtual void EmitImpl(llvm::Serializer& S) const;
1027  static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D,
1028                                            ASTContext& C);
1029};
1030
1031/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1032/// GNU "missing LHS" extension is in use.
1033///
1034class ConditionalOperator : public Expr {
1035  enum { COND, LHS, RHS, END_EXPR };
1036  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1037public:
1038  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1039    : Expr(ConditionalOperatorClass, t) {
1040    SubExprs[COND] = cond;
1041    SubExprs[LHS] = lhs;
1042    SubExprs[RHS] = rhs;
1043  }
1044
1045  // getCond - Return the expression representing the condition for
1046  //  the ?: operator.
1047  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1048
1049  // getTrueExpr - Return the subexpression representing the value of the ?:
1050  //  expression if the condition evaluates to true.  In most cases this value
1051  //  will be the same as getLHS() except a GCC extension allows the left
1052  //  subexpression to be omitted, and instead of the condition be returned.
1053  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1054  //  is only evaluated once.
1055  Expr *getTrueExpr() const {
1056    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1057  }
1058
1059  // getTrueExpr - Return the subexpression representing the value of the ?:
1060  // expression if the condition evaluates to false. This is the same as getRHS.
1061  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1062
1063  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1064  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1065
1066  virtual SourceRange getSourceRange() const {
1067    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1068  }
1069  static bool classof(const Stmt *T) {
1070    return T->getStmtClass() == ConditionalOperatorClass;
1071  }
1072  static bool classof(const ConditionalOperator *) { return true; }
1073
1074  // Iterators
1075  virtual child_iterator child_begin();
1076  virtual child_iterator child_end();
1077
1078  virtual void EmitImpl(llvm::Serializer& S) const;
1079  static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1080};
1081
1082/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1083class AddrLabelExpr : public Expr {
1084  SourceLocation AmpAmpLoc, LabelLoc;
1085  LabelStmt *Label;
1086public:
1087  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1088                QualType t)
1089    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1090
1091  virtual SourceRange getSourceRange() const {
1092    return SourceRange(AmpAmpLoc, LabelLoc);
1093  }
1094
1095  LabelStmt *getLabel() const { return Label; }
1096
1097  static bool classof(const Stmt *T) {
1098    return T->getStmtClass() == AddrLabelExprClass;
1099  }
1100  static bool classof(const AddrLabelExpr *) { return true; }
1101
1102  // Iterators
1103  virtual child_iterator child_begin();
1104  virtual child_iterator child_end();
1105
1106  virtual void EmitImpl(llvm::Serializer& S) const;
1107  static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1108};
1109
1110/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1111/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1112/// takes the value of the last subexpression.
1113class StmtExpr : public Expr {
1114  Stmt *SubStmt;
1115  SourceLocation LParenLoc, RParenLoc;
1116public:
1117  StmtExpr(CompoundStmt *substmt, QualType T,
1118           SourceLocation lp, SourceLocation rp) :
1119    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1120
1121  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1122  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1123
1124  virtual SourceRange getSourceRange() const {
1125    return SourceRange(LParenLoc, RParenLoc);
1126  }
1127
1128  static bool classof(const Stmt *T) {
1129    return T->getStmtClass() == StmtExprClass;
1130  }
1131  static bool classof(const StmtExpr *) { return true; }
1132
1133  // Iterators
1134  virtual child_iterator child_begin();
1135  virtual child_iterator child_end();
1136
1137  virtual void EmitImpl(llvm::Serializer& S) const;
1138  static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1139};
1140
1141/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p.
1142/// This AST node represents a function that returns 1 if two *types* (not
1143/// expressions) are compatible. The result of this built-in function can be
1144/// used in integer constant expressions.
1145class TypesCompatibleExpr : public Expr {
1146  QualType Type1;
1147  QualType Type2;
1148  SourceLocation BuiltinLoc, RParenLoc;
1149public:
1150  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1151                      QualType t1, QualType t2, SourceLocation RP) :
1152    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1153    BuiltinLoc(BLoc), RParenLoc(RP) {}
1154
1155  QualType getArgType1() const { return Type1; }
1156  QualType getArgType2() const { return Type2; }
1157
1158  virtual SourceRange getSourceRange() const {
1159    return SourceRange(BuiltinLoc, RParenLoc);
1160  }
1161  static bool classof(const Stmt *T) {
1162    return T->getStmtClass() == TypesCompatibleExprClass;
1163  }
1164  static bool classof(const TypesCompatibleExpr *) { return true; }
1165
1166  // Iterators
1167  virtual child_iterator child_begin();
1168  virtual child_iterator child_end();
1169
1170  virtual void EmitImpl(llvm::Serializer& S) const;
1171  static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1172};
1173
1174/// ShuffleVectorExpr - clang-specific builtin-in function
1175/// __builtin_shufflevector.
1176/// This AST node represents a operator that does a constant
1177/// shuffle, similar to LLVM's shufflevector instruction. It takes
1178/// two vectors and a variable number of constant indices,
1179/// and returns the appropriately shuffled vector.
1180class ShuffleVectorExpr : public Expr {
1181  SourceLocation BuiltinLoc, RParenLoc;
1182
1183  // SubExprs - the list of values passed to the __builtin_shufflevector
1184  // function. The first two are vectors, and the rest are constant
1185  // indices.  The number of values in this list is always
1186  // 2+the number of indices in the vector type.
1187  Stmt **SubExprs;
1188  unsigned NumExprs;
1189
1190public:
1191  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1192                    QualType Type, SourceLocation BLoc,
1193                    SourceLocation RP) :
1194    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1195    RParenLoc(RP), NumExprs(nexpr) {
1196
1197    SubExprs = new Stmt*[nexpr];
1198    for (unsigned i = 0; i < nexpr; i++)
1199      SubExprs[i] = args[i];
1200  }
1201
1202  virtual SourceRange getSourceRange() const {
1203    return SourceRange(BuiltinLoc, RParenLoc);
1204  }
1205  static bool classof(const Stmt *T) {
1206    return T->getStmtClass() == ShuffleVectorExprClass;
1207  }
1208  static bool classof(const ShuffleVectorExpr *) { return true; }
1209
1210  ~ShuffleVectorExpr() {
1211    delete [] SubExprs;
1212  }
1213
1214  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1215  /// constant expression, the actual arguments passed in, and the function
1216  /// pointers.
1217  unsigned getNumSubExprs() const { return NumExprs; }
1218
1219  /// getExpr - Return the Expr at the specified index.
1220  Expr *getExpr(unsigned Index) {
1221    assert((Index < NumExprs) && "Arg access out of range!");
1222    return cast<Expr>(SubExprs[Index]);
1223  }
1224  const Expr *getExpr(unsigned Index) const {
1225    assert((Index < NumExprs) && "Arg access out of range!");
1226    return cast<Expr>(SubExprs[Index]);
1227  }
1228
1229  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1230    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1231    return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue();
1232  }
1233
1234  // Iterators
1235  virtual child_iterator child_begin();
1236  virtual child_iterator child_end();
1237
1238  virtual void EmitImpl(llvm::Serializer& S) const;
1239  static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1240};
1241
1242/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1243/// This AST node is similar to the conditional operator (?:) in C, with
1244/// the following exceptions:
1245/// - the test expression much be a constant expression.
1246/// - the expression returned has it's type unaltered by promotion rules.
1247/// - does not evaluate the expression that was not chosen.
1248class ChooseExpr : public Expr {
1249  enum { COND, LHS, RHS, END_EXPR };
1250  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1251  SourceLocation BuiltinLoc, RParenLoc;
1252public:
1253  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1254             SourceLocation RP)
1255    : Expr(ChooseExprClass, t),
1256      BuiltinLoc(BLoc), RParenLoc(RP) {
1257      SubExprs[COND] = cond;
1258      SubExprs[LHS] = lhs;
1259      SubExprs[RHS] = rhs;
1260    }
1261
1262  /// isConditionTrue - Return true if the condition is true.  This is always
1263  /// statically knowable for a well-formed choosexpr.
1264  bool isConditionTrue(ASTContext &C) const;
1265
1266  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1267  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1268  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1269
1270  virtual SourceRange getSourceRange() const {
1271    return SourceRange(BuiltinLoc, RParenLoc);
1272  }
1273  static bool classof(const Stmt *T) {
1274    return T->getStmtClass() == ChooseExprClass;
1275  }
1276  static bool classof(const ChooseExpr *) { return true; }
1277
1278  // Iterators
1279  virtual child_iterator child_begin();
1280  virtual child_iterator child_end();
1281
1282  virtual void EmitImpl(llvm::Serializer& S) const;
1283  static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1284};
1285
1286/// OverloadExpr - Clang builtin function __builtin_overload.
1287/// This AST node provides a way to overload functions in C.
1288///
1289/// The first argument is required to be a constant expression, for the number
1290/// of arguments passed to each candidate function.
1291///
1292/// The next N arguments, where N is the value of the constant expression,
1293/// are the values to be passed as arguments.
1294///
1295/// The rest of the arguments are values of pointer to function type, which
1296/// are the candidate functions for overloading.
1297///
1298/// The result is a equivalent to a CallExpr taking N arguments to the
1299/// candidate function whose parameter types match the types of the N arguments.
1300///
1301/// example: float Z = __builtin_overload(2, X, Y, modf, mod, modl);
1302/// If X and Y are long doubles, Z will assigned the result of modl(X, Y);
1303/// If X and Y are floats, Z will be assigned the result of modf(X, Y);
1304class OverloadExpr : public Expr {
1305  // SubExprs - the list of values passed to the __builtin_overload function.
1306  // SubExpr[0] is a constant expression
1307  // SubExpr[1-N] are the parameters to pass to the matching function call
1308  // SubExpr[N-...] are the candidate functions, of type pointer to function.
1309  Stmt **SubExprs;
1310
1311  // NumExprs - the size of the SubExprs array
1312  unsigned NumExprs;
1313
1314  // The index of the matching candidate function
1315  unsigned FnIndex;
1316
1317  SourceLocation BuiltinLoc;
1318  SourceLocation RParenLoc;
1319public:
1320  OverloadExpr(Expr **args, unsigned nexprs, unsigned idx, QualType t,
1321               SourceLocation bloc, SourceLocation rploc)
1322    : Expr(OverloadExprClass, t), NumExprs(nexprs), FnIndex(idx),
1323      BuiltinLoc(bloc), RParenLoc(rploc) {
1324    SubExprs = new Stmt*[nexprs];
1325    for (unsigned i = 0; i != nexprs; ++i)
1326      SubExprs[i] = args[i];
1327  }
1328  ~OverloadExpr() {
1329    delete [] SubExprs;
1330  }
1331
1332  /// arg_begin - Return a pointer to the list of arguments that will be passed
1333  /// to the matching candidate function, skipping over the initial constant
1334  /// expression.
1335  typedef ConstExprIterator const_arg_iterator;
1336  const_arg_iterator arg_begin() const { return &SubExprs[0]+1; }
1337  const_arg_iterator arg_end(ASTContext& Ctx) const {
1338    return &SubExprs[0]+1+getNumArgs(Ctx);
1339  }
1340
1341  /// getNumArgs - Return the number of arguments to pass to the candidate
1342  /// functions.
1343  unsigned getNumArgs(ASTContext &Ctx) const {
1344    return getExpr(0)->getIntegerConstantExprValue(Ctx).getZExtValue();
1345  }
1346
1347  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1348  /// constant expression, the actual arguments passed in, and the function
1349  /// pointers.
1350  unsigned getNumSubExprs() const { return NumExprs; }
1351
1352  /// getExpr - Return the Expr at the specified index.
1353  Expr *getExpr(unsigned Index) const {
1354    assert((Index < NumExprs) && "Arg access out of range!");
1355    return cast<Expr>(SubExprs[Index]);
1356  }
1357
1358  /// getFn - Return the matching candidate function for this OverloadExpr.
1359  Expr *getFn() const { return cast<Expr>(SubExprs[FnIndex]); }
1360
1361  virtual SourceRange getSourceRange() const {
1362    return SourceRange(BuiltinLoc, RParenLoc);
1363  }
1364  static bool classof(const Stmt *T) {
1365    return T->getStmtClass() == OverloadExprClass;
1366  }
1367  static bool classof(const OverloadExpr *) { return true; }
1368
1369  // Iterators
1370  virtual child_iterator child_begin();
1371  virtual child_iterator child_end();
1372
1373  virtual void EmitImpl(llvm::Serializer& S) const;
1374  static OverloadExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1375};
1376
1377/// VAArgExpr, used for the builtin function __builtin_va_start.
1378class VAArgExpr : public Expr {
1379  Stmt *Val;
1380  SourceLocation BuiltinLoc, RParenLoc;
1381public:
1382  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1383    : Expr(VAArgExprClass, t),
1384      Val(e),
1385      BuiltinLoc(BLoc),
1386      RParenLoc(RPLoc) { }
1387
1388  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1389  Expr *getSubExpr() { return cast<Expr>(Val); }
1390  virtual SourceRange getSourceRange() const {
1391    return SourceRange(BuiltinLoc, RParenLoc);
1392  }
1393  static bool classof(const Stmt *T) {
1394    return T->getStmtClass() == VAArgExprClass;
1395  }
1396  static bool classof(const VAArgExpr *) { return true; }
1397
1398  // Iterators
1399  virtual child_iterator child_begin();
1400  virtual child_iterator child_end();
1401
1402  virtual void EmitImpl(llvm::Serializer& S) const;
1403  static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1404};
1405
1406/// InitListExpr - used for struct and array initializers, such as:
1407///    struct foo x = { 1, { 2, 3 } };
1408///
1409/// Because C is somewhat loose with braces, the AST does not necessarily
1410/// directly model the C source.  Instead, the semantic analyzer aims to make
1411/// the InitListExprs match up with the type of the decl being initialized.  We
1412/// have the following exceptions:
1413///
1414///  1. Elements at the end of the list may be dropped from the initializer.
1415///     These elements are defined to be initialized to zero.  For example:
1416///         int x[20] = { 1 };
1417///  2. Initializers may have excess initializers which are to be ignored by the
1418///     compiler.  For example:
1419///         int x[1] = { 1, 2 };
1420///  3. Redundant InitListExprs may be present around scalar elements.  These
1421///     always have a single element whose type is the same as the InitListExpr.
1422///     this can only happen for Type::isScalarType() types.
1423///         int x = { 1 };  int y[2] = { {1}, {2} };
1424///
1425class InitListExpr : public Expr {
1426  std::vector<Stmt *> InitExprs;
1427  SourceLocation LBraceLoc, RBraceLoc;
1428
1429  /// HadDesignators - Return true if there were any designators in this
1430  /// init list expr.  FIXME: this should be replaced by storing the designators
1431  /// somehow and updating codegen.
1432  bool HadDesignators;
1433public:
1434  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1435               SourceLocation rbraceloc, bool HadDesignators);
1436
1437  unsigned getNumInits() const { return InitExprs.size(); }
1438  bool hadDesignators() const { return HadDesignators; }
1439
1440  const Expr* getInit(unsigned Init) const {
1441    assert(Init < getNumInits() && "Initializer access out of range!");
1442    return cast<Expr>(InitExprs[Init]);
1443  }
1444
1445  Expr* getInit(unsigned Init) {
1446    assert(Init < getNumInits() && "Initializer access out of range!");
1447    return cast<Expr>(InitExprs[Init]);
1448  }
1449
1450  void setInit(unsigned Init, Expr *expr) {
1451    assert(Init < getNumInits() && "Initializer access out of range!");
1452    InitExprs[Init] = expr;
1453  }
1454
1455  // Dynamic removal/addition (for constructing implicit InitExpr's).
1456  void removeInit(unsigned Init) {
1457    InitExprs.erase(InitExprs.begin()+Init);
1458  }
1459  void addInit(unsigned Init, Expr *expr) {
1460    InitExprs.insert(InitExprs.begin()+Init, expr);
1461  }
1462
1463  // Explicit InitListExpr's originate from source code (and have valid source
1464  // locations). Implicit InitListExpr's are created by the semantic analyzer.
1465  bool isExplicit() {
1466    return LBraceLoc.isValid() && RBraceLoc.isValid();
1467  }
1468
1469  virtual SourceRange getSourceRange() const {
1470    return SourceRange(LBraceLoc, RBraceLoc);
1471  }
1472  static bool classof(const Stmt *T) {
1473    return T->getStmtClass() == InitListExprClass;
1474  }
1475  static bool classof(const InitListExpr *) { return true; }
1476
1477  // Iterators
1478  virtual child_iterator child_begin();
1479  virtual child_iterator child_end();
1480
1481  typedef std::vector<Stmt *>::iterator iterator;
1482  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
1483
1484  iterator begin() { return InitExprs.begin(); }
1485  iterator end() { return InitExprs.end(); }
1486  reverse_iterator rbegin() { return InitExprs.rbegin(); }
1487  reverse_iterator rend() { return InitExprs.rend(); }
1488
1489  // Serailization.
1490  virtual void EmitImpl(llvm::Serializer& S) const;
1491  static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1492
1493private:
1494  // Used by serializer.
1495  InitListExpr() : Expr(InitListExprClass, QualType()) {}
1496};
1497
1498//===----------------------------------------------------------------------===//
1499// Clang Extensions
1500//===----------------------------------------------------------------------===//
1501
1502
1503/// ExtVectorElementExpr - This represents access to specific elements of a
1504/// vector, and may occur on the left hand side or right hand side.  For example
1505/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
1506///
1507class ExtVectorElementExpr : public Expr {
1508  Stmt *Base;
1509  IdentifierInfo &Accessor;
1510  SourceLocation AccessorLoc;
1511public:
1512  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
1513                       SourceLocation loc)
1514    : Expr(ExtVectorElementExprClass, ty),
1515      Base(base), Accessor(accessor), AccessorLoc(loc) {}
1516
1517  const Expr *getBase() const { return cast<Expr>(Base); }
1518  Expr *getBase() { return cast<Expr>(Base); }
1519
1520  IdentifierInfo &getAccessor() const { return Accessor; }
1521
1522  /// getNumElements - Get the number of components being selected.
1523  unsigned getNumElements() const;
1524
1525  /// containsDuplicateElements - Return true if any element access is
1526  /// repeated.
1527  bool containsDuplicateElements() const;
1528
1529  /// getEncodedElementAccess - Encode the elements accessed into an llvm
1530  /// aggregate Constant of ConstantInt(s).
1531  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
1532
1533  virtual SourceRange getSourceRange() const {
1534    return SourceRange(getBase()->getLocStart(), AccessorLoc);
1535  }
1536
1537  static bool classof(const Stmt *T) {
1538    return T->getStmtClass() == ExtVectorElementExprClass;
1539  }
1540  static bool classof(const ExtVectorElementExpr *) { return true; }
1541
1542  // Iterators
1543  virtual child_iterator child_begin();
1544  virtual child_iterator child_end();
1545
1546  virtual void EmitImpl(llvm::Serializer& S) const;
1547  static ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1548};
1549
1550
1551/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
1552/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1553class BlockExpr : public Expr {
1554protected:
1555  BlockDecl *TheBlock;
1556public:
1557  BlockExpr(BlockDecl *BD, QualType ty) : Expr(BlockExprClass, ty),
1558            TheBlock(BD) {}
1559
1560  BlockDecl *getBlockDecl() { return TheBlock; }
1561
1562  // Convenience functions for probing the underlying BlockDecl.
1563  SourceLocation getCaretLocation() const;
1564  const Stmt *getBody() const;
1565  Stmt *getBody();
1566
1567  virtual SourceRange getSourceRange() const {
1568    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
1569  }
1570
1571  /// getFunctionType - Return the underlying function type for this block.
1572  const FunctionType *getFunctionType() const;
1573
1574  static bool classof(const Stmt *T) {
1575    return T->getStmtClass() == BlockExprClass;
1576  }
1577  static bool classof(const BlockExpr *) { return true; }
1578
1579  // Iterators
1580  virtual child_iterator child_begin();
1581  virtual child_iterator child_end();
1582
1583  virtual void EmitImpl(llvm::Serializer& S) const;
1584  static BlockExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1585};
1586
1587/// BlockDeclRefExpr - A reference to a declared variable, function,
1588/// enum, etc.
1589class BlockDeclRefExpr : public Expr {
1590  ValueDecl *D;
1591  SourceLocation Loc;
1592  bool IsByRef;
1593public:
1594  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef) :
1595       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef) {}
1596
1597  ValueDecl *getDecl() { return D; }
1598  const ValueDecl *getDecl() const { return D; }
1599  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
1600
1601  bool isByRef() const { return IsByRef; }
1602
1603  static bool classof(const Stmt *T) {
1604    return T->getStmtClass() == BlockDeclRefExprClass;
1605  }
1606  static bool classof(const BlockDeclRefExpr *) { return true; }
1607
1608  // Iterators
1609  virtual child_iterator child_begin();
1610  virtual child_iterator child_end();
1611
1612  virtual void EmitImpl(llvm::Serializer& S) const;
1613  static BlockDeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1614};
1615
1616}  // end namespace clang
1617
1618#endif
1619