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