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