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