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