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