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