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