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