Expr.h revision b11382497a923b0d7009e85a1d8eb7bf93ec6d0d
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, const char *StrData,
1209                               unsigned ByteLength, bool Wide, bool Pascal,
1210                               QualType Ty,
1211                               const SourceLocation *Loc, unsigned NumStrs);
1212
1213  /// Simple constructor for string literals made from one token.
1214  static StringLiteral *Create(ASTContext &C, const char *StrData,
1215                               unsigned ByteLength, bool Wide,
1216                               bool Pascal, QualType Ty, SourceLocation Loc) {
1217    return Create(C, StrData, ByteLength, Wide, Pascal, Ty, &Loc, 1);
1218  }
1219
1220  /// \brief Construct an empty string literal.
1221  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1222
1223  llvm::StringRef getString() const {
1224    return llvm::StringRef(StrData, ByteLength);
1225  }
1226
1227  unsigned getByteLength() const { return ByteLength; }
1228
1229  /// \brief Sets the string data to the given string data.
1230  void setString(ASTContext &C, llvm::StringRef Str);
1231
1232  bool isWide() const { return IsWide; }
1233  bool isPascal() const { return IsPascal; }
1234
1235  bool containsNonAsciiOrNull() const {
1236    llvm::StringRef Str = getString();
1237    for (unsigned i = 0, e = Str.size(); i != e; ++i)
1238      if (!isascii(Str[i]) || !Str[i])
1239        return true;
1240    return false;
1241  }
1242  /// getNumConcatenated - Get the number of string literal tokens that were
1243  /// concatenated in translation phase #6 to form this string literal.
1244  unsigned getNumConcatenated() const { return NumConcatenated; }
1245
1246  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1247    assert(TokNum < NumConcatenated && "Invalid tok number");
1248    return TokLocs[TokNum];
1249  }
1250  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1251    assert(TokNum < NumConcatenated && "Invalid tok number");
1252    TokLocs[TokNum] = L;
1253  }
1254
1255  /// getLocationOfByte - Return a source location that points to the specified
1256  /// byte of this string literal.
1257  ///
1258  /// Strings are amazingly complex.  They can be formed from multiple tokens
1259  /// and can have escape sequences in them in addition to the usual trigraph
1260  /// and escaped newline business.  This routine handles this complexity.
1261  ///
1262  SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1263                                   const LangOptions &Features,
1264                                   const TargetInfo &Target) const;
1265
1266  typedef const SourceLocation *tokloc_iterator;
1267  tokloc_iterator tokloc_begin() const { return TokLocs; }
1268  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1269
1270  SourceRange getSourceRange() const {
1271    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1272  }
1273  static bool classof(const Stmt *T) {
1274    return T->getStmtClass() == StringLiteralClass;
1275  }
1276  static bool classof(const StringLiteral *) { return true; }
1277
1278  // Iterators
1279  child_range children() { return child_range(); }
1280};
1281
1282/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1283/// AST node is only formed if full location information is requested.
1284class ParenExpr : public Expr {
1285  SourceLocation L, R;
1286  Stmt *Val;
1287public:
1288  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1289    : Expr(ParenExprClass, val->getType(),
1290           val->getValueKind(), val->getObjectKind(),
1291           val->isTypeDependent(), val->isValueDependent(),
1292           val->containsUnexpandedParameterPack()),
1293      L(l), R(r), Val(val) {}
1294
1295  /// \brief Construct an empty parenthesized expression.
1296  explicit ParenExpr(EmptyShell Empty)
1297    : Expr(ParenExprClass, Empty) { }
1298
1299  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1300  Expr *getSubExpr() { return cast<Expr>(Val); }
1301  void setSubExpr(Expr *E) { Val = E; }
1302
1303  SourceRange getSourceRange() const { return SourceRange(L, R); }
1304
1305  /// \brief Get the location of the left parentheses '('.
1306  SourceLocation getLParen() const { return L; }
1307  void setLParen(SourceLocation Loc) { L = Loc; }
1308
1309  /// \brief Get the location of the right parentheses ')'.
1310  SourceLocation getRParen() const { return R; }
1311  void setRParen(SourceLocation Loc) { R = Loc; }
1312
1313  static bool classof(const Stmt *T) {
1314    return T->getStmtClass() == ParenExprClass;
1315  }
1316  static bool classof(const ParenExpr *) { return true; }
1317
1318  // Iterators
1319  child_range children() { return child_range(&Val, &Val+1); }
1320};
1321
1322
1323/// UnaryOperator - This represents the unary-expression's (except sizeof and
1324/// alignof), the postinc/postdec operators from postfix-expression, and various
1325/// extensions.
1326///
1327/// Notes on various nodes:
1328///
1329/// Real/Imag - These return the real/imag part of a complex operand.  If
1330///   applied to a non-complex value, the former returns its operand and the
1331///   later returns zero in the type of the operand.
1332///
1333class UnaryOperator : public Expr {
1334public:
1335  typedef UnaryOperatorKind Opcode;
1336
1337private:
1338  unsigned Opc : 5;
1339  SourceLocation Loc;
1340  Stmt *Val;
1341public:
1342
1343  UnaryOperator(Expr *input, Opcode opc, QualType type,
1344                ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1345    : Expr(UnaryOperatorClass, type, VK, OK,
1346           input->isTypeDependent() || type->isDependentType(),
1347           input->isValueDependent(),
1348           input->containsUnexpandedParameterPack()),
1349      Opc(opc), Loc(l), Val(input) {}
1350
1351  /// \brief Build an empty unary operator.
1352  explicit UnaryOperator(EmptyShell Empty)
1353    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1354
1355  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1356  void setOpcode(Opcode O) { Opc = O; }
1357
1358  Expr *getSubExpr() const { return cast<Expr>(Val); }
1359  void setSubExpr(Expr *E) { Val = E; }
1360
1361  /// getOperatorLoc - Return the location of the operator.
1362  SourceLocation getOperatorLoc() const { return Loc; }
1363  void setOperatorLoc(SourceLocation L) { Loc = L; }
1364
1365  /// isPostfix - Return true if this is a postfix operation, like x++.
1366  static bool isPostfix(Opcode Op) {
1367    return Op == UO_PostInc || Op == UO_PostDec;
1368  }
1369
1370  /// isPrefix - Return true if this is a prefix operation, like --x.
1371  static bool isPrefix(Opcode Op) {
1372    return Op == UO_PreInc || Op == UO_PreDec;
1373  }
1374
1375  bool isPrefix() const { return isPrefix(getOpcode()); }
1376  bool isPostfix() const { return isPostfix(getOpcode()); }
1377  bool isIncrementOp() const {
1378    return Opc == UO_PreInc || Opc == UO_PostInc;
1379  }
1380  bool isIncrementDecrementOp() const {
1381    return Opc <= UO_PreDec;
1382  }
1383  static bool isArithmeticOp(Opcode Op) {
1384    return Op >= UO_Plus && Op <= UO_LNot;
1385  }
1386  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1387
1388  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1389  /// corresponds to, e.g. "sizeof" or "[pre]++"
1390  static const char *getOpcodeStr(Opcode Op);
1391
1392  /// \brief Retrieve the unary opcode that corresponds to the given
1393  /// overloaded operator.
1394  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1395
1396  /// \brief Retrieve the overloaded operator kind that corresponds to
1397  /// the given unary opcode.
1398  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1399
1400  SourceRange getSourceRange() const {
1401    if (isPostfix())
1402      return SourceRange(Val->getLocStart(), Loc);
1403    else
1404      return SourceRange(Loc, Val->getLocEnd());
1405  }
1406  SourceLocation getExprLoc() const { return Loc; }
1407
1408  static bool classof(const Stmt *T) {
1409    return T->getStmtClass() == UnaryOperatorClass;
1410  }
1411  static bool classof(const UnaryOperator *) { return true; }
1412
1413  // Iterators
1414  child_range children() { return child_range(&Val, &Val+1); }
1415};
1416
1417/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1418/// offsetof(record-type, member-designator). For example, given:
1419/// @code
1420/// struct S {
1421///   float f;
1422///   double d;
1423/// };
1424/// struct T {
1425///   int i;
1426///   struct S s[10];
1427/// };
1428/// @endcode
1429/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1430
1431class OffsetOfExpr : public Expr {
1432public:
1433  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1434  class OffsetOfNode {
1435  public:
1436    /// \brief The kind of offsetof node we have.
1437    enum Kind {
1438      /// \brief An index into an array.
1439      Array = 0x00,
1440      /// \brief A field.
1441      Field = 0x01,
1442      /// \brief A field in a dependent type, known only by its name.
1443      Identifier = 0x02,
1444      /// \brief An implicit indirection through a C++ base class, when the
1445      /// field found is in a base class.
1446      Base = 0x03
1447    };
1448
1449  private:
1450    enum { MaskBits = 2, Mask = 0x03 };
1451
1452    /// \brief The source range that covers this part of the designator.
1453    SourceRange Range;
1454
1455    /// \brief The data describing the designator, which comes in three
1456    /// different forms, depending on the lower two bits.
1457    ///   - An unsigned index into the array of Expr*'s stored after this node
1458    ///     in memory, for [constant-expression] designators.
1459    ///   - A FieldDecl*, for references to a known field.
1460    ///   - An IdentifierInfo*, for references to a field with a given name
1461    ///     when the class type is dependent.
1462    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1463    ///     base class.
1464    uintptr_t Data;
1465
1466  public:
1467    /// \brief Create an offsetof node that refers to an array element.
1468    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1469                 SourceLocation RBracketLoc)
1470      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1471
1472    /// \brief Create an offsetof node that refers to a field.
1473    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1474                 SourceLocation NameLoc)
1475      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1476        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1477
1478    /// \brief Create an offsetof node that refers to an identifier.
1479    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1480                 SourceLocation NameLoc)
1481      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1482        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1483
1484    /// \brief Create an offsetof node that refers into a C++ base class.
1485    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1486      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1487
1488    /// \brief Determine what kind of offsetof node this is.
1489    Kind getKind() const {
1490      return static_cast<Kind>(Data & Mask);
1491    }
1492
1493    /// \brief For an array element node, returns the index into the array
1494    /// of expressions.
1495    unsigned getArrayExprIndex() const {
1496      assert(getKind() == Array);
1497      return Data >> 2;
1498    }
1499
1500    /// \brief For a field offsetof node, returns the field.
1501    FieldDecl *getField() const {
1502      assert(getKind() == Field);
1503      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1504    }
1505
1506    /// \brief For a field or identifier offsetof node, returns the name of
1507    /// the field.
1508    IdentifierInfo *getFieldName() const;
1509
1510    /// \brief For a base class node, returns the base specifier.
1511    CXXBaseSpecifier *getBase() const {
1512      assert(getKind() == Base);
1513      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1514    }
1515
1516    /// \brief Retrieve the source range that covers this offsetof node.
1517    ///
1518    /// For an array element node, the source range contains the locations of
1519    /// the square brackets. For a field or identifier node, the source range
1520    /// contains the location of the period (if there is one) and the
1521    /// identifier.
1522    SourceRange getSourceRange() const { return Range; }
1523  };
1524
1525private:
1526
1527  SourceLocation OperatorLoc, RParenLoc;
1528  // Base type;
1529  TypeSourceInfo *TSInfo;
1530  // Number of sub-components (i.e. instances of OffsetOfNode).
1531  unsigned NumComps;
1532  // Number of sub-expressions (i.e. array subscript expressions).
1533  unsigned NumExprs;
1534
1535  OffsetOfExpr(ASTContext &C, QualType type,
1536               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1537               OffsetOfNode* compsPtr, unsigned numComps,
1538               Expr** exprsPtr, unsigned numExprs,
1539               SourceLocation RParenLoc);
1540
1541  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1542    : Expr(OffsetOfExprClass, EmptyShell()),
1543      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1544
1545public:
1546
1547  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1548                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1549                              OffsetOfNode* compsPtr, unsigned numComps,
1550                              Expr** exprsPtr, unsigned numExprs,
1551                              SourceLocation RParenLoc);
1552
1553  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1554                                   unsigned NumComps, unsigned NumExprs);
1555
1556  /// getOperatorLoc - Return the location of the operator.
1557  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1558  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1559
1560  /// \brief Return the location of the right parentheses.
1561  SourceLocation getRParenLoc() const { return RParenLoc; }
1562  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1563
1564  TypeSourceInfo *getTypeSourceInfo() const {
1565    return TSInfo;
1566  }
1567  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1568    TSInfo = tsi;
1569  }
1570
1571  const OffsetOfNode &getComponent(unsigned Idx) const {
1572    assert(Idx < NumComps && "Subscript out of range");
1573    return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1574  }
1575
1576  void setComponent(unsigned Idx, OffsetOfNode ON) {
1577    assert(Idx < NumComps && "Subscript out of range");
1578    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1579  }
1580
1581  unsigned getNumComponents() const {
1582    return NumComps;
1583  }
1584
1585  Expr* getIndexExpr(unsigned Idx) {
1586    assert(Idx < NumExprs && "Subscript out of range");
1587    return reinterpret_cast<Expr **>(
1588                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1589  }
1590  const Expr *getIndexExpr(unsigned Idx) const {
1591    return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1592  }
1593
1594  void setIndexExpr(unsigned Idx, Expr* E) {
1595    assert(Idx < NumComps && "Subscript out of range");
1596    reinterpret_cast<Expr **>(
1597                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1598  }
1599
1600  unsigned getNumExpressions() const {
1601    return NumExprs;
1602  }
1603
1604  SourceRange getSourceRange() const {
1605    return SourceRange(OperatorLoc, RParenLoc);
1606  }
1607
1608  static bool classof(const Stmt *T) {
1609    return T->getStmtClass() == OffsetOfExprClass;
1610  }
1611
1612  static bool classof(const OffsetOfExpr *) { return true; }
1613
1614  // Iterators
1615  child_range children() {
1616    Stmt **begin =
1617      reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1618                               + NumComps);
1619    return child_range(begin, begin + NumExprs);
1620  }
1621};
1622
1623/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1624/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
1625/// vec_step (OpenCL 1.1 6.11.12).
1626class UnaryExprOrTypeTraitExpr : public Expr {
1627  unsigned Kind : 2;
1628  bool isType : 1;    // true if operand is a type, false if an expression
1629  union {
1630    TypeSourceInfo *Ty;
1631    Stmt *Ex;
1632  } Argument;
1633  SourceLocation OpLoc, RParenLoc;
1634
1635public:
1636  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1637                           QualType resultType, SourceLocation op,
1638                           SourceLocation rp) :
1639      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1640           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1641           // Value-dependent if the argument is type-dependent.
1642           TInfo->getType()->isDependentType(),
1643           TInfo->getType()->containsUnexpandedParameterPack()),
1644      Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) {
1645    Argument.Ty = TInfo;
1646  }
1647
1648  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1649                           QualType resultType, SourceLocation op,
1650                           SourceLocation rp) :
1651      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1652           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1653           // Value-dependent if the argument is type-dependent.
1654           E->isTypeDependent(),
1655           E->containsUnexpandedParameterPack()),
1656      Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) {
1657    Argument.Ex = E;
1658  }
1659
1660  /// \brief Construct an empty sizeof/alignof expression.
1661  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1662    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1663
1664  UnaryExprOrTypeTrait getKind() const {
1665    return static_cast<UnaryExprOrTypeTrait>(Kind);
1666  }
1667  void setKind(UnaryExprOrTypeTrait K) { Kind = K; }
1668
1669  bool isArgumentType() const { return isType; }
1670  QualType getArgumentType() const {
1671    return getArgumentTypeInfo()->getType();
1672  }
1673  TypeSourceInfo *getArgumentTypeInfo() const {
1674    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1675    return Argument.Ty;
1676  }
1677  Expr *getArgumentExpr() {
1678    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1679    return static_cast<Expr*>(Argument.Ex);
1680  }
1681  const Expr *getArgumentExpr() const {
1682    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
1683  }
1684
1685  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1686  void setArgument(TypeSourceInfo *TInfo) {
1687    Argument.Ty = TInfo;
1688    isType = true;
1689  }
1690
1691  /// Gets the argument type, or the type of the argument expression, whichever
1692  /// is appropriate.
1693  QualType getTypeOfArgument() const {
1694    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1695  }
1696
1697  SourceLocation getOperatorLoc() const { return OpLoc; }
1698  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1699
1700  SourceLocation getRParenLoc() const { return RParenLoc; }
1701  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1702
1703  SourceRange getSourceRange() const {
1704    return SourceRange(OpLoc, RParenLoc);
1705  }
1706
1707  static bool classof(const Stmt *T) {
1708    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
1709  }
1710  static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; }
1711
1712  // Iterators
1713  child_range children();
1714};
1715
1716//===----------------------------------------------------------------------===//
1717// Postfix Operators.
1718//===----------------------------------------------------------------------===//
1719
1720/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1721class ArraySubscriptExpr : public Expr {
1722  enum { LHS, RHS, END_EXPR=2 };
1723  Stmt* SubExprs[END_EXPR];
1724  SourceLocation RBracketLoc;
1725public:
1726  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1727                     ExprValueKind VK, ExprObjectKind OK,
1728                     SourceLocation rbracketloc)
1729  : Expr(ArraySubscriptExprClass, t, VK, OK,
1730         lhs->isTypeDependent() || rhs->isTypeDependent(),
1731         lhs->isValueDependent() || rhs->isValueDependent(),
1732         (lhs->containsUnexpandedParameterPack() ||
1733          rhs->containsUnexpandedParameterPack())),
1734    RBracketLoc(rbracketloc) {
1735    SubExprs[LHS] = lhs;
1736    SubExprs[RHS] = rhs;
1737  }
1738
1739  /// \brief Create an empty array subscript expression.
1740  explicit ArraySubscriptExpr(EmptyShell Shell)
1741    : Expr(ArraySubscriptExprClass, Shell) { }
1742
1743  /// An array access can be written A[4] or 4[A] (both are equivalent).
1744  /// - getBase() and getIdx() always present the normalized view: A[4].
1745  ///    In this case getBase() returns "A" and getIdx() returns "4".
1746  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1747  ///    4[A] getLHS() returns "4".
1748  /// Note: Because vector element access is also written A[4] we must
1749  /// predicate the format conversion in getBase and getIdx only on the
1750  /// the type of the RHS, as it is possible for the LHS to be a vector of
1751  /// integer type
1752  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1753  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1754  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1755
1756  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1757  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1758  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1759
1760  Expr *getBase() {
1761    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1762  }
1763
1764  const Expr *getBase() const {
1765    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1766  }
1767
1768  Expr *getIdx() {
1769    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1770  }
1771
1772  const Expr *getIdx() const {
1773    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1774  }
1775
1776  SourceRange getSourceRange() const {
1777    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1778  }
1779
1780  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1781  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1782
1783  SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1784
1785  static bool classof(const Stmt *T) {
1786    return T->getStmtClass() == ArraySubscriptExprClass;
1787  }
1788  static bool classof(const ArraySubscriptExpr *) { return true; }
1789
1790  // Iterators
1791  child_range children() {
1792    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
1793  }
1794};
1795
1796
1797/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1798/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1799/// while its subclasses may represent alternative syntax that (semantically)
1800/// results in a function call. For example, CXXOperatorCallExpr is
1801/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1802/// "str1 + str2" to resolve to a function call.
1803class CallExpr : public Expr {
1804  enum { FN=0, PREARGS_START=1 };
1805  Stmt **SubExprs;
1806  unsigned NumArgs;
1807  SourceLocation RParenLoc;
1808
1809protected:
1810  // These versions of the constructor are for derived classes.
1811  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
1812           Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
1813           SourceLocation rparenloc);
1814  CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
1815
1816  Stmt *getPreArg(unsigned i) {
1817    assert(i < getNumPreArgs() && "Prearg access out of range!");
1818    return SubExprs[PREARGS_START+i];
1819  }
1820  const Stmt *getPreArg(unsigned i) const {
1821    assert(i < getNumPreArgs() && "Prearg access out of range!");
1822    return SubExprs[PREARGS_START+i];
1823  }
1824  void setPreArg(unsigned i, Stmt *PreArg) {
1825    assert(i < getNumPreArgs() && "Prearg access out of range!");
1826    SubExprs[PREARGS_START+i] = PreArg;
1827  }
1828
1829  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
1830
1831public:
1832  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1833           ExprValueKind VK, SourceLocation rparenloc);
1834
1835  /// \brief Build an empty call expression.
1836  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1837
1838  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1839  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1840  void setCallee(Expr *F) { SubExprs[FN] = F; }
1841
1842  Decl *getCalleeDecl();
1843  const Decl *getCalleeDecl() const {
1844    return const_cast<CallExpr*>(this)->getCalleeDecl();
1845  }
1846
1847  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1848  FunctionDecl *getDirectCallee();
1849  const FunctionDecl *getDirectCallee() const {
1850    return const_cast<CallExpr*>(this)->getDirectCallee();
1851  }
1852
1853  /// getNumArgs - Return the number of actual arguments to this call.
1854  ///
1855  unsigned getNumArgs() const { return NumArgs; }
1856
1857  /// \brief Retrieve the call arguments.
1858  Expr **getArgs() {
1859    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
1860  }
1861
1862  /// getArg - Return the specified argument.
1863  Expr *getArg(unsigned Arg) {
1864    assert(Arg < NumArgs && "Arg access out of range!");
1865    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1866  }
1867  const Expr *getArg(unsigned Arg) const {
1868    assert(Arg < NumArgs && "Arg access out of range!");
1869    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1870  }
1871
1872  /// setArg - Set the specified argument.
1873  void setArg(unsigned Arg, Expr *ArgExpr) {
1874    assert(Arg < NumArgs && "Arg access out of range!");
1875    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
1876  }
1877
1878  /// setNumArgs - This changes the number of arguments present in this call.
1879  /// Any orphaned expressions are deleted by this, and any new operands are set
1880  /// to null.
1881  void setNumArgs(ASTContext& C, unsigned NumArgs);
1882
1883  typedef ExprIterator arg_iterator;
1884  typedef ConstExprIterator const_arg_iterator;
1885
1886  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
1887  arg_iterator arg_end() {
1888    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1889  }
1890  const_arg_iterator arg_begin() const {
1891    return SubExprs+PREARGS_START+getNumPreArgs();
1892  }
1893  const_arg_iterator arg_end() const {
1894    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1895  }
1896
1897  /// getNumCommas - Return the number of commas that must have been present in
1898  /// this function call.
1899  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1900
1901  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1902  /// not, return 0.
1903  unsigned isBuiltinCall(const ASTContext &Context) const;
1904
1905  /// getCallReturnType - Get the return type of the call expr. This is not
1906  /// always the type of the expr itself, if the return type is a reference
1907  /// type.
1908  QualType getCallReturnType() const;
1909
1910  SourceLocation getRParenLoc() const { return RParenLoc; }
1911  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1912
1913  SourceRange getSourceRange() const;
1914
1915  static bool classof(const Stmt *T) {
1916    return T->getStmtClass() >= firstCallExprConstant &&
1917           T->getStmtClass() <= lastCallExprConstant;
1918  }
1919  static bool classof(const CallExpr *) { return true; }
1920
1921  // Iterators
1922  child_range children() {
1923    return child_range(&SubExprs[0],
1924                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
1925  }
1926};
1927
1928/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1929///
1930class MemberExpr : public Expr {
1931  /// Extra data stored in some member expressions.
1932  struct MemberNameQualifier {
1933    /// \brief The nested-name-specifier that qualifies the name, including
1934    /// source-location information.
1935    NestedNameSpecifierLoc QualifierLoc;
1936
1937    /// \brief The DeclAccessPair through which the MemberDecl was found due to
1938    /// name qualifiers.
1939    DeclAccessPair FoundDecl;
1940  };
1941
1942  /// Base - the expression for the base pointer or structure references.  In
1943  /// X.F, this is "X".
1944  Stmt *Base;
1945
1946  /// MemberDecl - This is the decl being referenced by the field/member name.
1947  /// In X.F, this is the decl referenced by F.
1948  ValueDecl *MemberDecl;
1949
1950  /// MemberLoc - This is the location of the member name.
1951  SourceLocation MemberLoc;
1952
1953  /// MemberDNLoc - Provides source/type location info for the
1954  /// declaration name embedded in MemberDecl.
1955  DeclarationNameLoc MemberDNLoc;
1956
1957  /// IsArrow - True if this is "X->F", false if this is "X.F".
1958  bool IsArrow : 1;
1959
1960  /// \brief True if this member expression used a nested-name-specifier to
1961  /// refer to the member, e.g., "x->Base::f", or found its member via a using
1962  /// declaration.  When true, a MemberNameQualifier
1963  /// structure is allocated immediately after the MemberExpr.
1964  bool HasQualifierOrFoundDecl : 1;
1965
1966  /// \brief True if this member expression specified a template argument list
1967  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1968  /// structure (and its TemplateArguments) are allocated immediately after
1969  /// the MemberExpr or, if the member expression also has a qualifier, after
1970  /// the MemberNameQualifier structure.
1971  bool HasExplicitTemplateArgumentList : 1;
1972
1973  /// \brief Retrieve the qualifier that preceded the member name, if any.
1974  MemberNameQualifier *getMemberQualifier() {
1975    assert(HasQualifierOrFoundDecl);
1976    return reinterpret_cast<MemberNameQualifier *> (this + 1);
1977  }
1978
1979  /// \brief Retrieve the qualifier that preceded the member name, if any.
1980  const MemberNameQualifier *getMemberQualifier() const {
1981    return const_cast<MemberExpr *>(this)->getMemberQualifier();
1982  }
1983
1984public:
1985  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1986             const DeclarationNameInfo &NameInfo, QualType ty,
1987             ExprValueKind VK, ExprObjectKind OK)
1988    : Expr(MemberExprClass, ty, VK, OK,
1989           base->isTypeDependent(), base->isValueDependent(),
1990           base->containsUnexpandedParameterPack()),
1991      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
1992      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
1993      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {
1994    assert(memberdecl->getDeclName() == NameInfo.getName());
1995  }
1996
1997  // NOTE: this constructor should be used only when it is known that
1998  // the member name can not provide additional syntactic info
1999  // (i.e., source locations for C++ operator names or type source info
2000  // for constructors, destructors and conversion oeprators).
2001  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2002             SourceLocation l, QualType ty,
2003             ExprValueKind VK, ExprObjectKind OK)
2004    : Expr(MemberExprClass, ty, VK, OK,
2005           base->isTypeDependent(), base->isValueDependent(),
2006           base->containsUnexpandedParameterPack()),
2007      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
2008      IsArrow(isarrow),
2009      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
2010
2011  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
2012                            NestedNameSpecifierLoc QualifierLoc,
2013                            ValueDecl *memberdecl, DeclAccessPair founddecl,
2014                            DeclarationNameInfo MemberNameInfo,
2015                            const TemplateArgumentListInfo *targs,
2016                            QualType ty, ExprValueKind VK, ExprObjectKind OK);
2017
2018  void setBase(Expr *E) { Base = E; }
2019  Expr *getBase() const { return cast<Expr>(Base); }
2020
2021  /// \brief Retrieve the member declaration to which this expression refers.
2022  ///
2023  /// The returned declaration will either be a FieldDecl or (in C++)
2024  /// a CXXMethodDecl.
2025  ValueDecl *getMemberDecl() const { return MemberDecl; }
2026  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2027
2028  /// \brief Retrieves the declaration found by lookup.
2029  DeclAccessPair getFoundDecl() const {
2030    if (!HasQualifierOrFoundDecl)
2031      return DeclAccessPair::make(getMemberDecl(),
2032                                  getMemberDecl()->getAccess());
2033    return getMemberQualifier()->FoundDecl;
2034  }
2035
2036  /// \brief Determines whether this member expression actually had
2037  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2038  /// x->Base::foo.
2039  bool hasQualifier() const { return getQualifier() != 0; }
2040
2041  /// \brief If the member name was qualified, retrieves the
2042  /// nested-name-specifier that precedes the member name. Otherwise, returns
2043  /// NULL.
2044  NestedNameSpecifier *getQualifier() const {
2045    if (!HasQualifierOrFoundDecl)
2046      return 0;
2047
2048    return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2049  }
2050
2051  /// \brief If the member name was qualified, retrieves the
2052  /// nested-name-specifier that precedes the member name, with source-location
2053  /// information.
2054  NestedNameSpecifierLoc getQualifierLoc() const {
2055    if (!hasQualifier())
2056      return NestedNameSpecifierLoc();
2057
2058    return getMemberQualifier()->QualifierLoc;
2059  }
2060
2061  /// \brief Determines whether this member expression actually had a C++
2062  /// template argument list explicitly specified, e.g., x.f<int>.
2063  bool hasExplicitTemplateArgs() const {
2064    return HasExplicitTemplateArgumentList;
2065  }
2066
2067  /// \brief Copies the template arguments (if present) into the given
2068  /// structure.
2069  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2070    if (hasExplicitTemplateArgs())
2071      getExplicitTemplateArgs().copyInto(List);
2072  }
2073
2074  /// \brief Retrieve the explicit template argument list that
2075  /// follow the member template name.  This must only be called on an
2076  /// expression with explicit template arguments.
2077  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
2078    assert(HasExplicitTemplateArgumentList);
2079    if (!HasQualifierOrFoundDecl)
2080      return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
2081
2082    return *reinterpret_cast<ExplicitTemplateArgumentList *>(
2083                                                      getMemberQualifier() + 1);
2084  }
2085
2086  /// \brief Retrieve the explicit template argument list that
2087  /// followed the member template name.  This must only be called on
2088  /// an expression with explicit template arguments.
2089  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
2090    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2091  }
2092
2093  /// \brief Retrieves the optional explicit template arguments.
2094  /// This points to the same data as getExplicitTemplateArgs(), but
2095  /// returns null if there are no explicit template arguments.
2096  const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const {
2097    if (!hasExplicitTemplateArgs()) return 0;
2098    return &getExplicitTemplateArgs();
2099  }
2100
2101  /// \brief Retrieve the location of the left angle bracket following the
2102  /// member name ('<'), if any.
2103  SourceLocation getLAngleLoc() const {
2104    if (!HasExplicitTemplateArgumentList)
2105      return SourceLocation();
2106
2107    return getExplicitTemplateArgs().LAngleLoc;
2108  }
2109
2110  /// \brief Retrieve the template arguments provided as part of this
2111  /// template-id.
2112  const TemplateArgumentLoc *getTemplateArgs() const {
2113    if (!HasExplicitTemplateArgumentList)
2114      return 0;
2115
2116    return getExplicitTemplateArgs().getTemplateArgs();
2117  }
2118
2119  /// \brief Retrieve the number of template arguments provided as part of this
2120  /// template-id.
2121  unsigned getNumTemplateArgs() const {
2122    if (!HasExplicitTemplateArgumentList)
2123      return 0;
2124
2125    return getExplicitTemplateArgs().NumTemplateArgs;
2126  }
2127
2128  /// \brief Retrieve the location of the right angle bracket following the
2129  /// template arguments ('>').
2130  SourceLocation getRAngleLoc() const {
2131    if (!HasExplicitTemplateArgumentList)
2132      return SourceLocation();
2133
2134    return getExplicitTemplateArgs().RAngleLoc;
2135  }
2136
2137  /// \brief Retrieve the member declaration name info.
2138  DeclarationNameInfo getMemberNameInfo() const {
2139    return DeclarationNameInfo(MemberDecl->getDeclName(),
2140                               MemberLoc, MemberDNLoc);
2141  }
2142
2143  bool isArrow() const { return IsArrow; }
2144  void setArrow(bool A) { IsArrow = A; }
2145
2146  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2147  /// location of 'F'.
2148  SourceLocation getMemberLoc() const { return MemberLoc; }
2149  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2150
2151  SourceRange getSourceRange() const;
2152
2153  SourceLocation getExprLoc() const { return MemberLoc; }
2154
2155  /// \brief Determine whether the base of this explicit is implicit.
2156  bool isImplicitAccess() const {
2157    return getBase() && getBase()->isImplicitCXXThis();
2158  }
2159
2160  static bool classof(const Stmt *T) {
2161    return T->getStmtClass() == MemberExprClass;
2162  }
2163  static bool classof(const MemberExpr *) { return true; }
2164
2165  // Iterators
2166  child_range children() { return child_range(&Base, &Base+1); }
2167
2168  friend class ASTReader;
2169  friend class ASTStmtWriter;
2170};
2171
2172/// CompoundLiteralExpr - [C99 6.5.2.5]
2173///
2174class CompoundLiteralExpr : public Expr {
2175  /// LParenLoc - If non-null, this is the location of the left paren in a
2176  /// compound literal like "(int){4}".  This can be null if this is a
2177  /// synthesized compound expression.
2178  SourceLocation LParenLoc;
2179
2180  /// The type as written.  This can be an incomplete array type, in
2181  /// which case the actual expression type will be different.
2182  TypeSourceInfo *TInfo;
2183  Stmt *Init;
2184  bool FileScope;
2185public:
2186  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2187                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2188    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2189           tinfo->getType()->isDependentType(),
2190           init->isValueDependent(),
2191           init->containsUnexpandedParameterPack()),
2192      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
2193
2194  /// \brief Construct an empty compound literal.
2195  explicit CompoundLiteralExpr(EmptyShell Empty)
2196    : Expr(CompoundLiteralExprClass, Empty) { }
2197
2198  const Expr *getInitializer() const { return cast<Expr>(Init); }
2199  Expr *getInitializer() { return cast<Expr>(Init); }
2200  void setInitializer(Expr *E) { Init = E; }
2201
2202  bool isFileScope() const { return FileScope; }
2203  void setFileScope(bool FS) { FileScope = FS; }
2204
2205  SourceLocation getLParenLoc() const { return LParenLoc; }
2206  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2207
2208  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
2209  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
2210
2211  SourceRange getSourceRange() const {
2212    // FIXME: Init should never be null.
2213    if (!Init)
2214      return SourceRange();
2215    if (LParenLoc.isInvalid())
2216      return Init->getSourceRange();
2217    return SourceRange(LParenLoc, Init->getLocEnd());
2218  }
2219
2220  static bool classof(const Stmt *T) {
2221    return T->getStmtClass() == CompoundLiteralExprClass;
2222  }
2223  static bool classof(const CompoundLiteralExpr *) { return true; }
2224
2225  // Iterators
2226  child_range children() { return child_range(&Init, &Init+1); }
2227};
2228
2229/// CastExpr - Base class for type casts, including both implicit
2230/// casts (ImplicitCastExpr) and explicit casts that have some
2231/// representation in the source code (ExplicitCastExpr's derived
2232/// classes).
2233class CastExpr : public Expr {
2234public:
2235  typedef clang::CastKind CastKind;
2236
2237private:
2238  Stmt *Op;
2239
2240  void CheckCastConsistency() const {
2241#ifndef NDEBUG
2242    switch (getCastKind()) {
2243    case CK_DerivedToBase:
2244    case CK_UncheckedDerivedToBase:
2245    case CK_DerivedToBaseMemberPointer:
2246    case CK_BaseToDerived:
2247    case CK_BaseToDerivedMemberPointer:
2248      assert(!path_empty() && "Cast kind should have a base path!");
2249      break;
2250
2251    // These should not have an inheritance path.
2252    case CK_BitCast:
2253    case CK_Dynamic:
2254    case CK_ToUnion:
2255    case CK_ArrayToPointerDecay:
2256    case CK_FunctionToPointerDecay:
2257    case CK_NullToMemberPointer:
2258    case CK_NullToPointer:
2259    case CK_ConstructorConversion:
2260    case CK_IntegralToPointer:
2261    case CK_PointerToIntegral:
2262    case CK_ToVoid:
2263    case CK_VectorSplat:
2264    case CK_IntegralCast:
2265    case CK_IntegralToFloating:
2266    case CK_FloatingToIntegral:
2267    case CK_FloatingCast:
2268    case CK_AnyPointerToObjCPointerCast:
2269    case CK_AnyPointerToBlockPointerCast:
2270    case CK_ObjCObjectLValueCast:
2271    case CK_FloatingRealToComplex:
2272    case CK_FloatingComplexToReal:
2273    case CK_FloatingComplexCast:
2274    case CK_FloatingComplexToIntegralComplex:
2275    case CK_IntegralRealToComplex:
2276    case CK_IntegralComplexToReal:
2277    case CK_IntegralComplexCast:
2278    case CK_IntegralComplexToFloatingComplex:
2279    case CK_ObjCProduceObject:
2280    case CK_ObjCConsumeObject:
2281      assert(!getType()->isBooleanType() && "unheralded conversion to bool");
2282      // fallthrough to check for null base path
2283
2284    case CK_Dependent:
2285    case CK_LValueToRValue:
2286    case CK_GetObjCProperty:
2287    case CK_NoOp:
2288    case CK_PointerToBoolean:
2289    case CK_IntegralToBoolean:
2290    case CK_FloatingToBoolean:
2291    case CK_MemberPointerToBoolean:
2292    case CK_FloatingComplexToBoolean:
2293    case CK_IntegralComplexToBoolean:
2294    case CK_LValueBitCast:            // -> bool&
2295    case CK_UserDefinedConversion:    // operator bool()
2296      assert(path_empty() && "Cast kind should not have a base path!");
2297      break;
2298    }
2299#endif
2300  }
2301
2302  const CXXBaseSpecifier * const *path_buffer() const {
2303    return const_cast<CastExpr*>(this)->path_buffer();
2304  }
2305  CXXBaseSpecifier **path_buffer();
2306
2307  void setBasePathSize(unsigned basePathSize) {
2308    CastExprBits.BasePathSize = basePathSize;
2309    assert(CastExprBits.BasePathSize == basePathSize &&
2310           "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2311  }
2312
2313protected:
2314  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2315           const CastKind kind, Expr *op, unsigned BasePathSize) :
2316    Expr(SC, ty, VK, OK_Ordinary,
2317         // Cast expressions are type-dependent if the type is
2318         // dependent (C++ [temp.dep.expr]p3).
2319         ty->isDependentType(),
2320         // Cast expressions are value-dependent if the type is
2321         // dependent or if the subexpression is value-dependent.
2322         ty->isDependentType() || (op && op->isValueDependent()),
2323         (ty->containsUnexpandedParameterPack() ||
2324          op->containsUnexpandedParameterPack())),
2325    Op(op) {
2326    assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2327    CastExprBits.Kind = kind;
2328    setBasePathSize(BasePathSize);
2329    CheckCastConsistency();
2330  }
2331
2332  /// \brief Construct an empty cast.
2333  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2334    : Expr(SC, Empty) {
2335    setBasePathSize(BasePathSize);
2336  }
2337
2338public:
2339  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2340  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2341  const char *getCastKindName() const;
2342
2343  Expr *getSubExpr() { return cast<Expr>(Op); }
2344  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2345  void setSubExpr(Expr *E) { Op = E; }
2346
2347  /// \brief Retrieve the cast subexpression as it was written in the source
2348  /// code, looking through any implicit casts or other intermediate nodes
2349  /// introduced by semantic analysis.
2350  Expr *getSubExprAsWritten();
2351  const Expr *getSubExprAsWritten() const {
2352    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2353  }
2354
2355  typedef CXXBaseSpecifier **path_iterator;
2356  typedef const CXXBaseSpecifier * const *path_const_iterator;
2357  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2358  unsigned path_size() const { return CastExprBits.BasePathSize; }
2359  path_iterator path_begin() { return path_buffer(); }
2360  path_iterator path_end() { return path_buffer() + path_size(); }
2361  path_const_iterator path_begin() const { return path_buffer(); }
2362  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2363
2364  void setCastPath(const CXXCastPath &Path);
2365
2366  static bool classof(const Stmt *T) {
2367    return T->getStmtClass() >= firstCastExprConstant &&
2368           T->getStmtClass() <= lastCastExprConstant;
2369  }
2370  static bool classof(const CastExpr *) { return true; }
2371
2372  // Iterators
2373  child_range children() { return child_range(&Op, &Op+1); }
2374};
2375
2376/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2377/// conversions, which have no direct representation in the original
2378/// source code. For example: converting T[]->T*, void f()->void
2379/// (*f)(), float->double, short->int, etc.
2380///
2381/// In C, implicit casts always produce rvalues. However, in C++, an
2382/// implicit cast whose result is being bound to a reference will be
2383/// an lvalue or xvalue. For example:
2384///
2385/// @code
2386/// class Base { };
2387/// class Derived : public Base { };
2388/// Derived &&ref();
2389/// void f(Derived d) {
2390///   Base& b = d; // initializer is an ImplicitCastExpr
2391///                // to an lvalue of type Base
2392///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2393///                     // to an xvalue of type Base
2394/// }
2395/// @endcode
2396class ImplicitCastExpr : public CastExpr {
2397private:
2398  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2399                   unsigned BasePathLength, ExprValueKind VK)
2400    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2401  }
2402
2403  /// \brief Construct an empty implicit cast.
2404  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2405    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2406
2407public:
2408  enum OnStack_t { OnStack };
2409  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2410                   ExprValueKind VK)
2411    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2412  }
2413
2414  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2415                                  CastKind Kind, Expr *Operand,
2416                                  const CXXCastPath *BasePath,
2417                                  ExprValueKind Cat);
2418
2419  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2420
2421  SourceRange getSourceRange() const {
2422    return getSubExpr()->getSourceRange();
2423  }
2424
2425  static bool classof(const Stmt *T) {
2426    return T->getStmtClass() == ImplicitCastExprClass;
2427  }
2428  static bool classof(const ImplicitCastExpr *) { return true; }
2429};
2430
2431/// ExplicitCastExpr - An explicit cast written in the source
2432/// code.
2433///
2434/// This class is effectively an abstract class, because it provides
2435/// the basic representation of an explicitly-written cast without
2436/// specifying which kind of cast (C cast, functional cast, static
2437/// cast, etc.) was written; specific derived classes represent the
2438/// particular style of cast and its location information.
2439///
2440/// Unlike implicit casts, explicit cast nodes have two different
2441/// types: the type that was written into the source code, and the
2442/// actual type of the expression as determined by semantic
2443/// analysis. These types may differ slightly. For example, in C++ one
2444/// can cast to a reference type, which indicates that the resulting
2445/// expression will be an lvalue or xvalue. The reference type, however,
2446/// will not be used as the type of the expression.
2447class ExplicitCastExpr : public CastExpr {
2448  /// TInfo - Source type info for the (written) type
2449  /// this expression is casting to.
2450  TypeSourceInfo *TInfo;
2451
2452protected:
2453  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2454                   CastKind kind, Expr *op, unsigned PathSize,
2455                   TypeSourceInfo *writtenTy)
2456    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2457
2458  /// \brief Construct an empty explicit cast.
2459  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2460    : CastExpr(SC, Shell, PathSize) { }
2461
2462public:
2463  /// getTypeInfoAsWritten - Returns the type source info for the type
2464  /// that this expression is casting to.
2465  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2466  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2467
2468  /// getTypeAsWritten - Returns the type that this expression is
2469  /// casting to, as written in the source code.
2470  QualType getTypeAsWritten() const { return TInfo->getType(); }
2471
2472  static bool classof(const Stmt *T) {
2473     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2474            T->getStmtClass() <= lastExplicitCastExprConstant;
2475  }
2476  static bool classof(const ExplicitCastExpr *) { return true; }
2477};
2478
2479/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2480/// cast in C++ (C++ [expr.cast]), which uses the syntax
2481/// (Type)expr. For example: @c (int)f.
2482class CStyleCastExpr : public ExplicitCastExpr {
2483  SourceLocation LPLoc; // the location of the left paren
2484  SourceLocation RPLoc; // the location of the right paren
2485
2486  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2487                 unsigned PathSize, TypeSourceInfo *writtenTy,
2488                 SourceLocation l, SourceLocation r)
2489    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2490                       writtenTy), LPLoc(l), RPLoc(r) {}
2491
2492  /// \brief Construct an empty C-style explicit cast.
2493  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2494    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2495
2496public:
2497  static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2498                                ExprValueKind VK, CastKind K,
2499                                Expr *Op, const CXXCastPath *BasePath,
2500                                TypeSourceInfo *WrittenTy, SourceLocation L,
2501                                SourceLocation R);
2502
2503  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2504
2505  SourceLocation getLParenLoc() const { return LPLoc; }
2506  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2507
2508  SourceLocation getRParenLoc() const { return RPLoc; }
2509  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2510
2511  SourceRange getSourceRange() const {
2512    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2513  }
2514  static bool classof(const Stmt *T) {
2515    return T->getStmtClass() == CStyleCastExprClass;
2516  }
2517  static bool classof(const CStyleCastExpr *) { return true; }
2518};
2519
2520/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2521///
2522/// This expression node kind describes a builtin binary operation,
2523/// such as "x + y" for integer values "x" and "y". The operands will
2524/// already have been converted to appropriate types (e.g., by
2525/// performing promotions or conversions).
2526///
2527/// In C++, where operators may be overloaded, a different kind of
2528/// expression node (CXXOperatorCallExpr) is used to express the
2529/// invocation of an overloaded operator with operator syntax. Within
2530/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2531/// used to store an expression "x + y" depends on the subexpressions
2532/// for x and y. If neither x or y is type-dependent, and the "+"
2533/// operator resolves to a built-in operation, BinaryOperator will be
2534/// used to express the computation (x and y may still be
2535/// value-dependent). If either x or y is type-dependent, or if the
2536/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2537/// be used to express the computation.
2538class BinaryOperator : public Expr {
2539public:
2540  typedef BinaryOperatorKind Opcode;
2541
2542private:
2543  unsigned Opc : 6;
2544  SourceLocation OpLoc;
2545
2546  enum { LHS, RHS, END_EXPR };
2547  Stmt* SubExprs[END_EXPR];
2548public:
2549
2550  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2551                 ExprValueKind VK, ExprObjectKind OK,
2552                 SourceLocation opLoc)
2553    : Expr(BinaryOperatorClass, ResTy, VK, OK,
2554           lhs->isTypeDependent() || rhs->isTypeDependent(),
2555           lhs->isValueDependent() || rhs->isValueDependent(),
2556           (lhs->containsUnexpandedParameterPack() ||
2557            rhs->containsUnexpandedParameterPack())),
2558      Opc(opc), OpLoc(opLoc) {
2559    SubExprs[LHS] = lhs;
2560    SubExprs[RHS] = rhs;
2561    assert(!isCompoundAssignmentOp() &&
2562           "Use ArithAssignBinaryOperator for compound assignments");
2563  }
2564
2565  /// \brief Construct an empty binary operator.
2566  explicit BinaryOperator(EmptyShell Empty)
2567    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2568
2569  SourceLocation getOperatorLoc() const { return OpLoc; }
2570  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2571
2572  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2573  void setOpcode(Opcode O) { Opc = O; }
2574
2575  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2576  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2577  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2578  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2579
2580  SourceRange getSourceRange() const {
2581    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2582  }
2583
2584  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2585  /// corresponds to, e.g. "<<=".
2586  static const char *getOpcodeStr(Opcode Op);
2587
2588  const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2589
2590  /// \brief Retrieve the binary opcode that corresponds to the given
2591  /// overloaded operator.
2592  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2593
2594  /// \brief Retrieve the overloaded operator kind that corresponds to
2595  /// the given binary opcode.
2596  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2597
2598  /// predicates to categorize the respective opcodes.
2599  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2600  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2601  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2602  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2603  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2604  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2605
2606  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2607  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2608
2609  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2610  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2611
2612  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2613  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2614
2615  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2616  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2617
2618  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2619  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2620
2621  static bool isAssignmentOp(Opcode Opc) {
2622    return Opc >= BO_Assign && Opc <= BO_OrAssign;
2623  }
2624  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2625
2626  static bool isCompoundAssignmentOp(Opcode Opc) {
2627    return Opc > BO_Assign && Opc <= BO_OrAssign;
2628  }
2629  bool isCompoundAssignmentOp() const {
2630    return isCompoundAssignmentOp(getOpcode());
2631  }
2632
2633  static bool isShiftAssignOp(Opcode Opc) {
2634    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2635  }
2636  bool isShiftAssignOp() const {
2637    return isShiftAssignOp(getOpcode());
2638  }
2639
2640  static bool classof(const Stmt *S) {
2641    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2642           S->getStmtClass() <= lastBinaryOperatorConstant;
2643  }
2644  static bool classof(const BinaryOperator *) { return true; }
2645
2646  // Iterators
2647  child_range children() {
2648    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2649  }
2650
2651protected:
2652  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2653                 ExprValueKind VK, ExprObjectKind OK,
2654                 SourceLocation opLoc, bool dead)
2655    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
2656           lhs->isTypeDependent() || rhs->isTypeDependent(),
2657           lhs->isValueDependent() || rhs->isValueDependent(),
2658           (lhs->containsUnexpandedParameterPack() ||
2659            rhs->containsUnexpandedParameterPack())),
2660      Opc(opc), OpLoc(opLoc) {
2661    SubExprs[LHS] = lhs;
2662    SubExprs[RHS] = rhs;
2663  }
2664
2665  BinaryOperator(StmtClass SC, EmptyShell Empty)
2666    : Expr(SC, Empty), Opc(BO_MulAssign) { }
2667};
2668
2669/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2670/// track of the type the operation is performed in.  Due to the semantics of
2671/// these operators, the operands are promoted, the aritmetic performed, an
2672/// implicit conversion back to the result type done, then the assignment takes
2673/// place.  This captures the intermediate type which the computation is done
2674/// in.
2675class CompoundAssignOperator : public BinaryOperator {
2676  QualType ComputationLHSType;
2677  QualType ComputationResultType;
2678public:
2679  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
2680                         ExprValueKind VK, ExprObjectKind OK,
2681                         QualType CompLHSType, QualType CompResultType,
2682                         SourceLocation OpLoc)
2683    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true),
2684      ComputationLHSType(CompLHSType),
2685      ComputationResultType(CompResultType) {
2686    assert(isCompoundAssignmentOp() &&
2687           "Only should be used for compound assignments");
2688  }
2689
2690  /// \brief Build an empty compound assignment operator expression.
2691  explicit CompoundAssignOperator(EmptyShell Empty)
2692    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2693
2694  // The two computation types are the type the LHS is converted
2695  // to for the computation and the type of the result; the two are
2696  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2697  QualType getComputationLHSType() const { return ComputationLHSType; }
2698  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2699
2700  QualType getComputationResultType() const { return ComputationResultType; }
2701  void setComputationResultType(QualType T) { ComputationResultType = T; }
2702
2703  static bool classof(const CompoundAssignOperator *) { return true; }
2704  static bool classof(const Stmt *S) {
2705    return S->getStmtClass() == CompoundAssignOperatorClass;
2706  }
2707};
2708
2709/// AbstractConditionalOperator - An abstract base class for
2710/// ConditionalOperator and BinaryConditionalOperator.
2711class AbstractConditionalOperator : public Expr {
2712  SourceLocation QuestionLoc, ColonLoc;
2713  friend class ASTStmtReader;
2714
2715protected:
2716  AbstractConditionalOperator(StmtClass SC, QualType T,
2717                              ExprValueKind VK, ExprObjectKind OK,
2718                              bool TD, bool VD,
2719                              bool ContainsUnexpandedParameterPack,
2720                              SourceLocation qloc,
2721                              SourceLocation cloc)
2722    : Expr(SC, T, VK, OK, TD, VD, ContainsUnexpandedParameterPack),
2723      QuestionLoc(qloc), ColonLoc(cloc) {}
2724
2725  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
2726    : Expr(SC, Empty) { }
2727
2728public:
2729  // getCond - Return the expression representing the condition for
2730  //   the ?: operator.
2731  Expr *getCond() const;
2732
2733  // getTrueExpr - Return the subexpression representing the value of
2734  //   the expression if the condition evaluates to true.
2735  Expr *getTrueExpr() const;
2736
2737  // getFalseExpr - Return the subexpression representing the value of
2738  //   the expression if the condition evaluates to false.  This is
2739  //   the same as getRHS.
2740  Expr *getFalseExpr() const;
2741
2742  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2743  SourceLocation getColonLoc() const { return ColonLoc; }
2744
2745  static bool classof(const Stmt *T) {
2746    return T->getStmtClass() == ConditionalOperatorClass ||
2747           T->getStmtClass() == BinaryConditionalOperatorClass;
2748  }
2749  static bool classof(const AbstractConditionalOperator *) { return true; }
2750};
2751
2752/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
2753/// middle" extension is a BinaryConditionalOperator.
2754class ConditionalOperator : public AbstractConditionalOperator {
2755  enum { COND, LHS, RHS, END_EXPR };
2756  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2757
2758  friend class ASTStmtReader;
2759public:
2760  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2761                      SourceLocation CLoc, Expr *rhs,
2762                      QualType t, ExprValueKind VK, ExprObjectKind OK)
2763    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
2764           // FIXME: the type of the conditional operator doesn't
2765           // depend on the type of the conditional, but the standard
2766           // seems to imply that it could. File a bug!
2767           (lhs->isTypeDependent() || rhs->isTypeDependent()),
2768           (cond->isValueDependent() || lhs->isValueDependent() ||
2769            rhs->isValueDependent()),
2770           (cond->containsUnexpandedParameterPack() ||
2771            lhs->containsUnexpandedParameterPack() ||
2772            rhs->containsUnexpandedParameterPack()),
2773                                  QLoc, CLoc) {
2774    SubExprs[COND] = cond;
2775    SubExprs[LHS] = lhs;
2776    SubExprs[RHS] = rhs;
2777  }
2778
2779  /// \brief Build an empty conditional operator.
2780  explicit ConditionalOperator(EmptyShell Empty)
2781    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
2782
2783  // getCond - Return the expression representing the condition for
2784  //   the ?: operator.
2785  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2786
2787  // getTrueExpr - Return the subexpression representing the value of
2788  //   the expression if the condition evaluates to true.
2789  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
2790
2791  // getFalseExpr - Return the subexpression representing the value of
2792  //   the expression if the condition evaluates to false.  This is
2793  //   the same as getRHS.
2794  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2795
2796  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2797  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2798
2799  SourceRange getSourceRange() const {
2800    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2801  }
2802  static bool classof(const Stmt *T) {
2803    return T->getStmtClass() == ConditionalOperatorClass;
2804  }
2805  static bool classof(const ConditionalOperator *) { return true; }
2806
2807  // Iterators
2808  child_range children() {
2809    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2810  }
2811};
2812
2813/// BinaryConditionalOperator - The GNU extension to the conditional
2814/// operator which allows the middle operand to be omitted.
2815///
2816/// This is a different expression kind on the assumption that almost
2817/// every client ends up needing to know that these are different.
2818class BinaryConditionalOperator : public AbstractConditionalOperator {
2819  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
2820
2821  /// - the common condition/left-hand-side expression, which will be
2822  ///   evaluated as the opaque value
2823  /// - the condition, expressed in terms of the opaque value
2824  /// - the left-hand-side, expressed in terms of the opaque value
2825  /// - the right-hand-side
2826  Stmt *SubExprs[NUM_SUBEXPRS];
2827  OpaqueValueExpr *OpaqueValue;
2828
2829  friend class ASTStmtReader;
2830public:
2831  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
2832                            Expr *cond, Expr *lhs, Expr *rhs,
2833                            SourceLocation qloc, SourceLocation cloc,
2834                            QualType t, ExprValueKind VK, ExprObjectKind OK)
2835    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
2836           (common->isTypeDependent() || rhs->isTypeDependent()),
2837           (common->isValueDependent() || rhs->isValueDependent()),
2838           (common->containsUnexpandedParameterPack() ||
2839            rhs->containsUnexpandedParameterPack()),
2840                                  qloc, cloc),
2841      OpaqueValue(opaqueValue) {
2842    SubExprs[COMMON] = common;
2843    SubExprs[COND] = cond;
2844    SubExprs[LHS] = lhs;
2845    SubExprs[RHS] = rhs;
2846
2847    OpaqueValue->setSourceExpr(common);
2848  }
2849
2850  /// \brief Build an empty conditional operator.
2851  explicit BinaryConditionalOperator(EmptyShell Empty)
2852    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
2853
2854  /// \brief getCommon - Return the common expression, written to the
2855  ///   left of the condition.  The opaque value will be bound to the
2856  ///   result of this expression.
2857  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
2858
2859  /// \brief getOpaqueValue - Return the opaque value placeholder.
2860  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
2861
2862  /// \brief getCond - Return the condition expression; this is defined
2863  ///   in terms of the opaque value.
2864  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2865
2866  /// \brief getTrueExpr - Return the subexpression which will be
2867  ///   evaluated if the condition evaluates to true;  this is defined
2868  ///   in terms of the opaque value.
2869  Expr *getTrueExpr() const {
2870    return cast<Expr>(SubExprs[LHS]);
2871  }
2872
2873  /// \brief getFalseExpr - Return the subexpression which will be
2874  ///   evaluated if the condnition evaluates to false; this is
2875  ///   defined in terms of the opaque value.
2876  Expr *getFalseExpr() const {
2877    return cast<Expr>(SubExprs[RHS]);
2878  }
2879
2880  SourceRange getSourceRange() const {
2881    return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd());
2882  }
2883  static bool classof(const Stmt *T) {
2884    return T->getStmtClass() == BinaryConditionalOperatorClass;
2885  }
2886  static bool classof(const BinaryConditionalOperator *) { return true; }
2887
2888  // Iterators
2889  child_range children() {
2890    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
2891  }
2892};
2893
2894inline Expr *AbstractConditionalOperator::getCond() const {
2895  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2896    return co->getCond();
2897  return cast<BinaryConditionalOperator>(this)->getCond();
2898}
2899
2900inline Expr *AbstractConditionalOperator::getTrueExpr() const {
2901  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2902    return co->getTrueExpr();
2903  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
2904}
2905
2906inline Expr *AbstractConditionalOperator::getFalseExpr() const {
2907  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2908    return co->getFalseExpr();
2909  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
2910}
2911
2912/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2913class AddrLabelExpr : public Expr {
2914  SourceLocation AmpAmpLoc, LabelLoc;
2915  LabelDecl *Label;
2916public:
2917  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
2918                QualType t)
2919    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false),
2920      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2921
2922  /// \brief Build an empty address of a label expression.
2923  explicit AddrLabelExpr(EmptyShell Empty)
2924    : Expr(AddrLabelExprClass, Empty) { }
2925
2926  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2927  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2928  SourceLocation getLabelLoc() const { return LabelLoc; }
2929  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2930
2931  SourceRange getSourceRange() const {
2932    return SourceRange(AmpAmpLoc, LabelLoc);
2933  }
2934
2935  LabelDecl *getLabel() const { return Label; }
2936  void setLabel(LabelDecl *L) { Label = L; }
2937
2938  static bool classof(const Stmt *T) {
2939    return T->getStmtClass() == AddrLabelExprClass;
2940  }
2941  static bool classof(const AddrLabelExpr *) { return true; }
2942
2943  // Iterators
2944  child_range children() { return child_range(); }
2945};
2946
2947/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2948/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2949/// takes the value of the last subexpression.
2950///
2951/// A StmtExpr is always an r-value; values "returned" out of a
2952/// StmtExpr will be copied.
2953class StmtExpr : public Expr {
2954  Stmt *SubStmt;
2955  SourceLocation LParenLoc, RParenLoc;
2956public:
2957  // FIXME: Does type-dependence need to be computed differently?
2958  StmtExpr(CompoundStmt *substmt, QualType T,
2959           SourceLocation lp, SourceLocation rp) :
2960    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
2961         T->isDependentType(), false, false),
2962    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2963
2964  /// \brief Build an empty statement expression.
2965  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2966
2967  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2968  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2969  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2970
2971  SourceRange getSourceRange() const {
2972    return SourceRange(LParenLoc, RParenLoc);
2973  }
2974
2975  SourceLocation getLParenLoc() const { return LParenLoc; }
2976  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2977  SourceLocation getRParenLoc() const { return RParenLoc; }
2978  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2979
2980  static bool classof(const Stmt *T) {
2981    return T->getStmtClass() == StmtExprClass;
2982  }
2983  static bool classof(const StmtExpr *) { return true; }
2984
2985  // Iterators
2986  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
2987};
2988
2989
2990/// ShuffleVectorExpr - clang-specific builtin-in function
2991/// __builtin_shufflevector.
2992/// This AST node represents a operator that does a constant
2993/// shuffle, similar to LLVM's shufflevector instruction. It takes
2994/// two vectors and a variable number of constant indices,
2995/// and returns the appropriately shuffled vector.
2996class ShuffleVectorExpr : public Expr {
2997  SourceLocation BuiltinLoc, RParenLoc;
2998
2999  // SubExprs - the list of values passed to the __builtin_shufflevector
3000  // function. The first two are vectors, and the rest are constant
3001  // indices.  The number of values in this list is always
3002  // 2+the number of indices in the vector type.
3003  Stmt **SubExprs;
3004  unsigned NumExprs;
3005
3006public:
3007  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3008                    QualType Type, SourceLocation BLoc,
3009                    SourceLocation RP);
3010
3011  /// \brief Build an empty vector-shuffle expression.
3012  explicit ShuffleVectorExpr(EmptyShell Empty)
3013    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3014
3015  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3016  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3017
3018  SourceLocation getRParenLoc() const { return RParenLoc; }
3019  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3020
3021  SourceRange getSourceRange() const {
3022    return SourceRange(BuiltinLoc, RParenLoc);
3023  }
3024  static bool classof(const Stmt *T) {
3025    return T->getStmtClass() == ShuffleVectorExprClass;
3026  }
3027  static bool classof(const ShuffleVectorExpr *) { return true; }
3028
3029  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
3030  /// constant expression, the actual arguments passed in, and the function
3031  /// pointers.
3032  unsigned getNumSubExprs() const { return NumExprs; }
3033
3034  /// \brief Retrieve the array of expressions.
3035  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3036
3037  /// getExpr - Return the Expr at the specified index.
3038  Expr *getExpr(unsigned Index) {
3039    assert((Index < NumExprs) && "Arg access out of range!");
3040    return cast<Expr>(SubExprs[Index]);
3041  }
3042  const Expr *getExpr(unsigned Index) const {
3043    assert((Index < NumExprs) && "Arg access out of range!");
3044    return cast<Expr>(SubExprs[Index]);
3045  }
3046
3047  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
3048
3049  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
3050    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3051    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
3052  }
3053
3054  // Iterators
3055  child_range children() {
3056    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3057  }
3058};
3059
3060/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3061/// This AST node is similar to the conditional operator (?:) in C, with
3062/// the following exceptions:
3063/// - the test expression must be a integer constant expression.
3064/// - the expression returned acts like the chosen subexpression in every
3065///   visible way: the type is the same as that of the chosen subexpression,
3066///   and all predicates (whether it's an l-value, whether it's an integer
3067///   constant expression, etc.) return the same result as for the chosen
3068///   sub-expression.
3069class ChooseExpr : public Expr {
3070  enum { COND, LHS, RHS, END_EXPR };
3071  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3072  SourceLocation BuiltinLoc, RParenLoc;
3073public:
3074  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3075             QualType t, ExprValueKind VK, ExprObjectKind OK,
3076             SourceLocation RP, bool TypeDependent, bool ValueDependent)
3077    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3078           (cond->containsUnexpandedParameterPack() ||
3079            lhs->containsUnexpandedParameterPack() ||
3080            rhs->containsUnexpandedParameterPack())),
3081      BuiltinLoc(BLoc), RParenLoc(RP) {
3082      SubExprs[COND] = cond;
3083      SubExprs[LHS] = lhs;
3084      SubExprs[RHS] = rhs;
3085    }
3086
3087  /// \brief Build an empty __builtin_choose_expr.
3088  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3089
3090  /// isConditionTrue - Return whether the condition is true (i.e. not
3091  /// equal to zero).
3092  bool isConditionTrue(const ASTContext &C) const;
3093
3094  /// getChosenSubExpr - Return the subexpression chosen according to the
3095  /// condition.
3096  Expr *getChosenSubExpr(const ASTContext &C) const {
3097    return isConditionTrue(C) ? getLHS() : getRHS();
3098  }
3099
3100  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3101  void setCond(Expr *E) { SubExprs[COND] = E; }
3102  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3103  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3104  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3105  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3106
3107  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3108  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3109
3110  SourceLocation getRParenLoc() const { return RParenLoc; }
3111  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3112
3113  SourceRange getSourceRange() const {
3114    return SourceRange(BuiltinLoc, RParenLoc);
3115  }
3116  static bool classof(const Stmt *T) {
3117    return T->getStmtClass() == ChooseExprClass;
3118  }
3119  static bool classof(const ChooseExpr *) { return true; }
3120
3121  // Iterators
3122  child_range children() {
3123    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3124  }
3125};
3126
3127/// GNUNullExpr - Implements the GNU __null extension, which is a name
3128/// for a null pointer constant that has integral type (e.g., int or
3129/// long) and is the same size and alignment as a pointer. The __null
3130/// extension is typically only used by system headers, which define
3131/// NULL as __null in C++ rather than using 0 (which is an integer
3132/// that may not match the size of a pointer).
3133class GNUNullExpr : public Expr {
3134  /// TokenLoc - The location of the __null keyword.
3135  SourceLocation TokenLoc;
3136
3137public:
3138  GNUNullExpr(QualType Ty, SourceLocation Loc)
3139    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false),
3140      TokenLoc(Loc) { }
3141
3142  /// \brief Build an empty GNU __null expression.
3143  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3144
3145  /// getTokenLocation - The location of the __null token.
3146  SourceLocation getTokenLocation() const { return TokenLoc; }
3147  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3148
3149  SourceRange getSourceRange() const {
3150    return SourceRange(TokenLoc);
3151  }
3152  static bool classof(const Stmt *T) {
3153    return T->getStmtClass() == GNUNullExprClass;
3154  }
3155  static bool classof(const GNUNullExpr *) { return true; }
3156
3157  // Iterators
3158  child_range children() { return child_range(); }
3159};
3160
3161/// VAArgExpr, used for the builtin function __builtin_va_arg.
3162class VAArgExpr : public Expr {
3163  Stmt *Val;
3164  TypeSourceInfo *TInfo;
3165  SourceLocation BuiltinLoc, RParenLoc;
3166public:
3167  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3168            SourceLocation RPLoc, QualType t)
3169    : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3170           t->isDependentType(), false,
3171           (TInfo->getType()->containsUnexpandedParameterPack() ||
3172            e->containsUnexpandedParameterPack())),
3173      Val(e), TInfo(TInfo),
3174      BuiltinLoc(BLoc),
3175      RParenLoc(RPLoc) { }
3176
3177  /// \brief Create an empty __builtin_va_arg expression.
3178  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3179
3180  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3181  Expr *getSubExpr() { return cast<Expr>(Val); }
3182  void setSubExpr(Expr *E) { Val = E; }
3183
3184  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3185  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3186
3187  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3188  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3189
3190  SourceLocation getRParenLoc() const { return RParenLoc; }
3191  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3192
3193  SourceRange getSourceRange() const {
3194    return SourceRange(BuiltinLoc, RParenLoc);
3195  }
3196  static bool classof(const Stmt *T) {
3197    return T->getStmtClass() == VAArgExprClass;
3198  }
3199  static bool classof(const VAArgExpr *) { return true; }
3200
3201  // Iterators
3202  child_range children() { return child_range(&Val, &Val+1); }
3203};
3204
3205/// @brief Describes an C or C++ initializer list.
3206///
3207/// InitListExpr describes an initializer list, which can be used to
3208/// initialize objects of different types, including
3209/// struct/class/union types, arrays, and vectors. For example:
3210///
3211/// @code
3212/// struct foo x = { 1, { 2, 3 } };
3213/// @endcode
3214///
3215/// Prior to semantic analysis, an initializer list will represent the
3216/// initializer list as written by the user, but will have the
3217/// placeholder type "void". This initializer list is called the
3218/// syntactic form of the initializer, and may contain C99 designated
3219/// initializers (represented as DesignatedInitExprs), initializations
3220/// of subobject members without explicit braces, and so on. Clients
3221/// interested in the original syntax of the initializer list should
3222/// use the syntactic form of the initializer list.
3223///
3224/// After semantic analysis, the initializer list will represent the
3225/// semantic form of the initializer, where the initializations of all
3226/// subobjects are made explicit with nested InitListExpr nodes and
3227/// C99 designators have been eliminated by placing the designated
3228/// initializations into the subobject they initialize. Additionally,
3229/// any "holes" in the initialization, where no initializer has been
3230/// specified for a particular subobject, will be replaced with
3231/// implicitly-generated ImplicitValueInitExpr expressions that
3232/// value-initialize the subobjects. Note, however, that the
3233/// initializer lists may still have fewer initializers than there are
3234/// elements to initialize within the object.
3235///
3236/// Given the semantic form of the initializer list, one can retrieve
3237/// the original syntactic form of that initializer list (if it
3238/// exists) using getSyntacticForm(). Since many initializer lists
3239/// have the same syntactic and semantic forms, getSyntacticForm() may
3240/// return NULL, indicating that the current initializer list also
3241/// serves as its syntactic form.
3242class InitListExpr : public Expr {
3243  // FIXME: Eliminate this vector in favor of ASTContext allocation
3244  typedef ASTVector<Stmt *> InitExprsTy;
3245  InitExprsTy InitExprs;
3246  SourceLocation LBraceLoc, RBraceLoc;
3247
3248  /// Contains the initializer list that describes the syntactic form
3249  /// written in the source code.
3250  InitListExpr *SyntacticForm;
3251
3252  /// \brief Either:
3253  ///  If this initializer list initializes an array with more elements than
3254  ///  there are initializers in the list, specifies an expression to be used
3255  ///  for value initialization of the rest of the elements.
3256  /// Or
3257  ///  If this initializer list initializes a union, specifies which
3258  ///  field within the union will be initialized.
3259  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3260
3261  /// Whether this initializer list originally had a GNU array-range
3262  /// designator in it. This is a temporary marker used by CodeGen.
3263  bool HadArrayRangeDesignator;
3264
3265public:
3266  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3267               Expr **initexprs, unsigned numinits,
3268               SourceLocation rbraceloc);
3269
3270  /// \brief Build an empty initializer list.
3271  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
3272    : Expr(InitListExprClass, Empty), InitExprs(C) { }
3273
3274  unsigned getNumInits() const { return InitExprs.size(); }
3275
3276  /// \brief Retrieve the set of initializers.
3277  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3278
3279  const Expr *getInit(unsigned Init) const {
3280    assert(Init < getNumInits() && "Initializer access out of range!");
3281    return cast_or_null<Expr>(InitExprs[Init]);
3282  }
3283
3284  Expr *getInit(unsigned Init) {
3285    assert(Init < getNumInits() && "Initializer access out of range!");
3286    return cast_or_null<Expr>(InitExprs[Init]);
3287  }
3288
3289  void setInit(unsigned Init, Expr *expr) {
3290    assert(Init < getNumInits() && "Initializer access out of range!");
3291    InitExprs[Init] = expr;
3292  }
3293
3294  /// \brief Reserve space for some number of initializers.
3295  void reserveInits(ASTContext &C, unsigned NumInits);
3296
3297  /// @brief Specify the number of initializers
3298  ///
3299  /// If there are more than @p NumInits initializers, the remaining
3300  /// initializers will be destroyed. If there are fewer than @p
3301  /// NumInits initializers, NULL expressions will be added for the
3302  /// unknown initializers.
3303  void resizeInits(ASTContext &Context, unsigned NumInits);
3304
3305  /// @brief Updates the initializer at index @p Init with the new
3306  /// expression @p expr, and returns the old expression at that
3307  /// location.
3308  ///
3309  /// When @p Init is out of range for this initializer list, the
3310  /// initializer list will be extended with NULL expressions to
3311  /// accommodate the new entry.
3312  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3313
3314  /// \brief If this initializer list initializes an array with more elements
3315  /// than there are initializers in the list, specifies an expression to be
3316  /// used for value initialization of the rest of the elements.
3317  Expr *getArrayFiller() {
3318    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3319  }
3320  const Expr *getArrayFiller() const {
3321    return const_cast<InitListExpr *>(this)->getArrayFiller();
3322  }
3323  void setArrayFiller(Expr *filler);
3324
3325  /// \brief If this initializes a union, specifies which field in the
3326  /// union to initialize.
3327  ///
3328  /// Typically, this field is the first named field within the
3329  /// union. However, a designated initializer can specify the
3330  /// initialization of a different field within the union.
3331  FieldDecl *getInitializedFieldInUnion() {
3332    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3333  }
3334  const FieldDecl *getInitializedFieldInUnion() const {
3335    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3336  }
3337  void setInitializedFieldInUnion(FieldDecl *FD) {
3338    ArrayFillerOrUnionFieldInit = FD;
3339  }
3340
3341  // Explicit InitListExpr's originate from source code (and have valid source
3342  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3343  bool isExplicit() {
3344    return LBraceLoc.isValid() && RBraceLoc.isValid();
3345  }
3346
3347  SourceLocation getLBraceLoc() const { return LBraceLoc; }
3348  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3349  SourceLocation getRBraceLoc() const { return RBraceLoc; }
3350  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3351
3352  /// @brief Retrieve the initializer list that describes the
3353  /// syntactic form of the initializer.
3354  ///
3355  ///
3356  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
3357  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
3358
3359  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
3360  void sawArrayRangeDesignator(bool ARD = true) {
3361    HadArrayRangeDesignator = ARD;
3362  }
3363
3364  SourceRange getSourceRange() const;
3365
3366  static bool classof(const Stmt *T) {
3367    return T->getStmtClass() == InitListExprClass;
3368  }
3369  static bool classof(const InitListExpr *) { return true; }
3370
3371  // Iterators
3372  child_range children() {
3373    if (InitExprs.empty()) return child_range();
3374    return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3375  }
3376
3377  typedef InitExprsTy::iterator iterator;
3378  typedef InitExprsTy::const_iterator const_iterator;
3379  typedef InitExprsTy::reverse_iterator reverse_iterator;
3380  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3381
3382  iterator begin() { return InitExprs.begin(); }
3383  const_iterator begin() const { return InitExprs.begin(); }
3384  iterator end() { return InitExprs.end(); }
3385  const_iterator end() const { return InitExprs.end(); }
3386  reverse_iterator rbegin() { return InitExprs.rbegin(); }
3387  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3388  reverse_iterator rend() { return InitExprs.rend(); }
3389  const_reverse_iterator rend() const { return InitExprs.rend(); }
3390
3391  friend class ASTStmtReader;
3392  friend class ASTStmtWriter;
3393};
3394
3395/// @brief Represents a C99 designated initializer expression.
3396///
3397/// A designated initializer expression (C99 6.7.8) contains one or
3398/// more designators (which can be field designators, array
3399/// designators, or GNU array-range designators) followed by an
3400/// expression that initializes the field or element(s) that the
3401/// designators refer to. For example, given:
3402///
3403/// @code
3404/// struct point {
3405///   double x;
3406///   double y;
3407/// };
3408/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3409/// @endcode
3410///
3411/// The InitListExpr contains three DesignatedInitExprs, the first of
3412/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3413/// designators, one array designator for @c [2] followed by one field
3414/// designator for @c .y. The initalization expression will be 1.0.
3415class DesignatedInitExpr : public Expr {
3416public:
3417  /// \brief Forward declaration of the Designator class.
3418  class Designator;
3419
3420private:
3421  /// The location of the '=' or ':' prior to the actual initializer
3422  /// expression.
3423  SourceLocation EqualOrColonLoc;
3424
3425  /// Whether this designated initializer used the GNU deprecated
3426  /// syntax rather than the C99 '=' syntax.
3427  bool GNUSyntax : 1;
3428
3429  /// The number of designators in this initializer expression.
3430  unsigned NumDesignators : 15;
3431
3432  /// \brief The designators in this designated initialization
3433  /// expression.
3434  Designator *Designators;
3435
3436  /// The number of subexpressions of this initializer expression,
3437  /// which contains both the initializer and any additional
3438  /// expressions used by array and array-range designators.
3439  unsigned NumSubExprs : 16;
3440
3441
3442  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3443                     const Designator *Designators,
3444                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
3445                     Expr **IndexExprs, unsigned NumIndexExprs,
3446                     Expr *Init);
3447
3448  explicit DesignatedInitExpr(unsigned NumSubExprs)
3449    : Expr(DesignatedInitExprClass, EmptyShell()),
3450      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3451
3452public:
3453  /// A field designator, e.g., ".x".
3454  struct FieldDesignator {
3455    /// Refers to the field that is being initialized. The low bit
3456    /// of this field determines whether this is actually a pointer
3457    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3458    /// initially constructed, a field designator will store an
3459    /// IdentifierInfo*. After semantic analysis has resolved that
3460    /// name, the field designator will instead store a FieldDecl*.
3461    uintptr_t NameOrField;
3462
3463    /// The location of the '.' in the designated initializer.
3464    unsigned DotLoc;
3465
3466    /// The location of the field name in the designated initializer.
3467    unsigned FieldLoc;
3468  };
3469
3470  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3471  struct ArrayOrRangeDesignator {
3472    /// Location of the first index expression within the designated
3473    /// initializer expression's list of subexpressions.
3474    unsigned Index;
3475    /// The location of the '[' starting the array range designator.
3476    unsigned LBracketLoc;
3477    /// The location of the ellipsis separating the start and end
3478    /// indices. Only valid for GNU array-range designators.
3479    unsigned EllipsisLoc;
3480    /// The location of the ']' terminating the array range designator.
3481    unsigned RBracketLoc;
3482  };
3483
3484  /// @brief Represents a single C99 designator.
3485  ///
3486  /// @todo This class is infuriatingly similar to clang::Designator,
3487  /// but minor differences (storing indices vs. storing pointers)
3488  /// keep us from reusing it. Try harder, later, to rectify these
3489  /// differences.
3490  class Designator {
3491    /// @brief The kind of designator this describes.
3492    enum {
3493      FieldDesignator,
3494      ArrayDesignator,
3495      ArrayRangeDesignator
3496    } Kind;
3497
3498    union {
3499      /// A field designator, e.g., ".x".
3500      struct FieldDesignator Field;
3501      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3502      struct ArrayOrRangeDesignator ArrayOrRange;
3503    };
3504    friend class DesignatedInitExpr;
3505
3506  public:
3507    Designator() {}
3508
3509    /// @brief Initializes a field designator.
3510    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3511               SourceLocation FieldLoc)
3512      : Kind(FieldDesignator) {
3513      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3514      Field.DotLoc = DotLoc.getRawEncoding();
3515      Field.FieldLoc = FieldLoc.getRawEncoding();
3516    }
3517
3518    /// @brief Initializes an array designator.
3519    Designator(unsigned Index, SourceLocation LBracketLoc,
3520               SourceLocation RBracketLoc)
3521      : Kind(ArrayDesignator) {
3522      ArrayOrRange.Index = Index;
3523      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3524      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3525      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3526    }
3527
3528    /// @brief Initializes a GNU array-range designator.
3529    Designator(unsigned Index, SourceLocation LBracketLoc,
3530               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3531      : Kind(ArrayRangeDesignator) {
3532      ArrayOrRange.Index = Index;
3533      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3534      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3535      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3536    }
3537
3538    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3539    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3540    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3541
3542    IdentifierInfo *getFieldName() const;
3543
3544    FieldDecl *getField() const {
3545      assert(Kind == FieldDesignator && "Only valid on a field designator");
3546      if (Field.NameOrField & 0x01)
3547        return 0;
3548      else
3549        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3550    }
3551
3552    void setField(FieldDecl *FD) {
3553      assert(Kind == FieldDesignator && "Only valid on a field designator");
3554      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3555    }
3556
3557    SourceLocation getDotLoc() const {
3558      assert(Kind == FieldDesignator && "Only valid on a field designator");
3559      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3560    }
3561
3562    SourceLocation getFieldLoc() const {
3563      assert(Kind == FieldDesignator && "Only valid on a field designator");
3564      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3565    }
3566
3567    SourceLocation getLBracketLoc() const {
3568      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3569             "Only valid on an array or array-range designator");
3570      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3571    }
3572
3573    SourceLocation getRBracketLoc() const {
3574      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3575             "Only valid on an array or array-range designator");
3576      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3577    }
3578
3579    SourceLocation getEllipsisLoc() const {
3580      assert(Kind == ArrayRangeDesignator &&
3581             "Only valid on an array-range designator");
3582      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3583    }
3584
3585    unsigned getFirstExprIndex() const {
3586      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3587             "Only valid on an array or array-range designator");
3588      return ArrayOrRange.Index;
3589    }
3590
3591    SourceLocation getStartLocation() const {
3592      if (Kind == FieldDesignator)
3593        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3594      else
3595        return getLBracketLoc();
3596    }
3597    SourceLocation getEndLocation() const {
3598      return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
3599    }
3600    SourceRange getSourceRange() const {
3601      return SourceRange(getStartLocation(), getEndLocation());
3602    }
3603  };
3604
3605  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3606                                    unsigned NumDesignators,
3607                                    Expr **IndexExprs, unsigned NumIndexExprs,
3608                                    SourceLocation EqualOrColonLoc,
3609                                    bool GNUSyntax, Expr *Init);
3610
3611  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3612
3613  /// @brief Returns the number of designators in this initializer.
3614  unsigned size() const { return NumDesignators; }
3615
3616  // Iterator access to the designators.
3617  typedef Designator *designators_iterator;
3618  designators_iterator designators_begin() { return Designators; }
3619  designators_iterator designators_end() {
3620    return Designators + NumDesignators;
3621  }
3622
3623  typedef const Designator *const_designators_iterator;
3624  const_designators_iterator designators_begin() const { return Designators; }
3625  const_designators_iterator designators_end() const {
3626    return Designators + NumDesignators;
3627  }
3628
3629  typedef std::reverse_iterator<designators_iterator>
3630          reverse_designators_iterator;
3631  reverse_designators_iterator designators_rbegin() {
3632    return reverse_designators_iterator(designators_end());
3633  }
3634  reverse_designators_iterator designators_rend() {
3635    return reverse_designators_iterator(designators_begin());
3636  }
3637
3638  typedef std::reverse_iterator<const_designators_iterator>
3639          const_reverse_designators_iterator;
3640  const_reverse_designators_iterator designators_rbegin() const {
3641    return const_reverse_designators_iterator(designators_end());
3642  }
3643  const_reverse_designators_iterator designators_rend() const {
3644    return const_reverse_designators_iterator(designators_begin());
3645  }
3646
3647  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3648
3649  void setDesignators(ASTContext &C, const Designator *Desigs,
3650                      unsigned NumDesigs);
3651
3652  Expr *getArrayIndex(const Designator& D);
3653  Expr *getArrayRangeStart(const Designator& D);
3654  Expr *getArrayRangeEnd(const Designator& D);
3655
3656  /// @brief Retrieve the location of the '=' that precedes the
3657  /// initializer value itself, if present.
3658  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3659  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3660
3661  /// @brief Determines whether this designated initializer used the
3662  /// deprecated GNU syntax for designated initializers.
3663  bool usesGNUSyntax() const { return GNUSyntax; }
3664  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3665
3666  /// @brief Retrieve the initializer value.
3667  Expr *getInit() const {
3668    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3669  }
3670
3671  void setInit(Expr *init) {
3672    *child_begin() = init;
3673  }
3674
3675  /// \brief Retrieve the total number of subexpressions in this
3676  /// designated initializer expression, including the actual
3677  /// initialized value and any expressions that occur within array
3678  /// and array-range designators.
3679  unsigned getNumSubExprs() const { return NumSubExprs; }
3680
3681  Expr *getSubExpr(unsigned Idx) {
3682    assert(Idx < NumSubExprs && "Subscript out of range");
3683    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3684    Ptr += sizeof(DesignatedInitExpr);
3685    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3686  }
3687
3688  void setSubExpr(unsigned Idx, Expr *E) {
3689    assert(Idx < NumSubExprs && "Subscript out of range");
3690    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3691    Ptr += sizeof(DesignatedInitExpr);
3692    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3693  }
3694
3695  /// \brief Replaces the designator at index @p Idx with the series
3696  /// of designators in [First, Last).
3697  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3698                        const Designator *Last);
3699
3700  SourceRange getDesignatorsSourceRange() const;
3701
3702  SourceRange getSourceRange() const;
3703
3704  static bool classof(const Stmt *T) {
3705    return T->getStmtClass() == DesignatedInitExprClass;
3706  }
3707  static bool classof(const DesignatedInitExpr *) { return true; }
3708
3709  // Iterators
3710  child_range children() {
3711    Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
3712    return child_range(begin, begin + NumSubExprs);
3713  }
3714};
3715
3716/// \brief Represents an implicitly-generated value initialization of
3717/// an object of a given type.
3718///
3719/// Implicit value initializations occur within semantic initializer
3720/// list expressions (InitListExpr) as placeholders for subobject
3721/// initializations not explicitly specified by the user.
3722///
3723/// \see InitListExpr
3724class ImplicitValueInitExpr : public Expr {
3725public:
3726  explicit ImplicitValueInitExpr(QualType ty)
3727    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
3728           false, false, false) { }
3729
3730  /// \brief Construct an empty implicit value initialization.
3731  explicit ImplicitValueInitExpr(EmptyShell Empty)
3732    : Expr(ImplicitValueInitExprClass, Empty) { }
3733
3734  static bool classof(const Stmt *T) {
3735    return T->getStmtClass() == ImplicitValueInitExprClass;
3736  }
3737  static bool classof(const ImplicitValueInitExpr *) { return true; }
3738
3739  SourceRange getSourceRange() const {
3740    return SourceRange();
3741  }
3742
3743  // Iterators
3744  child_range children() { return child_range(); }
3745};
3746
3747
3748class ParenListExpr : public Expr {
3749  Stmt **Exprs;
3750  unsigned NumExprs;
3751  SourceLocation LParenLoc, RParenLoc;
3752
3753public:
3754  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3755                unsigned numexprs, SourceLocation rparenloc);
3756
3757  /// \brief Build an empty paren list.
3758  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3759
3760  unsigned getNumExprs() const { return NumExprs; }
3761
3762  const Expr* getExpr(unsigned Init) const {
3763    assert(Init < getNumExprs() && "Initializer access out of range!");
3764    return cast_or_null<Expr>(Exprs[Init]);
3765  }
3766
3767  Expr* getExpr(unsigned Init) {
3768    assert(Init < getNumExprs() && "Initializer access out of range!");
3769    return cast_or_null<Expr>(Exprs[Init]);
3770  }
3771
3772  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3773
3774  SourceLocation getLParenLoc() const { return LParenLoc; }
3775  SourceLocation getRParenLoc() const { return RParenLoc; }
3776
3777  SourceRange getSourceRange() const {
3778    return SourceRange(LParenLoc, RParenLoc);
3779  }
3780  static bool classof(const Stmt *T) {
3781    return T->getStmtClass() == ParenListExprClass;
3782  }
3783  static bool classof(const ParenListExpr *) { return true; }
3784
3785  // Iterators
3786  child_range children() {
3787    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
3788  }
3789
3790  friend class ASTStmtReader;
3791  friend class ASTStmtWriter;
3792};
3793
3794
3795/// \brief Represents a C1X generic selection.
3796///
3797/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling
3798/// expression, followed by one or more generic associations.  Each generic
3799/// association specifies a type name and an expression, or "default" and an
3800/// expression (in which case it is known as a default generic association).
3801/// The type and value of the generic selection are identical to those of its
3802/// result expression, which is defined as the expression in the generic
3803/// association with a type name that is compatible with the type of the
3804/// controlling expression, or the expression in the default generic association
3805/// if no types are compatible.  For example:
3806///
3807/// @code
3808/// _Generic(X, double: 1, float: 2, default: 3)
3809/// @endcode
3810///
3811/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
3812/// or 3 if "hello".
3813///
3814/// As an extension, generic selections are allowed in C++, where the following
3815/// additional semantics apply:
3816///
3817/// Any generic selection whose controlling expression is type-dependent or
3818/// which names a dependent type in its association list is result-dependent,
3819/// which means that the choice of result expression is dependent.
3820/// Result-dependent generic associations are both type- and value-dependent.
3821class GenericSelectionExpr : public Expr {
3822  enum { CONTROLLING, END_EXPR };
3823  TypeSourceInfo **AssocTypes;
3824  Stmt **SubExprs;
3825  unsigned NumAssocs, ResultIndex;
3826  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
3827
3828public:
3829  GenericSelectionExpr(ASTContext &Context,
3830                       SourceLocation GenericLoc, Expr *ControllingExpr,
3831                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3832                       unsigned NumAssocs, SourceLocation DefaultLoc,
3833                       SourceLocation RParenLoc,
3834                       bool ContainsUnexpandedParameterPack,
3835                       unsigned ResultIndex);
3836
3837  /// This constructor is used in the result-dependent case.
3838  GenericSelectionExpr(ASTContext &Context,
3839                       SourceLocation GenericLoc, Expr *ControllingExpr,
3840                       TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3841                       unsigned NumAssocs, SourceLocation DefaultLoc,
3842                       SourceLocation RParenLoc,
3843                       bool ContainsUnexpandedParameterPack);
3844
3845  explicit GenericSelectionExpr(EmptyShell Empty)
3846    : Expr(GenericSelectionExprClass, Empty) { }
3847
3848  unsigned getNumAssocs() const { return NumAssocs; }
3849
3850  SourceLocation getGenericLoc() const { return GenericLoc; }
3851  SourceLocation getDefaultLoc() const { return DefaultLoc; }
3852  SourceLocation getRParenLoc() const { return RParenLoc; }
3853
3854  const Expr *getAssocExpr(unsigned i) const {
3855    return cast<Expr>(SubExprs[END_EXPR+i]);
3856  }
3857  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
3858
3859  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
3860    return AssocTypes[i];
3861  }
3862  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
3863
3864  QualType getAssocType(unsigned i) const {
3865    if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
3866      return TS->getType();
3867    else
3868      return QualType();
3869  }
3870
3871  const Expr *getControllingExpr() const {
3872    return cast<Expr>(SubExprs[CONTROLLING]);
3873  }
3874  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
3875
3876  /// Whether this generic selection is result-dependent.
3877  bool isResultDependent() const { return ResultIndex == -1U; }
3878
3879  /// The zero-based index of the result expression's generic association in
3880  /// the generic selection's association list.  Defined only if the
3881  /// generic selection is not result-dependent.
3882  unsigned getResultIndex() const {
3883    assert(!isResultDependent() && "Generic selection is result-dependent");
3884    return ResultIndex;
3885  }
3886
3887  /// The generic selection's result expression.  Defined only if the
3888  /// generic selection is not result-dependent.
3889  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
3890  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
3891
3892  SourceRange getSourceRange() const {
3893    return SourceRange(GenericLoc, RParenLoc);
3894  }
3895  static bool classof(const Stmt *T) {
3896    return T->getStmtClass() == GenericSelectionExprClass;
3897  }
3898  static bool classof(const GenericSelectionExpr *) { return true; }
3899
3900  child_range children() {
3901    return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
3902  }
3903
3904  friend class ASTStmtReader;
3905};
3906
3907//===----------------------------------------------------------------------===//
3908// Clang Extensions
3909//===----------------------------------------------------------------------===//
3910
3911
3912/// ExtVectorElementExpr - This represents access to specific elements of a
3913/// vector, and may occur on the left hand side or right hand side.  For example
3914/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3915///
3916/// Note that the base may have either vector or pointer to vector type, just
3917/// like a struct field reference.
3918///
3919class ExtVectorElementExpr : public Expr {
3920  Stmt *Base;
3921  IdentifierInfo *Accessor;
3922  SourceLocation AccessorLoc;
3923public:
3924  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
3925                       IdentifierInfo &accessor, SourceLocation loc)
3926    : Expr(ExtVectorElementExprClass, ty, VK,
3927           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
3928           base->isTypeDependent(), base->isValueDependent(),
3929           base->containsUnexpandedParameterPack()),
3930      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3931
3932  /// \brief Build an empty vector element expression.
3933  explicit ExtVectorElementExpr(EmptyShell Empty)
3934    : Expr(ExtVectorElementExprClass, Empty) { }
3935
3936  const Expr *getBase() const { return cast<Expr>(Base); }
3937  Expr *getBase() { return cast<Expr>(Base); }
3938  void setBase(Expr *E) { Base = E; }
3939
3940  IdentifierInfo &getAccessor() const { return *Accessor; }
3941  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3942
3943  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3944  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3945
3946  /// getNumElements - Get the number of components being selected.
3947  unsigned getNumElements() const;
3948
3949  /// containsDuplicateElements - Return true if any element access is
3950  /// repeated.
3951  bool containsDuplicateElements() const;
3952
3953  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3954  /// aggregate Constant of ConstantInt(s).
3955  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3956
3957  SourceRange getSourceRange() const {
3958    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3959  }
3960
3961  /// isArrow - Return true if the base expression is a pointer to vector,
3962  /// return false if the base expression is a vector.
3963  bool isArrow() const;
3964
3965  static bool classof(const Stmt *T) {
3966    return T->getStmtClass() == ExtVectorElementExprClass;
3967  }
3968  static bool classof(const ExtVectorElementExpr *) { return true; }
3969
3970  // Iterators
3971  child_range children() { return child_range(&Base, &Base+1); }
3972};
3973
3974
3975/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3976/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3977class BlockExpr : public Expr {
3978protected:
3979  BlockDecl *TheBlock;
3980public:
3981  BlockExpr(BlockDecl *BD, QualType ty)
3982    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
3983           ty->isDependentType(), false, false),
3984      TheBlock(BD) {}
3985
3986  /// \brief Build an empty block expression.
3987  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3988
3989  const BlockDecl *getBlockDecl() const { return TheBlock; }
3990  BlockDecl *getBlockDecl() { return TheBlock; }
3991  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3992
3993  // Convenience functions for probing the underlying BlockDecl.
3994  SourceLocation getCaretLocation() const;
3995  const Stmt *getBody() const;
3996  Stmt *getBody();
3997
3998  SourceRange getSourceRange() const {
3999    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
4000  }
4001
4002  /// getFunctionType - Return the underlying function type for this block.
4003  const FunctionType *getFunctionType() const;
4004
4005  static bool classof(const Stmt *T) {
4006    return T->getStmtClass() == BlockExprClass;
4007  }
4008  static bool classof(const BlockExpr *) { return true; }
4009
4010  // Iterators
4011  child_range children() { return child_range(); }
4012};
4013
4014/// BlockDeclRefExpr - A reference to a local variable declared in an
4015/// enclosing scope.
4016class BlockDeclRefExpr : public Expr {
4017  VarDecl *D;
4018  SourceLocation Loc;
4019  bool IsByRef : 1;
4020  bool ConstQualAdded : 1;
4021public:
4022  BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
4023                   SourceLocation l, bool ByRef, bool constAdded = false);
4024
4025  // \brief Build an empty reference to a declared variable in a
4026  // block.
4027  explicit BlockDeclRefExpr(EmptyShell Empty)
4028    : Expr(BlockDeclRefExprClass, Empty) { }
4029
4030  VarDecl *getDecl() { return D; }
4031  const VarDecl *getDecl() const { return D; }
4032  void setDecl(VarDecl *VD) { D = VD; }
4033
4034  SourceLocation getLocation() const { return Loc; }
4035  void setLocation(SourceLocation L) { Loc = L; }
4036
4037  SourceRange getSourceRange() const { return SourceRange(Loc); }
4038
4039  bool isByRef() const { return IsByRef; }
4040  void setByRef(bool BR) { IsByRef = BR; }
4041
4042  bool isConstQualAdded() const { return ConstQualAdded; }
4043  void setConstQualAdded(bool C) { ConstQualAdded = C; }
4044
4045  static bool classof(const Stmt *T) {
4046    return T->getStmtClass() == BlockDeclRefExprClass;
4047  }
4048  static bool classof(const BlockDeclRefExpr *) { return true; }
4049
4050  // Iterators
4051  child_range children() { return child_range(); }
4052};
4053
4054/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4055/// This AST node provides support for reinterpreting a type to another
4056/// type of the same size.
4057class AsTypeExpr : public Expr {
4058private:
4059  Expr* SrcExpr;
4060  QualType DstType;
4061  SourceLocation BuiltinLoc, RParenLoc;
4062
4063public:
4064  AsTypeExpr(Expr* SrcExpr, QualType DstType,
4065             ExprValueKind VK, ExprObjectKind OK,
4066             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4067  : Expr(AsTypeExprClass, DstType, VK, OK, false, false, false),
4068  SrcExpr(SrcExpr), DstType(DstType),
4069  BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4070
4071  /// \brief Build an empty __builtin_astype
4072  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4073
4074  /// getSrcExpr - Return the Expr to be converted.
4075  Expr *getSrcExpr() const { return SrcExpr; }
4076  QualType getDstType() const { return DstType; }
4077
4078  SourceRange getSourceRange() const {
4079    return SourceRange(BuiltinLoc, RParenLoc);
4080  }
4081
4082  static bool classof(const Stmt *T) {
4083    return T->getStmtClass() == AsTypeExprClass;
4084  }
4085  static bool classof(const AsTypeExpr *) { return true; }
4086
4087  // Iterators
4088  child_range children() { return child_range(); }
4089};
4090}  // end namespace clang
4091
4092#endif
4093