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