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