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