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