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