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