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