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