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