Expr.h revision ba0f61cf5363f80e3241dc754235dfb246afe320
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 "clang/AST/DeclAccessPair.h"
21#include "clang/AST/ASTVector.h"
22#include "clang/AST/UsuallyTinyPtrVector.h"
23#include "llvm/ADT/APSInt.h"
24#include "llvm/ADT/APFloat.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include <vector>
28
29namespace clang {
30  class ASTContext;
31  class APValue;
32  class Decl;
33  class IdentifierInfo;
34  class ParmVarDecl;
35  class NamedDecl;
36  class ValueDecl;
37  class BlockDecl;
38  class CXXBaseSpecifier;
39  class CXXOperatorCallExpr;
40  class CXXMemberCallExpr;
41  class TemplateArgumentLoc;
42  class TemplateArgumentListInfo;
43
44/// \brief A simple array of base specifiers.
45typedef UsuallyTinyPtrVector<const CXXBaseSpecifier> CXXBaseSpecifierArray;
46
47/// Expr - This represents one expression.  Note that Expr's are subclasses of
48/// Stmt.  This allows an expression to be transparently used any place a Stmt
49/// is required.
50///
51class Expr : public Stmt {
52  QualType TR;
53
54  virtual void ANCHOR(); // key function.
55protected:
56  /// TypeDependent - Whether this expression is type-dependent
57  /// (C++ [temp.dep.expr]).
58  bool TypeDependent : 1;
59
60  /// ValueDependent - Whether this expression is value-dependent
61  /// (C++ [temp.dep.constexpr]).
62  bool ValueDependent : 1;
63
64  Expr(StmtClass SC, QualType T, bool TD, bool VD)
65    : Stmt(SC), TypeDependent(TD), ValueDependent(VD) {
66    setType(T);
67  }
68
69  /// \brief Construct an empty expression.
70  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
71
72public:
73  /// \brief Increases the reference count for this expression.
74  ///
75  /// Invoke the Retain() operation when this expression
76  /// is being shared by another owner.
77  Expr *Retain() {
78    Stmt::Retain();
79    return this;
80  }
81
82  QualType getType() const { return TR; }
83  void setType(QualType t) {
84    // In C++, the type of an expression is always adjusted so that it
85    // will not have reference type an expression will never have
86    // reference type (C++ [expr]p6). Use
87    // QualType::getNonReferenceType() to retrieve the non-reference
88    // type. Additionally, inspect Expr::isLvalue to determine whether
89    // an expression that is adjusted in this manner should be
90    // considered an lvalue.
91    assert((t.isNull() || !t->isReferenceType()) &&
92           "Expressions can't have reference type");
93
94    TR = t;
95  }
96
97  /// isValueDependent - Determines whether this expression is
98  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
99  /// array bound of "Chars" in the following example is
100  /// value-dependent.
101  /// @code
102  /// template<int Size, char (&Chars)[Size]> struct meta_string;
103  /// @endcode
104  bool isValueDependent() const { return ValueDependent; }
105
106  /// \brief Set whether this expression is value-dependent or not.
107  void setValueDependent(bool VD) { ValueDependent = VD; }
108
109  /// isTypeDependent - Determines whether this expression is
110  /// type-dependent (C++ [temp.dep.expr]), which means that its type
111  /// could change from one template instantiation to the next. For
112  /// example, the expressions "x" and "x + y" are type-dependent in
113  /// the following code, but "y" is not type-dependent:
114  /// @code
115  /// template<typename T>
116  /// void add(T x, int y) {
117  ///   x + y;
118  /// }
119  /// @endcode
120  bool isTypeDependent() const { return TypeDependent; }
121
122  /// \brief Set whether this expression is type-dependent or not.
123  void setTypeDependent(bool TD) { TypeDependent = TD; }
124
125  /// SourceLocation tokens are not useful in isolation - they are low level
126  /// value objects created/interpreted by SourceManager. We assume AST
127  /// clients will have a pointer to the respective SourceManager.
128  virtual SourceRange getSourceRange() const = 0;
129
130  /// getExprLoc - Return the preferred location for the arrow when diagnosing
131  /// a problem with a generic expression.
132  virtual SourceLocation getExprLoc() const { return getLocStart(); }
133
134  /// isUnusedResultAWarning - Return true if this immediate expression should
135  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
136  /// with location to warn on and the source range[s] to report with the
137  /// warning.
138  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
139                              SourceRange &R2, ASTContext &Ctx) const;
140
141  /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
142  /// incomplete type other than void. Nonarray expressions that can be lvalues:
143  ///  - name, where name must be a variable
144  ///  - e[i]
145  ///  - (e), where e must be an lvalue
146  ///  - e.name, where e must be an lvalue
147  ///  - e->name
148  ///  - *e, the type of e cannot be a function type
149  ///  - string-constant
150  ///  - reference type [C++ [expr]]
151  ///  - b ? x : y, where x and y are lvalues of suitable types [C++]
152  ///
153  enum isLvalueResult {
154    LV_Valid,
155    LV_NotObjectType,
156    LV_IncompleteVoidType,
157    LV_DuplicateVectorComponents,
158    LV_InvalidExpression,
159    LV_MemberFunction,
160    LV_SubObjCPropertySetting,
161    LV_ClassTemporary
162  };
163  isLvalueResult isLvalue(ASTContext &Ctx) const;
164
165  // Same as above, but excluding checks for non-object and void types in C
166  isLvalueResult isLvalueInternal(ASTContext &Ctx) const;
167
168  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
169  /// does not have an incomplete type, does not have a const-qualified type,
170  /// and if it is a structure or union, does not have any member (including,
171  /// recursively, any member or element of all contained aggregates or unions)
172  /// with a const-qualified type.
173  ///
174  /// \param Loc [in] [out] - A source location which *may* be filled
175  /// in with the location of the expression making this a
176  /// non-modifiable lvalue, if specified.
177  enum isModifiableLvalueResult {
178    MLV_Valid,
179    MLV_NotObjectType,
180    MLV_IncompleteVoidType,
181    MLV_DuplicateVectorComponents,
182    MLV_InvalidExpression,
183    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
184    MLV_IncompleteType,
185    MLV_ConstQualified,
186    MLV_ArrayType,
187    MLV_NotBlockQualified,
188    MLV_ReadonlyProperty,
189    MLV_NoSetterProperty,
190    MLV_MemberFunction,
191    MLV_SubObjCPropertySetting,
192    MLV_ClassTemporary
193  };
194  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
195                                              SourceLocation *Loc = 0) const;
196
197  /// \brief If this expression refers to a bit-field, retrieve the
198  /// declaration of that bit-field.
199  FieldDecl *getBitField();
200
201  const FieldDecl *getBitField() const {
202    return const_cast<Expr*>(this)->getBitField();
203  }
204
205  /// \brief Returns whether this expression refers to a vector element.
206  bool refersToVectorElement() const;
207
208  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
209  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
210  /// but also int expressions which are produced by things like comparisons in
211  /// C.
212  bool isKnownToHaveBooleanValue() const;
213
214  /// isIntegerConstantExpr - Return true if this expression is a valid integer
215  /// constant expression, and, if so, return its value in Result.  If not a
216  /// valid i-c-e, return false and fill in Loc (if specified) with the location
217  /// of the invalid expression.
218  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
219                             SourceLocation *Loc = 0,
220                             bool isEvaluated = true) const;
221  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
222    llvm::APSInt X;
223    return isIntegerConstantExpr(X, Ctx, Loc);
224  }
225  /// isConstantInitializer - Returns true if this expression is a constant
226  /// initializer, which can be emitted at compile-time.
227  bool isConstantInitializer(ASTContext &Ctx) const;
228
229  /// EvalResult is a struct with detailed info about an evaluated expression.
230  struct EvalResult {
231    /// Val - This is the value the expression can be folded to.
232    APValue Val;
233
234    /// HasSideEffects - Whether the evaluated expression has side effects.
235    /// For example, (f() && 0) can be folded, but it still has side effects.
236    bool HasSideEffects;
237
238    /// Diag - If the expression is unfoldable, then Diag contains a note
239    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
240    /// position for the error, and DiagExpr is the expression that caused
241    /// the error.
242    /// If the expression is foldable, but not an integer constant expression,
243    /// Diag contains a note diagnostic that describes why it isn't an integer
244    /// constant expression. If the expression *is* an integer constant
245    /// expression, then Diag will be zero.
246    unsigned Diag;
247    const Expr *DiagExpr;
248    SourceLocation DiagLoc;
249
250    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
251
252    // isGlobalLValue - Return true if the evaluated lvalue expression
253    // is global.
254    bool isGlobalLValue() const;
255    // hasSideEffects - Return true if the evaluated expression has
256    // side effects.
257    bool hasSideEffects() const {
258      return HasSideEffects;
259    }
260  };
261
262  /// Evaluate - Return true if this is a constant which we can fold using
263  /// any crazy technique (that has nothing to do with language standards) that
264  /// we want to.  If this function returns true, it returns the folded constant
265  /// in Result.
266  bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
267
268  /// EvaluateAsBooleanCondition - Return true if this is a constant
269  /// which we we can fold and convert to a boolean condition using
270  /// any crazy technique that we want to.
271  bool EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const;
272
273  /// isEvaluatable - Call Evaluate to see if this expression can be constant
274  /// folded, but discard the result.
275  bool isEvaluatable(ASTContext &Ctx) const;
276
277  /// HasSideEffects - This routine returns true for all those expressions
278  /// which must be evaluated each time and must not be optimization away
279  /// or evaluated at compile time. Example is a function call, volatile
280  /// variable read.
281  bool HasSideEffects(ASTContext &Ctx) const;
282
283  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
284  /// must be called on an expression that constant folds to an integer.
285  llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
286
287  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
288  /// with link time known address.
289  bool EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const;
290
291  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
292  bool EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const;
293
294  /// \brief Enumeration used to describe how \c isNullPointerConstant()
295  /// should cope with value-dependent expressions.
296  enum NullPointerConstantValueDependence {
297    /// \brief Specifies that the expression should never be value-dependent.
298    NPC_NeverValueDependent = 0,
299
300    /// \brief Specifies that a value-dependent expression of integral or
301    /// dependent type should be considered a null pointer constant.
302    NPC_ValueDependentIsNull,
303
304    /// \brief Specifies that a value-dependent expression should be considered
305    /// to never be a null pointer constant.
306    NPC_ValueDependentIsNotNull
307  };
308
309  /// isNullPointerConstant - C99 6.3.2.3p3 -  Return true if this is either an
310  /// integer constant expression with the value zero, or if this is one that is
311  /// cast to void*.
312  bool isNullPointerConstant(ASTContext &Ctx,
313                             NullPointerConstantValueDependence NPC) const;
314
315  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
316  /// write barrier.
317  bool isOBJCGCCandidate(ASTContext &Ctx) const;
318
319  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
320  ///  its subexpression.  If that subexpression is also a ParenExpr,
321  ///  then this method recursively returns its subexpression, and so forth.
322  ///  Otherwise, the method returns the current Expr.
323  Expr *IgnoreParens();
324
325  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
326  /// or CastExprs, returning their operand.
327  Expr *IgnoreParenCasts();
328
329  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off any
330  /// ParenExpr or ImplicitCastExprs, returning their operand.
331  Expr *IgnoreParenImpCasts();
332
333  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
334  /// value (including ptr->int casts of the same size).  Strip off any
335  /// ParenExpr or CastExprs, returning their operand.
336  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
337
338  /// \brief Determine whether this expression is a default function argument.
339  ///
340  /// Default arguments are implicitly generated in the abstract syntax tree
341  /// by semantic analysis for function calls, object constructions, etc. in
342  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
343  /// this routine also looks through any implicit casts to determine whether
344  /// the expression is a default argument.
345  bool isDefaultArgument() const;
346
347  /// \brief Determine whether this expression directly creates a
348  /// temporary object (of class type).
349  bool isTemporaryObject() const { return getTemporaryObject() != 0; }
350
351  /// \brief If this expression directly creates a temporary object of
352  /// class type, return the expression that actually constructs that
353  /// temporary object.
354  const Expr *getTemporaryObject() const;
355
356  const Expr *IgnoreParens() const {
357    return const_cast<Expr*>(this)->IgnoreParens();
358  }
359  const Expr *IgnoreParenCasts() const {
360    return const_cast<Expr*>(this)->IgnoreParenCasts();
361  }
362  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
363    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
364  }
365
366  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
367  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
368
369  static bool classof(const Stmt *T) {
370    return T->getStmtClass() >= firstExprConstant &&
371           T->getStmtClass() <= lastExprConstant;
372  }
373  static bool classof(const Expr *) { return true; }
374};
375
376
377//===----------------------------------------------------------------------===//
378// Primary Expressions.
379//===----------------------------------------------------------------------===//
380
381/// \brief Represents the qualifier that may precede a C++ name, e.g., the
382/// "std::" in "std::sort".
383struct NameQualifier {
384  /// \brief The nested name specifier.
385  NestedNameSpecifier *NNS;
386
387  /// \brief The source range covered by the nested name specifier.
388  SourceRange Range;
389};
390
391/// \brief Represents an explicit template argument list in C++, e.g.,
392/// the "<int>" in "sort<int>".
393struct ExplicitTemplateArgumentList {
394  /// \brief The source location of the left angle bracket ('<');
395  SourceLocation LAngleLoc;
396
397  /// \brief The source location of the right angle bracket ('>');
398  SourceLocation RAngleLoc;
399
400  /// \brief The number of template arguments in TemplateArgs.
401  /// The actual template arguments (if any) are stored after the
402  /// ExplicitTemplateArgumentList structure.
403  unsigned NumTemplateArgs;
404
405  /// \brief Retrieve the template arguments
406  TemplateArgumentLoc *getTemplateArgs() {
407    return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
408  }
409
410  /// \brief Retrieve the template arguments
411  const TemplateArgumentLoc *getTemplateArgs() const {
412    return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
413  }
414
415  void initializeFrom(const TemplateArgumentListInfo &List);
416  void copyInto(TemplateArgumentListInfo &List) const;
417  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
418};
419
420/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
421/// enum, etc.
422class DeclRefExpr : public Expr {
423  enum {
424    // Flag on DecoratedD that specifies when this declaration reference
425    // expression has a C++ nested-name-specifier.
426    HasQualifierFlag = 0x01,
427    // Flag on DecoratedD that specifies when this declaration reference
428    // expression has an explicit C++ template argument list.
429    HasExplicitTemplateArgumentListFlag = 0x02
430  };
431
432  // DecoratedD - The declaration that we are referencing, plus two bits to
433  // indicate whether (1) the declaration's name was explicitly qualified and
434  // (2) the declaration's name was followed by an explicit template
435  // argument list.
436  llvm::PointerIntPair<ValueDecl *, 2> DecoratedD;
437
438  // Loc - The location of the declaration name itself.
439  SourceLocation Loc;
440
441  /// \brief Retrieve the qualifier that preceded the declaration name, if any.
442  NameQualifier *getNameQualifier() {
443    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
444      return 0;
445
446    return reinterpret_cast<NameQualifier *> (this + 1);
447  }
448
449  /// \brief Retrieve the qualifier that preceded the member name, if any.
450  const NameQualifier *getNameQualifier() const {
451    return const_cast<DeclRefExpr *>(this)->getNameQualifier();
452  }
453
454  /// \brief Retrieve the explicit template argument list that followed the
455  /// member template name, if any.
456  ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() {
457    if ((DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag) == 0)
458      return 0;
459
460    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
461      return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
462
463    return reinterpret_cast<ExplicitTemplateArgumentList *>(
464                                                      getNameQualifier() + 1);
465  }
466
467  /// \brief Retrieve the explicit template argument list that followed the
468  /// member template name, if any.
469  const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const {
470    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgumentList();
471  }
472
473  DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
474              ValueDecl *D, SourceLocation NameLoc,
475              const TemplateArgumentListInfo *TemplateArgs,
476              QualType T);
477
478protected:
479  /// \brief Computes the type- and value-dependence flags for this
480  /// declaration reference expression.
481  void computeDependence();
482
483  DeclRefExpr(StmtClass SC, ValueDecl *d, QualType t, SourceLocation l) :
484    Expr(SC, t, false, false), DecoratedD(d, 0), Loc(l) {
485    computeDependence();
486  }
487
488public:
489  DeclRefExpr(ValueDecl *d, QualType t, SourceLocation l) :
490    Expr(DeclRefExprClass, t, false, false), DecoratedD(d, 0), Loc(l) {
491    computeDependence();
492  }
493
494  /// \brief Construct an empty declaration reference expression.
495  explicit DeclRefExpr(EmptyShell Empty)
496    : Expr(DeclRefExprClass, Empty) { }
497
498  static DeclRefExpr *Create(ASTContext &Context,
499                             NestedNameSpecifier *Qualifier,
500                             SourceRange QualifierRange,
501                             ValueDecl *D,
502                             SourceLocation NameLoc,
503                             QualType T,
504                             const TemplateArgumentListInfo *TemplateArgs = 0);
505
506  ValueDecl *getDecl() { return DecoratedD.getPointer(); }
507  const ValueDecl *getDecl() const { return DecoratedD.getPointer(); }
508  void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); }
509
510  SourceLocation getLocation() const { return Loc; }
511  void setLocation(SourceLocation L) { Loc = L; }
512  virtual SourceRange getSourceRange() const;
513
514  /// \brief Determine whether this declaration reference was preceded by a
515  /// C++ nested-name-specifier, e.g., \c N::foo.
516  bool hasQualifier() const { return DecoratedD.getInt() & HasQualifierFlag; }
517
518  /// \brief If the name was qualified, retrieves the source range of
519  /// the nested-name-specifier that precedes the name. Otherwise,
520  /// returns an empty source range.
521  SourceRange getQualifierRange() const {
522    if (!hasQualifier())
523      return SourceRange();
524
525    return getNameQualifier()->Range;
526  }
527
528  /// \brief If the name was qualified, retrieves the nested-name-specifier
529  /// that precedes the name. Otherwise, returns NULL.
530  NestedNameSpecifier *getQualifier() const {
531    if (!hasQualifier())
532      return 0;
533
534    return getNameQualifier()->NNS;
535  }
536
537  /// \brief Determines whether this member expression actually had a C++
538  /// template argument list explicitly specified, e.g., x.f<int>.
539  bool hasExplicitTemplateArgumentList() const {
540    return DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag;
541  }
542
543  /// \brief Copies the template arguments (if present) into the given
544  /// structure.
545  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
546    if (hasExplicitTemplateArgumentList())
547      getExplicitTemplateArgumentList()->copyInto(List);
548  }
549
550  /// \brief Retrieve the location of the left angle bracket following the
551  /// member name ('<'), if any.
552  SourceLocation getLAngleLoc() const {
553    if (!hasExplicitTemplateArgumentList())
554      return SourceLocation();
555
556    return getExplicitTemplateArgumentList()->LAngleLoc;
557  }
558
559  /// \brief Retrieve the template arguments provided as part of this
560  /// template-id.
561  const TemplateArgumentLoc *getTemplateArgs() const {
562    if (!hasExplicitTemplateArgumentList())
563      return 0;
564
565    return getExplicitTemplateArgumentList()->getTemplateArgs();
566  }
567
568  /// \brief Retrieve the number of template arguments provided as part of this
569  /// template-id.
570  unsigned getNumTemplateArgs() const {
571    if (!hasExplicitTemplateArgumentList())
572      return 0;
573
574    return getExplicitTemplateArgumentList()->NumTemplateArgs;
575  }
576
577  /// \brief Retrieve the location of the right angle bracket following the
578  /// template arguments ('>').
579  SourceLocation getRAngleLoc() const {
580    if (!hasExplicitTemplateArgumentList())
581      return SourceLocation();
582
583    return getExplicitTemplateArgumentList()->RAngleLoc;
584  }
585
586  static bool classof(const Stmt *T) {
587    return T->getStmtClass() == DeclRefExprClass;
588  }
589  static bool classof(const DeclRefExpr *) { return true; }
590
591  // Iterators
592  virtual child_iterator child_begin();
593  virtual child_iterator child_end();
594};
595
596/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
597class PredefinedExpr : public Expr {
598public:
599  enum IdentType {
600    Func,
601    Function,
602    PrettyFunction,
603    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
604    /// 'virtual' keyword is omitted for virtual member functions.
605    PrettyFunctionNoVirtual
606  };
607
608private:
609  SourceLocation Loc;
610  IdentType Type;
611public:
612  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
613    : Expr(PredefinedExprClass, type, type->isDependentType(),
614           type->isDependentType()), Loc(l), Type(IT) {}
615
616  /// \brief Construct an empty predefined expression.
617  explicit PredefinedExpr(EmptyShell Empty)
618    : Expr(PredefinedExprClass, Empty) { }
619
620  IdentType getIdentType() const { return Type; }
621  void setIdentType(IdentType IT) { Type = IT; }
622
623  SourceLocation getLocation() const { return Loc; }
624  void setLocation(SourceLocation L) { Loc = L; }
625
626  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
627
628  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
629
630  static bool classof(const Stmt *T) {
631    return T->getStmtClass() == PredefinedExprClass;
632  }
633  static bool classof(const PredefinedExpr *) { return true; }
634
635  // Iterators
636  virtual child_iterator child_begin();
637  virtual child_iterator child_end();
638};
639
640class IntegerLiteral : public Expr {
641  llvm::APInt Value;
642  SourceLocation Loc;
643public:
644  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
645  // or UnsignedLongLongTy
646  IntegerLiteral(const llvm::APInt &V, QualType type, SourceLocation l)
647    : Expr(IntegerLiteralClass, type, false, false), Value(V), Loc(l) {
648    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
649  }
650
651  /// \brief Construct an empty integer literal.
652  explicit IntegerLiteral(EmptyShell Empty)
653    : Expr(IntegerLiteralClass, Empty) { }
654
655  const llvm::APInt &getValue() const { return Value; }
656  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
657
658  /// \brief Retrieve the location of the literal.
659  SourceLocation getLocation() const { return Loc; }
660
661  void setValue(const llvm::APInt &Val) { Value = Val; }
662  void setLocation(SourceLocation Location) { Loc = Location; }
663
664  static bool classof(const Stmt *T) {
665    return T->getStmtClass() == IntegerLiteralClass;
666  }
667  static bool classof(const IntegerLiteral *) { return true; }
668
669  // Iterators
670  virtual child_iterator child_begin();
671  virtual child_iterator child_end();
672};
673
674class CharacterLiteral : public Expr {
675  unsigned Value;
676  SourceLocation Loc;
677  bool IsWide;
678public:
679  // type should be IntTy
680  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
681    : Expr(CharacterLiteralClass, type, false, false), Value(value), Loc(l),
682      IsWide(iswide) {
683  }
684
685  /// \brief Construct an empty character literal.
686  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
687
688  SourceLocation getLocation() const { return Loc; }
689  bool isWide() const { return IsWide; }
690
691  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
692
693  unsigned getValue() const { return Value; }
694
695  void setLocation(SourceLocation Location) { Loc = Location; }
696  void setWide(bool W) { IsWide = W; }
697  void setValue(unsigned Val) { Value = Val; }
698
699  static bool classof(const Stmt *T) {
700    return T->getStmtClass() == CharacterLiteralClass;
701  }
702  static bool classof(const CharacterLiteral *) { return true; }
703
704  // Iterators
705  virtual child_iterator child_begin();
706  virtual child_iterator child_end();
707};
708
709class FloatingLiteral : public Expr {
710  llvm::APFloat Value;
711  bool IsExact : 1;
712  SourceLocation Loc;
713public:
714  FloatingLiteral(const llvm::APFloat &V, bool isexact,
715                  QualType Type, SourceLocation L)
716    : Expr(FloatingLiteralClass, Type, false, false), Value(V),
717      IsExact(isexact), Loc(L) {}
718
719  /// \brief Construct an empty floating-point literal.
720  explicit FloatingLiteral(EmptyShell Empty)
721    : Expr(FloatingLiteralClass, Empty), Value(0.0) { }
722
723  const llvm::APFloat &getValue() const { return Value; }
724  void setValue(const llvm::APFloat &Val) { Value = Val; }
725
726  bool isExact() const { return IsExact; }
727  void setExact(bool E) { IsExact = E; }
728
729  /// getValueAsApproximateDouble - This returns the value as an inaccurate
730  /// double.  Note that this may cause loss of precision, but is useful for
731  /// debugging dumps, etc.
732  double getValueAsApproximateDouble() const;
733
734  SourceLocation getLocation() const { return Loc; }
735  void setLocation(SourceLocation L) { Loc = L; }
736
737  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
738
739  static bool classof(const Stmt *T) {
740    return T->getStmtClass() == FloatingLiteralClass;
741  }
742  static bool classof(const FloatingLiteral *) { return true; }
743
744  // Iterators
745  virtual child_iterator child_begin();
746  virtual child_iterator child_end();
747};
748
749/// ImaginaryLiteral - We support imaginary integer and floating point literals,
750/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
751/// IntegerLiteral classes.  Instances of this class always have a Complex type
752/// whose element type matches the subexpression.
753///
754class ImaginaryLiteral : public Expr {
755  Stmt *Val;
756public:
757  ImaginaryLiteral(Expr *val, QualType Ty)
758    : Expr(ImaginaryLiteralClass, Ty, false, false), Val(val) {}
759
760  /// \brief Build an empty imaginary literal.
761  explicit ImaginaryLiteral(EmptyShell Empty)
762    : Expr(ImaginaryLiteralClass, Empty) { }
763
764  const Expr *getSubExpr() const { return cast<Expr>(Val); }
765  Expr *getSubExpr() { return cast<Expr>(Val); }
766  void setSubExpr(Expr *E) { Val = E; }
767
768  virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
769  static bool classof(const Stmt *T) {
770    return T->getStmtClass() == ImaginaryLiteralClass;
771  }
772  static bool classof(const ImaginaryLiteral *) { return true; }
773
774  // Iterators
775  virtual child_iterator child_begin();
776  virtual child_iterator child_end();
777};
778
779/// StringLiteral - This represents a string literal expression, e.g. "foo"
780/// or L"bar" (wide strings).  The actual string is returned by getStrData()
781/// is NOT null-terminated, and the length of the string is determined by
782/// calling getByteLength().  The C type for a string is always a
783/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
784/// not.
785///
786/// Note that strings in C can be formed by concatenation of multiple string
787/// literal pptokens in translation phase #6.  This keeps track of the locations
788/// of each of these pieces.
789///
790/// Strings in C can also be truncated and extended by assigning into arrays,
791/// e.g. with constructs like:
792///   char X[2] = "foobar";
793/// In this case, getByteLength() will return 6, but the string literal will
794/// have type "char[2]".
795class StringLiteral : public Expr {
796  const char *StrData;
797  unsigned ByteLength;
798  bool IsWide;
799  unsigned NumConcatenated;
800  SourceLocation TokLocs[1];
801
802  StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, false, false) {}
803
804protected:
805  virtual void DoDestroy(ASTContext &C);
806
807public:
808  /// This is the "fully general" constructor that allows representation of
809  /// strings formed from multiple concatenated tokens.
810  static StringLiteral *Create(ASTContext &C, const char *StrData,
811                               unsigned ByteLength, bool Wide, QualType Ty,
812                               const SourceLocation *Loc, unsigned NumStrs);
813
814  /// Simple constructor for string literals made from one token.
815  static StringLiteral *Create(ASTContext &C, const char *StrData,
816                               unsigned ByteLength,
817                               bool Wide, QualType Ty, SourceLocation Loc) {
818    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
819  }
820
821  /// \brief Construct an empty string literal.
822  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
823
824  llvm::StringRef getString() const {
825    return llvm::StringRef(StrData, ByteLength);
826  }
827  // FIXME: These are deprecated, replace with StringRef.
828  const char *getStrData() const { return StrData; }
829  unsigned getByteLength() const { return ByteLength; }
830
831  /// \brief Sets the string data to the given string data.
832  void setString(ASTContext &C, llvm::StringRef Str);
833
834  bool isWide() const { return IsWide; }
835  void setWide(bool W) { IsWide = W; }
836
837  bool containsNonAsciiOrNull() const {
838    llvm::StringRef Str = getString();
839    for (unsigned i = 0, e = Str.size(); i != e; ++i)
840      if (!isascii(Str[i]) || !Str[i])
841        return true;
842    return false;
843  }
844  /// getNumConcatenated - Get the number of string literal tokens that were
845  /// concatenated in translation phase #6 to form this string literal.
846  unsigned getNumConcatenated() const { return NumConcatenated; }
847
848  SourceLocation getStrTokenLoc(unsigned TokNum) const {
849    assert(TokNum < NumConcatenated && "Invalid tok number");
850    return TokLocs[TokNum];
851  }
852  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
853    assert(TokNum < NumConcatenated && "Invalid tok number");
854    TokLocs[TokNum] = L;
855  }
856
857  typedef const SourceLocation *tokloc_iterator;
858  tokloc_iterator tokloc_begin() const { return TokLocs; }
859  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
860
861  virtual SourceRange getSourceRange() const {
862    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
863  }
864  static bool classof(const Stmt *T) {
865    return T->getStmtClass() == StringLiteralClass;
866  }
867  static bool classof(const StringLiteral *) { return true; }
868
869  // Iterators
870  virtual child_iterator child_begin();
871  virtual child_iterator child_end();
872};
873
874/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
875/// AST node is only formed if full location information is requested.
876class ParenExpr : public Expr {
877  SourceLocation L, R;
878  Stmt *Val;
879public:
880  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
881    : Expr(ParenExprClass, val->getType(),
882           val->isTypeDependent(), val->isValueDependent()),
883      L(l), R(r), Val(val) {}
884
885  /// \brief Construct an empty parenthesized expression.
886  explicit ParenExpr(EmptyShell Empty)
887    : Expr(ParenExprClass, Empty) { }
888
889  const Expr *getSubExpr() const { return cast<Expr>(Val); }
890  Expr *getSubExpr() { return cast<Expr>(Val); }
891  void setSubExpr(Expr *E) { Val = E; }
892
893  virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
894
895  /// \brief Get the location of the left parentheses '('.
896  SourceLocation getLParen() const { return L; }
897  void setLParen(SourceLocation Loc) { L = Loc; }
898
899  /// \brief Get the location of the right parentheses ')'.
900  SourceLocation getRParen() const { return R; }
901  void setRParen(SourceLocation Loc) { R = Loc; }
902
903  static bool classof(const Stmt *T) {
904    return T->getStmtClass() == ParenExprClass;
905  }
906  static bool classof(const ParenExpr *) { return true; }
907
908  // Iterators
909  virtual child_iterator child_begin();
910  virtual child_iterator child_end();
911};
912
913
914/// UnaryOperator - This represents the unary-expression's (except sizeof and
915/// alignof), the postinc/postdec operators from postfix-expression, and various
916/// extensions.
917///
918/// Notes on various nodes:
919///
920/// Real/Imag - These return the real/imag part of a complex operand.  If
921///   applied to a non-complex value, the former returns its operand and the
922///   later returns zero in the type of the operand.
923///
924/// __builtin_offsetof(type, a.b[10]) is represented as a unary operator whose
925///   subexpression is a compound literal with the various MemberExpr and
926///   ArraySubscriptExpr's applied to it. (This is only used in C)
927///
928class UnaryOperator : public Expr {
929public:
930  // Note that additions to this should also update the StmtVisitor class.
931  enum Opcode {
932    PostInc, PostDec, // [C99 6.5.2.4] Postfix increment and decrement operators
933    PreInc, PreDec,   // [C99 6.5.3.1] Prefix increment and decrement operators.
934    AddrOf, Deref,    // [C99 6.5.3.2] Address and indirection operators.
935    Plus, Minus,      // [C99 6.5.3.3] Unary arithmetic operators.
936    Not, LNot,        // [C99 6.5.3.3] Unary arithmetic operators.
937    Real, Imag,       // "__real expr"/"__imag expr" Extension.
938    Extension,        // __extension__ marker.
939    OffsetOf          // __builtin_offsetof
940  };
941private:
942  Stmt *Val;
943  Opcode Opc;
944  SourceLocation Loc;
945public:
946
947  UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
948    : Expr(UnaryOperatorClass, type,
949           input->isTypeDependent() && opc != OffsetOf,
950           input->isValueDependent()),
951      Val(input), Opc(opc), Loc(l) {}
952
953  /// \brief Build an empty unary operator.
954  explicit UnaryOperator(EmptyShell Empty)
955    : Expr(UnaryOperatorClass, Empty), Opc(AddrOf) { }
956
957  Opcode getOpcode() const { return Opc; }
958  void setOpcode(Opcode O) { Opc = O; }
959
960  Expr *getSubExpr() const { return cast<Expr>(Val); }
961  void setSubExpr(Expr *E) { Val = E; }
962
963  /// getOperatorLoc - Return the location of the operator.
964  SourceLocation getOperatorLoc() const { return Loc; }
965  void setOperatorLoc(SourceLocation L) { Loc = L; }
966
967  /// isPostfix - Return true if this is a postfix operation, like x++.
968  static bool isPostfix(Opcode Op) {
969    return Op == PostInc || Op == PostDec;
970  }
971
972  /// isPostfix - Return true if this is a prefix operation, like --x.
973  static bool isPrefix(Opcode Op) {
974    return Op == PreInc || Op == PreDec;
975  }
976
977  bool isPrefix() const { return isPrefix(Opc); }
978  bool isPostfix() const { return isPostfix(Opc); }
979  bool isIncrementOp() const {return Opc==PreInc || Opc==PostInc; }
980  bool isIncrementDecrementOp() const { return Opc>=PostInc && Opc<=PreDec; }
981  bool isOffsetOfOp() const { return Opc == OffsetOf; }
982  static bool isArithmeticOp(Opcode Op) { return Op >= Plus && Op <= LNot; }
983  bool isArithmeticOp() const { return isArithmeticOp(Opc); }
984
985  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
986  /// corresponds to, e.g. "sizeof" or "[pre]++"
987  static const char *getOpcodeStr(Opcode Op);
988
989  /// \brief Retrieve the unary opcode that corresponds to the given
990  /// overloaded operator.
991  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
992
993  /// \brief Retrieve the overloaded operator kind that corresponds to
994  /// the given unary opcode.
995  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
996
997  virtual SourceRange getSourceRange() const {
998    if (isPostfix())
999      return SourceRange(Val->getLocStart(), Loc);
1000    else
1001      return SourceRange(Loc, Val->getLocEnd());
1002  }
1003  virtual SourceLocation getExprLoc() const { return Loc; }
1004
1005  static bool classof(const Stmt *T) {
1006    return T->getStmtClass() == UnaryOperatorClass;
1007  }
1008  static bool classof(const UnaryOperator *) { return true; }
1009
1010  // Iterators
1011  virtual child_iterator child_begin();
1012  virtual child_iterator child_end();
1013};
1014
1015/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1016/// offsetof(record-type, member-designator). For example, given:
1017/// @code
1018/// struct S {
1019///   float f;
1020///   double d;
1021/// };
1022/// struct T {
1023///   int i;
1024///   struct S s[10];
1025/// };
1026/// @endcode
1027/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1028
1029class OffsetOfExpr : public Expr {
1030public:
1031  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1032  class OffsetOfNode {
1033  public:
1034    /// \brief The kind of offsetof node we have.
1035    enum Kind {
1036      /// \brief An index into an array.
1037      Array = 0x00,
1038      /// \brief A field.
1039      Field = 0x01,
1040      /// \brief A field in a dependent type, known only by its name.
1041      Identifier = 0x02,
1042      /// \brief An implicit indirection through a C++ base class, when the
1043      /// field found is in a base class.
1044      Base = 0x03
1045    };
1046
1047  private:
1048    enum { MaskBits = 2, Mask = 0x03 };
1049
1050    /// \brief The source range that covers this part of the designator.
1051    SourceRange Range;
1052
1053    /// \brief The data describing the designator, which comes in three
1054    /// different forms, depending on the lower two bits.
1055    ///   - An unsigned index into the array of Expr*'s stored after this node
1056    ///     in memory, for [constant-expression] designators.
1057    ///   - A FieldDecl*, for references to a known field.
1058    ///   - An IdentifierInfo*, for references to a field with a given name
1059    ///     when the class type is dependent.
1060    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1061    ///     base class.
1062    uintptr_t Data;
1063
1064  public:
1065    /// \brief Create an offsetof node that refers to an array element.
1066    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1067                 SourceLocation RBracketLoc)
1068      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1069
1070    /// \brief Create an offsetof node that refers to a field.
1071    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1072                 SourceLocation NameLoc)
1073      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1074        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1075
1076    /// \brief Create an offsetof node that refers to an identifier.
1077    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1078                 SourceLocation NameLoc)
1079      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1080        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1081
1082    /// \brief Create an offsetof node that refers into a C++ base class.
1083    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1084      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1085
1086    /// \brief Determine what kind of offsetof node this is.
1087    Kind getKind() const {
1088      return static_cast<Kind>(Data & Mask);
1089    }
1090
1091    /// \brief For an array element node, returns the index into the array
1092    /// of expressions.
1093    unsigned getArrayExprIndex() const {
1094      assert(getKind() == Array);
1095      return Data >> 2;
1096    }
1097
1098    /// \brief For a field offsetof node, returns the field.
1099    FieldDecl *getField() const {
1100      assert(getKind() == Field);
1101      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1102    }
1103
1104    /// \brief For a field or identifier offsetof node, returns the name of
1105    /// the field.
1106    IdentifierInfo *getFieldName() const;
1107
1108    /// \brief For a base class node, returns the base specifier.
1109    CXXBaseSpecifier *getBase() const {
1110      assert(getKind() == Base);
1111      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1112    }
1113
1114    /// \brief Retrieve the source range that covers this offsetof node.
1115    ///
1116    /// For an array element node, the source range contains the locations of
1117    /// the square brackets. For a field or identifier node, the source range
1118    /// contains the location of the period (if there is one) and the
1119    /// identifier.
1120    SourceRange getRange() const { return Range; }
1121  };
1122
1123private:
1124
1125  SourceLocation OperatorLoc, RParenLoc;
1126  // Base type;
1127  TypeSourceInfo *TSInfo;
1128  // Number of sub-components (i.e. instances of OffsetOfNode).
1129  unsigned NumComps;
1130  // Number of sub-expressions (i.e. array subscript expressions).
1131  unsigned NumExprs;
1132
1133  OffsetOfExpr(ASTContext &C, QualType type,
1134               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1135               OffsetOfNode* compsPtr, unsigned numComps,
1136               Expr** exprsPtr, unsigned numExprs,
1137               SourceLocation RParenLoc);
1138
1139  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1140    : Expr(OffsetOfExprClass, EmptyShell()),
1141      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1142
1143public:
1144
1145  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1146                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1147                              OffsetOfNode* compsPtr, unsigned numComps,
1148                              Expr** exprsPtr, unsigned numExprs,
1149                              SourceLocation RParenLoc);
1150
1151  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1152                                   unsigned NumComps, unsigned NumExprs);
1153
1154  /// getOperatorLoc - Return the location of the operator.
1155  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1156  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1157
1158  /// \brief Return the location of the right parentheses.
1159  SourceLocation getRParenLoc() const { return RParenLoc; }
1160  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1161
1162  TypeSourceInfo *getTypeSourceInfo() const {
1163    return TSInfo;
1164  }
1165  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1166    TSInfo = tsi;
1167  }
1168
1169  const OffsetOfNode &getComponent(unsigned Idx) {
1170    assert(Idx < NumComps && "Subscript out of range");
1171    return reinterpret_cast<OffsetOfNode *> (this + 1)[Idx];
1172  }
1173
1174  void setComponent(unsigned Idx, OffsetOfNode ON) {
1175    assert(Idx < NumComps && "Subscript out of range");
1176    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1177  }
1178
1179  unsigned getNumComponents() const {
1180    return NumComps;
1181  }
1182
1183  Expr* getIndexExpr(unsigned Idx) {
1184    assert(Idx < NumExprs && "Subscript out of range");
1185    return reinterpret_cast<Expr **>(
1186                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1187  }
1188
1189  void setIndexExpr(unsigned Idx, Expr* E) {
1190    assert(Idx < NumComps && "Subscript out of range");
1191    reinterpret_cast<Expr **>(
1192                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1193  }
1194
1195  unsigned getNumExpressions() const {
1196    return NumExprs;
1197  }
1198
1199  virtual SourceRange getSourceRange() const {
1200    return SourceRange(OperatorLoc, RParenLoc);
1201  }
1202
1203  static bool classof(const Stmt *T) {
1204    return T->getStmtClass() == OffsetOfExprClass;
1205  }
1206
1207  static bool classof(const OffsetOfExpr *) { return true; }
1208
1209  // Iterators
1210  virtual child_iterator child_begin();
1211  virtual child_iterator child_end();
1212};
1213
1214/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
1215/// types and expressions.
1216class SizeOfAlignOfExpr : public Expr {
1217  bool isSizeof : 1;  // true if sizeof, false if alignof.
1218  bool isType : 1;    // true if operand is a type, false if an expression
1219  union {
1220    TypeSourceInfo *Ty;
1221    Stmt *Ex;
1222  } Argument;
1223  SourceLocation OpLoc, RParenLoc;
1224
1225protected:
1226  virtual void DoDestroy(ASTContext& C);
1227
1228public:
1229  SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo,
1230                    QualType resultType, SourceLocation op,
1231                    SourceLocation rp) :
1232      Expr(SizeOfAlignOfExprClass, resultType,
1233           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1234           // Value-dependent if the argument is type-dependent.
1235           TInfo->getType()->isDependentType()),
1236      isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
1237    Argument.Ty = TInfo;
1238  }
1239
1240  SizeOfAlignOfExpr(bool issizeof, Expr *E,
1241                    QualType resultType, SourceLocation op,
1242                    SourceLocation rp) :
1243      Expr(SizeOfAlignOfExprClass, resultType,
1244           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1245           // Value-dependent if the argument is type-dependent.
1246           E->isTypeDependent()),
1247      isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
1248    Argument.Ex = E;
1249  }
1250
1251  /// \brief Construct an empty sizeof/alignof expression.
1252  explicit SizeOfAlignOfExpr(EmptyShell Empty)
1253    : Expr(SizeOfAlignOfExprClass, Empty) { }
1254
1255  bool isSizeOf() const { return isSizeof; }
1256  void setSizeof(bool S) { isSizeof = S; }
1257
1258  bool isArgumentType() const { return isType; }
1259  QualType getArgumentType() const {
1260    return getArgumentTypeInfo()->getType();
1261  }
1262  TypeSourceInfo *getArgumentTypeInfo() const {
1263    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1264    return Argument.Ty;
1265  }
1266  Expr *getArgumentExpr() {
1267    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1268    return static_cast<Expr*>(Argument.Ex);
1269  }
1270  const Expr *getArgumentExpr() const {
1271    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
1272  }
1273
1274  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1275  void setArgument(TypeSourceInfo *TInfo) {
1276    Argument.Ty = TInfo;
1277    isType = true;
1278  }
1279
1280  /// Gets the argument type, or the type of the argument expression, whichever
1281  /// is appropriate.
1282  QualType getTypeOfArgument() const {
1283    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1284  }
1285
1286  SourceLocation getOperatorLoc() const { return OpLoc; }
1287  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1288
1289  SourceLocation getRParenLoc() const { return RParenLoc; }
1290  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1291
1292  virtual SourceRange getSourceRange() const {
1293    return SourceRange(OpLoc, RParenLoc);
1294  }
1295
1296  static bool classof(const Stmt *T) {
1297    return T->getStmtClass() == SizeOfAlignOfExprClass;
1298  }
1299  static bool classof(const SizeOfAlignOfExpr *) { return true; }
1300
1301  // Iterators
1302  virtual child_iterator child_begin();
1303  virtual child_iterator child_end();
1304};
1305
1306//===----------------------------------------------------------------------===//
1307// Postfix Operators.
1308//===----------------------------------------------------------------------===//
1309
1310/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1311class ArraySubscriptExpr : public Expr {
1312  enum { LHS, RHS, END_EXPR=2 };
1313  Stmt* SubExprs[END_EXPR];
1314  SourceLocation RBracketLoc;
1315public:
1316  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1317                     SourceLocation rbracketloc)
1318  : Expr(ArraySubscriptExprClass, t,
1319         lhs->isTypeDependent() || rhs->isTypeDependent(),
1320         lhs->isValueDependent() || rhs->isValueDependent()),
1321    RBracketLoc(rbracketloc) {
1322    SubExprs[LHS] = lhs;
1323    SubExprs[RHS] = rhs;
1324  }
1325
1326  /// \brief Create an empty array subscript expression.
1327  explicit ArraySubscriptExpr(EmptyShell Shell)
1328    : Expr(ArraySubscriptExprClass, Shell) { }
1329
1330  /// An array access can be written A[4] or 4[A] (both are equivalent).
1331  /// - getBase() and getIdx() always present the normalized view: A[4].
1332  ///    In this case getBase() returns "A" and getIdx() returns "4".
1333  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1334  ///    4[A] getLHS() returns "4".
1335  /// Note: Because vector element access is also written A[4] we must
1336  /// predicate the format conversion in getBase and getIdx only on the
1337  /// the type of the RHS, as it is possible for the LHS to be a vector of
1338  /// integer type
1339  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1340  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1341  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1342
1343  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1344  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1345  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1346
1347  Expr *getBase() {
1348    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1349  }
1350
1351  const Expr *getBase() const {
1352    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1353  }
1354
1355  Expr *getIdx() {
1356    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1357  }
1358
1359  const Expr *getIdx() const {
1360    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1361  }
1362
1363  virtual SourceRange getSourceRange() const {
1364    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1365  }
1366
1367  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1368  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1369
1370  virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1371
1372  static bool classof(const Stmt *T) {
1373    return T->getStmtClass() == ArraySubscriptExprClass;
1374  }
1375  static bool classof(const ArraySubscriptExpr *) { return true; }
1376
1377  // Iterators
1378  virtual child_iterator child_begin();
1379  virtual child_iterator child_end();
1380};
1381
1382
1383/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1384/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1385/// while its subclasses may represent alternative syntax that (semantically)
1386/// results in a function call. For example, CXXOperatorCallExpr is
1387/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1388/// "str1 + str2" to resolve to a function call.
1389class CallExpr : public Expr {
1390  enum { FN=0, ARGS_START=1 };
1391  Stmt **SubExprs;
1392  unsigned NumArgs;
1393  SourceLocation RParenLoc;
1394
1395protected:
1396  // This version of the constructor is for derived classes.
1397  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
1398           QualType t, SourceLocation rparenloc);
1399
1400  virtual void DoDestroy(ASTContext& C);
1401
1402public:
1403  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1404           SourceLocation rparenloc);
1405
1406  /// \brief Build an empty call expression.
1407  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1408
1409  ~CallExpr() {}
1410
1411  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1412  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1413  void setCallee(Expr *F) { SubExprs[FN] = F; }
1414
1415  Decl *getCalleeDecl();
1416  const Decl *getCalleeDecl() const {
1417    return const_cast<CallExpr*>(this)->getCalleeDecl();
1418  }
1419
1420  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1421  FunctionDecl *getDirectCallee();
1422  const FunctionDecl *getDirectCallee() const {
1423    return const_cast<CallExpr*>(this)->getDirectCallee();
1424  }
1425
1426  /// getNumArgs - Return the number of actual arguments to this call.
1427  ///
1428  unsigned getNumArgs() const { return NumArgs; }
1429
1430  /// getArg - Return the specified argument.
1431  Expr *getArg(unsigned Arg) {
1432    assert(Arg < NumArgs && "Arg access out of range!");
1433    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1434  }
1435  const Expr *getArg(unsigned Arg) const {
1436    assert(Arg < NumArgs && "Arg access out of range!");
1437    return cast<Expr>(SubExprs[Arg+ARGS_START]);
1438  }
1439
1440  /// setArg - Set the specified argument.
1441  void setArg(unsigned Arg, Expr *ArgExpr) {
1442    assert(Arg < NumArgs && "Arg access out of range!");
1443    SubExprs[Arg+ARGS_START] = ArgExpr;
1444  }
1445
1446  /// setNumArgs - This changes the number of arguments present in this call.
1447  /// Any orphaned expressions are deleted by this, and any new operands are set
1448  /// to null.
1449  void setNumArgs(ASTContext& C, unsigned NumArgs);
1450
1451  typedef ExprIterator arg_iterator;
1452  typedef ConstExprIterator const_arg_iterator;
1453
1454  arg_iterator arg_begin() { return SubExprs+ARGS_START; }
1455  arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
1456  const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
1457  const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
1458
1459  /// getNumCommas - Return the number of commas that must have been present in
1460  /// this function call.
1461  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1462
1463  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1464  /// not, return 0.
1465  unsigned isBuiltinCall(ASTContext &Context) const;
1466
1467  /// getCallReturnType - Get the return type of the call expr. This is not
1468  /// always the type of the expr itself, if the return type is a reference
1469  /// type.
1470  QualType getCallReturnType() const;
1471
1472  SourceLocation getRParenLoc() const { return RParenLoc; }
1473  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1474
1475  virtual SourceRange getSourceRange() const {
1476    return SourceRange(getCallee()->getLocStart(), RParenLoc);
1477  }
1478
1479  static bool classof(const Stmt *T) {
1480    return T->getStmtClass() >= firstCallExprConstant &&
1481           T->getStmtClass() <= lastCallExprConstant;
1482  }
1483  static bool classof(const CallExpr *) { return true; }
1484
1485  // Iterators
1486  virtual child_iterator child_begin();
1487  virtual child_iterator child_end();
1488};
1489
1490/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1491///
1492class MemberExpr : public Expr {
1493  /// Extra data stored in some member expressions.
1494  struct MemberNameQualifier : public NameQualifier {
1495    DeclAccessPair FoundDecl;
1496  };
1497
1498  /// Base - the expression for the base pointer or structure references.  In
1499  /// X.F, this is "X".
1500  Stmt *Base;
1501
1502  /// MemberDecl - This is the decl being referenced by the field/member name.
1503  /// In X.F, this is the decl referenced by F.
1504  ValueDecl *MemberDecl;
1505
1506  /// MemberLoc - This is the location of the member name.
1507  SourceLocation MemberLoc;
1508
1509  /// IsArrow - True if this is "X->F", false if this is "X.F".
1510  bool IsArrow : 1;
1511
1512  /// \brief True if this member expression used a nested-name-specifier to
1513  /// refer to the member, e.g., "x->Base::f", or found its member via a using
1514  /// declaration.  When true, a MemberNameQualifier
1515  /// structure is allocated immediately after the MemberExpr.
1516  bool HasQualifierOrFoundDecl : 1;
1517
1518  /// \brief True if this member expression specified a template argument list
1519  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1520  /// structure (and its TemplateArguments) are allocated immediately after
1521  /// the MemberExpr or, if the member expression also has a qualifier, after
1522  /// the MemberNameQualifier structure.
1523  bool HasExplicitTemplateArgumentList : 1;
1524
1525  /// \brief Retrieve the qualifier that preceded the member name, if any.
1526  MemberNameQualifier *getMemberQualifier() {
1527    assert(HasQualifierOrFoundDecl);
1528    return reinterpret_cast<MemberNameQualifier *> (this + 1);
1529  }
1530
1531  /// \brief Retrieve the qualifier that preceded the member name, if any.
1532  const MemberNameQualifier *getMemberQualifier() const {
1533    return const_cast<MemberExpr *>(this)->getMemberQualifier();
1534  }
1535
1536  /// \brief Retrieve the explicit template argument list that followed the
1537  /// member template name, if any.
1538  ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() {
1539    if (!HasExplicitTemplateArgumentList)
1540      return 0;
1541
1542    if (!HasQualifierOrFoundDecl)
1543      return reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
1544
1545    return reinterpret_cast<ExplicitTemplateArgumentList *>(
1546                                                      getMemberQualifier() + 1);
1547  }
1548
1549  /// \brief Retrieve the explicit template argument list that followed the
1550  /// member template name, if any.
1551  const ExplicitTemplateArgumentList *getExplicitTemplateArgumentList() const {
1552    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgumentList();
1553  }
1554
1555public:
1556  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1557             SourceLocation l, QualType ty)
1558    : Expr(MemberExprClass, ty,
1559           base->isTypeDependent(), base->isValueDependent()),
1560      Base(base), MemberDecl(memberdecl), MemberLoc(l), IsArrow(isarrow),
1561      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
1562
1563  /// \brief Build an empty member reference expression.
1564  explicit MemberExpr(EmptyShell Empty)
1565    : Expr(MemberExprClass, Empty), HasQualifierOrFoundDecl(false),
1566      HasExplicitTemplateArgumentList(false) { }
1567
1568  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
1569                            NestedNameSpecifier *qual, SourceRange qualrange,
1570                            ValueDecl *memberdecl, DeclAccessPair founddecl,
1571                            SourceLocation l,
1572                            const TemplateArgumentListInfo *targs,
1573                            QualType ty);
1574
1575  void setBase(Expr *E) { Base = E; }
1576  Expr *getBase() const { return cast<Expr>(Base); }
1577
1578  /// \brief Retrieve the member declaration to which this expression refers.
1579  ///
1580  /// The returned declaration will either be a FieldDecl or (in C++)
1581  /// a CXXMethodDecl.
1582  ValueDecl *getMemberDecl() const { return MemberDecl; }
1583  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
1584
1585  /// \brief Retrieves the declaration found by lookup.
1586  DeclAccessPair getFoundDecl() const {
1587    if (!HasQualifierOrFoundDecl)
1588      return DeclAccessPair::make(getMemberDecl(),
1589                                  getMemberDecl()->getAccess());
1590    return getMemberQualifier()->FoundDecl;
1591  }
1592
1593  /// \brief Determines whether this member expression actually had
1594  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
1595  /// x->Base::foo.
1596  bool hasQualifier() const { return getQualifier() != 0; }
1597
1598  /// \brief If the member name was qualified, retrieves the source range of
1599  /// the nested-name-specifier that precedes the member name. Otherwise,
1600  /// returns an empty source range.
1601  SourceRange getQualifierRange() const {
1602    if (!HasQualifierOrFoundDecl)
1603      return SourceRange();
1604
1605    return getMemberQualifier()->Range;
1606  }
1607
1608  /// \brief If the member name was qualified, retrieves the
1609  /// nested-name-specifier that precedes the member name. Otherwise, returns
1610  /// NULL.
1611  NestedNameSpecifier *getQualifier() const {
1612    if (!HasQualifierOrFoundDecl)
1613      return 0;
1614
1615    return getMemberQualifier()->NNS;
1616  }
1617
1618  /// \brief Determines whether this member expression actually had a C++
1619  /// template argument list explicitly specified, e.g., x.f<int>.
1620  bool hasExplicitTemplateArgumentList() const {
1621    return HasExplicitTemplateArgumentList;
1622  }
1623
1624  /// \brief Copies the template arguments (if present) into the given
1625  /// structure.
1626  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1627    if (hasExplicitTemplateArgumentList())
1628      getExplicitTemplateArgumentList()->copyInto(List);
1629  }
1630
1631  /// \brief Retrieve the location of the left angle bracket following the
1632  /// member name ('<'), if any.
1633  SourceLocation getLAngleLoc() const {
1634    if (!HasExplicitTemplateArgumentList)
1635      return SourceLocation();
1636
1637    return getExplicitTemplateArgumentList()->LAngleLoc;
1638  }
1639
1640  /// \brief Retrieve the template arguments provided as part of this
1641  /// template-id.
1642  const TemplateArgumentLoc *getTemplateArgs() const {
1643    if (!HasExplicitTemplateArgumentList)
1644      return 0;
1645
1646    return getExplicitTemplateArgumentList()->getTemplateArgs();
1647  }
1648
1649  /// \brief Retrieve the number of template arguments provided as part of this
1650  /// template-id.
1651  unsigned getNumTemplateArgs() const {
1652    if (!HasExplicitTemplateArgumentList)
1653      return 0;
1654
1655    return getExplicitTemplateArgumentList()->NumTemplateArgs;
1656  }
1657
1658  /// \brief Retrieve the location of the right angle bracket following the
1659  /// template arguments ('>').
1660  SourceLocation getRAngleLoc() const {
1661    if (!HasExplicitTemplateArgumentList)
1662      return SourceLocation();
1663
1664    return getExplicitTemplateArgumentList()->RAngleLoc;
1665  }
1666
1667  bool isArrow() const { return IsArrow; }
1668  void setArrow(bool A) { IsArrow = A; }
1669
1670  /// getMemberLoc - Return the location of the "member", in X->F, it is the
1671  /// location of 'F'.
1672  SourceLocation getMemberLoc() const { return MemberLoc; }
1673  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
1674
1675  virtual SourceRange getSourceRange() const {
1676    // If we have an implicit base (like a C++ implicit this),
1677    // make sure not to return its location
1678    SourceLocation EndLoc = MemberLoc;
1679    if (HasExplicitTemplateArgumentList)
1680      EndLoc = getRAngleLoc();
1681
1682    SourceLocation BaseLoc = getBase()->getLocStart();
1683    if (BaseLoc.isInvalid())
1684      return SourceRange(MemberLoc, EndLoc);
1685    return SourceRange(BaseLoc, EndLoc);
1686  }
1687
1688  virtual SourceLocation getExprLoc() const { return MemberLoc; }
1689
1690  static bool classof(const Stmt *T) {
1691    return T->getStmtClass() == MemberExprClass;
1692  }
1693  static bool classof(const MemberExpr *) { return true; }
1694
1695  // Iterators
1696  virtual child_iterator child_begin();
1697  virtual child_iterator child_end();
1698};
1699
1700/// CompoundLiteralExpr - [C99 6.5.2.5]
1701///
1702class CompoundLiteralExpr : public Expr {
1703  /// LParenLoc - If non-null, this is the location of the left paren in a
1704  /// compound literal like "(int){4}".  This can be null if this is a
1705  /// synthesized compound expression.
1706  SourceLocation LParenLoc;
1707
1708  /// The type as written.  This can be an incomplete array type, in
1709  /// which case the actual expression type will be different.
1710  TypeSourceInfo *TInfo;
1711  Stmt *Init;
1712  bool FileScope;
1713public:
1714  // FIXME: Can compound literals be value-dependent?
1715  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
1716                      QualType T, Expr *init, bool fileScope)
1717    : Expr(CompoundLiteralExprClass, T,
1718           tinfo->getType()->isDependentType(), false),
1719      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
1720
1721  /// \brief Construct an empty compound literal.
1722  explicit CompoundLiteralExpr(EmptyShell Empty)
1723    : Expr(CompoundLiteralExprClass, Empty) { }
1724
1725  const Expr *getInitializer() const { return cast<Expr>(Init); }
1726  Expr *getInitializer() { return cast<Expr>(Init); }
1727  void setInitializer(Expr *E) { Init = E; }
1728
1729  bool isFileScope() const { return FileScope; }
1730  void setFileScope(bool FS) { FileScope = FS; }
1731
1732  SourceLocation getLParenLoc() const { return LParenLoc; }
1733  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1734
1735  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
1736  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
1737
1738  virtual SourceRange getSourceRange() const {
1739    // FIXME: Init should never be null.
1740    if (!Init)
1741      return SourceRange();
1742    if (LParenLoc.isInvalid())
1743      return Init->getSourceRange();
1744    return SourceRange(LParenLoc, Init->getLocEnd());
1745  }
1746
1747  static bool classof(const Stmt *T) {
1748    return T->getStmtClass() == CompoundLiteralExprClass;
1749  }
1750  static bool classof(const CompoundLiteralExpr *) { return true; }
1751
1752  // Iterators
1753  virtual child_iterator child_begin();
1754  virtual child_iterator child_end();
1755};
1756
1757/// CastExpr - Base class for type casts, including both implicit
1758/// casts (ImplicitCastExpr) and explicit casts that have some
1759/// representation in the source code (ExplicitCastExpr's derived
1760/// classes).
1761class CastExpr : public Expr {
1762public:
1763  /// CastKind - the kind of cast this represents.
1764  enum CastKind {
1765    /// CK_Unknown - Unknown cast kind.
1766    /// FIXME: The goal is to get rid of this and make all casts have a
1767    /// kind so that the AST client doesn't have to try to figure out what's
1768    /// going on.
1769    CK_Unknown,
1770
1771    /// CK_BitCast - Used for reinterpret_cast.
1772    CK_BitCast,
1773
1774    /// CK_NoOp - Used for const_cast.
1775    CK_NoOp,
1776
1777    /// CK_BaseToDerived - Base to derived class casts.
1778    CK_BaseToDerived,
1779
1780    /// CK_DerivedToBase - Derived to base class casts.
1781    CK_DerivedToBase,
1782
1783    /// CK_UncheckedDerivedToBase - Derived to base class casts that
1784    /// assume that the derived pointer is not null.
1785    CK_UncheckedDerivedToBase,
1786
1787    /// CK_Dynamic - Dynamic cast.
1788    CK_Dynamic,
1789
1790    /// CK_ToUnion - Cast to union (GCC extension).
1791    CK_ToUnion,
1792
1793    /// CK_ArrayToPointerDecay - Array to pointer decay.
1794    CK_ArrayToPointerDecay,
1795
1796    // CK_FunctionToPointerDecay - Function to pointer decay.
1797    CK_FunctionToPointerDecay,
1798
1799    /// CK_NullToMemberPointer - Null pointer to member pointer.
1800    CK_NullToMemberPointer,
1801
1802    /// CK_BaseToDerivedMemberPointer - Member pointer in base class to
1803    /// member pointer in derived class.
1804    CK_BaseToDerivedMemberPointer,
1805
1806    /// CK_DerivedToBaseMemberPointer - Member pointer in derived class to
1807    /// member pointer in base class.
1808    CK_DerivedToBaseMemberPointer,
1809
1810    /// CK_UserDefinedConversion - Conversion using a user defined type
1811    /// conversion function.
1812    CK_UserDefinedConversion,
1813
1814    /// CK_ConstructorConversion - Conversion by constructor
1815    CK_ConstructorConversion,
1816
1817    /// CK_IntegralToPointer - Integral to pointer
1818    CK_IntegralToPointer,
1819
1820    /// CK_PointerToIntegral - Pointer to integral
1821    CK_PointerToIntegral,
1822
1823    /// CK_ToVoid - Cast to void.
1824    CK_ToVoid,
1825
1826    /// CK_VectorSplat - Casting from an integer/floating type to an extended
1827    /// vector type with the same element type as the src type. Splats the
1828    /// src expression into the destination expression.
1829    CK_VectorSplat,
1830
1831    /// CK_IntegralCast - Casting between integral types of different size.
1832    CK_IntegralCast,
1833
1834    /// CK_IntegralToFloating - Integral to floating point.
1835    CK_IntegralToFloating,
1836
1837    /// CK_FloatingToIntegral - Floating point to integral.
1838    CK_FloatingToIntegral,
1839
1840    /// CK_FloatingCast - Casting between floating types of different size.
1841    CK_FloatingCast,
1842
1843    /// CK_MemberPointerToBoolean - Member pointer to boolean
1844    CK_MemberPointerToBoolean,
1845
1846    /// CK_AnyPointerToObjCPointerCast - Casting any pointer to objective-c
1847    /// pointer
1848    CK_AnyPointerToObjCPointerCast,
1849    /// CK_AnyPointerToBlockPointerCast - Casting any pointer to block
1850    /// pointer
1851    CK_AnyPointerToBlockPointerCast
1852
1853  };
1854
1855private:
1856  CastKind Kind;
1857  Stmt *Op;
1858
1859  /// BasePath - For derived-to-base and base-to-derived casts, the base array
1860  /// contains the inheritance path.
1861  CXXBaseSpecifierArray BasePath;
1862
1863  void CheckBasePath() const {
1864#ifndef NDEBUG
1865    switch (getCastKind()) {
1866    case CK_DerivedToBase:
1867    case CK_UncheckedDerivedToBase:
1868    case CK_DerivedToBaseMemberPointer:
1869    case CK_BaseToDerived:
1870    case CK_BaseToDerivedMemberPointer:
1871      assert(!BasePath.empty() && "Cast kind should have a base path!");
1872      break;
1873
1874    // These should not have an inheritance path.
1875    case CK_Unknown:
1876    case CK_BitCast:
1877    case CK_NoOp:
1878    case CK_Dynamic:
1879    case CK_ToUnion:
1880    case CK_ArrayToPointerDecay:
1881    case CK_FunctionToPointerDecay:
1882    case CK_NullToMemberPointer:
1883    case CK_UserDefinedConversion:
1884    case CK_ConstructorConversion:
1885    case CK_IntegralToPointer:
1886    case CK_PointerToIntegral:
1887    case CK_ToVoid:
1888    case CK_VectorSplat:
1889    case CK_IntegralCast:
1890    case CK_IntegralToFloating:
1891    case CK_FloatingToIntegral:
1892    case CK_FloatingCast:
1893    case CK_MemberPointerToBoolean:
1894    case CK_AnyPointerToObjCPointerCast:
1895    case CK_AnyPointerToBlockPointerCast:
1896      assert(BasePath.empty() && "Cast kind should not have a base path!");
1897      break;
1898    }
1899#endif
1900  }
1901
1902protected:
1903  CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op,
1904           CXXBaseSpecifierArray BasePath) :
1905    Expr(SC, ty,
1906         // Cast expressions are type-dependent if the type is
1907         // dependent (C++ [temp.dep.expr]p3).
1908         ty->isDependentType(),
1909         // Cast expressions are value-dependent if the type is
1910         // dependent or if the subexpression is value-dependent.
1911         ty->isDependentType() || (op && op->isValueDependent())),
1912    Kind(kind), Op(op), BasePath(BasePath) {
1913      CheckBasePath();
1914    }
1915
1916  /// \brief Construct an empty cast.
1917  CastExpr(StmtClass SC, EmptyShell Empty)
1918    : Expr(SC, Empty) { }
1919
1920  virtual void DoDestroy(ASTContext &C);
1921
1922public:
1923  CastKind getCastKind() const { return Kind; }
1924  void setCastKind(CastKind K) { Kind = K; }
1925  const char *getCastKindName() const;
1926
1927  Expr *getSubExpr() { return cast<Expr>(Op); }
1928  const Expr *getSubExpr() const { return cast<Expr>(Op); }
1929  void setSubExpr(Expr *E) { Op = E; }
1930
1931  /// \brief Retrieve the cast subexpression as it was written in the source
1932  /// code, looking through any implicit casts or other intermediate nodes
1933  /// introduced by semantic analysis.
1934  Expr *getSubExprAsWritten();
1935  const Expr *getSubExprAsWritten() const {
1936    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
1937  }
1938
1939  const CXXBaseSpecifierArray& getBasePath() const { return BasePath; }
1940
1941  static bool classof(const Stmt *T) {
1942    return T->getStmtClass() >= firstCastExprConstant &&
1943           T->getStmtClass() <= lastCastExprConstant;
1944  }
1945  static bool classof(const CastExpr *) { return true; }
1946
1947  // Iterators
1948  virtual child_iterator child_begin();
1949  virtual child_iterator child_end();
1950};
1951
1952/// ImplicitCastExpr - Allows us to explicitly represent implicit type
1953/// conversions, which have no direct representation in the original
1954/// source code. For example: converting T[]->T*, void f()->void
1955/// (*f)(), float->double, short->int, etc.
1956///
1957/// In C, implicit casts always produce rvalues. However, in C++, an
1958/// implicit cast whose result is being bound to a reference will be
1959/// an lvalue. For example:
1960///
1961/// @code
1962/// class Base { };
1963/// class Derived : public Base { };
1964/// void f(Derived d) {
1965///   Base& b = d; // initializer is an ImplicitCastExpr to an lvalue of type Base
1966/// }
1967/// @endcode
1968class ImplicitCastExpr : public CastExpr {
1969  /// LvalueCast - Whether this cast produces an lvalue.
1970  bool LvalueCast;
1971
1972public:
1973  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
1974                   CXXBaseSpecifierArray BasePath, bool Lvalue)
1975    : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePath),
1976    LvalueCast(Lvalue) { }
1977
1978  /// \brief Construct an empty implicit cast.
1979  explicit ImplicitCastExpr(EmptyShell Shell)
1980    : CastExpr(ImplicitCastExprClass, Shell) { }
1981
1982  virtual SourceRange getSourceRange() const {
1983    return getSubExpr()->getSourceRange();
1984  }
1985
1986  /// isLvalueCast - Whether this cast produces an lvalue.
1987  bool isLvalueCast() const { return LvalueCast; }
1988
1989  /// setLvalueCast - Set whether this cast produces an lvalue.
1990  void setLvalueCast(bool Lvalue) { LvalueCast = Lvalue; }
1991
1992  static bool classof(const Stmt *T) {
1993    return T->getStmtClass() == ImplicitCastExprClass;
1994  }
1995  static bool classof(const ImplicitCastExpr *) { return true; }
1996};
1997
1998/// ExplicitCastExpr - An explicit cast written in the source
1999/// code.
2000///
2001/// This class is effectively an abstract class, because it provides
2002/// the basic representation of an explicitly-written cast without
2003/// specifying which kind of cast (C cast, functional cast, static
2004/// cast, etc.) was written; specific derived classes represent the
2005/// particular style of cast and its location information.
2006///
2007/// Unlike implicit casts, explicit cast nodes have two different
2008/// types: the type that was written into the source code, and the
2009/// actual type of the expression as determined by semantic
2010/// analysis. These types may differ slightly. For example, in C++ one
2011/// can cast to a reference type, which indicates that the resulting
2012/// expression will be an lvalue. The reference type, however, will
2013/// not be used as the type of the expression.
2014class ExplicitCastExpr : public CastExpr {
2015  /// TInfo - Source type info for the (written) type
2016  /// this expression is casting to.
2017  TypeSourceInfo *TInfo;
2018
2019protected:
2020  ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind,
2021                   Expr *op, CXXBaseSpecifierArray BasePath,
2022                   TypeSourceInfo *writtenTy)
2023    : CastExpr(SC, exprTy, kind, op, BasePath), TInfo(writtenTy) {}
2024
2025  /// \brief Construct an empty explicit cast.
2026  ExplicitCastExpr(StmtClass SC, EmptyShell Shell)
2027    : CastExpr(SC, Shell) { }
2028
2029public:
2030  /// getTypeInfoAsWritten - Returns the type source info for the type
2031  /// that this expression is casting to.
2032  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2033  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2034
2035  /// getTypeAsWritten - Returns the type that this expression is
2036  /// casting to, as written in the source code.
2037  QualType getTypeAsWritten() const { return TInfo->getType(); }
2038
2039  static bool classof(const Stmt *T) {
2040     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2041            T->getStmtClass() <= lastExplicitCastExprConstant;
2042  }
2043  static bool classof(const ExplicitCastExpr *) { return true; }
2044};
2045
2046/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2047/// cast in C++ (C++ [expr.cast]), which uses the syntax
2048/// (Type)expr. For example: @c (int)f.
2049class CStyleCastExpr : public ExplicitCastExpr {
2050  SourceLocation LPLoc; // the location of the left paren
2051  SourceLocation RPLoc; // the location of the right paren
2052public:
2053  CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op,
2054                 CXXBaseSpecifierArray BasePath, TypeSourceInfo *writtenTy,
2055                 SourceLocation l, SourceLocation r)
2056    : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, BasePath,
2057                       writtenTy), LPLoc(l), RPLoc(r) {}
2058
2059  /// \brief Construct an empty C-style explicit cast.
2060  explicit CStyleCastExpr(EmptyShell Shell)
2061    : ExplicitCastExpr(CStyleCastExprClass, Shell) { }
2062
2063  SourceLocation getLParenLoc() const { return LPLoc; }
2064  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2065
2066  SourceLocation getRParenLoc() const { return RPLoc; }
2067  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2068
2069  virtual SourceRange getSourceRange() const {
2070    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2071  }
2072  static bool classof(const Stmt *T) {
2073    return T->getStmtClass() == CStyleCastExprClass;
2074  }
2075  static bool classof(const CStyleCastExpr *) { return true; }
2076};
2077
2078/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2079///
2080/// This expression node kind describes a builtin binary operation,
2081/// such as "x + y" for integer values "x" and "y". The operands will
2082/// already have been converted to appropriate types (e.g., by
2083/// performing promotions or conversions).
2084///
2085/// In C++, where operators may be overloaded, a different kind of
2086/// expression node (CXXOperatorCallExpr) is used to express the
2087/// invocation of an overloaded operator with operator syntax. Within
2088/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2089/// used to store an expression "x + y" depends on the subexpressions
2090/// for x and y. If neither x or y is type-dependent, and the "+"
2091/// operator resolves to a built-in operation, BinaryOperator will be
2092/// used to express the computation (x and y may still be
2093/// value-dependent). If either x or y is type-dependent, or if the
2094/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2095/// be used to express the computation.
2096class BinaryOperator : public Expr {
2097public:
2098  enum Opcode {
2099    // Operators listed in order of precedence.
2100    // Note that additions to this should also update the StmtVisitor class.
2101    PtrMemD, PtrMemI, // [C++ 5.5] Pointer-to-member operators.
2102    Mul, Div, Rem,    // [C99 6.5.5] Multiplicative operators.
2103    Add, Sub,         // [C99 6.5.6] Additive operators.
2104    Shl, Shr,         // [C99 6.5.7] Bitwise shift operators.
2105    LT, GT, LE, GE,   // [C99 6.5.8] Relational operators.
2106    EQ, NE,           // [C99 6.5.9] Equality operators.
2107    And,              // [C99 6.5.10] Bitwise AND operator.
2108    Xor,              // [C99 6.5.11] Bitwise XOR operator.
2109    Or,               // [C99 6.5.12] Bitwise OR operator.
2110    LAnd,             // [C99 6.5.13] Logical AND operator.
2111    LOr,              // [C99 6.5.14] Logical OR operator.
2112    Assign, MulAssign,// [C99 6.5.16] Assignment operators.
2113    DivAssign, RemAssign,
2114    AddAssign, SubAssign,
2115    ShlAssign, ShrAssign,
2116    AndAssign, XorAssign,
2117    OrAssign,
2118    Comma             // [C99 6.5.17] Comma operator.
2119  };
2120private:
2121  enum { LHS, RHS, END_EXPR };
2122  Stmt* SubExprs[END_EXPR];
2123  Opcode Opc;
2124  SourceLocation OpLoc;
2125public:
2126
2127  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2128                 SourceLocation opLoc)
2129    : Expr(BinaryOperatorClass, ResTy,
2130           lhs->isTypeDependent() || rhs->isTypeDependent(),
2131           lhs->isValueDependent() || rhs->isValueDependent()),
2132      Opc(opc), OpLoc(opLoc) {
2133    SubExprs[LHS] = lhs;
2134    SubExprs[RHS] = rhs;
2135    assert(!isCompoundAssignmentOp() &&
2136           "Use ArithAssignBinaryOperator for compound assignments");
2137  }
2138
2139  /// \brief Construct an empty binary operator.
2140  explicit BinaryOperator(EmptyShell Empty)
2141    : Expr(BinaryOperatorClass, Empty), Opc(Comma) { }
2142
2143  SourceLocation getOperatorLoc() const { return OpLoc; }
2144  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2145
2146  Opcode getOpcode() const { return Opc; }
2147  void setOpcode(Opcode O) { Opc = O; }
2148
2149  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2150  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2151  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2152  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2153
2154  virtual SourceRange getSourceRange() const {
2155    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2156  }
2157
2158  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2159  /// corresponds to, e.g. "<<=".
2160  static const char *getOpcodeStr(Opcode Op);
2161
2162  /// \brief Retrieve the binary opcode that corresponds to the given
2163  /// overloaded operator.
2164  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2165
2166  /// \brief Retrieve the overloaded operator kind that corresponds to
2167  /// the given binary opcode.
2168  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2169
2170  /// predicates to categorize the respective opcodes.
2171  bool isMultiplicativeOp() const { return Opc >= Mul && Opc <= Rem; }
2172  static bool isAdditiveOp(Opcode Opc) { return Opc == Add || Opc == Sub; }
2173  bool isAdditiveOp() const { return isAdditiveOp(Opc); }
2174  static bool isShiftOp(Opcode Opc) { return Opc == Shl || Opc == Shr; }
2175  bool isShiftOp() const { return isShiftOp(Opc); }
2176
2177  static bool isBitwiseOp(Opcode Opc) { return Opc >= And && Opc <= Or; }
2178  bool isBitwiseOp() const { return isBitwiseOp(Opc); }
2179
2180  static bool isRelationalOp(Opcode Opc) { return Opc >= LT && Opc <= GE; }
2181  bool isRelationalOp() const { return isRelationalOp(Opc); }
2182
2183  static bool isEqualityOp(Opcode Opc) { return Opc == EQ || Opc == NE; }
2184  bool isEqualityOp() const { return isEqualityOp(Opc); }
2185
2186  static bool isComparisonOp(Opcode Opc) { return Opc >= LT && Opc <= NE; }
2187  bool isComparisonOp() const { return isComparisonOp(Opc); }
2188
2189  static bool isLogicalOp(Opcode Opc) { return Opc == LAnd || Opc == LOr; }
2190  bool isLogicalOp() const { return isLogicalOp(Opc); }
2191
2192  bool isAssignmentOp() const { return Opc >= Assign && Opc <= OrAssign; }
2193  bool isCompoundAssignmentOp() const { return Opc > Assign && Opc <= OrAssign;}
2194  bool isShiftAssignOp() const { return Opc == ShlAssign || Opc == ShrAssign; }
2195
2196  static bool classof(const Stmt *S) {
2197    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2198           S->getStmtClass() <= lastBinaryOperatorConstant;
2199  }
2200  static bool classof(const BinaryOperator *) { return true; }
2201
2202  // Iterators
2203  virtual child_iterator child_begin();
2204  virtual child_iterator child_end();
2205
2206protected:
2207  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2208                 SourceLocation opLoc, bool dead)
2209    : Expr(CompoundAssignOperatorClass, ResTy,
2210           lhs->isTypeDependent() || rhs->isTypeDependent(),
2211           lhs->isValueDependent() || rhs->isValueDependent()),
2212      Opc(opc), OpLoc(opLoc) {
2213    SubExprs[LHS] = lhs;
2214    SubExprs[RHS] = rhs;
2215  }
2216
2217  BinaryOperator(StmtClass SC, EmptyShell Empty)
2218    : Expr(SC, Empty), Opc(MulAssign) { }
2219};
2220
2221/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2222/// track of the type the operation is performed in.  Due to the semantics of
2223/// these operators, the operands are promoted, the aritmetic performed, an
2224/// implicit conversion back to the result type done, then the assignment takes
2225/// place.  This captures the intermediate type which the computation is done
2226/// in.
2227class CompoundAssignOperator : public BinaryOperator {
2228  QualType ComputationLHSType;
2229  QualType ComputationResultType;
2230public:
2231  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
2232                         QualType ResType, QualType CompLHSType,
2233                         QualType CompResultType,
2234                         SourceLocation OpLoc)
2235    : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
2236      ComputationLHSType(CompLHSType),
2237      ComputationResultType(CompResultType) {
2238    assert(isCompoundAssignmentOp() &&
2239           "Only should be used for compound assignments");
2240  }
2241
2242  /// \brief Build an empty compound assignment operator expression.
2243  explicit CompoundAssignOperator(EmptyShell Empty)
2244    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2245
2246  // The two computation types are the type the LHS is converted
2247  // to for the computation and the type of the result; the two are
2248  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2249  QualType getComputationLHSType() const { return ComputationLHSType; }
2250  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2251
2252  QualType getComputationResultType() const { return ComputationResultType; }
2253  void setComputationResultType(QualType T) { ComputationResultType = T; }
2254
2255  static bool classof(const CompoundAssignOperator *) { return true; }
2256  static bool classof(const Stmt *S) {
2257    return S->getStmtClass() == CompoundAssignOperatorClass;
2258  }
2259};
2260
2261/// ConditionalOperator - The ?: operator.  Note that LHS may be null when the
2262/// GNU "missing LHS" extension is in use.
2263///
2264class ConditionalOperator : public Expr {
2265  enum { COND, LHS, RHS, END_EXPR };
2266  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2267  SourceLocation QuestionLoc, ColonLoc;
2268public:
2269  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2270                      SourceLocation CLoc, Expr *rhs, QualType t)
2271    : Expr(ConditionalOperatorClass, t,
2272           // FIXME: the type of the conditional operator doesn't
2273           // depend on the type of the conditional, but the standard
2274           // seems to imply that it could. File a bug!
2275           ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
2276           (cond->isValueDependent() ||
2277            (lhs && lhs->isValueDependent()) ||
2278            (rhs && rhs->isValueDependent()))),
2279      QuestionLoc(QLoc),
2280      ColonLoc(CLoc) {
2281    SubExprs[COND] = cond;
2282    SubExprs[LHS] = lhs;
2283    SubExprs[RHS] = rhs;
2284  }
2285
2286  /// \brief Build an empty conditional operator.
2287  explicit ConditionalOperator(EmptyShell Empty)
2288    : Expr(ConditionalOperatorClass, Empty) { }
2289
2290  // getCond - Return the expression representing the condition for
2291  //  the ?: operator.
2292  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2293  void setCond(Expr *E) { SubExprs[COND] = E; }
2294
2295  // getTrueExpr - Return the subexpression representing the value of the ?:
2296  //  expression if the condition evaluates to true.  In most cases this value
2297  //  will be the same as getLHS() except a GCC extension allows the left
2298  //  subexpression to be omitted, and instead of the condition be returned.
2299  //  e.g: x ?: y is shorthand for x ? x : y, except that the expression "x"
2300  //  is only evaluated once.
2301  Expr *getTrueExpr() const {
2302    return cast<Expr>(SubExprs[LHS] ? SubExprs[LHS] : SubExprs[COND]);
2303  }
2304
2305  // getTrueExpr - Return the subexpression representing the value of the ?:
2306  // expression if the condition evaluates to false. This is the same as getRHS.
2307  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2308
2309  Expr *getLHS() const { return cast_or_null<Expr>(SubExprs[LHS]); }
2310  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2311
2312  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2313  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2314
2315  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2316  void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
2317
2318  SourceLocation getColonLoc() const { return ColonLoc; }
2319  void setColonLoc(SourceLocation L) { ColonLoc = L; }
2320
2321  virtual SourceRange getSourceRange() const {
2322    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2323  }
2324  static bool classof(const Stmt *T) {
2325    return T->getStmtClass() == ConditionalOperatorClass;
2326  }
2327  static bool classof(const ConditionalOperator *) { return true; }
2328
2329  // Iterators
2330  virtual child_iterator child_begin();
2331  virtual child_iterator child_end();
2332};
2333
2334/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2335class AddrLabelExpr : public Expr {
2336  SourceLocation AmpAmpLoc, LabelLoc;
2337  LabelStmt *Label;
2338public:
2339  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
2340                QualType t)
2341    : Expr(AddrLabelExprClass, t, false, false),
2342      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2343
2344  /// \brief Build an empty address of a label expression.
2345  explicit AddrLabelExpr(EmptyShell Empty)
2346    : Expr(AddrLabelExprClass, Empty) { }
2347
2348  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2349  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2350  SourceLocation getLabelLoc() const { return LabelLoc; }
2351  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2352
2353  virtual SourceRange getSourceRange() const {
2354    return SourceRange(AmpAmpLoc, LabelLoc);
2355  }
2356
2357  LabelStmt *getLabel() const { return Label; }
2358  void setLabel(LabelStmt *S) { Label = S; }
2359
2360  static bool classof(const Stmt *T) {
2361    return T->getStmtClass() == AddrLabelExprClass;
2362  }
2363  static bool classof(const AddrLabelExpr *) { return true; }
2364
2365  // Iterators
2366  virtual child_iterator child_begin();
2367  virtual child_iterator child_end();
2368};
2369
2370/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2371/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2372/// takes the value of the last subexpression.
2373class StmtExpr : public Expr {
2374  Stmt *SubStmt;
2375  SourceLocation LParenLoc, RParenLoc;
2376public:
2377  // FIXME: Does type-dependence need to be computed differently?
2378  StmtExpr(CompoundStmt *substmt, QualType T,
2379           SourceLocation lp, SourceLocation rp) :
2380    Expr(StmtExprClass, T, T->isDependentType(), false),
2381    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2382
2383  /// \brief Build an empty statement expression.
2384  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2385
2386  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2387  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2388  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2389
2390  virtual SourceRange getSourceRange() const {
2391    return SourceRange(LParenLoc, RParenLoc);
2392  }
2393
2394  SourceLocation getLParenLoc() const { return LParenLoc; }
2395  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2396  SourceLocation getRParenLoc() const { return RParenLoc; }
2397  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2398
2399  static bool classof(const Stmt *T) {
2400    return T->getStmtClass() == StmtExprClass;
2401  }
2402  static bool classof(const StmtExpr *) { return true; }
2403
2404  // Iterators
2405  virtual child_iterator child_begin();
2406  virtual child_iterator child_end();
2407};
2408
2409/// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
2410/// This AST node represents a function that returns 1 if two *types* (not
2411/// expressions) are compatible. The result of this built-in function can be
2412/// used in integer constant expressions.
2413class TypesCompatibleExpr : public Expr {
2414  QualType Type1;
2415  QualType Type2;
2416  SourceLocation BuiltinLoc, RParenLoc;
2417public:
2418  TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
2419                      QualType t1, QualType t2, SourceLocation RP) :
2420    Expr(TypesCompatibleExprClass, ReturnType, false, false),
2421    Type1(t1), Type2(t2), BuiltinLoc(BLoc), RParenLoc(RP) {}
2422
2423  /// \brief Build an empty __builtin_type_compatible_p expression.
2424  explicit TypesCompatibleExpr(EmptyShell Empty)
2425    : Expr(TypesCompatibleExprClass, Empty) { }
2426
2427  QualType getArgType1() const { return Type1; }
2428  void setArgType1(QualType T) { Type1 = T; }
2429  QualType getArgType2() const { return Type2; }
2430  void setArgType2(QualType T) { Type2 = T; }
2431
2432  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2433  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2434
2435  SourceLocation getRParenLoc() const { return RParenLoc; }
2436  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2437
2438  virtual SourceRange getSourceRange() const {
2439    return SourceRange(BuiltinLoc, RParenLoc);
2440  }
2441  static bool classof(const Stmt *T) {
2442    return T->getStmtClass() == TypesCompatibleExprClass;
2443  }
2444  static bool classof(const TypesCompatibleExpr *) { return true; }
2445
2446  // Iterators
2447  virtual child_iterator child_begin();
2448  virtual child_iterator child_end();
2449};
2450
2451/// ShuffleVectorExpr - clang-specific builtin-in function
2452/// __builtin_shufflevector.
2453/// This AST node represents a operator that does a constant
2454/// shuffle, similar to LLVM's shufflevector instruction. It takes
2455/// two vectors and a variable number of constant indices,
2456/// and returns the appropriately shuffled vector.
2457class ShuffleVectorExpr : public Expr {
2458  SourceLocation BuiltinLoc, RParenLoc;
2459
2460  // SubExprs - the list of values passed to the __builtin_shufflevector
2461  // function. The first two are vectors, and the rest are constant
2462  // indices.  The number of values in this list is always
2463  // 2+the number of indices in the vector type.
2464  Stmt **SubExprs;
2465  unsigned NumExprs;
2466
2467protected:
2468  virtual void DoDestroy(ASTContext &C);
2469
2470public:
2471  // FIXME: Can a shufflevector be value-dependent?  Does type-dependence need
2472  // to be computed differently?
2473  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2474                    QualType Type, SourceLocation BLoc,
2475                    SourceLocation RP) :
2476    Expr(ShuffleVectorExprClass, Type, Type->isDependentType(), false),
2477    BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) {
2478
2479    SubExprs = new (C) Stmt*[nexpr];
2480    for (unsigned i = 0; i < nexpr; i++)
2481      SubExprs[i] = args[i];
2482  }
2483
2484  /// \brief Build an empty vector-shuffle expression.
2485  explicit ShuffleVectorExpr(EmptyShell Empty)
2486    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2487
2488  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2489  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2490
2491  SourceLocation getRParenLoc() const { return RParenLoc; }
2492  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2493
2494  virtual SourceRange getSourceRange() const {
2495    return SourceRange(BuiltinLoc, RParenLoc);
2496  }
2497  static bool classof(const Stmt *T) {
2498    return T->getStmtClass() == ShuffleVectorExprClass;
2499  }
2500  static bool classof(const ShuffleVectorExpr *) { return true; }
2501
2502  ~ShuffleVectorExpr() {}
2503
2504  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
2505  /// constant expression, the actual arguments passed in, and the function
2506  /// pointers.
2507  unsigned getNumSubExprs() const { return NumExprs; }
2508
2509  /// getExpr - Return the Expr at the specified index.
2510  Expr *getExpr(unsigned Index) {
2511    assert((Index < NumExprs) && "Arg access out of range!");
2512    return cast<Expr>(SubExprs[Index]);
2513  }
2514  const Expr *getExpr(unsigned Index) const {
2515    assert((Index < NumExprs) && "Arg access out of range!");
2516    return cast<Expr>(SubExprs[Index]);
2517  }
2518
2519  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2520
2521  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2522    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2523    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2524  }
2525
2526  // Iterators
2527  virtual child_iterator child_begin();
2528  virtual child_iterator child_end();
2529};
2530
2531/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2532/// This AST node is similar to the conditional operator (?:) in C, with
2533/// the following exceptions:
2534/// - the test expression must be a integer constant expression.
2535/// - the expression returned acts like the chosen subexpression in every
2536///   visible way: the type is the same as that of the chosen subexpression,
2537///   and all predicates (whether it's an l-value, whether it's an integer
2538///   constant expression, etc.) return the same result as for the chosen
2539///   sub-expression.
2540class ChooseExpr : public Expr {
2541  enum { COND, LHS, RHS, END_EXPR };
2542  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2543  SourceLocation BuiltinLoc, RParenLoc;
2544public:
2545  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
2546             SourceLocation RP, bool TypeDependent, bool ValueDependent)
2547    : Expr(ChooseExprClass, t, TypeDependent, ValueDependent),
2548      BuiltinLoc(BLoc), RParenLoc(RP) {
2549      SubExprs[COND] = cond;
2550      SubExprs[LHS] = lhs;
2551      SubExprs[RHS] = rhs;
2552    }
2553
2554  /// \brief Build an empty __builtin_choose_expr.
2555  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
2556
2557  /// isConditionTrue - Return whether the condition is true (i.e. not
2558  /// equal to zero).
2559  bool isConditionTrue(ASTContext &C) const;
2560
2561  /// getChosenSubExpr - Return the subexpression chosen according to the
2562  /// condition.
2563  Expr *getChosenSubExpr(ASTContext &C) const {
2564    return isConditionTrue(C) ? getLHS() : getRHS();
2565  }
2566
2567  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2568  void setCond(Expr *E) { SubExprs[COND] = E; }
2569  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2570  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2571  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2572  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2573
2574  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2575  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2576
2577  SourceLocation getRParenLoc() const { return RParenLoc; }
2578  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2579
2580  virtual SourceRange getSourceRange() const {
2581    return SourceRange(BuiltinLoc, RParenLoc);
2582  }
2583  static bool classof(const Stmt *T) {
2584    return T->getStmtClass() == ChooseExprClass;
2585  }
2586  static bool classof(const ChooseExpr *) { return true; }
2587
2588  // Iterators
2589  virtual child_iterator child_begin();
2590  virtual child_iterator child_end();
2591};
2592
2593/// GNUNullExpr - Implements the GNU __null extension, which is a name
2594/// for a null pointer constant that has integral type (e.g., int or
2595/// long) and is the same size and alignment as a pointer. The __null
2596/// extension is typically only used by system headers, which define
2597/// NULL as __null in C++ rather than using 0 (which is an integer
2598/// that may not match the size of a pointer).
2599class GNUNullExpr : public Expr {
2600  /// TokenLoc - The location of the __null keyword.
2601  SourceLocation TokenLoc;
2602
2603public:
2604  GNUNullExpr(QualType Ty, SourceLocation Loc)
2605    : Expr(GNUNullExprClass, Ty, false, false), TokenLoc(Loc) { }
2606
2607  /// \brief Build an empty GNU __null expression.
2608  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
2609
2610  /// getTokenLocation - The location of the __null token.
2611  SourceLocation getTokenLocation() const { return TokenLoc; }
2612  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
2613
2614  virtual SourceRange getSourceRange() const {
2615    return SourceRange(TokenLoc);
2616  }
2617  static bool classof(const Stmt *T) {
2618    return T->getStmtClass() == GNUNullExprClass;
2619  }
2620  static bool classof(const GNUNullExpr *) { return true; }
2621
2622  // Iterators
2623  virtual child_iterator child_begin();
2624  virtual child_iterator child_end();
2625};
2626
2627/// VAArgExpr, used for the builtin function __builtin_va_arg.
2628class VAArgExpr : public Expr {
2629  Stmt *Val;
2630  SourceLocation BuiltinLoc, RParenLoc;
2631public:
2632  VAArgExpr(SourceLocation BLoc, Expr* e, QualType t, SourceLocation RPLoc)
2633    : Expr(VAArgExprClass, t, t->isDependentType(), false),
2634      Val(e),
2635      BuiltinLoc(BLoc),
2636      RParenLoc(RPLoc) { }
2637
2638  /// \brief Create an empty __builtin_va_arg expression.
2639  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
2640
2641  const Expr *getSubExpr() const { return cast<Expr>(Val); }
2642  Expr *getSubExpr() { return cast<Expr>(Val); }
2643  void setSubExpr(Expr *E) { Val = E; }
2644
2645  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2646  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2647
2648  SourceLocation getRParenLoc() const { return RParenLoc; }
2649  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2650
2651  virtual SourceRange getSourceRange() const {
2652    return SourceRange(BuiltinLoc, RParenLoc);
2653  }
2654  static bool classof(const Stmt *T) {
2655    return T->getStmtClass() == VAArgExprClass;
2656  }
2657  static bool classof(const VAArgExpr *) { return true; }
2658
2659  // Iterators
2660  virtual child_iterator child_begin();
2661  virtual child_iterator child_end();
2662};
2663
2664/// @brief Describes an C or C++ initializer list.
2665///
2666/// InitListExpr describes an initializer list, which can be used to
2667/// initialize objects of different types, including
2668/// struct/class/union types, arrays, and vectors. For example:
2669///
2670/// @code
2671/// struct foo x = { 1, { 2, 3 } };
2672/// @endcode
2673///
2674/// Prior to semantic analysis, an initializer list will represent the
2675/// initializer list as written by the user, but will have the
2676/// placeholder type "void". This initializer list is called the
2677/// syntactic form of the initializer, and may contain C99 designated
2678/// initializers (represented as DesignatedInitExprs), initializations
2679/// of subobject members without explicit braces, and so on. Clients
2680/// interested in the original syntax of the initializer list should
2681/// use the syntactic form of the initializer list.
2682///
2683/// After semantic analysis, the initializer list will represent the
2684/// semantic form of the initializer, where the initializations of all
2685/// subobjects are made explicit with nested InitListExpr nodes and
2686/// C99 designators have been eliminated by placing the designated
2687/// initializations into the subobject they initialize. Additionally,
2688/// any "holes" in the initialization, where no initializer has been
2689/// specified for a particular subobject, will be replaced with
2690/// implicitly-generated ImplicitValueInitExpr expressions that
2691/// value-initialize the subobjects. Note, however, that the
2692/// initializer lists may still have fewer initializers than there are
2693/// elements to initialize within the object.
2694///
2695/// Given the semantic form of the initializer list, one can retrieve
2696/// the original syntactic form of that initializer list (if it
2697/// exists) using getSyntacticForm(). Since many initializer lists
2698/// have the same syntactic and semantic forms, getSyntacticForm() may
2699/// return NULL, indicating that the current initializer list also
2700/// serves as its syntactic form.
2701class InitListExpr : public Expr {
2702  // FIXME: Eliminate this vector in favor of ASTContext allocation
2703  typedef ASTVector<Stmt *> InitExprsTy;
2704  InitExprsTy InitExprs;
2705  SourceLocation LBraceLoc, RBraceLoc;
2706
2707  /// Contains the initializer list that describes the syntactic form
2708  /// written in the source code.
2709  InitListExpr *SyntacticForm;
2710
2711  /// If this initializer list initializes a union, specifies which
2712  /// field within the union will be initialized.
2713  FieldDecl *UnionFieldInit;
2714
2715  /// Whether this initializer list originally had a GNU array-range
2716  /// designator in it. This is a temporary marker used by CodeGen.
2717  bool HadArrayRangeDesignator;
2718
2719public:
2720  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
2721               Expr **initexprs, unsigned numinits,
2722               SourceLocation rbraceloc);
2723
2724  /// \brief Build an empty initializer list.
2725  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
2726    : Expr(InitListExprClass, Empty), InitExprs(C) { }
2727
2728  unsigned getNumInits() const { return InitExprs.size(); }
2729
2730  const Expr* getInit(unsigned Init) const {
2731    assert(Init < getNumInits() && "Initializer access out of range!");
2732    return cast_or_null<Expr>(InitExprs[Init]);
2733  }
2734
2735  Expr* getInit(unsigned Init) {
2736    assert(Init < getNumInits() && "Initializer access out of range!");
2737    return cast_or_null<Expr>(InitExprs[Init]);
2738  }
2739
2740  void setInit(unsigned Init, Expr *expr) {
2741    assert(Init < getNumInits() && "Initializer access out of range!");
2742    InitExprs[Init] = expr;
2743  }
2744
2745  /// \brief Reserve space for some number of initializers.
2746  void reserveInits(ASTContext &C, unsigned NumInits);
2747
2748  /// @brief Specify the number of initializers
2749  ///
2750  /// If there are more than @p NumInits initializers, the remaining
2751  /// initializers will be destroyed. If there are fewer than @p
2752  /// NumInits initializers, NULL expressions will be added for the
2753  /// unknown initializers.
2754  void resizeInits(ASTContext &Context, unsigned NumInits);
2755
2756  /// @brief Updates the initializer at index @p Init with the new
2757  /// expression @p expr, and returns the old expression at that
2758  /// location.
2759  ///
2760  /// When @p Init is out of range for this initializer list, the
2761  /// initializer list will be extended with NULL expressions to
2762  /// accomodate the new entry.
2763  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
2764
2765  /// \brief If this initializes a union, specifies which field in the
2766  /// union to initialize.
2767  ///
2768  /// Typically, this field is the first named field within the
2769  /// union. However, a designated initializer can specify the
2770  /// initialization of a different field within the union.
2771  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2772  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2773
2774  // Explicit InitListExpr's originate from source code (and have valid source
2775  // locations). Implicit InitListExpr's are created by the semantic analyzer.
2776  bool isExplicit() {
2777    return LBraceLoc.isValid() && RBraceLoc.isValid();
2778  }
2779
2780  SourceLocation getLBraceLoc() const { return LBraceLoc; }
2781  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2782  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2783  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2784
2785  /// @brief Retrieve the initializer list that describes the
2786  /// syntactic form of the initializer.
2787  ///
2788  ///
2789  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2790  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2791
2792  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2793  void sawArrayRangeDesignator(bool ARD = true) {
2794    HadArrayRangeDesignator = ARD;
2795  }
2796
2797  virtual SourceRange getSourceRange() const {
2798    return SourceRange(LBraceLoc, RBraceLoc);
2799  }
2800  static bool classof(const Stmt *T) {
2801    return T->getStmtClass() == InitListExprClass;
2802  }
2803  static bool classof(const InitListExpr *) { return true; }
2804
2805  // Iterators
2806  virtual child_iterator child_begin();
2807  virtual child_iterator child_end();
2808
2809  typedef InitExprsTy::iterator iterator;
2810  typedef InitExprsTy::reverse_iterator reverse_iterator;
2811
2812  iterator begin() { return InitExprs.begin(); }
2813  iterator end() { return InitExprs.end(); }
2814  reverse_iterator rbegin() { return InitExprs.rbegin(); }
2815  reverse_iterator rend() { return InitExprs.rend(); }
2816};
2817
2818/// @brief Represents a C99 designated initializer expression.
2819///
2820/// A designated initializer expression (C99 6.7.8) contains one or
2821/// more designators (which can be field designators, array
2822/// designators, or GNU array-range designators) followed by an
2823/// expression that initializes the field or element(s) that the
2824/// designators refer to. For example, given:
2825///
2826/// @code
2827/// struct point {
2828///   double x;
2829///   double y;
2830/// };
2831/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2832/// @endcode
2833///
2834/// The InitListExpr contains three DesignatedInitExprs, the first of
2835/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2836/// designators, one array designator for @c [2] followed by one field
2837/// designator for @c .y. The initalization expression will be 1.0.
2838class DesignatedInitExpr : public Expr {
2839public:
2840  /// \brief Forward declaration of the Designator class.
2841  class Designator;
2842
2843private:
2844  /// The location of the '=' or ':' prior to the actual initializer
2845  /// expression.
2846  SourceLocation EqualOrColonLoc;
2847
2848  /// Whether this designated initializer used the GNU deprecated
2849  /// syntax rather than the C99 '=' syntax.
2850  bool GNUSyntax : 1;
2851
2852  /// The number of designators in this initializer expression.
2853  unsigned NumDesignators : 15;
2854
2855  /// \brief The designators in this designated initialization
2856  /// expression.
2857  Designator *Designators;
2858
2859  /// The number of subexpressions of this initializer expression,
2860  /// which contains both the initializer and any additional
2861  /// expressions used by array and array-range designators.
2862  unsigned NumSubExprs : 16;
2863
2864
2865  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
2866                     const Designator *Designators,
2867                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
2868                     Expr **IndexExprs, unsigned NumIndexExprs,
2869                     Expr *Init);
2870
2871  explicit DesignatedInitExpr(unsigned NumSubExprs)
2872    : Expr(DesignatedInitExprClass, EmptyShell()),
2873      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
2874
2875protected:
2876  virtual void DoDestroy(ASTContext &C);
2877
2878  void DestroyDesignators(ASTContext &C);
2879
2880public:
2881  /// A field designator, e.g., ".x".
2882  struct FieldDesignator {
2883    /// Refers to the field that is being initialized. The low bit
2884    /// of this field determines whether this is actually a pointer
2885    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
2886    /// initially constructed, a field designator will store an
2887    /// IdentifierInfo*. After semantic analysis has resolved that
2888    /// name, the field designator will instead store a FieldDecl*.
2889    uintptr_t NameOrField;
2890
2891    /// The location of the '.' in the designated initializer.
2892    unsigned DotLoc;
2893
2894    /// The location of the field name in the designated initializer.
2895    unsigned FieldLoc;
2896  };
2897
2898  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2899  struct ArrayOrRangeDesignator {
2900    /// Location of the first index expression within the designated
2901    /// initializer expression's list of subexpressions.
2902    unsigned Index;
2903    /// The location of the '[' starting the array range designator.
2904    unsigned LBracketLoc;
2905    /// The location of the ellipsis separating the start and end
2906    /// indices. Only valid for GNU array-range designators.
2907    unsigned EllipsisLoc;
2908    /// The location of the ']' terminating the array range designator.
2909    unsigned RBracketLoc;
2910  };
2911
2912  /// @brief Represents a single C99 designator.
2913  ///
2914  /// @todo This class is infuriatingly similar to clang::Designator,
2915  /// but minor differences (storing indices vs. storing pointers)
2916  /// keep us from reusing it. Try harder, later, to rectify these
2917  /// differences.
2918  class Designator {
2919    /// @brief The kind of designator this describes.
2920    enum {
2921      FieldDesignator,
2922      ArrayDesignator,
2923      ArrayRangeDesignator
2924    } Kind;
2925
2926    union {
2927      /// A field designator, e.g., ".x".
2928      struct FieldDesignator Field;
2929      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
2930      struct ArrayOrRangeDesignator ArrayOrRange;
2931    };
2932    friend class DesignatedInitExpr;
2933
2934  public:
2935    Designator() {}
2936
2937    /// @brief Initializes a field designator.
2938    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
2939               SourceLocation FieldLoc)
2940      : Kind(FieldDesignator) {
2941      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
2942      Field.DotLoc = DotLoc.getRawEncoding();
2943      Field.FieldLoc = FieldLoc.getRawEncoding();
2944    }
2945
2946    /// @brief Initializes an array designator.
2947    Designator(unsigned Index, SourceLocation LBracketLoc,
2948               SourceLocation RBracketLoc)
2949      : Kind(ArrayDesignator) {
2950      ArrayOrRange.Index = Index;
2951      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2952      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
2953      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2954    }
2955
2956    /// @brief Initializes a GNU array-range designator.
2957    Designator(unsigned Index, SourceLocation LBracketLoc,
2958               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
2959      : Kind(ArrayRangeDesignator) {
2960      ArrayOrRange.Index = Index;
2961      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
2962      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
2963      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
2964    }
2965
2966    bool isFieldDesignator() const { return Kind == FieldDesignator; }
2967    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
2968    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
2969
2970    IdentifierInfo * getFieldName();
2971
2972    FieldDecl *getField() {
2973      assert(Kind == FieldDesignator && "Only valid on a field designator");
2974      if (Field.NameOrField & 0x01)
2975        return 0;
2976      else
2977        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
2978    }
2979
2980    void setField(FieldDecl *FD) {
2981      assert(Kind == FieldDesignator && "Only valid on a field designator");
2982      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
2983    }
2984
2985    SourceLocation getDotLoc() const {
2986      assert(Kind == FieldDesignator && "Only valid on a field designator");
2987      return SourceLocation::getFromRawEncoding(Field.DotLoc);
2988    }
2989
2990    SourceLocation getFieldLoc() const {
2991      assert(Kind == FieldDesignator && "Only valid on a field designator");
2992      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
2993    }
2994
2995    SourceLocation getLBracketLoc() const {
2996      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
2997             "Only valid on an array or array-range designator");
2998      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
2999    }
3000
3001    SourceLocation getRBracketLoc() const {
3002      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3003             "Only valid on an array or array-range designator");
3004      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3005    }
3006
3007    SourceLocation getEllipsisLoc() const {
3008      assert(Kind == ArrayRangeDesignator &&
3009             "Only valid on an array-range designator");
3010      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3011    }
3012
3013    unsigned getFirstExprIndex() const {
3014      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3015             "Only valid on an array or array-range designator");
3016      return ArrayOrRange.Index;
3017    }
3018
3019    SourceLocation getStartLocation() const {
3020      if (Kind == FieldDesignator)
3021        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3022      else
3023        return getLBracketLoc();
3024    }
3025  };
3026
3027  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3028                                    unsigned NumDesignators,
3029                                    Expr **IndexExprs, unsigned NumIndexExprs,
3030                                    SourceLocation EqualOrColonLoc,
3031                                    bool GNUSyntax, Expr *Init);
3032
3033  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3034
3035  /// @brief Returns the number of designators in this initializer.
3036  unsigned size() const { return NumDesignators; }
3037
3038  // Iterator access to the designators.
3039  typedef Designator* designators_iterator;
3040  designators_iterator designators_begin() { return Designators; }
3041  designators_iterator designators_end() {
3042    return Designators + NumDesignators;
3043  }
3044
3045  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3046
3047  void setDesignators(ASTContext &C, const Designator *Desigs,
3048                      unsigned NumDesigs);
3049
3050  Expr *getArrayIndex(const Designator& D);
3051  Expr *getArrayRangeStart(const Designator& D);
3052  Expr *getArrayRangeEnd(const Designator& D);
3053
3054  /// @brief Retrieve the location of the '=' that precedes the
3055  /// initializer value itself, if present.
3056  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3057  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3058
3059  /// @brief Determines whether this designated initializer used the
3060  /// deprecated GNU syntax for designated initializers.
3061  bool usesGNUSyntax() const { return GNUSyntax; }
3062  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3063
3064  /// @brief Retrieve the initializer value.
3065  Expr *getInit() const {
3066    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3067  }
3068
3069  void setInit(Expr *init) {
3070    *child_begin() = init;
3071  }
3072
3073  /// \brief Retrieve the total number of subexpressions in this
3074  /// designated initializer expression, including the actual
3075  /// initialized value and any expressions that occur within array
3076  /// and array-range designators.
3077  unsigned getNumSubExprs() const { return NumSubExprs; }
3078
3079  Expr *getSubExpr(unsigned Idx) {
3080    assert(Idx < NumSubExprs && "Subscript out of range");
3081    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3082    Ptr += sizeof(DesignatedInitExpr);
3083    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3084  }
3085
3086  void setSubExpr(unsigned Idx, Expr *E) {
3087    assert(Idx < NumSubExprs && "Subscript out of range");
3088    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3089    Ptr += sizeof(DesignatedInitExpr);
3090    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3091  }
3092
3093  /// \brief Replaces the designator at index @p Idx with the series
3094  /// of designators in [First, Last).
3095  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3096                        const Designator *Last);
3097
3098  virtual SourceRange getSourceRange() const;
3099
3100  static bool classof(const Stmt *T) {
3101    return T->getStmtClass() == DesignatedInitExprClass;
3102  }
3103  static bool classof(const DesignatedInitExpr *) { return true; }
3104
3105  // Iterators
3106  virtual child_iterator child_begin();
3107  virtual child_iterator child_end();
3108};
3109
3110/// \brief Represents an implicitly-generated value initialization of
3111/// an object of a given type.
3112///
3113/// Implicit value initializations occur within semantic initializer
3114/// list expressions (InitListExpr) as placeholders for subobject
3115/// initializations not explicitly specified by the user.
3116///
3117/// \see InitListExpr
3118class ImplicitValueInitExpr : public Expr {
3119public:
3120  explicit ImplicitValueInitExpr(QualType ty)
3121    : Expr(ImplicitValueInitExprClass, ty, false, false) { }
3122
3123  /// \brief Construct an empty implicit value initialization.
3124  explicit ImplicitValueInitExpr(EmptyShell Empty)
3125    : Expr(ImplicitValueInitExprClass, Empty) { }
3126
3127  static bool classof(const Stmt *T) {
3128    return T->getStmtClass() == ImplicitValueInitExprClass;
3129  }
3130  static bool classof(const ImplicitValueInitExpr *) { return true; }
3131
3132  virtual SourceRange getSourceRange() const {
3133    return SourceRange();
3134  }
3135
3136  // Iterators
3137  virtual child_iterator child_begin();
3138  virtual child_iterator child_end();
3139};
3140
3141
3142class ParenListExpr : public Expr {
3143  Stmt **Exprs;
3144  unsigned NumExprs;
3145  SourceLocation LParenLoc, RParenLoc;
3146
3147protected:
3148  virtual void DoDestroy(ASTContext& C);
3149
3150public:
3151  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3152                unsigned numexprs, SourceLocation rparenloc);
3153
3154  ~ParenListExpr() {}
3155
3156  /// \brief Build an empty paren list.
3157  //explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3158
3159  unsigned getNumExprs() const { return NumExprs; }
3160
3161  const Expr* getExpr(unsigned Init) const {
3162    assert(Init < getNumExprs() && "Initializer access out of range!");
3163    return cast_or_null<Expr>(Exprs[Init]);
3164  }
3165
3166  Expr* getExpr(unsigned Init) {
3167    assert(Init < getNumExprs() && "Initializer access out of range!");
3168    return cast_or_null<Expr>(Exprs[Init]);
3169  }
3170
3171  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3172
3173  SourceLocation getLParenLoc() const { return LParenLoc; }
3174  SourceLocation getRParenLoc() const { return RParenLoc; }
3175
3176  virtual SourceRange getSourceRange() const {
3177    return SourceRange(LParenLoc, RParenLoc);
3178  }
3179  static bool classof(const Stmt *T) {
3180    return T->getStmtClass() == ParenListExprClass;
3181  }
3182  static bool classof(const ParenListExpr *) { return true; }
3183
3184  // Iterators
3185  virtual child_iterator child_begin();
3186  virtual child_iterator child_end();
3187};
3188
3189
3190//===----------------------------------------------------------------------===//
3191// Clang Extensions
3192//===----------------------------------------------------------------------===//
3193
3194
3195/// ExtVectorElementExpr - This represents access to specific elements of a
3196/// vector, and may occur on the left hand side or right hand side.  For example
3197/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3198///
3199/// Note that the base may have either vector or pointer to vector type, just
3200/// like a struct field reference.
3201///
3202class ExtVectorElementExpr : public Expr {
3203  Stmt *Base;
3204  IdentifierInfo *Accessor;
3205  SourceLocation AccessorLoc;
3206public:
3207  ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
3208                       SourceLocation loc)
3209    : Expr(ExtVectorElementExprClass, ty, base->isTypeDependent(),
3210           base->isValueDependent()),
3211      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3212
3213  /// \brief Build an empty vector element expression.
3214  explicit ExtVectorElementExpr(EmptyShell Empty)
3215    : Expr(ExtVectorElementExprClass, Empty) { }
3216
3217  const Expr *getBase() const { return cast<Expr>(Base); }
3218  Expr *getBase() { return cast<Expr>(Base); }
3219  void setBase(Expr *E) { Base = E; }
3220
3221  IdentifierInfo &getAccessor() const { return *Accessor; }
3222  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3223
3224  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3225  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3226
3227  /// getNumElements - Get the number of components being selected.
3228  unsigned getNumElements() const;
3229
3230  /// containsDuplicateElements - Return true if any element access is
3231  /// repeated.
3232  bool containsDuplicateElements() const;
3233
3234  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3235  /// aggregate Constant of ConstantInt(s).
3236  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3237
3238  virtual SourceRange getSourceRange() const {
3239    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3240  }
3241
3242  /// isArrow - Return true if the base expression is a pointer to vector,
3243  /// return false if the base expression is a vector.
3244  bool isArrow() const;
3245
3246  static bool classof(const Stmt *T) {
3247    return T->getStmtClass() == ExtVectorElementExprClass;
3248  }
3249  static bool classof(const ExtVectorElementExpr *) { return true; }
3250
3251  // Iterators
3252  virtual child_iterator child_begin();
3253  virtual child_iterator child_end();
3254};
3255
3256
3257/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3258/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3259class BlockExpr : public Expr {
3260protected:
3261  BlockDecl *TheBlock;
3262  bool HasBlockDeclRefExprs;
3263public:
3264  BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
3265    : Expr(BlockExprClass, ty, ty->isDependentType(), false),
3266      TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
3267
3268  /// \brief Build an empty block expression.
3269  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3270
3271  const BlockDecl *getBlockDecl() const { return TheBlock; }
3272  BlockDecl *getBlockDecl() { return TheBlock; }
3273  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3274
3275  // Convenience functions for probing the underlying BlockDecl.
3276  SourceLocation getCaretLocation() const;
3277  const Stmt *getBody() const;
3278  Stmt *getBody();
3279
3280  virtual SourceRange getSourceRange() const {
3281    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3282  }
3283
3284  /// getFunctionType - Return the underlying function type for this block.
3285  const FunctionType *getFunctionType() const;
3286
3287  /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
3288  /// inside of the block that reference values outside the block.
3289  bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
3290  void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
3291
3292  static bool classof(const Stmt *T) {
3293    return T->getStmtClass() == BlockExprClass;
3294  }
3295  static bool classof(const BlockExpr *) { return true; }
3296
3297  // Iterators
3298  virtual child_iterator child_begin();
3299  virtual child_iterator child_end();
3300};
3301
3302/// BlockDeclRefExpr - A reference to a declared variable, function,
3303/// enum, etc.
3304class BlockDeclRefExpr : public Expr {
3305  ValueDecl *D;
3306  SourceLocation Loc;
3307  bool IsByRef : 1;
3308  bool ConstQualAdded : 1;
3309  Stmt *CopyConstructorVal;
3310public:
3311  // FIXME: Fix type/value dependence!
3312  BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
3313                   bool constAdded = false,
3314                   Stmt *copyConstructorVal = 0)
3315  : Expr(BlockDeclRefExprClass, t, false, false), D(d), Loc(l), IsByRef(ByRef),
3316    ConstQualAdded(constAdded),  CopyConstructorVal(copyConstructorVal) {}
3317
3318  // \brief Build an empty reference to a declared variable in a
3319  // block.
3320  explicit BlockDeclRefExpr(EmptyShell Empty)
3321    : Expr(BlockDeclRefExprClass, Empty) { }
3322
3323  ValueDecl *getDecl() { return D; }
3324  const ValueDecl *getDecl() const { return D; }
3325  void setDecl(ValueDecl *VD) { D = VD; }
3326
3327  SourceLocation getLocation() const { return Loc; }
3328  void setLocation(SourceLocation L) { Loc = L; }
3329
3330  virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
3331
3332  bool isByRef() const { return IsByRef; }
3333  void setByRef(bool BR) { IsByRef = BR; }
3334
3335  bool isConstQualAdded() const { return ConstQualAdded; }
3336  void setConstQualAdded(bool C) { ConstQualAdded = C; }
3337
3338  const Expr *getCopyConstructorExpr() const
3339    { return cast_or_null<Expr>(CopyConstructorVal); }
3340  Expr *getCopyConstructorExpr()
3341    { return cast_or_null<Expr>(CopyConstructorVal); }
3342  void setCopyConstructorExpr(Expr *E) { CopyConstructorVal = E; }
3343
3344  static bool classof(const Stmt *T) {
3345    return T->getStmtClass() == BlockDeclRefExprClass;
3346  }
3347  static bool classof(const BlockDeclRefExpr *) { return true; }
3348
3349  // Iterators
3350  virtual child_iterator child_begin();
3351  virtual child_iterator child_end();
3352};
3353
3354}  // end namespace clang
3355
3356#endif
3357