Expr.h revision b137299ce5bb6c36fbba651858600857fda4dd50
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  class CXXOperatorCallExpr;
35  class CXXMemberCallExpr;
36
37/// Expr - This represents one expression.  Note that Expr's are subclasses of
38/// Stmt.  This allows an expression to be transparently used any place a Stmt
39/// is required.
40///
41class Expr : public Stmt {
42  QualType TR;
43
44  /// TypeDependent - Whether this expression is type-dependent
45  /// (C++ [temp.dep.expr]).
46  bool TypeDependent : 1;
47
48  /// ValueDependent - Whether this expression is value-dependent
49  /// (C++ [temp.dep.constexpr]).
50  bool ValueDependent : 1;
51
52protected:
53  // FIXME: Eventually, this constructor should go away and we should
54  // require every subclass to provide type/value-dependence
55  // information.
56  Expr(StmtClass SC, QualType T)
57    : Stmt(SC), TypeDependent(false), ValueDependent(false) {
58    setType(T);
59  }
60
61  Expr(StmtClass SC, QualType T, bool TD, bool VD)
62    : Stmt(SC), TypeDependent(TD), ValueDependent(VD) {
63    setType(T);
64  }
65
66public:
67  QualType getType() const { return TR; }
68  void setType(QualType t) {
69    // In C++, the type of an expression is always adjusted so that it
70    // will not have reference type an expression will never have
71    // reference type (C++ [expr]p6). Use
72    // QualType::getNonReferenceType() to retrieve the non-reference
73    // type. Additionally, inspect Expr::isLvalue to determine whether
74    // an expression that is adjusted in this manner should be
75    // considered an lvalue.
76    assert((TR.isNull() || !TR->isReferenceType()) &&
77           "Expressions can't have reference type");
78
79    TR = t;
80  }
81
82  /// isValueDependent - Determines whether this expression is
83  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
84  /// array bound of "Chars" in the following example is
85  /// value-dependent.
86  /// @code
87  /// template<int Size, char (&Chars)[Size]> struct meta_string;
88  /// @endcode
89  bool isValueDependent() const { return ValueDependent; }
90
91  /// isTypeDependent - Determines whether this expression is
92  /// type-dependent (C++ [temp.dep.expr]), which means that its type
93  /// could change from one template instantiation to the next. For
94  /// example, the expressions "x" and "x + y" are type-dependent in
95  /// the following code, but "y" is not type-dependent:
96  /// @code
97  /// template<typename T>
98  /// void add(T x, int y) {
99  ///   x + y;
100  /// }
101  /// @endcode
102  bool isTypeDependent() const { return TypeDependent; }
103
104  /// SourceLocation tokens are not useful in isolation - they are low level
105  /// value objects created/interpreted by SourceManager. We assume AST
106  /// clients will have a pointer to the respective SourceManager.
107  virtual SourceRange getSourceRange() const = 0;
108
109  /// getExprLoc - Return the preferred location for the arrow when diagnosing
110  /// a problem with a generic expression.
111  virtual SourceLocation getExprLoc() const { return getLocStart(); }
112
113  /// isUnusedResultAWarning - Return true if this immediate expression should
114  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
115  /// with location to warn on and the source range[s] to report with the
116  /// warning.
117  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
118                              SourceRange &R2) const;
119
120  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
121  /// incomplete type other than void. Nonarray expressions that can be lvalues:
122  ///  - name, where name must be a variable
123  ///  - e[i]
124  ///  - (e), where e must be an lvalue
125  ///  - e.name, where e must be an lvalue
126  ///  - e->name
127  ///  - *e, the type of e cannot be a function type
128  ///  - string-constant
129  ///  - reference type [C++ [expr]]
130  ///
131  enum isLvalueResult {
132    LV_Valid,
133    LV_NotObjectType,
134    LV_IncompleteVoidType,
135    LV_DuplicateVectorComponents,
136    LV_InvalidExpression,
137    LV_MemberFunction
138  };
139  isLvalueResult isLvalue(ASTContext &Ctx) const;
140
141  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
142  /// does not have an incomplete type, does not have a const-qualified type,
143  /// and if it is a structure or union, does not have any member (including,
144  /// recursively, any member or element of all contained aggregates or unions)
145  /// with a const-qualified type.
146  enum isModifiableLvalueResult {
147    MLV_Valid,
148    MLV_NotObjectType,
149    MLV_IncompleteVoidType,
150    MLV_DuplicateVectorComponents,
151    MLV_InvalidExpression,
152    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
153    MLV_IncompleteType,
154    MLV_ConstQualified,
155    MLV_ArrayType,
156    MLV_NotBlockQualified,
157    MLV_ReadonlyProperty,
158    MLV_NoSetterProperty,
159    MLV_MemberFunction
160  };
161  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx) const;
162
163  bool isBitField();
164
165  /// getIntegerConstantExprValue() - Return the value of an integer
166  /// constant expression. The expression must be a valid integer
167  /// constant expression as determined by isIntegerConstantExpr.
168  llvm::APSInt getIntegerConstantExprValue(ASTContext &Ctx) const {
169    llvm::APSInt X;
170    bool success = isIntegerConstantExpr(X, Ctx);
171    success = success;
172    assert(success && "Illegal argument to getIntegerConstantExpr");
173    return X;
174  }
175
176  /// isIntegerConstantExpr - Return true if this expression is a valid integer
177  /// constant expression, and, if so, return its value in Result.  If not a
178  /// valid i-c-e, return false and fill in Loc (if specified) with the location
179  /// of the invalid expression.
180  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
181                             SourceLocation *Loc = 0,
182                             bool isEvaluated = true) const;
183  bool isIntegerConstantExprInternal(llvm::APSInt &Result, ASTContext &Ctx,
184                             SourceLocation *Loc = 0,
185                             bool isEvaluated = true) const;
186  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
187    llvm::APSInt X;
188    return isIntegerConstantExpr(X, Ctx, Loc);
189  }
190  /// isConstantInitializer - Returns true if this expression is a constant
191  /// initializer, which can be emitted at compile-time.
192  bool isConstantInitializer(ASTContext &Ctx) const;
193
194  /// EvalResult is a struct with detailed info about an evaluated expression.
195  struct EvalResult {
196    /// Val - This is the value the expression can be folded to.
197    APValue Val;
198
199    /// HasSideEffects - Whether the evaluated expression has side effects.
200    /// For example, (f() && 0) can be folded, but it still has side effects.
201    bool HasSideEffects;
202
203    /// Diag - If the expression is unfoldable, then Diag contains a note
204    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
205    /// position for the error, and DiagExpr is the expression that caused
206    /// the error.
207    /// If the expression is foldable, but not an integer constant expression,
208    /// Diag contains a note diagnostic that describes why it isn't an integer
209    /// constant expression. If the expression *is* an integer constant
210    /// expression, then Diag will be zero.
211    unsigned Diag;
212    const Expr *DiagExpr;
213    SourceLocation DiagLoc;
214
215    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
216  };
217
218  /// Evaluate - Return true if this is a constant which we can fold using
219  /// any crazy technique (that has nothing to do with language standards) that
220  /// we want to.  If this function returns true, it returns the folded constant
221  /// in Result.
222  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
223
224  /// isEvaluatable - Call Evaluate to see if this expression can be constant
225  /// folded, but discard the result.
226  bool isEvaluatable(ASTContext &Ctx) const;
227
228  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
229  /// must be called on an expression that constant folds to an integer.
230  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
231
232  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
233  /// integer constant expression with the value zero, or if this is one that is
234  /// cast to void*.
235  bool isNullPointerConstant(ASTContext &Ctx) const;
236
237  /// hasGlobalStorage - Return true if this expression has static storage
238  /// duration.  This means that the address of this expression is a link-time
239  /// constant.
240  bool hasGlobalStorage() const;
241
242  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
243  ///  its subexpression.  If that subexpression is also a ParenExpr,
244  ///  then this method recursively returns its subexpression, and so forth.
245  ///  Otherwise, the method returns the current Expr.
246  Expr* IgnoreParens();
247
248  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
249  /// or CastExprs, returning their operand.
250  Expr *IgnoreParenCasts();
251
252  const Expr* IgnoreParens() const {
253    return const_cast<Expr*>(this)->IgnoreParens();
254  }
255  const Expr *IgnoreParenCasts() const {
256    return const_cast<Expr*>(this)->IgnoreParenCasts();
257  }
258
259  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
260  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
261
262  static bool classof(const Stmt *T) {
263    return T->getStmtClass() >= firstExprConstant &&
264           T->getStmtClass() <= lastExprConstant;
265  }
266  static bool classof(const Expr *) { return true; }
267
268  static inline Expr* Create(llvm::Deserializer& D, ASTContext& C) {
269    return cast<Expr>(Stmt::Create(D, C));
270  }
271};
272
273
274//===----------------------------------------------------------------------===//
275// Primary Expressions.
276//===----------------------------------------------------------------------===//
277
278/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
279/// enum, etc.
280class DeclRefExpr : public Expr {
281  NamedDecl *D;
282  SourceLocation Loc;
283
284protected:
285  // FIXME: Eventually, this constructor will go away and all subclasses
286  // will have to provide the type- and value-dependent flags.
287  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l) :
288    Expr(SC, t), D(d), Loc(l) {}
289
290  DeclRefExpr(StmtClass SC, NamedDecl *d, QualType t, SourceLocation l, bool TD,
291              bool VD) :
292    Expr(SC, t, TD, VD), D(d), Loc(l) {}
293
294public:
295  // FIXME: Eventually, this constructor will go away and all clients
296  // will have to provide the type- and value-dependent flags.
297  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l) :
298    Expr(DeclRefExprClass, t), D(d), Loc(l) {}
299
300  DeclRefExpr(NamedDecl *d, QualType t, SourceLocation l, bool TD, bool VD) :
301    Expr(DeclRefExprClass, t, TD, VD), D(d), Loc(l) {}
302
303  NamedDecl *getDecl() { return D; }
304  const NamedDecl *getDecl() const { return D; }
305  void setDecl(NamedDecl *NewD) { D = NewD; }
306
307  SourceLocation getLocation() const { return Loc; }
308  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
309
310  static bool classof(const Stmt *T) {
311    return T->getStmtClass() == DeclRefExprClass ||
312           T->getStmtClass() == CXXConditionDeclExprClass ||
313           T->getStmtClass() == QualifiedDeclRefExprClass;
314  }
315  static bool classof(const DeclRefExpr *) { return true; }
316
317  // Iterators
318  virtual child_iterator child_begin();
319  virtual child_iterator child_end();
320
321  virtual void EmitImpl(llvm::Serializer& S) const;
322  static DeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
323};
324
325/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
326class PredefinedExpr : public Expr {
327public:
328  enum IdentType {
329    Func,
330    Function,
331    PrettyFunction
332  };
333
334private:
335  SourceLocation Loc;
336  IdentType Type;
337public:
338  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
339    : Expr(PredefinedExprClass, type), Loc(l), Type(IT) {}
340
341  IdentType getIdentType() const { return Type; }
342
343  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
344
345  static bool classof(const Stmt *T) {
346    return T->getStmtClass() == PredefinedExprClass;
347  }
348  static bool classof(const PredefinedExpr *) { return true; }
349
350  // Iterators
351  virtual child_iterator child_begin();
352  virtual child_iterator child_end();
353
354  virtual void EmitImpl(llvm::Serializer& S) const;
355  static PredefinedExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
356};
357
358class IntegerLiteral : public Expr {
359  llvm::APInt Value;
360  SourceLocation Loc;
361public:
362  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
363  // or UnsignedLongLongTy
364  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
365    : Expr(IntegerLiteralClass, type), Value(V), Loc(l) {
366    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
367  }
368  const llvm::APInt &getValue() const { return Value; }
369  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
370
371  static bool classof(const Stmt *T) {
372    return T->getStmtClass() == IntegerLiteralClass;
373  }
374  static bool classof(const IntegerLiteral *) { return true; }
375
376  // Iterators
377  virtual child_iterator child_begin();
378  virtual child_iterator child_end();
379
380  virtual void EmitImpl(llvm::Serializer& S) const;
381  static IntegerLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
382};
383
384class CharacterLiteral : public Expr {
385  unsigned Value;
386  SourceLocation Loc;
387  bool IsWide;
388public:
389  // type should be IntTy
390  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
391    : Expr(CharacterLiteralClass, type), Value(value), Loc(l), IsWide(iswide) {
392  }
393  SourceLocation getLoc() const { return Loc; }
394  bool isWide() const { return IsWide; }
395
396  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
397
398  unsigned getValue() const { return Value; }
399
400  static bool classof(const Stmt *T) {
401    return T->getStmtClass() == CharacterLiteralClass;
402  }
403  static bool classof(const CharacterLiteral *) { return true; }
404
405  // Iterators
406  virtual child_iterator child_begin();
407  virtual child_iterator child_end();
408
409  virtual void EmitImpl(llvm::Serializer& S) const;
410  static CharacterLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
411};
412
413class FloatingLiteral : public Expr {
414  llvm::APFloat Value;
415  bool IsExact : 1;
416  SourceLocation Loc;
417public:
418  FloatingLiteral(const llvm::APFloat &V, bool* isexact,
419                  QualType Type, SourceLocation L)
420    : Expr(FloatingLiteralClass, Type), Value(V), IsExact(*isexact), Loc(L) {}
421
422  const llvm::APFloat &getValue() const { return Value; }
423
424  bool isExact() const { return IsExact; }
425
426  /// getValueAsApproximateDouble - This returns the value as an inaccurate
427  /// double.  Note that this may cause loss of precision, but is useful for
428  /// debugging dumps, etc.
429  double getValueAsApproximateDouble() const;
430
431  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
432
433  static bool classof(const Stmt *T) {
434    return T->getStmtClass() == FloatingLiteralClass;
435  }
436  static bool classof(const FloatingLiteral *) { return true; }
437
438  // Iterators
439  virtual child_iterator child_begin();
440  virtual child_iterator child_end();
441
442  virtual void EmitImpl(llvm::Serializer& S) const;
443  static FloatingLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
444};
445
446/// ImaginaryLiteral - We support imaginary integer and floating point literals,
447/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
448/// IntegerLiteral classes.  Instances of this class always have a Complex type
449/// whose element type matches the subexpression.
450///
451class ImaginaryLiteral : public Expr {
452  Stmt *Val;
453public:
454  ImaginaryLiteral(Expr *val, QualType Ty)
455    : Expr(ImaginaryLiteralClass, Ty), Val(val) {}
456
457  const Expr *getSubExpr() const { return cast<Expr>(Val); }
458  Expr *getSubExpr() { return cast<Expr>(Val); }
459
460  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
461  static bool classof(const Stmt *T) {
462    return T->getStmtClass() == ImaginaryLiteralClass;
463  }
464  static bool classof(const ImaginaryLiteral *) { return true; }
465
466  // Iterators
467  virtual child_iterator child_begin();
468  virtual child_iterator child_end();
469
470  virtual void EmitImpl(llvm::Serializer& S) const;
471  static ImaginaryLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
472};
473
474/// StringLiteral - This represents a string literal expression, e.g. "foo"
475/// or L"bar" (wide strings).  The actual string is returned by getStrData()
476/// is NOT null-terminated, and the length of the string is determined by
477/// calling getByteLength().  The C type for a string is always a
478/// ConstantArrayType.
479///
480/// Note that strings in C can be formed by concatenation of multiple string
481/// literal pptokens in trnaslation phase #6.  This keeps track of the locations
482/// of each of these pieces.
483class StringLiteral : public Expr {
484  const char *StrData;
485  unsigned ByteLength;
486  bool IsWide;
487  unsigned NumConcatenated;
488  SourceLocation TokLocs[1];
489
490  StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty) {}
491public:
492  /// This is the "fully general" constructor that allows representation of
493  /// strings formed from multiple concatenated tokens.
494  static StringLiteral *Create(ASTContext &C, const char *StrData,
495                               unsigned ByteLength, bool Wide, QualType Ty,
496                               SourceLocation *Loc, unsigned NumStrs);
497
498  /// Simple constructor for string literals made from one token.
499  static StringLiteral *Create(ASTContext &C, const char *StrData,
500                               unsigned ByteLength,
501                               bool Wide, QualType Ty, SourceLocation Loc) {
502    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
503  }
504
505  void Destroy(ASTContext &C);
506
507  const char *getStrData() const { return StrData; }
508  unsigned getByteLength() const { return ByteLength; }
509  bool isWide() const { return IsWide; }
510
511  /// getNumConcatenated - Get the number of string literal tokens that were
512  /// concatenated in translation phase #6 to form this string literal.
513  unsigned getNumConcatenated() const { return NumConcatenated; }
514
515  SourceLocation getStrTokenLoc(unsigned TokNum) const {
516    assert(TokNum < NumConcatenated && "Invalid tok number");
517    return TokLocs[TokNum];
518  }
519
520  typedef const SourceLocation *tokloc_iterator;
521  tokloc_iterator tokloc_begin() const { return TokLocs; }
522  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
523
524
525  virtual SourceRange getSourceRange() const {
526    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
527  }
528  static bool classof(const Stmt *T) {
529    return T->getStmtClass() == StringLiteralClass;
530  }
531  static bool classof(const StringLiteral *) { return true; }
532
533  // Iterators
534  virtual child_iterator child_begin();
535  virtual child_iterator child_end();
536
537  virtual void EmitImpl(llvm::Serializer& S) const;
538  static StringLiteral* CreateImpl(llvm::Deserializer& D, ASTContext& C);
539};
540
541/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
542/// AST node is only formed if full location information is requested.
543class ParenExpr : public Expr {
544  SourceLocation L, R;
545  Stmt *Val;
546public:
547  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
548    : Expr(ParenExprClass, val->getType(),
549           val->isTypeDependent(), val->isValueDependent()),
550      L(l), R(r), Val(val) {}
551
552  const Expr *getSubExpr() const { return cast<Expr>(Val); }
553  Expr *getSubExpr() { return cast<Expr>(Val); }
554  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
555
556  static bool classof(const Stmt *T) {
557    return T->getStmtClass() == ParenExprClass;
558  }
559  static bool classof(const ParenExpr *) { return true; }
560
561  // Iterators
562  virtual child_iterator child_begin();
563  virtual child_iterator child_end();
564
565  virtual void EmitImpl(llvm::Serializer& S) const;
566  static ParenExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
567};
568
569
570/// UnaryOperator - This represents the unary-expression's (except sizeof and
571/// alignof), the postinc/postdec operators from postfix-expression, and various
572/// extensions.
573///
574/// Notes on various nodes:
575///
576/// Real/Imag - These return the real/imag part of a complex operand.  If
577///   applied to a non-complex value, the former returns its operand and the
578///   later returns zero in the type of the operand.
579///
580/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
581///   subexpression is a compound literal with the various MemberExpr and
582///   ArraySubscriptExpr's applied to it.
583///
584class UnaryOperator : public Expr {
585public:
586  // Note that additions to this should also update the StmtVisitor class.
587  enum Opcode {
588    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
589    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
590    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
591    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
592    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
593    Real, Imag,       // "__real expr"/"__imag expr" Extension.
594    Extension,        // __extension__ marker.
595    OffsetOf          // __builtin_offsetof
596  };
597private:
598  Stmt *Val;
599  Opcode Opc;
600  SourceLocation Loc;
601public:
602
603  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
604    : Expr(UnaryOperatorClass, type,
605           input->isTypeDependent() && opc != OffsetOf,
606           input->isValueDependent()),
607      Val(input), Opc(opc), Loc(l) {}
608
609  Opcode getOpcode() const { return Opc; }
610  Expr *getSubExpr() const { return cast<Expr>(Val); }
611
612  /// getOperatorLoc - Return the location of the operator.
613  SourceLocation getOperatorLoc() const { return Loc; }
614
615  /// isPostfix - Return true if this is a postfix operation, like x++.
616  static bool isPostfix(Opcode Op) {
617    return Op == PostInc || Op == PostDec;
618  }
619
620  /// isPostfix - Return true if this is a prefix operation, like --x.
621  static bool isPrefix(Opcode Op) {
622    return Op == PreInc || Op == PreDec;
623  }
624
625  bool isPrefix() const { return isPrefix(Opc); }
626  bool isPostfix() const { return isPostfix(Opc); }
627  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
628  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
629  bool isOffsetOfOp() const { return Opc == OffsetOf; }
630  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
631
632  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
633  /// corresponds to, e.g. "sizeof" or "[pre]++"
634  static const char *getOpcodeStr(Opcode Op);
635
636  virtual SourceRange getSourceRange() const {
637    if (isPostfix())
638      return SourceRange(Val->getLocStart(), Loc);
639    else
640      return SourceRange(Loc, Val->getLocEnd());
641  }
642  virtual SourceLocation getExprLoc() const { return Loc; }
643
644  static bool classof(const Stmt *T) {
645    return T->getStmtClass() == UnaryOperatorClass;
646  }
647  static bool classof(const UnaryOperator *) { return true; }
648
649  int64_t evaluateOffsetOf(ASTContext& C) const;
650
651  // Iterators
652  virtual child_iterator child_begin();
653  virtual child_iterator child_end();
654
655  virtual void EmitImpl(llvm::Serializer& S) const;
656  static UnaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
657};
658
659/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
660/// types and expressions.
661class SizeOfAlignOfExpr : public Expr {
662  bool isSizeof : 1;  // true if sizeof, false if alignof.
663  bool isType : 1;    // true if operand is a type, false if an expression
664  union {
665    void *Ty;
666    Stmt *Ex;
667  } Argument;
668  SourceLocation OpLoc, RParenLoc;
669public:
670  SizeOfAlignOfExpr(bool issizeof, bool istype, void *argument,
671                    QualType resultType, SourceLocation op,
672                    SourceLocation rp) :
673      Expr(SizeOfAlignOfExprClass, resultType), isSizeof(issizeof),
674      isType(istype), OpLoc(op), RParenLoc(rp) {
675    if (isType)
676      Argument.Ty = argument;
677    else
678      // argument was an Expr*, so cast it back to that to be safe
679      Argument.Ex = static_cast<Expr*>(argument);
680  }
681
682  virtual void Destroy(ASTContext& C);
683
684  bool isSizeOf() const { return isSizeof; }
685  bool isArgumentType() const { return isType; }
686  QualType getArgumentType() const {
687    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
688    return QualType::getFromOpaquePtr(Argument.Ty);
689  }
690  Expr *getArgumentExpr() {
691    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
692    return static_cast<Expr*>(Argument.Ex);
693  }
694  const Expr *getArgumentExpr() const {
695    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
696  }
697
698  /// Gets the argument type, or the type of the argument expression, whichever
699  /// is appropriate.
700  QualType getTypeOfArgument() const {
701    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
702  }
703
704  SourceLocation getOperatorLoc() const { return OpLoc; }
705
706  virtual SourceRange getSourceRange() const {
707    return SourceRange(OpLoc, RParenLoc);
708  }
709
710  static bool classof(const Stmt *T) {
711    return T->getStmtClass() == SizeOfAlignOfExprClass;
712  }
713  static bool classof(const SizeOfAlignOfExpr *) { return true; }
714
715  // Iterators
716  virtual child_iterator child_begin();
717  virtual child_iterator child_end();
718
719  virtual void EmitImpl(llvm::Serializer& S) const;
720  static SizeOfAlignOfExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
721};
722
723//===----------------------------------------------------------------------===//
724// Postfix Operators.
725//===----------------------------------------------------------------------===//
726
727/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
728class ArraySubscriptExpr : public Expr {
729  enum { LHS, RHS, END_EXPR=2 };
730  Stmt* SubExprs[END_EXPR];
731  SourceLocation RBracketLoc;
732public:
733  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
734                     SourceLocation rbracketloc)
735  : Expr(ArraySubscriptExprClass, t), RBracketLoc(rbracketloc) {
736    SubExprs[LHS] = lhs;
737    SubExprs[RHS] = rhs;
738  }
739
740  /// An array access can be written A[4] or 4[A] (both are equivalent).
741  /// - getBase() and getIdx() always present the normalized view: A[4].
742  ///    In this case getBase() returns "A" and getIdx() returns "4".
743  /// - getLHS() and getRHS() present the syntactic view. e.g. for
744  ///    4[A] getLHS() returns "4".
745  /// Note: Because vector element access is also written A[4] we must
746  /// predicate the format conversion in getBase and getIdx only on the
747  /// the type of the RHS, as it is possible for the LHS to be a vector of
748  /// integer type
749  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
750  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
751
752  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
753  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
754
755  Expr *getBase() {
756    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
757  }
758
759  const Expr *getBase() const {
760    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
761  }
762
763  Expr *getIdx() {
764    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
765  }
766
767  const Expr *getIdx() const {
768    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
769  }
770
771  virtual SourceRange getSourceRange() const {
772    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
773  }
774
775  SourceLocation getRBracketLoc() const { return RBracketLoc; }
776  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
777
778  static bool classof(const Stmt *T) {
779    return T->getStmtClass() == ArraySubscriptExprClass;
780  }
781  static bool classof(const ArraySubscriptExpr *) { return true; }
782
783  // Iterators
784  virtual child_iterator child_begin();
785  virtual child_iterator child_end();
786
787  virtual void EmitImpl(llvm::Serializer& S) const;
788  static ArraySubscriptExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
789};
790
791
792/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
793/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
794/// while its subclasses may represent alternative syntax that (semantically)
795/// results in a function call. For example, CXXOperatorCallExpr is
796/// a subclass for overloaded operator calls that use operator syntax, e.g.,
797/// "str1 + str2" to resolve to a function call.
798class CallExpr : public Expr {
799  enum { FN=0, ARGS_START=1 };
800  Stmt **SubExprs;
801  unsigned NumArgs;
802  SourceLocation RParenLoc;
803
804  // This version of the ctor is for deserialization.
805  CallExpr(StmtClass SC, Stmt** subexprs, unsigned numargs, QualType t,
806           SourceLocation rparenloc)
807  : Expr(SC,t), SubExprs(subexprs),
808    NumArgs(numargs), RParenLoc(rparenloc) {}
809
810protected:
811  // This version of the constructor is for derived classes.
812  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
813           QualType t, SourceLocation rparenloc);
814
815public:
816  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
817           SourceLocation rparenloc);
818
819  ~CallExpr() {}
820
821  void Destroy(ASTContext& C);
822
823  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
824  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
825  void setCallee(Expr *F) { SubExprs[FN] = F; }
826
827  /// getNumArgs - Return the number of actual arguments to this call.
828  ///
829  unsigned getNumArgs() const { return NumArgs; }
830
831  /// getArg - Return the specified argument.
832  Expr *getArg(unsigned Arg) {
833    assert(Arg < NumArgs && "Arg access out of range!");
834    return cast<Expr>(SubExprs[Arg+ARGS_START]);
835  }
836  const Expr *getArg(unsigned Arg) const {
837    assert(Arg < NumArgs && "Arg access out of range!");
838    return cast<Expr>(SubExprs[Arg+ARGS_START]);
839  }
840
841  // FIXME: Why is this needed?  Why not just create the CallExpr with the
842  // corect number of arguments?  It makes the ASTs less brittle.
843  /// setArg - Set the specified argument.
844  void setArg(unsigned Arg, Expr *ArgExpr) {
845    assert(Arg < NumArgs && "Arg access out of range!");
846    SubExprs[Arg+ARGS_START] = ArgExpr;
847  }
848
849  // FIXME: It would be great to just get rid of this.  There is only one
850  // callee of this method, and it probably could be refactored to not use
851  // this method and instead just create a CallExpr with the right number of
852  // arguments.
853  /// setNumArgs - This changes the number of arguments present in this call.
854  /// Any orphaned expressions are deleted by this, and any new operands are set
855  /// to null.
856  void setNumArgs(ASTContext& C, unsigned NumArgs);
857
858  typedef ExprIterator arg_iterator;
859  typedef ConstExprIterator const_arg_iterator;
860
861  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
862  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
863  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
864  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
865
866  /// getNumCommas - Return the number of commas that must have been present in
867  /// this function call.
868  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
869
870  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
871  /// not, return 0.
872  unsigned isBuiltinCall(ASTContext &Context) const;
873
874  SourceLocation getRParenLoc() const { return RParenLoc; }
875
876  virtual SourceRange getSourceRange() const {
877    return SourceRange(getCallee()->getLocStart(), RParenLoc);
878  }
879
880  static bool classof(const Stmt *T) {
881    return T->getStmtClass() == CallExprClass ||
882           T->getStmtClass() == CXXOperatorCallExprClass ||
883           T->getStmtClass() == CXXMemberCallExprClass;
884  }
885  static bool classof(const CallExpr *) { return true; }
886  static bool classof(const CXXOperatorCallExpr *) { return true; }
887  static bool classof(const CXXMemberCallExpr *) { return true; }
888
889  // Iterators
890  virtual child_iterator child_begin();
891  virtual child_iterator child_end();
892
893  virtual void EmitImpl(llvm::Serializer& S) const;
894  static CallExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C,
895                              StmtClass SC);
896};
897
898/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.
899///
900class MemberExpr : public Expr {
901  Stmt *Base;
902  NamedDecl *MemberDecl;
903  SourceLocation MemberLoc;
904  bool IsArrow;      // True if this is "X->F", false if this is "X.F".
905public:
906  MemberExpr(Expr *base, bool isarrow, NamedDecl *memberdecl, SourceLocation l,
907             QualType ty)
908    : Expr(MemberExprClass, ty),
909      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow) {}
910
911  void setBase(Expr *E) { Base = E; }
912  Expr *getBase() const { return cast<Expr>(Base); }
913  NamedDecl *getMemberDecl() const { return MemberDecl; }
914  void setMemberDecl(NamedDecl *D) { MemberDecl = D; }
915  bool isArrow() const { return IsArrow; }
916  SourceLocation getMemberLoc() const { return MemberLoc; }
917
918  virtual SourceRange getSourceRange() const {
919    return SourceRange(getBase()->getLocStart(), MemberLoc);
920  }
921
922  virtual SourceLocation getExprLoc() const { return MemberLoc; }
923
924  static bool classof(const Stmt *T) {
925    return T->getStmtClass() == MemberExprClass;
926  }
927  static bool classof(const MemberExpr *) { return true; }
928
929  // Iterators
930  virtual child_iterator child_begin();
931  virtual child_iterator child_end();
932
933  virtual void EmitImpl(llvm::Serializer& S) const;
934  static MemberExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
935};
936
937/// CompoundLiteralExpr - [C99 6.5.2.5]
938///
939class CompoundLiteralExpr : public Expr {
940  /// LParenLoc - If non-null, this is the location of the left paren in a
941  /// compound literal like "(int){4}".  This can be null if this is a
942  /// synthesized compound expression.
943  SourceLocation LParenLoc;
944  Stmt *Init;
945  bool FileScope;
946public:
947  CompoundLiteralExpr(SourceLocation lparenloc, QualType ty, Expr *init,
948                      bool fileScope)
949    : Expr(CompoundLiteralExprClass, ty), LParenLoc(lparenloc), Init(init),
950      FileScope(fileScope) {}
951
952  const Expr *getInitializer() const { return cast<Expr>(Init); }
953  Expr *getInitializer() { return cast<Expr>(Init); }
954
955  bool isFileScope() const { return FileScope; }
956
957  SourceLocation getLParenLoc() const { return LParenLoc; }
958
959  virtual SourceRange getSourceRange() const {
960    // FIXME: Init should never be null.
961    if (!Init)
962      return SourceRange();
963    if (LParenLoc.isInvalid())
964      return Init->getSourceRange();
965    return SourceRange(LParenLoc, Init->getLocEnd());
966  }
967
968  static bool classof(const Stmt *T) {
969    return T->getStmtClass() == CompoundLiteralExprClass;
970  }
971  static bool classof(const CompoundLiteralExpr *) { return true; }
972
973  // Iterators
974  virtual child_iterator child_begin();
975  virtual child_iterator child_end();
976
977  virtual void EmitImpl(llvm::Serializer& S) const;
978  static CompoundLiteralExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
979};
980
981/// CastExpr - Base class for type casts, including both implicit
982/// casts (ImplicitCastExpr) and explicit casts that have some
983/// representation in the source code (ExplicitCastExpr's derived
984/// classes).
985class CastExpr : public Expr {
986  Stmt *Op;
987protected:
988  CastExpr(StmtClass SC, QualType ty, Expr *op) :
989    Expr(SC, ty,
990         // Cast expressions are type-dependent if the type is
991         // dependent (C++ [temp.dep.expr]p3).
992         ty->isDependentType(),
993         // Cast expressions are value-dependent if the type is
994         // dependent or if the subexpression is value-dependent.
995         ty->isDependentType() || (op && op->isValueDependent())),
996    Op(op) {}
997
998public:
999  Expr *getSubExpr() { return cast<Expr>(Op); }
1000  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1001
1002  static bool classof(const Stmt *T) {
1003    StmtClass SC = T->getStmtClass();
1004    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1005      return true;
1006
1007    if (SC >= ImplicitCastExprClass && SC <= CStyleCastExprClass)
1008      return true;
1009
1010    return false;
1011  }
1012  static bool classof(const CastExpr *) { return true; }
1013
1014  // Iterators
1015  virtual child_iterator child_begin();
1016  virtual child_iterator child_end();
1017};
1018
1019/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1020/// conversions, which have no direct representation in the original
1021/// source code. For example: converting T[]->T*, void f()->void
1022/// (*f)(), float->double, short->int, etc.
1023///
1024/// In C, implicit casts always produce rvalues. However, in C++, an
1025/// implicit cast whose result is being bound to a reference will be
1026/// an lvalue. For example:
1027///
1028/// @code
1029/// class Base { };
1030/// class Derived : public Base { };
1031/// void f(Derived d) {
1032///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1033/// }
1034/// @endcode
1035class ImplicitCastExpr : public CastExpr {
1036  /// LvalueCast - Whether this cast produces an lvalue.
1037  bool LvalueCast;
1038
1039public:
1040  ImplicitCastExpr(QualType ty, Expr *op, bool Lvalue) :
1041    CastExpr(ImplicitCastExprClass, ty, op), LvalueCast(Lvalue) { }
1042
1043  virtual SourceRange getSourceRange() const {
1044    return getSubExpr()->getSourceRange();
1045  }
1046
1047  /// isLvalueCast - Whether this cast produces an lvalue.
1048  bool isLvalueCast() const { return LvalueCast; }
1049
1050  /// setLvalueCast - Set whether this cast produces an lvalue.
1051  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1052
1053  static bool classof(const Stmt *T) {
1054    return T->getStmtClass() == ImplicitCastExprClass;
1055  }
1056  static bool classof(const ImplicitCastExpr *) { return true; }
1057
1058  virtual void EmitImpl(llvm::Serializer& S) const;
1059  static ImplicitCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1060};
1061
1062/// ExplicitCastExpr - An explicit cast written in the source
1063/// code.
1064///
1065/// This class is effectively an abstract class, because it provides
1066/// the basic representation of an explicitly-written cast without
1067/// specifying which kind of cast (C cast, functional cast, static
1068/// cast, etc.) was written; specific derived classes represent the
1069/// particular style of cast and its location information.
1070///
1071/// Unlike implicit casts, explicit cast nodes have two different
1072/// types: the type that was written into the source code, and the
1073/// actual type of the expression as determined by semantic
1074/// analysis. These types may differ slightly. For example, in C++ one
1075/// can cast to a reference type, which indicates that the resulting
1076/// expression will be an lvalue. The reference type, however, will
1077/// not be used as the type of the expression.
1078class ExplicitCastExpr : public CastExpr {
1079  /// TypeAsWritten - The type that this expression is casting to, as
1080  /// written in the source code.
1081  QualType TypeAsWritten;
1082
1083protected:
1084  ExplicitCastExpr(StmtClass SC, QualType exprTy, Expr *op, QualType writtenTy)
1085    : CastExpr(SC, exprTy, op), TypeAsWritten(writtenTy) {}
1086
1087public:
1088  /// getTypeAsWritten - Returns the type that this expression is
1089  /// casting to, as written in the source code.
1090  QualType getTypeAsWritten() const { return TypeAsWritten; }
1091
1092  static bool classof(const Stmt *T) {
1093    StmtClass SC = T->getStmtClass();
1094    if (SC >= ExplicitCastExprClass && SC <= CStyleCastExprClass)
1095      return true;
1096    if (SC >= CXXNamedCastExprClass && SC <= CXXFunctionalCastExprClass)
1097      return true;
1098
1099    return false;
1100  }
1101  static bool classof(const ExplicitCastExpr *) { return true; }
1102};
1103
1104/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
1105/// cast in C++ (C++ [expr.cast]), which uses the syntax
1106/// (Type)expr. For example: @c (int)f.
1107class CStyleCastExpr : public ExplicitCastExpr {
1108  SourceLocation LPLoc; // the location of the left paren
1109  SourceLocation RPLoc; // the location of the right paren
1110public:
1111  CStyleCastExpr(QualType exprTy, Expr *op, QualType writtenTy,
1112                    SourceLocation l, SourceLocation r) :
1113    ExplicitCastExpr(CStyleCastExprClass, exprTy, op, writtenTy),
1114    LPLoc(l), RPLoc(r) {}
1115
1116  SourceLocation getLParenLoc() const { return LPLoc; }
1117  SourceLocation getRParenLoc() const { return RPLoc; }
1118
1119  virtual SourceRange getSourceRange() const {
1120    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
1121  }
1122  static bool classof(const Stmt *T) {
1123    return T->getStmtClass() == CStyleCastExprClass;
1124  }
1125  static bool classof(const CStyleCastExpr *) { return true; }
1126
1127  virtual void EmitImpl(llvm::Serializer& S) const;
1128  static CStyleCastExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1129};
1130
1131class BinaryOperator : public Expr {
1132public:
1133  enum Opcode {
1134    // Operators listed in order of precedence.
1135    // Note that additions to this should also update the StmtVisitor class.
1136    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
1137    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
1138    Add, Sub,         // [C99 6.5.6] Additive operators.
1139    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
1140    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
1141    EQ, NE,           // [C99 6.5.9] Equality operators.
1142    And,              // [C99 6.5.10] Bitwise AND operator.
1143    Xor,              // [C99 6.5.11] Bitwise XOR operator.
1144    Or,               // [C99 6.5.12] Bitwise OR operator.
1145    LAnd,             // [C99 6.5.13] Logical AND operator.
1146    LOr,              // [C99 6.5.14] Logical OR operator.
1147    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
1148    DivAssign, RemAssign,
1149    AddAssign, SubAssign,
1150    ShlAssign, ShrAssign,
1151    AndAssign, XorAssign,
1152    OrAssign,
1153    Comma             // [C99 6.5.17] Comma operator.
1154  };
1155private:
1156  enum { LHS, RHS, END_EXPR };
1157  Stmt* SubExprs[END_EXPR];
1158  Opcode Opc;
1159  SourceLocation OpLoc;
1160public:
1161
1162  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1163                 SourceLocation opLoc)
1164    : Expr(BinaryOperatorClass, ResTy,
1165           lhs->isTypeDependent() || rhs->isTypeDependent(),
1166           lhs->isValueDependent() || rhs->isValueDependent()),
1167      Opc(opc), OpLoc(opLoc) {
1168    SubExprs[LHS] = lhs;
1169    SubExprs[RHS] = rhs;
1170    assert(!isCompoundAssignmentOp() &&
1171           "Use ArithAssignBinaryOperator for compound assignments");
1172  }
1173
1174  SourceLocation getOperatorLoc() const { return OpLoc; }
1175  Opcode getOpcode() const { return Opc; }
1176  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1177  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1178  virtual SourceRange getSourceRange() const {
1179    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
1180  }
1181
1182  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1183  /// corresponds to, e.g. "<<=".
1184  static const char *getOpcodeStr(Opcode Op);
1185
1186  /// predicates to categorize the respective opcodes.
1187  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
1188  bool isAdditiveOp() const { return Opc == Add || Opc == Sub; }
1189  bool isShiftOp() const { return Opc == Shl || Opc == Shr; }
1190  bool isBitwiseOp() const { return Opc >= And && Opc <= Or; }
1191
1192  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
1193  bool isRelationalOp() const { return isRelationalOp(Opc); }
1194
1195  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
1196  bool isEqualityOp() const { return isEqualityOp(Opc); }
1197
1198  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
1199  bool isLogicalOp() const { return isLogicalOp(Opc); }
1200
1201  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
1202  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
1203  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
1204
1205  static bool classof(const Stmt *S) {
1206    return S->getStmtClass() == BinaryOperatorClass ||
1207           S->getStmtClass() == CompoundAssignOperatorClass;
1208  }
1209  static bool classof(const BinaryOperator *) { return true; }
1210
1211  // Iterators
1212  virtual child_iterator child_begin();
1213  virtual child_iterator child_end();
1214
1215  virtual void EmitImpl(llvm::Serializer& S) const;
1216  static BinaryOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1217
1218protected:
1219  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
1220                 SourceLocation oploc, bool dead)
1221    : Expr(CompoundAssignOperatorClass, ResTy), Opc(opc), OpLoc(oploc) {
1222    SubExprs[LHS] = lhs;
1223    SubExprs[RHS] = rhs;
1224  }
1225};
1226
1227/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
1228/// track of the type the operation is performed in.  Due to the semantics of
1229/// these operators, the operands are promoted, the aritmetic performed, an
1230/// implicit conversion back to the result type done, then the assignment takes
1231/// place.  This captures the intermediate type which the computation is done
1232/// in.
1233class CompoundAssignOperator : public BinaryOperator {
1234  QualType ComputationType;
1235public:
1236  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
1237                         QualType ResType, QualType CompType,
1238                         SourceLocation OpLoc)
1239    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
1240      ComputationType(CompType) {
1241    assert(isCompoundAssignmentOp() &&
1242           "Only should be used for compound assignments");
1243  }
1244
1245  QualType getComputationType() const { return ComputationType; }
1246
1247  static bool classof(const CompoundAssignOperator *) { return true; }
1248  static bool classof(const Stmt *S) {
1249    return S->getStmtClass() == CompoundAssignOperatorClass;
1250  }
1251
1252  virtual void EmitImpl(llvm::Serializer& S) const;
1253  static CompoundAssignOperator* CreateImpl(llvm::Deserializer& D,
1254                                            ASTContext& C);
1255};
1256
1257/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
1258/// GNU "missing LHS" extension is in use.
1259///
1260class ConditionalOperator : public Expr {
1261  enum { COND, LHS, RHS, END_EXPR };
1262  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1263public:
1264  ConditionalOperator(Expr *cond, Expr *lhs, Expr *rhs, QualType t)
1265    : Expr(ConditionalOperatorClass, t,
1266           // FIXME: the type of the conditional operator doesn't
1267           // depend on the type of the conditional, but the standard
1268           // seems to imply that it could. File a bug!
1269           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
1270           (cond->isValueDependent() ||
1271            (lhs && lhs->isValueDependent()) ||
1272            (rhs && rhs->isValueDependent()))) {
1273    SubExprs[COND] = cond;
1274    SubExprs[LHS] = lhs;
1275    SubExprs[RHS] = rhs;
1276  }
1277
1278  // getCond - Return the expression representing the condition for
1279  //  the ?: operator.
1280  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1281
1282  // getTrueExpr - Return the subexpression representing the value of the ?:
1283  //  expression if the condition evaluates to true.  In most cases this value
1284  //  will be the same as getLHS() except a GCC extension allows the left
1285  //  subexpression to be omitted, and instead of the condition be returned.
1286  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
1287  //  is only evaluated once.
1288  Expr *getTrueExpr() const {
1289    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
1290  }
1291
1292  // getTrueExpr - Return the subexpression representing the value of the ?:
1293  // expression if the condition evaluates to false. This is the same as getRHS.
1294  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
1295
1296  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
1297  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1298
1299  virtual SourceRange getSourceRange() const {
1300    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
1301  }
1302  static bool classof(const Stmt *T) {
1303    return T->getStmtClass() == ConditionalOperatorClass;
1304  }
1305  static bool classof(const ConditionalOperator *) { return true; }
1306
1307  // Iterators
1308  virtual child_iterator child_begin();
1309  virtual child_iterator child_end();
1310
1311  virtual void EmitImpl(llvm::Serializer& S) const;
1312  static ConditionalOperator* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1313};
1314
1315/// AddrLabelExpr - The GNU address of label extension, representing &&label.
1316class AddrLabelExpr : public Expr {
1317  SourceLocation AmpAmpLoc, LabelLoc;
1318  LabelStmt *Label;
1319public:
1320  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
1321                QualType t)
1322    : Expr(AddrLabelExprClass, t), AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
1323
1324  virtual SourceRange getSourceRange() const {
1325    return SourceRange(AmpAmpLoc, LabelLoc);
1326  }
1327
1328  LabelStmt *getLabel() const { return Label; }
1329
1330  static bool classof(const Stmt *T) {
1331    return T->getStmtClass() == AddrLabelExprClass;
1332  }
1333  static bool classof(const AddrLabelExpr *) { return true; }
1334
1335  // Iterators
1336  virtual child_iterator child_begin();
1337  virtual child_iterator child_end();
1338
1339  virtual void EmitImpl(llvm::Serializer& S) const;
1340  static AddrLabelExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1341};
1342
1343/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
1344/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
1345/// takes the value of the last subexpression.
1346class StmtExpr : public Expr {
1347  Stmt *SubStmt;
1348  SourceLocation LParenLoc, RParenLoc;
1349public:
1350  StmtExpr(CompoundStmt *substmt, QualType T,
1351           SourceLocation lp, SourceLocation rp) :
1352    Expr(StmtExprClass, T), SubStmt(substmt),  LParenLoc(lp), RParenLoc(rp) { }
1353
1354  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
1355  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
1356
1357  virtual SourceRange getSourceRange() const {
1358    return SourceRange(LParenLoc, RParenLoc);
1359  }
1360
1361  SourceLocation getLParenLoc() const { return LParenLoc; }
1362  SourceLocation getRParenLoc() const { return RParenLoc; }
1363
1364  static bool classof(const Stmt *T) {
1365    return T->getStmtClass() == StmtExprClass;
1366  }
1367  static bool classof(const StmtExpr *) { return true; }
1368
1369  // Iterators
1370  virtual child_iterator child_begin();
1371  virtual child_iterator child_end();
1372
1373  virtual void EmitImpl(llvm::Serializer& S) const;
1374  static StmtExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1375};
1376
1377/// TypesCompatibleExpr - GNU builtin-in function __builtin_type_compatible_p.
1378/// This AST node represents a function that returns 1 if two *types* (not
1379/// expressions) are compatible. The result of this built-in function can be
1380/// used in integer constant expressions.
1381class TypesCompatibleExpr : public Expr {
1382  QualType Type1;
1383  QualType Type2;
1384  SourceLocation BuiltinLoc, RParenLoc;
1385public:
1386  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
1387                      QualType t1, QualType t2, SourceLocation RP) :
1388    Expr(TypesCompatibleExprClass, ReturnType), Type1(t1), Type2(t2),
1389    BuiltinLoc(BLoc), RParenLoc(RP) {}
1390
1391  QualType getArgType1() const { return Type1; }
1392  QualType getArgType2() const { return Type2; }
1393
1394  virtual SourceRange getSourceRange() const {
1395    return SourceRange(BuiltinLoc, RParenLoc);
1396  }
1397  static bool classof(const Stmt *T) {
1398    return T->getStmtClass() == TypesCompatibleExprClass;
1399  }
1400  static bool classof(const TypesCompatibleExpr *) { return true; }
1401
1402  // Iterators
1403  virtual child_iterator child_begin();
1404  virtual child_iterator child_end();
1405
1406  virtual void EmitImpl(llvm::Serializer& S) const;
1407  static TypesCompatibleExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1408};
1409
1410/// ShuffleVectorExpr - clang-specific builtin-in function
1411/// __builtin_shufflevector.
1412/// This AST node represents a operator that does a constant
1413/// shuffle, similar to LLVM's shufflevector instruction. It takes
1414/// two vectors and a variable number of constant indices,
1415/// and returns the appropriately shuffled vector.
1416class ShuffleVectorExpr : public Expr {
1417  SourceLocation BuiltinLoc, RParenLoc;
1418
1419  // SubExprs - the list of values passed to the __builtin_shufflevector
1420  // function. The first two are vectors, and the rest are constant
1421  // indices.  The number of values in this list is always
1422  // 2+the number of indices in the vector type.
1423  Stmt **SubExprs;
1424  unsigned NumExprs;
1425
1426public:
1427  ShuffleVectorExpr(Expr **args, unsigned nexpr,
1428                    QualType Type, SourceLocation BLoc,
1429                    SourceLocation RP) :
1430    Expr(ShuffleVectorExprClass, Type), BuiltinLoc(BLoc),
1431    RParenLoc(RP), NumExprs(nexpr) {
1432
1433    SubExprs = new Stmt*[nexpr];
1434    for (unsigned i = 0; i < nexpr; i++)
1435      SubExprs[i] = args[i];
1436  }
1437
1438  virtual SourceRange getSourceRange() const {
1439    return SourceRange(BuiltinLoc, RParenLoc);
1440  }
1441  static bool classof(const Stmt *T) {
1442    return T->getStmtClass() == ShuffleVectorExprClass;
1443  }
1444  static bool classof(const ShuffleVectorExpr *) { return true; }
1445
1446  ~ShuffleVectorExpr() {
1447    delete [] SubExprs;
1448  }
1449
1450  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1451  /// constant expression, the actual arguments passed in, and the function
1452  /// pointers.
1453  unsigned getNumSubExprs() const { return NumExprs; }
1454
1455  /// getExpr - Return the Expr at the specified index.
1456  Expr *getExpr(unsigned Index) {
1457    assert((Index < NumExprs) && "Arg access out of range!");
1458    return cast<Expr>(SubExprs[Index]);
1459  }
1460  const Expr *getExpr(unsigned Index) const {
1461    assert((Index < NumExprs) && "Arg access out of range!");
1462    return cast<Expr>(SubExprs[Index]);
1463  }
1464
1465  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
1466    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
1467    return getExpr(N+2)->getIntegerConstantExprValue(Ctx).getZExtValue();
1468  }
1469
1470  // Iterators
1471  virtual child_iterator child_begin();
1472  virtual child_iterator child_end();
1473
1474  virtual void EmitImpl(llvm::Serializer& S) const;
1475  static ShuffleVectorExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1476};
1477
1478/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
1479/// This AST node is similar to the conditional operator (?:) in C, with
1480/// the following exceptions:
1481/// - the test expression must be a constant expression.
1482/// - the expression returned has it's type unaltered by promotion rules.
1483/// - does not evaluate the expression that was not chosen.
1484class ChooseExpr : public Expr {
1485  enum { COND, LHS, RHS, END_EXPR };
1486  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
1487  SourceLocation BuiltinLoc, RParenLoc;
1488public:
1489  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
1490             SourceLocation RP)
1491    : Expr(ChooseExprClass, t),
1492      BuiltinLoc(BLoc), RParenLoc(RP) {
1493      SubExprs[COND] = cond;
1494      SubExprs[LHS] = lhs;
1495      SubExprs[RHS] = rhs;
1496    }
1497
1498  /// isConditionTrue - Return true if the condition is true.  This is always
1499  /// statically knowable for a well-formed choosexpr.
1500  bool isConditionTrue(ASTContext &C) const;
1501
1502  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
1503  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1504  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1505
1506  virtual SourceRange getSourceRange() const {
1507    return SourceRange(BuiltinLoc, RParenLoc);
1508  }
1509  static bool classof(const Stmt *T) {
1510    return T->getStmtClass() == ChooseExprClass;
1511  }
1512  static bool classof(const ChooseExpr *) { return true; }
1513
1514  // Iterators
1515  virtual child_iterator child_begin();
1516  virtual child_iterator child_end();
1517
1518  virtual void EmitImpl(llvm::Serializer& S) const;
1519  static ChooseExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1520};
1521
1522/// GNUNullExpr - Implements the GNU __null extension, which is a name
1523/// for a null pointer constant that has integral type (e.g., int or
1524/// long) and is the same size and alignment as a pointer. The __null
1525/// extension is typically only used by system headers, which define
1526/// NULL as __null in C++ rather than using 0 (which is an integer
1527/// that may not match the size of a pointer).
1528class GNUNullExpr : public Expr {
1529  /// TokenLoc - The location of the __null keyword.
1530  SourceLocation TokenLoc;
1531
1532public:
1533  GNUNullExpr(QualType Ty, SourceLocation Loc)
1534    : Expr(GNUNullExprClass, Ty), TokenLoc(Loc) { }
1535
1536  /// getTokenLocation - The location of the __null token.
1537  SourceLocation getTokenLocation() const { return TokenLoc; }
1538
1539  virtual SourceRange getSourceRange() const {
1540    return SourceRange(TokenLoc);
1541  }
1542  static bool classof(const Stmt *T) {
1543    return T->getStmtClass() == GNUNullExprClass;
1544  }
1545  static bool classof(const GNUNullExpr *) { return true; }
1546
1547  // Iterators
1548  virtual child_iterator child_begin();
1549  virtual child_iterator child_end();
1550
1551  virtual void EmitImpl(llvm::Serializer& S) const;
1552  static GNUNullExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1553};
1554
1555/// OverloadExpr - Clang builtin function __builtin_overload.
1556/// This AST node provides a way to overload functions in C.
1557///
1558/// The first argument is required to be a constant expression, for the number
1559/// of arguments passed to each candidate function.
1560///
1561/// The next N arguments, where N is the value of the constant expression,
1562/// are the values to be passed as arguments.
1563///
1564/// The rest of the arguments are values of pointer to function type, which
1565/// are the candidate functions for overloading.
1566///
1567/// The result is a equivalent to a CallExpr taking N arguments to the
1568/// candidate function whose parameter types match the types of the N arguments.
1569///
1570/// example: float Z = __builtin_overload(2, X, Y, modf, mod, modl);
1571/// If X and Y are long doubles, Z will assigned the result of modl(X, Y);
1572/// If X and Y are floats, Z will be assigned the result of modf(X, Y);
1573class OverloadExpr : public Expr {
1574  // SubExprs - the list of values passed to the __builtin_overload function.
1575  // SubExpr[0] is a constant expression
1576  // SubExpr[1-N] are the parameters to pass to the matching function call
1577  // SubExpr[N-...] are the candidate functions, of type pointer to function.
1578  Stmt **SubExprs;
1579
1580  // NumExprs - the size of the SubExprs array
1581  unsigned NumExprs;
1582
1583  // The index of the matching candidate function
1584  unsigned FnIndex;
1585
1586  SourceLocation BuiltinLoc;
1587  SourceLocation RParenLoc;
1588public:
1589  OverloadExpr(ASTContext& C, Expr **args, unsigned nexprs, unsigned idx,
1590               QualType t, SourceLocation bloc, SourceLocation rploc)
1591    : Expr(OverloadExprClass, t), NumExprs(nexprs), FnIndex(idx),
1592      BuiltinLoc(bloc), RParenLoc(rploc) {
1593    SubExprs = new (C) Stmt*[nexprs];
1594    for (unsigned i = 0; i != nexprs; ++i)
1595      SubExprs[i] = args[i];
1596  }
1597
1598  ~OverloadExpr() {}
1599
1600  void Destroy(ASTContext& C);
1601
1602  /// arg_begin - Return a pointer to the list of arguments that will be passed
1603  /// to the matching candidate function, skipping over the initial constant
1604  /// expression.
1605  typedef ConstExprIterator const_arg_iterator;
1606  const_arg_iterator arg_begin() const { return &SubExprs[0]+1; }
1607  const_arg_iterator arg_end(ASTContext& Ctx) const {
1608    return &SubExprs[0]+1+getNumArgs(Ctx);
1609  }
1610
1611  /// getNumArgs - Return the number of arguments to pass to the candidate
1612  /// functions.
1613  unsigned getNumArgs(ASTContext &Ctx) const {
1614    return getExpr(0)->getIntegerConstantExprValue(Ctx).getZExtValue();
1615  }
1616
1617  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
1618  /// constant expression, the actual arguments passed in, and the function
1619  /// pointers.
1620  unsigned getNumSubExprs() const { return NumExprs; }
1621
1622  /// getExpr - Return the Expr at the specified index.
1623  Expr *getExpr(unsigned Index) const {
1624    assert((Index < NumExprs) && "Arg access out of range!");
1625    return cast<Expr>(SubExprs[Index]);
1626  }
1627
1628  /// getFn - Return the matching candidate function for this OverloadExpr.
1629  Expr *getFn() const { return cast<Expr>(SubExprs[FnIndex]); }
1630
1631  virtual SourceRange getSourceRange() const {
1632    return SourceRange(BuiltinLoc, RParenLoc);
1633  }
1634  static bool classof(const Stmt *T) {
1635    return T->getStmtClass() == OverloadExprClass;
1636  }
1637  static bool classof(const OverloadExpr *) { return true; }
1638
1639  // Iterators
1640  virtual child_iterator child_begin();
1641  virtual child_iterator child_end();
1642
1643  virtual void EmitImpl(llvm::Serializer& S) const;
1644  static OverloadExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1645};
1646
1647/// VAArgExpr, used for the builtin function __builtin_va_start.
1648class VAArgExpr : public Expr {
1649  Stmt *Val;
1650  SourceLocation BuiltinLoc, RParenLoc;
1651public:
1652  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
1653    : Expr(VAArgExprClass, t),
1654      Val(e),
1655      BuiltinLoc(BLoc),
1656      RParenLoc(RPLoc) { }
1657
1658  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1659  Expr *getSubExpr() { return cast<Expr>(Val); }
1660  virtual SourceRange getSourceRange() const {
1661    return SourceRange(BuiltinLoc, RParenLoc);
1662  }
1663  static bool classof(const Stmt *T) {
1664    return T->getStmtClass() == VAArgExprClass;
1665  }
1666  static bool classof(const VAArgExpr *) { return true; }
1667
1668  // Iterators
1669  virtual child_iterator child_begin();
1670  virtual child_iterator child_end();
1671
1672  virtual void EmitImpl(llvm::Serializer& S) const;
1673  static VAArgExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1674};
1675
1676/// @brief Describes an C or C++ initializer list.
1677///
1678/// InitListExpr describes an initializer list, which can be used to
1679/// initialize objects of different types, including
1680/// struct/class/union types, arrays, and vectors. For example:
1681///
1682/// @code
1683/// struct foo x = { 1, { 2, 3 } };
1684/// @endcode
1685///
1686/// Prior to semantic analysis, an initializer list will represent the
1687/// initializer list as written by the user, but will have the
1688/// placeholder type "void". This initializer list is called the
1689/// syntactic form of the initializer, and may contain C99 designated
1690/// initializers (represented as DesignatedInitExprs), initializations
1691/// of subobject members without explicit braces, and so on. Clients
1692/// interested in the original syntax of the initializer list should
1693/// use the syntactic form of the initializer list.
1694///
1695/// After semantic analysis, the initializer list will represent the
1696/// semantic form of the initializer, where the initializations of all
1697/// subobjects are made explicit with nested InitListExpr nodes and
1698/// C99 designators have been eliminated by placing the designated
1699/// initializations into the subobject they initialize. Additionally,
1700/// any "holes" in the initialization, where no initializer has been
1701/// specified for a particular subobject, will be replaced with
1702/// implicitly-generated ImplicitValueInitExpr expressions that
1703/// value-initialize the subobjects. Note, however, that the
1704/// initializer lists may still have fewer initializers than there are
1705/// elements to initialize within the object.
1706///
1707/// Given the semantic form of the initializer list, one can retrieve
1708/// the original syntactic form of that initializer list (if it
1709/// exists) using getSyntacticForm(). Since many initializer lists
1710/// have the same syntactic and semantic forms, getSyntacticForm() may
1711/// return NULL, indicating that the current initializer list also
1712/// serves as its syntactic form.
1713class InitListExpr : public Expr {
1714  std::vector<Stmt *> InitExprs;
1715  SourceLocation LBraceLoc, RBraceLoc;
1716
1717  /// Contains the initializer list that describes the syntactic form
1718  /// written in the source code.
1719  InitListExpr *SyntacticForm;
1720
1721  /// If this initializer list initializes a union, specifies which
1722  /// field within the union will be initialized.
1723  FieldDecl *UnionFieldInit;
1724
1725  /// Whether this initializer list originally had a GNU array-range
1726  /// designator in it. This is a temporary marker used by CodeGen.
1727  bool HadArrayRangeDesignator;
1728
1729public:
1730  InitListExpr(SourceLocation lbraceloc, Expr **initexprs, unsigned numinits,
1731               SourceLocation rbraceloc);
1732
1733  unsigned getNumInits() const { return InitExprs.size(); }
1734
1735  const Expr* getInit(unsigned Init) const {
1736    assert(Init < getNumInits() && "Initializer access out of range!");
1737    return cast_or_null<Expr>(InitExprs[Init]);
1738  }
1739
1740  Expr* getInit(unsigned Init) {
1741    assert(Init < getNumInits() && "Initializer access out of range!");
1742    return cast_or_null<Expr>(InitExprs[Init]);
1743  }
1744
1745  void setInit(unsigned Init, Expr *expr) {
1746    assert(Init < getNumInits() && "Initializer access out of range!");
1747    InitExprs[Init] = expr;
1748  }
1749
1750  /// @brief Specify the number of initializers
1751  ///
1752  /// If there are more than @p NumInits initializers, the remaining
1753  /// initializers will be destroyed. If there are fewer than @p
1754  /// NumInits initializers, NULL expressions will be added for the
1755  /// unknown initializers.
1756  void resizeInits(ASTContext &Context, unsigned NumInits);
1757
1758  /// @brief Updates the initializer at index @p Init with the new
1759  /// expression @p expr, and returns the old expression at that
1760  /// location.
1761  ///
1762  /// When @p Init is out of range for this initializer list, the
1763  /// initializer list will be extended with NULL expressions to
1764  /// accomodate the new entry.
1765  Expr *updateInit(unsigned Init, Expr *expr);
1766
1767  /// \brief If this initializes a union, specifies which field in the
1768  /// union to initialize.
1769  ///
1770  /// Typically, this field is the first named field within the
1771  /// union. However, a designated initializer can specify the
1772  /// initialization of a different field within the union.
1773  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
1774  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
1775
1776  // Explicit InitListExpr's originate from source code (and have valid source
1777  // locations). Implicit InitListExpr's are created by the semantic analyzer.
1778  bool isExplicit() {
1779    return LBraceLoc.isValid() && RBraceLoc.isValid();
1780  }
1781
1782  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
1783
1784  /// @brief Retrieve the initializer list that describes the
1785  /// syntactic form of the initializer.
1786  ///
1787  ///
1788  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
1789  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
1790
1791  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
1792  void sawArrayRangeDesignator() {
1793    HadArrayRangeDesignator = true;
1794  }
1795
1796  virtual SourceRange getSourceRange() const {
1797    return SourceRange(LBraceLoc, RBraceLoc);
1798  }
1799  static bool classof(const Stmt *T) {
1800    return T->getStmtClass() == InitListExprClass;
1801  }
1802  static bool classof(const InitListExpr *) { return true; }
1803
1804  // Iterators
1805  virtual child_iterator child_begin();
1806  virtual child_iterator child_end();
1807
1808  typedef std::vector<Stmt *>::iterator iterator;
1809  typedef std::vector<Stmt *>::reverse_iterator reverse_iterator;
1810
1811  iterator begin() { return InitExprs.begin(); }
1812  iterator end() { return InitExprs.end(); }
1813  reverse_iterator rbegin() { return InitExprs.rbegin(); }
1814  reverse_iterator rend() { return InitExprs.rend(); }
1815
1816  // Serailization.
1817  virtual void EmitImpl(llvm::Serializer& S) const;
1818  static InitListExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
1819
1820private:
1821  // Used by serializer.
1822  InitListExpr() : Expr(InitListExprClass, QualType()) {}
1823};
1824
1825/// @brief Represents a C99 designated initializer expression.
1826///
1827/// A designated initializer expression (C99 6.7.8) contains one or
1828/// more designators (which can be field designators, array
1829/// designators, or GNU array-range designators) followed by an
1830/// expression that initializes the field or element(s) that the
1831/// designators refer to. For example, given:
1832///
1833/// @code
1834/// struct point {
1835///   double x;
1836///   double y;
1837/// };
1838/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1839/// @endcode
1840///
1841/// The InitListExpr contains three DesignatedInitExprs, the first of
1842/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
1843/// designators, one array designator for @c [2] followed by one field
1844/// designator for @c .y. The initalization expression will be 1.0.
1845class DesignatedInitExpr : public Expr {
1846  /// The location of the '=' or ':' prior to the actual initializer
1847  /// expression.
1848  SourceLocation EqualOrColonLoc;
1849
1850  /// Whether this designated initializer used the GNU deprecated ':'
1851  /// syntax rather than the C99 '=' syntax.
1852  bool UsesColonSyntax : 1;
1853
1854  /// The number of designators in this initializer expression.
1855  unsigned NumDesignators : 15;
1856
1857  /// The number of subexpressions of this initializer expression,
1858  /// which contains both the initializer and any additional
1859  /// expressions used by array and array-range designators.
1860  unsigned NumSubExprs : 16;
1861
1862  DesignatedInitExpr(QualType Ty, unsigned NumDesignators,
1863                     SourceLocation EqualOrColonLoc, bool UsesColonSyntax,
1864                     unsigned NumSubExprs)
1865    : Expr(DesignatedInitExprClass, Ty),
1866      EqualOrColonLoc(EqualOrColonLoc), UsesColonSyntax(UsesColonSyntax),
1867      NumDesignators(NumDesignators), NumSubExprs(NumSubExprs) { }
1868
1869public:
1870  /// A field designator, e.g., ".x".
1871  struct FieldDesignator {
1872    /// Refers to the field that is being initialized. The low bit
1873    /// of this field determines whether this is actually a pointer
1874    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
1875    /// initially constructed, a field designator will store an
1876    /// IdentifierInfo*. After semantic analysis has resolved that
1877    /// name, the field designator will instead store a FieldDecl*.
1878    uintptr_t NameOrField;
1879
1880    /// The location of the '.' in the designated initializer.
1881    unsigned DotLoc;
1882
1883    /// The location of the field name in the designated initializer.
1884    unsigned FieldLoc;
1885  };
1886
1887  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
1888  struct ArrayOrRangeDesignator {
1889    /// Location of the first index expression within the designated
1890    /// initializer expression's list of subexpressions.
1891    unsigned Index;
1892    /// The location of the '[' starting the array range designator.
1893    unsigned LBracketLoc;
1894    /// The location of the ellipsis separating the start and end
1895    /// indices. Only valid for GNU array-range designators.
1896    unsigned EllipsisLoc;
1897    /// The location of the ']' terminating the array range designator.
1898    unsigned RBracketLoc;
1899  };
1900
1901  /// @brief Represents a single C99 designator.
1902  ///
1903  /// @todo This class is infuriatingly similar to clang::Designator,
1904  /// but minor differences (storing indices vs. storing pointers)
1905  /// keep us from reusing it. Try harder, later, to rectify these
1906  /// differences.
1907  class Designator {
1908    /// @brief The kind of designator this describes.
1909    enum {
1910      FieldDesignator,
1911      ArrayDesignator,
1912      ArrayRangeDesignator
1913    } Kind;
1914
1915    union {
1916      /// A field designator, e.g., ".x".
1917      struct FieldDesignator Field;
1918      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
1919      struct ArrayOrRangeDesignator ArrayOrRange;
1920    };
1921    friend class DesignatedInitExpr;
1922
1923  public:
1924    /// @brief Initializes a field designator.
1925    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
1926               SourceLocation FieldLoc)
1927      : Kind(FieldDesignator) {
1928      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
1929      Field.DotLoc = DotLoc.getRawEncoding();
1930      Field.FieldLoc = FieldLoc.getRawEncoding();
1931    }
1932
1933    /// @brief Initializes an array designator.
1934    Designator(unsigned Index, SourceLocation LBracketLoc,
1935               SourceLocation RBracketLoc)
1936      : Kind(ArrayDesignator) {
1937      ArrayOrRange.Index = Index;
1938      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
1939      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
1940      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
1941    }
1942
1943    /// @brief Initializes a GNU array-range designator.
1944    Designator(unsigned Index, SourceLocation LBracketLoc,
1945               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
1946      : Kind(ArrayRangeDesignator) {
1947      ArrayOrRange.Index = Index;
1948      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
1949      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
1950      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
1951    }
1952
1953    bool isFieldDesignator() const { return Kind == FieldDesignator; }
1954    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
1955    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
1956
1957    IdentifierInfo * getFieldName();
1958
1959    FieldDecl *getField() {
1960      assert(Kind == FieldDesignator && "Only valid on a field designator");
1961      if (Field.NameOrField & 0x01)
1962        return 0;
1963      else
1964        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
1965    }
1966
1967    void setField(FieldDecl *FD) {
1968      assert(Kind == FieldDesignator && "Only valid on a field designator");
1969      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
1970    }
1971
1972    SourceLocation getDotLoc() const {
1973      assert(Kind == FieldDesignator && "Only valid on a field designator");
1974      return SourceLocation::getFromRawEncoding(Field.DotLoc);
1975    }
1976
1977    SourceLocation getFieldLoc() const {
1978      assert(Kind == FieldDesignator && "Only valid on a field designator");
1979      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
1980    }
1981
1982    SourceLocation getLBracketLoc() const {
1983      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
1984             "Only valid on an array or array-range designator");
1985      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
1986    }
1987
1988    SourceLocation getRBracketLoc() const {
1989      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
1990             "Only valid on an array or array-range designator");
1991      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
1992    }
1993
1994    SourceLocation getEllipsisLoc() const {
1995      assert(Kind == ArrayRangeDesignator &&
1996             "Only valid on an array-range designator");
1997      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
1998    }
1999
2000    SourceLocation getStartLocation() const {
2001      if (Kind == FieldDesignator)
2002        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
2003      else
2004        return getLBracketLoc();
2005    }
2006  };
2007
2008  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
2009                                    unsigned NumDesignators,
2010                                    Expr **IndexExprs, unsigned NumIndexExprs,
2011                                    SourceLocation EqualOrColonLoc,
2012                                    bool UsesColonSyntax, Expr *Init);
2013
2014  /// @brief Returns the number of designators in this initializer.
2015  unsigned size() const { return NumDesignators; }
2016
2017  // Iterator access to the designators.
2018  typedef Designator* designators_iterator;
2019  designators_iterator designators_begin();
2020  designators_iterator designators_end();
2021
2022  Expr *getArrayIndex(const Designator& D);
2023  Expr *getArrayRangeStart(const Designator& D);
2024  Expr *getArrayRangeEnd(const Designator& D);
2025
2026  /// @brief Retrieve the location of the '=' that precedes the
2027  /// initializer value itself, if present.
2028  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
2029
2030  /// @brief Determines whether this designated initializer used the
2031  /// GNU 'fieldname:' syntax or the C99 '=' syntax.
2032  bool usesColonSyntax() const { return UsesColonSyntax; }
2033
2034  /// @brief Retrieve the initializer value.
2035  Expr *getInit() const {
2036    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
2037  }
2038
2039  void setInit(Expr *init) {
2040    *child_begin() = init;
2041  }
2042
2043  virtual SourceRange getSourceRange() const;
2044
2045  static bool classof(const Stmt *T) {
2046    return T->getStmtClass() == DesignatedInitExprClass;
2047  }
2048  static bool classof(const DesignatedInitExpr *) { return true; }
2049
2050  // Iterators
2051  virtual child_iterator child_begin();
2052  virtual child_iterator child_end();
2053};
2054
2055/// \brief Represents an implicitly-generated value initialization of
2056/// an object of a given type.
2057///
2058/// Implicit value initializations occur within semantic initializer
2059/// list expressions (InitListExpr) as placeholders for subobject
2060/// initializations not explicitly specified by the user.
2061///
2062/// \see InitListExpr
2063class ImplicitValueInitExpr : public Expr {
2064public:
2065  explicit ImplicitValueInitExpr(QualType ty)
2066    : Expr(ImplicitValueInitExprClass, ty) { }
2067
2068  static bool classof(const Stmt *T) {
2069    return T->getStmtClass() == ImplicitValueInitExprClass;
2070  }
2071  static bool classof(const ImplicitValueInitExpr *) { return true; }
2072
2073  virtual SourceRange getSourceRange() const {
2074    return SourceRange();
2075  }
2076
2077  // Iterators
2078  virtual child_iterator child_begin();
2079  virtual child_iterator child_end();
2080};
2081
2082//===----------------------------------------------------------------------===//
2083// Clang Extensions
2084//===----------------------------------------------------------------------===//
2085
2086
2087/// ExtVectorElementExpr - This represents access to specific elements of a
2088/// vector, and may occur on the left hand side or right hand side.  For example
2089/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
2090///
2091/// Note that the base may have either vector or pointer to vector type, just
2092/// like a struct field reference.
2093///
2094class ExtVectorElementExpr : public Expr {
2095  Stmt *Base;
2096  IdentifierInfo &Accessor;
2097  SourceLocation AccessorLoc;
2098public:
2099  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
2100                       SourceLocation loc)
2101    : Expr(ExtVectorElementExprClass, ty),
2102      Base(base), Accessor(accessor), AccessorLoc(loc) {}
2103
2104  const Expr *getBase() const { return cast<Expr>(Base); }
2105  Expr *getBase() { return cast<Expr>(Base); }
2106
2107  IdentifierInfo &getAccessor() const { return Accessor; }
2108
2109  /// getNumElements - Get the number of components being selected.
2110  unsigned getNumElements() const;
2111
2112  /// containsDuplicateElements - Return true if any element access is
2113  /// repeated.
2114  bool containsDuplicateElements() const;
2115
2116  /// getEncodedElementAccess - Encode the elements accessed into an llvm
2117  /// aggregate Constant of ConstantInt(s).
2118  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
2119
2120  virtual SourceRange getSourceRange() const {
2121    return SourceRange(getBase()->getLocStart(), AccessorLoc);
2122  }
2123
2124  /// isArrow - Return true if the base expression is a pointer to vector,
2125  /// return false if the base expression is a vector.
2126  bool isArrow() const;
2127
2128  static bool classof(const Stmt *T) {
2129    return T->getStmtClass() == ExtVectorElementExprClass;
2130  }
2131  static bool classof(const ExtVectorElementExpr *) { return true; }
2132
2133  // Iterators
2134  virtual child_iterator child_begin();
2135  virtual child_iterator child_end();
2136
2137  virtual void EmitImpl(llvm::Serializer& S) const;
2138  static ExtVectorElementExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
2139};
2140
2141
2142/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
2143/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
2144class BlockExpr : public Expr {
2145protected:
2146  BlockDecl *TheBlock;
2147public:
2148  BlockExpr(BlockDecl *BD, QualType ty) : Expr(BlockExprClass, ty),
2149            TheBlock(BD) {}
2150
2151  const BlockDecl *getBlockDecl() const { return TheBlock; }
2152  BlockDecl *getBlockDecl() { return TheBlock; }
2153
2154  // Convenience functions for probing the underlying BlockDecl.
2155  SourceLocation getCaretLocation() const;
2156  const Stmt *getBody() const;
2157  Stmt *getBody();
2158
2159  virtual SourceRange getSourceRange() const {
2160    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
2161  }
2162
2163  /// getFunctionType - Return the underlying function type for this block.
2164  const FunctionType *getFunctionType() const;
2165
2166  static bool classof(const Stmt *T) {
2167    return T->getStmtClass() == BlockExprClass;
2168  }
2169  static bool classof(const BlockExpr *) { return true; }
2170
2171  // Iterators
2172  virtual child_iterator child_begin();
2173  virtual child_iterator child_end();
2174
2175  virtual void EmitImpl(llvm::Serializer& S) const;
2176  static BlockExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
2177};
2178
2179/// BlockDeclRefExpr - A reference to a declared variable, function,
2180/// enum, etc.
2181class BlockDeclRefExpr : public Expr {
2182  ValueDecl *D;
2183  SourceLocation Loc;
2184  bool IsByRef;
2185public:
2186  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef) :
2187       Expr(BlockDeclRefExprClass, t), D(d), Loc(l), IsByRef(ByRef) {}
2188
2189  ValueDecl *getDecl() { return D; }
2190  const ValueDecl *getDecl() const { return D; }
2191  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
2192
2193  bool isByRef() const { return IsByRef; }
2194
2195  static bool classof(const Stmt *T) {
2196    return T->getStmtClass() == BlockDeclRefExprClass;
2197  }
2198  static bool classof(const BlockDeclRefExpr *) { return true; }
2199
2200  // Iterators
2201  virtual child_iterator child_begin();
2202  virtual child_iterator child_end();
2203
2204  virtual void EmitImpl(llvm::Serializer& S) const;
2205  static BlockDeclRefExpr* CreateImpl(llvm::Deserializer& D, ASTContext& C);
2206};
2207
2208}  // end namespace clang
2209
2210#endif
2211