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