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