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