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