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