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