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