Expr.h revision 75e85048e73fcde2ce9d8a48dfdb1220e132eb59
1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Expr interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPR_H
15#define LLVM_CLANG_AST_EXPR_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/Stmt.h"
19#include "clang/AST/Type.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/OperationKinds.h"
22#include "clang/AST/ASTVector.h"
23#include "clang/AST/UsuallyTinyPtrVector.h"
24#include "llvm/ADT/APSInt.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include <cctype>
29#include <vector>
30
31namespace clang {
32  class ASTContext;
33  class APValue;
34  class Decl;
35  class IdentifierInfo;
36  class ParmVarDecl;
37  class NamedDecl;
38  class ValueDecl;
39  class BlockDecl;
40  class CXXBaseSpecifier;
41  class CXXOperatorCallExpr;
42  class CXXMemberCallExpr;
43  class ObjCPropertyRefExpr;
44  class TemplateArgumentLoc;
45  class TemplateArgumentListInfo;
46  class OpaqueValueExpr;
47
48/// \brief A simple array of base specifiers.
49typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
50
51/// Expr - This represents one expression.  Note that Expr's are subclasses of
52/// Stmt.  This allows an expression to be transparently used any place a Stmt
53/// is required.
54///
55class Expr : public Stmt {
56  QualType TR;
57
58protected:
59  Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
60       bool TD, bool VD, bool ContainsUnexpandedParameterPack) : Stmt(SC) {
61    ExprBits.TypeDependent = TD;
62    ExprBits.ValueDependent = VD;
63    ExprBits.ValueKind = VK;
64    ExprBits.ObjectKind = OK;
65    ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
66    setType(T);
67  }
68
69  /// \brief Construct an empty expression.
70  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
71
72public:
73  QualType getType() const { return TR; }
74  void setType(QualType t) {
75    // In C++, the type of an expression is always adjusted so that it
76    // will not have reference type an expression will never have
77    // reference type (C++ [expr]p6). Use
78    // QualType::getNonReferenceType() to retrieve the non-reference
79    // type. Additionally, inspect Expr::isLvalue to determine whether
80    // an expression that is adjusted in this manner should be
81    // considered an lvalue.
82    assert((t.isNull() || !t->isReferenceType()) &&
83           "Expressions can't have reference type");
84
85    TR = t;
86  }
87
88  /// isValueDependent - Determines whether this expression is
89  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
90  /// array bound of "Chars" in the following example is
91  /// value-dependent.
92  /// @code
93  /// template<int Size, char (&Chars)[Size]> struct meta_string;
94  /// @endcode
95  bool isValueDependent() const { return ExprBits.ValueDependent; }
96
97  /// \brief Set whether this expression is value-dependent or not.
98  void setValueDependent(bool VD) { ExprBits.ValueDependent = VD; }
99
100  /// isTypeDependent - Determines whether this expression is
101  /// type-dependent (C++ [temp.dep.expr]), which means that its type
102  /// could change from one template instantiation to the next. For
103  /// example, the expressions "x" and "x + y" are type-dependent in
104  /// the following code, but "y" is not type-dependent:
105  /// @code
106  /// template<typename T>
107  /// void add(T x, int y) {
108  ///   x + y;
109  /// }
110  /// @endcode
111  bool isTypeDependent() const { return ExprBits.TypeDependent; }
112
113  /// \brief Set whether this expression is type-dependent or not.
114  void setTypeDependent(bool TD) { ExprBits.TypeDependent = TD; }
115
116  /// \brief Whether this expression contains an unexpanded parameter
117  /// pack (for C++0x variadic templates).
118  ///
119  /// Given the following function template:
120  ///
121  /// \code
122  /// template<typename F, typename ...Types>
123  /// void forward(const F &f, Types &&...args) {
124  ///   f(static_cast<Types&&>(args)...);
125  /// }
126  /// \endcode
127  ///
128  /// The expressions \c args and \c static_cast<Types&&>(args) both
129  /// contain parameter packs.
130  bool containsUnexpandedParameterPack() const {
131    return ExprBits.ContainsUnexpandedParameterPack;
132  }
133
134  /// \brief Set the bit that describes whether this expression
135  /// contains an unexpanded parameter pack.
136  void setContainsUnexpandedParameterPack(bool PP = true) {
137    ExprBits.ContainsUnexpandedParameterPack = PP;
138  }
139
140  /// getExprLoc - Return the preferred location for the arrow when diagnosing
141  /// a problem with a generic expression.
142  SourceLocation getExprLoc() const;
143
144  /// isUnusedResultAWarning - Return true if this immediate expression should
145  /// be warned about if the result is unused.  If so, fill in Loc and Ranges
146  /// with location to warn on and the source range[s] to report with the
147  /// warning.
148  bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
149                              SourceRange &R2, ASTContext &Ctx) const;
150
151  /// isLValue - True if this expression is an "l-value" according to
152  /// the rules of the current language.  C and C++ give somewhat
153  /// different rules for this concept, but in general, the result of
154  /// an l-value expression identifies a specific object whereas the
155  /// result of an r-value expression is a value detached from any
156  /// specific storage.
157  ///
158  /// C++0x divides the concept of "r-value" into pure r-values
159  /// ("pr-values") and so-called expiring values ("x-values"), which
160  /// identify specific objects that can be safely cannibalized for
161  /// their resources.  This is an unfortunate abuse of terminology on
162  /// the part of the C++ committee.  In Clang, when we say "r-value",
163  /// we generally mean a pr-value.
164  bool isLValue() const { return getValueKind() == VK_LValue; }
165  bool isRValue() const { return getValueKind() == VK_RValue; }
166  bool isXValue() const { return getValueKind() == VK_XValue; }
167  bool isGLValue() const { return getValueKind() != VK_RValue; }
168
169  enum LValueClassification {
170    LV_Valid,
171    LV_NotObjectType,
172    LV_IncompleteVoidType,
173    LV_DuplicateVectorComponents,
174    LV_InvalidExpression,
175    LV_MemberFunction,
176    LV_SubObjCPropertySetting,
177    LV_ClassTemporary
178  };
179  /// Reasons why an expression might not be an l-value.
180  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
181
182  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
183  /// does not have an incomplete type, does not have a const-qualified type,
184  /// and if it is a structure or union, does not have any member (including,
185  /// recursively, any member or element of all contained aggregates or unions)
186  /// with a const-qualified type.
187  ///
188  /// \param Loc [in] [out] - A source location which *may* be filled
189  /// in with the location of the expression making this a
190  /// non-modifiable lvalue, if specified.
191  enum isModifiableLvalueResult {
192    MLV_Valid,
193    MLV_NotObjectType,
194    MLV_IncompleteVoidType,
195    MLV_DuplicateVectorComponents,
196    MLV_InvalidExpression,
197    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
198    MLV_IncompleteType,
199    MLV_ConstQualified,
200    MLV_ArrayType,
201    MLV_NotBlockQualified,
202    MLV_ReadonlyProperty,
203    MLV_NoSetterProperty,
204    MLV_MemberFunction,
205    MLV_SubObjCPropertySetting,
206    MLV_ClassTemporary
207  };
208  isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
209                                              SourceLocation *Loc = 0) const;
210
211  /// \brief The return type of classify(). Represents the C++0x expression
212  ///        taxonomy.
213  class Classification {
214  public:
215    /// \brief The various classification results. Most of these mean prvalue.
216    enum Kinds {
217      CL_LValue,
218      CL_XValue,
219      CL_Function, // Functions cannot be lvalues in C.
220      CL_Void, // Void cannot be an lvalue in C.
221      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
222      CL_MemberFunction, // An expression referring to a member function
223      CL_SubObjCPropertySetting,
224      CL_ClassTemporary, // A prvalue of class type
225      CL_PRValue // A prvalue for any other reason, of any other type
226    };
227    /// \brief The results of modification testing.
228    enum ModifiableType {
229      CM_Untested, // testModifiable was false.
230      CM_Modifiable,
231      CM_RValue, // Not modifiable because it's an rvalue
232      CM_Function, // Not modifiable because it's a function; C++ only
233      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
234      CM_NotBlockQualified, // Not captured in the closure
235      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
236      CM_ConstQualified,
237      CM_ArrayType,
238      CM_IncompleteType
239    };
240
241  private:
242    friend class Expr;
243
244    unsigned short Kind;
245    unsigned short Modifiable;
246
247    explicit Classification(Kinds k, ModifiableType m)
248      : Kind(k), Modifiable(m)
249    {}
250
251  public:
252    Classification() {}
253
254    Kinds getKind() const { return static_cast<Kinds>(Kind); }
255    ModifiableType getModifiable() const {
256      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
257      return static_cast<ModifiableType>(Modifiable);
258    }
259    bool isLValue() const { return Kind == CL_LValue; }
260    bool isXValue() const { return Kind == CL_XValue; }
261    bool isGLValue() const { return Kind <= CL_XValue; }
262    bool isPRValue() const { return Kind >= CL_Function; }
263    bool isRValue() const { return Kind >= CL_XValue; }
264    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
265
266    /// \brief Create a simple, modifiably lvalue
267    static Classification makeSimpleLValue() {
268      return Classification(CL_LValue, CM_Modifiable);
269    }
270
271  };
272  /// \brief Classify - Classify this expression according to the C++0x
273  ///        expression taxonomy.
274  ///
275  /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the
276  /// old lvalue vs rvalue. This function determines the type of expression this
277  /// is. There are three expression types:
278  /// - lvalues are classical lvalues as in C++03.
279  /// - prvalues are equivalent to rvalues in C++03.
280  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
281  ///   function returning an rvalue reference.
282  /// lvalues and xvalues are collectively referred to as glvalues, while
283  /// prvalues and xvalues together form rvalues.
284  Classification Classify(ASTContext &Ctx) const {
285    return ClassifyImpl(Ctx, 0);
286  }
287
288  /// \brief ClassifyModifiable - Classify this expression according to the
289  ///        C++0x expression taxonomy, and see if it is valid on the left side
290  ///        of an assignment.
291  ///
292  /// This function extends classify in that it also tests whether the
293  /// expression is modifiable (C99 6.3.2.1p1).
294  /// \param Loc A source location that might be filled with a relevant location
295  ///            if the expression is not modifiable.
296  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
297    return ClassifyImpl(Ctx, &Loc);
298  }
299
300  /// getValueKindForType - Given a formal return or parameter type,
301  /// give its value kind.
302  static ExprValueKind getValueKindForType(QualType T) {
303    if (const ReferenceType *RT = T->getAs<ReferenceType>())
304      return (isa<LValueReferenceType>(RT)
305                ? VK_LValue
306                : (RT->getPointeeType()->isFunctionType()
307                     ? VK_LValue : VK_XValue));
308    return VK_RValue;
309  }
310
311  /// getValueKind - The value kind that this expression produces.
312  ExprValueKind getValueKind() const {
313    return static_cast<ExprValueKind>(ExprBits.ValueKind);
314  }
315
316  /// getObjectKind - The object kind that this expression produces.
317  /// Object kinds are meaningful only for expressions that yield an
318  /// l-value or x-value.
319  ExprObjectKind getObjectKind() const {
320    return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
321  }
322
323  bool isOrdinaryOrBitFieldObject() const {
324    ExprObjectKind OK = getObjectKind();
325    return (OK == OK_Ordinary || OK == OK_BitField);
326  }
327
328  /// setValueKind - Set the value kind produced by this expression.
329  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
330
331  /// setObjectKind - Set the object kind produced by this expression.
332  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
333
334private:
335  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
336
337public:
338
339  /// \brief If this expression refers to a bit-field, retrieve the
340  /// declaration of that bit-field.
341  FieldDecl *getBitField();
342
343  const FieldDecl *getBitField() const {
344    return const_cast<Expr*>(this)->getBitField();
345  }
346
347  /// \brief If this expression is an l-value for an Objective C
348  /// property, find the underlying property reference expression.
349  const ObjCPropertyRefExpr *getObjCProperty() const;
350
351  /// \brief Returns whether this expression refers to a vector element.
352  bool refersToVectorElement() const;
353
354  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
355  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
356  /// but also int expressions which are produced by things like comparisons in
357  /// C.
358  bool isKnownToHaveBooleanValue() const;
359
360  /// isIntegerConstantExpr - Return true if this expression is a valid integer
361  /// constant expression, and, if so, return its value in Result.  If not a
362  /// valid i-c-e, return false and fill in Loc (if specified) with the location
363  /// of the invalid expression.
364  bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
365                             SourceLocation *Loc = 0,
366                             bool isEvaluated = true) const;
367  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
368    llvm::APSInt X;
369    return isIntegerConstantExpr(X, Ctx, Loc);
370  }
371  /// isConstantInitializer - Returns true if this expression is a constant
372  /// initializer, which can be emitted at compile-time.
373  bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
374
375  /// EvalResult is a struct with detailed info about an evaluated expression.
376  struct EvalResult {
377    /// Val - This is the value the expression can be folded to.
378    APValue Val;
379
380    /// HasSideEffects - Whether the evaluated expression has side effects.
381    /// For example, (f() && 0) can be folded, but it still has side effects.
382    bool HasSideEffects;
383
384    /// Diag - If the expression is unfoldable, then Diag contains a note
385    /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
386    /// position for the error, and DiagExpr is the expression that caused
387    /// the error.
388    /// If the expression is foldable, but not an integer constant expression,
389    /// Diag contains a note diagnostic that describes why it isn't an integer
390    /// constant expression. If the expression *is* an integer constant
391    /// expression, then Diag will be zero.
392    unsigned Diag;
393    const Expr *DiagExpr;
394    SourceLocation DiagLoc;
395
396    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
397
398    // isGlobalLValue - Return true if the evaluated lvalue expression
399    // is global.
400    bool isGlobalLValue() const;
401    // hasSideEffects - Return true if the evaluated expression has
402    // side effects.
403    bool hasSideEffects() const {
404      return HasSideEffects;
405    }
406  };
407
408  /// Evaluate - Return true if this is a constant which we can fold using
409  /// any crazy technique (that has nothing to do with language standards) that
410  /// we want to.  If this function returns true, it returns the folded constant
411  /// in Result.
412  bool Evaluate(EvalResult &Result, const ASTContext &Ctx) const;
413
414  /// EvaluateAsBooleanCondition - Return true if this is a constant
415  /// which we we can fold and convert to a boolean condition using
416  /// any crazy technique that we want to.
417  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
418
419  /// isEvaluatable - Call Evaluate to see if this expression can be constant
420  /// folded, but discard the result.
421  bool isEvaluatable(const ASTContext &Ctx) const;
422
423  /// HasSideEffects - This routine returns true for all those expressions
424  /// which must be evaluated each time and must not be optimized away
425  /// or evaluated at compile time. Example is a function call, volatile
426  /// variable read.
427  bool HasSideEffects(const ASTContext &Ctx) const;
428
429  /// EvaluateAsInt - Call Evaluate and return the folded integer. This
430  /// must be called on an expression that constant folds to an integer.
431  llvm::APSInt EvaluateAsInt(const ASTContext &Ctx) const;
432
433  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
434  /// with link time known address.
435  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
436
437  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
438  bool EvaluateAsAnyLValue(EvalResult &Result, const ASTContext &Ctx) const;
439
440  /// \brief Enumeration used to describe the kind of Null pointer constant
441  /// returned from \c isNullPointerConstant().
442  enum NullPointerConstantKind {
443    /// \brief Expression is not a Null pointer constant.
444    NPCK_NotNull = 0,
445
446    /// \brief Expression is a Null pointer constant built from a zero integer.
447    NPCK_ZeroInteger,
448
449    /// \brief Expression is a C++0X nullptr.
450    NPCK_CXX0X_nullptr,
451
452    /// \brief Expression is a GNU-style __null constant.
453    NPCK_GNUNull
454  };
455
456  /// \brief Enumeration used to describe how \c isNullPointerConstant()
457  /// should cope with value-dependent expressions.
458  enum NullPointerConstantValueDependence {
459    /// \brief Specifies that the expression should never be value-dependent.
460    NPC_NeverValueDependent = 0,
461
462    /// \brief Specifies that a value-dependent expression of integral or
463    /// dependent type should be considered a null pointer constant.
464    NPC_ValueDependentIsNull,
465
466    /// \brief Specifies that a value-dependent expression should be considered
467    /// to never be a null pointer constant.
468    NPC_ValueDependentIsNotNull
469  };
470
471  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
472  /// a Null pointer constant. The return value can further distinguish the
473  /// kind of NULL pointer constant that was detected.
474  NullPointerConstantKind isNullPointerConstant(
475      ASTContext &Ctx,
476      NullPointerConstantValueDependence NPC) const;
477
478  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
479  /// write barrier.
480  bool isOBJCGCCandidate(ASTContext &Ctx) const;
481
482  /// \brief Returns true if this expression is a bound member function.
483  bool isBoundMemberFunction(ASTContext &Ctx) const;
484
485  /// \brief Result type of CanThrow().
486  enum CanThrowResult {
487    CT_Cannot,
488    CT_Dependent,
489    CT_Can
490  };
491  /// \brief Test if this expression, if evaluated, might throw, according to
492  ///        the rules of C++ [expr.unary.noexcept].
493  CanThrowResult CanThrow(ASTContext &C) const;
494
495  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
496  ///  its subexpression.  If that subexpression is also a ParenExpr,
497  ///  then this method recursively returns its subexpression, and so forth.
498  ///  Otherwise, the method returns the current Expr.
499  Expr *IgnoreParens();
500
501  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
502  /// or CastExprs, returning their operand.
503  Expr *IgnoreParenCasts();
504
505  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off any
506  /// ParenExpr or ImplicitCastExprs, returning their operand.
507  Expr *IgnoreParenImpCasts();
508
509  const Expr *IgnoreParenImpCasts() const {
510    return const_cast<Expr*>(this)->IgnoreParenImpCasts();
511  }
512
513  /// Ignore parentheses and lvalue casts.  Strip off any ParenExpr and
514  /// CastExprs that represent lvalue casts, returning their operand.
515  Expr *IgnoreParenLValueCasts();
516
517  const Expr *IgnoreParenLValueCasts() const {
518    return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
519  }
520
521  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
522  /// value (including ptr->int casts of the same size).  Strip off any
523  /// ParenExpr or CastExprs, returning their operand.
524  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
525
526  /// \brief Determine whether this expression is a default function argument.
527  ///
528  /// Default arguments are implicitly generated in the abstract syntax tree
529  /// by semantic analysis for function calls, object constructions, etc. in
530  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
531  /// this routine also looks through any implicit casts to determine whether
532  /// the expression is a default argument.
533  bool isDefaultArgument() const;
534
535  /// \brief Determine whether the result of this expression is a
536  /// temporary object of the given class type.
537  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
538
539  /// \brief Whether this expression is an implicit reference to 'this' in C++.
540  bool isImplicitCXXThis() const;
541
542  const Expr *IgnoreParens() const {
543    return const_cast<Expr*>(this)->IgnoreParens();
544  }
545  const Expr *IgnoreParenCasts() const {
546    return const_cast<Expr*>(this)->IgnoreParenCasts();
547  }
548  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
549    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
550  }
551
552  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
553  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
554
555  static bool classof(const Stmt *T) {
556    return T->getStmtClass() >= firstExprConstant &&
557           T->getStmtClass() <= lastExprConstant;
558  }
559  static bool classof(const Expr *) { return true; }
560};
561
562
563//===----------------------------------------------------------------------===//
564// Primary Expressions.
565//===----------------------------------------------------------------------===//
566
567/// OpaqueValueExpr - An expression referring to an opaque object of a
568/// fixed type and value class.  These don't correspond to concrete
569/// syntax; instead they're used to express operations (usually copy
570/// operations) on values whose source is generally obvious from
571/// context.
572class OpaqueValueExpr : public Expr {
573  friend class ASTStmtReader;
574  Expr *SourceExpr;
575  SourceLocation Loc;
576
577public:
578  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
579                  ExprObjectKind OK = OK_Ordinary)
580    : Expr(OpaqueValueExprClass, T, VK, OK,
581           T->isDependentType(), T->isDependentType(), false),
582      SourceExpr(0), Loc(Loc) {
583  }
584
585  /// Given an expression which invokes a copy constructor --- i.e.  a
586  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
587  /// find the OpaqueValueExpr that's the source of the construction.
588  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
589
590  explicit OpaqueValueExpr(EmptyShell Empty)
591    : Expr(OpaqueValueExprClass, Empty) { }
592
593  /// \brief Retrieve the location of this expression.
594  SourceLocation getLocation() const { return Loc; }
595
596  SourceRange getSourceRange() const {
597    if (SourceExpr) return SourceExpr->getSourceRange();
598    return Loc;
599  }
600  SourceLocation getExprLoc() const {
601    if (SourceExpr) return SourceExpr->getExprLoc();
602    return Loc;
603  }
604
605  child_range children() { return child_range(); }
606
607  /// The source expression of an opaque value expression is the
608  /// expression which originally generated the value.  This is
609  /// provided as a convenience for analyses that don't wish to
610  /// precisely model the execution behavior of the program.
611  ///
612  /// The source expression is typically set when building the
613  /// expression which binds the opaque value expression in the first
614  /// place.
615  Expr *getSourceExpr() const { return SourceExpr; }
616  void setSourceExpr(Expr *e) { SourceExpr = e; }
617
618  static bool classof(const Stmt *T) {
619    return T->getStmtClass() == OpaqueValueExprClass;
620  }
621  static bool classof(const OpaqueValueExpr *) { return true; }
622};
623
624/// \brief Represents the qualifier that may precede a C++ name, e.g., the
625/// "std::" in "std::sort".
626struct NameQualifier {
627  /// \brief The nested-name-specifier that qualifies the name, including
628  /// source-location information.
629  NestedNameSpecifierLoc QualifierLoc;
630};
631
632/// \brief Represents an explicit template argument list in C++, e.g.,
633/// the "<int>" in "sort<int>".
634struct ExplicitTemplateArgumentList {
635  /// \brief The source location of the left angle bracket ('<');
636  SourceLocation LAngleLoc;
637
638  /// \brief The source location of the right angle bracket ('>');
639  SourceLocation RAngleLoc;
640
641  /// \brief The number of template arguments in TemplateArgs.
642  /// The actual template arguments (if any) are stored after the
643  /// ExplicitTemplateArgumentList structure.
644  unsigned NumTemplateArgs;
645
646  /// \brief Retrieve the template arguments
647  TemplateArgumentLoc *getTemplateArgs() {
648    return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
649  }
650
651  /// \brief Retrieve the template arguments
652  const TemplateArgumentLoc *getTemplateArgs() const {
653    return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
654  }
655
656  void initializeFrom(const TemplateArgumentListInfo &List);
657  void initializeFrom(const TemplateArgumentListInfo &List,
658                      bool &Dependent, bool &ContainsUnexpandedParameterPack);
659  void copyInto(TemplateArgumentListInfo &List) const;
660  static std::size_t sizeFor(unsigned NumTemplateArgs);
661  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
662};
663
664/// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
665/// enum, etc.
666class DeclRefExpr : public Expr {
667  enum {
668    // Flag on DecoratedD that specifies when this declaration reference
669    // expression has a C++ nested-name-specifier.
670    HasQualifierFlag = 0x01,
671    // Flag on DecoratedD that specifies when this declaration reference
672    // expression has an explicit C++ template argument list.
673    HasExplicitTemplateArgumentListFlag = 0x02
674  };
675
676  // DecoratedD - The declaration that we are referencing, plus two bits to
677  // indicate whether (1) the declaration's name was explicitly qualified and
678  // (2) the declaration's name was followed by an explicit template
679  // argument list.
680  llvm::PointerIntPair<ValueDecl *, 2> DecoratedD;
681
682  // Loc - The location of the declaration name itself.
683  SourceLocation Loc;
684
685  /// DNLoc - Provides source/type location info for the
686  /// declaration name embedded in DecoratedD.
687  DeclarationNameLoc DNLoc;
688
689  /// \brief Retrieve the qualifier that preceded the declaration name, if any.
690  NameQualifier *getNameQualifier() {
691    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
692      return 0;
693
694    return reinterpret_cast<NameQualifier *> (this + 1);
695  }
696
697  /// \brief Retrieve the qualifier that preceded the member name, if any.
698  const NameQualifier *getNameQualifier() const {
699    return const_cast<DeclRefExpr *>(this)->getNameQualifier();
700  }
701
702  DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
703              ValueDecl *D, SourceLocation NameLoc,
704              const TemplateArgumentListInfo *TemplateArgs,
705              QualType T, ExprValueKind VK);
706
707  DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
708              ValueDecl *D, const DeclarationNameInfo &NameInfo,
709              const TemplateArgumentListInfo *TemplateArgs,
710              QualType T, ExprValueKind VK);
711
712  /// \brief Construct an empty declaration reference expression.
713  explicit DeclRefExpr(EmptyShell Empty)
714    : Expr(DeclRefExprClass, Empty) { }
715
716  /// \brief Computes the type- and value-dependence flags for this
717  /// declaration reference expression.
718  void computeDependence();
719
720public:
721  DeclRefExpr(ValueDecl *d, QualType t, ExprValueKind VK, SourceLocation l) :
722    Expr(DeclRefExprClass, t, VK, OK_Ordinary, false, false, false),
723    DecoratedD(d, 0), Loc(l) {
724    computeDependence();
725  }
726
727  static DeclRefExpr *Create(ASTContext &Context,
728                             NestedNameSpecifierLoc QualifierLoc,
729                             ValueDecl *D,
730                             SourceLocation NameLoc,
731                             QualType T, ExprValueKind VK,
732                             const TemplateArgumentListInfo *TemplateArgs = 0);
733
734  static DeclRefExpr *Create(ASTContext &Context,
735                             NestedNameSpecifierLoc QualifierLoc,
736                             ValueDecl *D,
737                             const DeclarationNameInfo &NameInfo,
738                             QualType T, ExprValueKind VK,
739                             const TemplateArgumentListInfo *TemplateArgs = 0);
740
741  /// \brief Construct an empty declaration reference expression.
742  static DeclRefExpr *CreateEmpty(ASTContext &Context,
743                                  bool HasQualifier,
744                                  bool HasExplicitTemplateArgs,
745                                  unsigned NumTemplateArgs);
746
747  ValueDecl *getDecl() { return DecoratedD.getPointer(); }
748  const ValueDecl *getDecl() const { return DecoratedD.getPointer(); }
749  void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); }
750
751  DeclarationNameInfo getNameInfo() const {
752    return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
753  }
754
755  SourceLocation getLocation() const { return Loc; }
756  void setLocation(SourceLocation L) { Loc = L; }
757  SourceRange getSourceRange() const;
758
759  /// \brief Determine whether this declaration reference was preceded by a
760  /// C++ nested-name-specifier, e.g., \c N::foo.
761  bool hasQualifier() const { return DecoratedD.getInt() & HasQualifierFlag; }
762
763  /// \brief If the name was qualified, retrieves the nested-name-specifier
764  /// that precedes the name. Otherwise, returns NULL.
765  NestedNameSpecifier *getQualifier() const {
766    if (!hasQualifier())
767      return 0;
768
769    return getNameQualifier()->QualifierLoc.getNestedNameSpecifier();
770  }
771
772  /// \brief If the name was qualified, retrieves the nested-name-specifier
773  /// that precedes the name, with source-location information.
774  NestedNameSpecifierLoc getQualifierLoc() const {
775    if (!hasQualifier())
776      return NestedNameSpecifierLoc();
777
778    return getNameQualifier()->QualifierLoc;
779  }
780
781  bool hasExplicitTemplateArgs() const {
782    return (DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag);
783  }
784
785  /// \brief Retrieve the explicit template argument list that followed the
786  /// member template name.
787  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
788    assert(hasExplicitTemplateArgs());
789
790    if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
791      return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
792
793    return *reinterpret_cast<ExplicitTemplateArgumentList *>(
794                                                      getNameQualifier() + 1);
795  }
796
797  /// \brief Retrieve the explicit template argument list that followed the
798  /// member template name.
799  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
800    return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
801  }
802
803  /// \brief Retrieves the optional explicit template arguments.
804  /// This points to the same data as getExplicitTemplateArgs(), but
805  /// returns null if there are no explicit template arguments.
806  const ExplicitTemplateArgumentList *getExplicitTemplateArgsOpt() const {
807    if (!hasExplicitTemplateArgs()) return 0;
808    return &getExplicitTemplateArgs();
809  }
810
811  /// \brief Copies the template arguments (if present) into the given
812  /// structure.
813  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
814    if (hasExplicitTemplateArgs())
815      getExplicitTemplateArgs().copyInto(List);
816  }
817
818  /// \brief Retrieve the location of the left angle bracket following the
819  /// member name ('<'), if any.
820  SourceLocation getLAngleLoc() const {
821    if (!hasExplicitTemplateArgs())
822      return SourceLocation();
823
824    return getExplicitTemplateArgs().LAngleLoc;
825  }
826
827  /// \brief Retrieve the template arguments provided as part of this
828  /// template-id.
829  const TemplateArgumentLoc *getTemplateArgs() const {
830    if (!hasExplicitTemplateArgs())
831      return 0;
832
833    return getExplicitTemplateArgs().getTemplateArgs();
834  }
835
836  /// \brief Retrieve the number of template arguments provided as part of this
837  /// template-id.
838  unsigned getNumTemplateArgs() const {
839    if (!hasExplicitTemplateArgs())
840      return 0;
841
842    return getExplicitTemplateArgs().NumTemplateArgs;
843  }
844
845  /// \brief Retrieve the location of the right angle bracket following the
846  /// template arguments ('>').
847  SourceLocation getRAngleLoc() const {
848    if (!hasExplicitTemplateArgs())
849      return SourceLocation();
850
851    return getExplicitTemplateArgs().RAngleLoc;
852  }
853
854  static bool classof(const Stmt *T) {
855    return T->getStmtClass() == DeclRefExprClass;
856  }
857  static bool classof(const DeclRefExpr *) { return true; }
858
859  // Iterators
860  child_range children() { return child_range(); }
861
862  friend class ASTStmtReader;
863  friend class ASTStmtWriter;
864};
865
866/// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
867class PredefinedExpr : public Expr {
868public:
869  enum IdentType {
870    Func,
871    Function,
872    PrettyFunction,
873    /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
874    /// 'virtual' keyword is omitted for virtual member functions.
875    PrettyFunctionNoVirtual
876  };
877
878private:
879  SourceLocation Loc;
880  IdentType Type;
881public:
882  PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
883    : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
884           type->isDependentType(), type->isDependentType(),
885           /*ContainsUnexpandedParameterPack=*/false),
886      Loc(l), Type(IT) {}
887
888  /// \brief Construct an empty predefined expression.
889  explicit PredefinedExpr(EmptyShell Empty)
890    : Expr(PredefinedExprClass, Empty) { }
891
892  IdentType getIdentType() const { return Type; }
893  void setIdentType(IdentType IT) { Type = IT; }
894
895  SourceLocation getLocation() const { return Loc; }
896  void setLocation(SourceLocation L) { Loc = L; }
897
898  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
899
900  SourceRange getSourceRange() const { return SourceRange(Loc); }
901
902  static bool classof(const Stmt *T) {
903    return T->getStmtClass() == PredefinedExprClass;
904  }
905  static bool classof(const PredefinedExpr *) { return true; }
906
907  // Iterators
908  child_range children() { return child_range(); }
909};
910
911/// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
912/// leaking memory.
913///
914/// For large floats/integers, APFloat/APInt will allocate memory from the heap
915/// to represent these numbers.  Unfortunately, when we use a BumpPtrAllocator
916/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
917/// the APFloat/APInt values will never get freed. APNumericStorage uses
918/// ASTContext's allocator for memory allocation.
919class APNumericStorage {
920  unsigned BitWidth;
921  union {
922    uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
923    uint64_t *pVal;  ///< Used to store the >64 bits integer value.
924  };
925
926  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
927
928  APNumericStorage(const APNumericStorage&); // do not implement
929  APNumericStorage& operator=(const APNumericStorage&); // do not implement
930
931protected:
932  APNumericStorage() : BitWidth(0), VAL(0) { }
933
934  llvm::APInt getIntValue() const {
935    unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
936    if (NumWords > 1)
937      return llvm::APInt(BitWidth, NumWords, pVal);
938    else
939      return llvm::APInt(BitWidth, VAL);
940  }
941  void setIntValue(ASTContext &C, const llvm::APInt &Val);
942};
943
944class APIntStorage : public APNumericStorage {
945public:
946  llvm::APInt getValue() const { return getIntValue(); }
947  void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); }
948};
949
950class APFloatStorage : public APNumericStorage {
951public:
952  llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); }
953  void setValue(ASTContext &C, const llvm::APFloat &Val) {
954    setIntValue(C, Val.bitcastToAPInt());
955  }
956};
957
958class IntegerLiteral : public Expr {
959  APIntStorage Num;
960  SourceLocation Loc;
961
962  /// \brief Construct an empty integer literal.
963  explicit IntegerLiteral(EmptyShell Empty)
964    : Expr(IntegerLiteralClass, Empty) { }
965
966public:
967  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
968  // or UnsignedLongLongTy
969  IntegerLiteral(ASTContext &C, const llvm::APInt &V,
970                 QualType type, SourceLocation l)
971    : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
972           false),
973      Loc(l) {
974    assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
975    setValue(C, V);
976  }
977
978  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
979  // or UnsignedLongLongTy
980  static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V,
981                                QualType type, SourceLocation l);
982  static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
983
984  llvm::APInt getValue() const { return Num.getValue(); }
985  SourceRange getSourceRange() const { return SourceRange(Loc); }
986
987  /// \brief Retrieve the location of the literal.
988  SourceLocation getLocation() const { return Loc; }
989
990  void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); }
991  void setLocation(SourceLocation Location) { Loc = Location; }
992
993  static bool classof(const Stmt *T) {
994    return T->getStmtClass() == IntegerLiteralClass;
995  }
996  static bool classof(const IntegerLiteral *) { return true; }
997
998  // Iterators
999  child_range children() { return child_range(); }
1000};
1001
1002class CharacterLiteral : public Expr {
1003  unsigned Value;
1004  SourceLocation Loc;
1005  bool IsWide;
1006public:
1007  // type should be IntTy
1008  CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
1009    : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1010           false),
1011      Value(value), Loc(l), IsWide(iswide) {
1012  }
1013
1014  /// \brief Construct an empty character literal.
1015  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1016
1017  SourceLocation getLocation() const { return Loc; }
1018  bool isWide() const { return IsWide; }
1019
1020  SourceRange getSourceRange() const { return SourceRange(Loc); }
1021
1022  unsigned getValue() const { return Value; }
1023
1024  void setLocation(SourceLocation Location) { Loc = Location; }
1025  void setWide(bool W) { IsWide = W; }
1026  void setValue(unsigned Val) { Value = Val; }
1027
1028  static bool classof(const Stmt *T) {
1029    return T->getStmtClass() == CharacterLiteralClass;
1030  }
1031  static bool classof(const CharacterLiteral *) { return true; }
1032
1033  // Iterators
1034  child_range children() { return child_range(); }
1035};
1036
1037class FloatingLiteral : public Expr {
1038  APFloatStorage Num;
1039  bool IsExact : 1;
1040  SourceLocation Loc;
1041
1042  FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
1043                  QualType Type, SourceLocation L)
1044    : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
1045           false),
1046      IsExact(isexact), Loc(L) {
1047    setValue(C, V);
1048  }
1049
1050  /// \brief Construct an empty floating-point literal.
1051  explicit FloatingLiteral(EmptyShell Empty)
1052    : Expr(FloatingLiteralClass, Empty), IsExact(false) { }
1053
1054public:
1055  static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
1056                                 bool isexact, QualType Type, SourceLocation L);
1057  static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
1058
1059  llvm::APFloat getValue() const { return Num.getValue(); }
1060  void setValue(ASTContext &C, const llvm::APFloat &Val) {
1061    Num.setValue(C, Val);
1062  }
1063
1064  bool isExact() const { return IsExact; }
1065  void setExact(bool E) { IsExact = E; }
1066
1067  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1068  /// double.  Note that this may cause loss of precision, but is useful for
1069  /// debugging dumps, etc.
1070  double getValueAsApproximateDouble() const;
1071
1072  SourceLocation getLocation() const { return Loc; }
1073  void setLocation(SourceLocation L) { Loc = L; }
1074
1075  SourceRange getSourceRange() const { return SourceRange(Loc); }
1076
1077  static bool classof(const Stmt *T) {
1078    return T->getStmtClass() == FloatingLiteralClass;
1079  }
1080  static bool classof(const FloatingLiteral *) { return true; }
1081
1082  // Iterators
1083  child_range children() { return child_range(); }
1084};
1085
1086/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1087/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1088/// IntegerLiteral classes.  Instances of this class always have a Complex type
1089/// whose element type matches the subexpression.
1090///
1091class ImaginaryLiteral : public Expr {
1092  Stmt *Val;
1093public:
1094  ImaginaryLiteral(Expr *val, QualType Ty)
1095    : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1096           false),
1097      Val(val) {}
1098
1099  /// \brief Build an empty imaginary literal.
1100  explicit ImaginaryLiteral(EmptyShell Empty)
1101    : Expr(ImaginaryLiteralClass, Empty) { }
1102
1103  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1104  Expr *getSubExpr() { return cast<Expr>(Val); }
1105  void setSubExpr(Expr *E) { Val = E; }
1106
1107  SourceRange getSourceRange() const { return Val->getSourceRange(); }
1108  static bool classof(const Stmt *T) {
1109    return T->getStmtClass() == ImaginaryLiteralClass;
1110  }
1111  static bool classof(const ImaginaryLiteral *) { return true; }
1112
1113  // Iterators
1114  child_range children() { return child_range(&Val, &Val+1); }
1115};
1116
1117/// StringLiteral - This represents a string literal expression, e.g. "foo"
1118/// or L"bar" (wide strings).  The actual string is returned by getStrData()
1119/// is NOT null-terminated, and the length of the string is determined by
1120/// calling getByteLength().  The C type for a string is always a
1121/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
1122/// not.
1123///
1124/// Note that strings in C can be formed by concatenation of multiple string
1125/// literal pptokens in translation phase #6.  This keeps track of the locations
1126/// of each of these pieces.
1127///
1128/// Strings in C can also be truncated and extended by assigning into arrays,
1129/// e.g. with constructs like:
1130///   char X[2] = "foobar";
1131/// In this case, getByteLength() will return 6, but the string literal will
1132/// have type "char[2]".
1133class StringLiteral : public Expr {
1134  const char *StrData;
1135  unsigned ByteLength;
1136  bool IsWide;
1137  unsigned NumConcatenated;
1138  SourceLocation TokLocs[1];
1139
1140  StringLiteral(QualType Ty) :
1141    Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false) {}
1142
1143public:
1144  /// This is the "fully general" constructor that allows representation of
1145  /// strings formed from multiple concatenated tokens.
1146  static StringLiteral *Create(ASTContext &C, const char *StrData,
1147                               unsigned ByteLength, bool Wide, QualType Ty,
1148                               const SourceLocation *Loc, unsigned NumStrs);
1149
1150  /// Simple constructor for string literals made from one token.
1151  static StringLiteral *Create(ASTContext &C, const char *StrData,
1152                               unsigned ByteLength,
1153                               bool Wide, QualType Ty, SourceLocation Loc) {
1154    return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
1155  }
1156
1157  /// \brief Construct an empty string literal.
1158  static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1159
1160  llvm::StringRef getString() const {
1161    return llvm::StringRef(StrData, ByteLength);
1162  }
1163
1164  unsigned getByteLength() const { return ByteLength; }
1165
1166  /// \brief Sets the string data to the given string data.
1167  void setString(ASTContext &C, llvm::StringRef Str);
1168
1169  bool isWide() const { return IsWide; }
1170  void setWide(bool W) { IsWide = W; }
1171
1172  bool containsNonAsciiOrNull() const {
1173    llvm::StringRef Str = getString();
1174    for (unsigned i = 0, e = Str.size(); i != e; ++i)
1175      if (!isascii(Str[i]) || !Str[i])
1176        return true;
1177    return false;
1178  }
1179  /// getNumConcatenated - Get the number of string literal tokens that were
1180  /// concatenated in translation phase #6 to form this string literal.
1181  unsigned getNumConcatenated() const { return NumConcatenated; }
1182
1183  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1184    assert(TokNum < NumConcatenated && "Invalid tok number");
1185    return TokLocs[TokNum];
1186  }
1187  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1188    assert(TokNum < NumConcatenated && "Invalid tok number");
1189    TokLocs[TokNum] = L;
1190  }
1191
1192  /// getLocationOfByte - Return a source location that points to the specified
1193  /// byte of this string literal.
1194  ///
1195  /// Strings are amazingly complex.  They can be formed from multiple tokens
1196  /// and can have escape sequences in them in addition to the usual trigraph
1197  /// and escaped newline business.  This routine handles this complexity.
1198  ///
1199  SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1200                                   const LangOptions &Features,
1201                                   const TargetInfo &Target) const;
1202
1203  typedef const SourceLocation *tokloc_iterator;
1204  tokloc_iterator tokloc_begin() const { return TokLocs; }
1205  tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1206
1207  SourceRange getSourceRange() const {
1208    return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1209  }
1210  static bool classof(const Stmt *T) {
1211    return T->getStmtClass() == StringLiteralClass;
1212  }
1213  static bool classof(const StringLiteral *) { return true; }
1214
1215  // Iterators
1216  child_range children() { return child_range(); }
1217};
1218
1219/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1220/// AST node is only formed if full location information is requested.
1221class ParenExpr : public Expr {
1222  SourceLocation L, R;
1223  Stmt *Val;
1224public:
1225  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1226    : Expr(ParenExprClass, val->getType(),
1227           val->getValueKind(), val->getObjectKind(),
1228           val->isTypeDependent(), val->isValueDependent(),
1229           val->containsUnexpandedParameterPack()),
1230      L(l), R(r), Val(val) {}
1231
1232  /// \brief Construct an empty parenthesized expression.
1233  explicit ParenExpr(EmptyShell Empty)
1234    : Expr(ParenExprClass, Empty) { }
1235
1236  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1237  Expr *getSubExpr() { return cast<Expr>(Val); }
1238  void setSubExpr(Expr *E) { Val = E; }
1239
1240  SourceRange getSourceRange() const { return SourceRange(L, R); }
1241
1242  /// \brief Get the location of the left parentheses '('.
1243  SourceLocation getLParen() const { return L; }
1244  void setLParen(SourceLocation Loc) { L = Loc; }
1245
1246  /// \brief Get the location of the right parentheses ')'.
1247  SourceLocation getRParen() const { return R; }
1248  void setRParen(SourceLocation Loc) { R = Loc; }
1249
1250  static bool classof(const Stmt *T) {
1251    return T->getStmtClass() == ParenExprClass;
1252  }
1253  static bool classof(const ParenExpr *) { return true; }
1254
1255  // Iterators
1256  child_range children() { return child_range(&Val, &Val+1); }
1257};
1258
1259
1260/// UnaryOperator - This represents the unary-expression's (except sizeof and
1261/// alignof), the postinc/postdec operators from postfix-expression, and various
1262/// extensions.
1263///
1264/// Notes on various nodes:
1265///
1266/// Real/Imag - These return the real/imag part of a complex operand.  If
1267///   applied to a non-complex value, the former returns its operand and the
1268///   later returns zero in the type of the operand.
1269///
1270class UnaryOperator : public Expr {
1271public:
1272  typedef UnaryOperatorKind Opcode;
1273
1274private:
1275  unsigned Opc : 5;
1276  SourceLocation Loc;
1277  Stmt *Val;
1278public:
1279
1280  UnaryOperator(Expr *input, Opcode opc, QualType type,
1281                ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1282    : Expr(UnaryOperatorClass, type, VK, OK,
1283           input->isTypeDependent() || type->isDependentType(),
1284           input->isValueDependent(),
1285           input->containsUnexpandedParameterPack()),
1286      Opc(opc), Loc(l), Val(input) {}
1287
1288  /// \brief Build an empty unary operator.
1289  explicit UnaryOperator(EmptyShell Empty)
1290    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1291
1292  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1293  void setOpcode(Opcode O) { Opc = O; }
1294
1295  Expr *getSubExpr() const { return cast<Expr>(Val); }
1296  void setSubExpr(Expr *E) { Val = E; }
1297
1298  /// getOperatorLoc - Return the location of the operator.
1299  SourceLocation getOperatorLoc() const { return Loc; }
1300  void setOperatorLoc(SourceLocation L) { Loc = L; }
1301
1302  /// isPostfix - Return true if this is a postfix operation, like x++.
1303  static bool isPostfix(Opcode Op) {
1304    return Op == UO_PostInc || Op == UO_PostDec;
1305  }
1306
1307  /// isPrefix - Return true if this is a prefix operation, like --x.
1308  static bool isPrefix(Opcode Op) {
1309    return Op == UO_PreInc || Op == UO_PreDec;
1310  }
1311
1312  bool isPrefix() const { return isPrefix(getOpcode()); }
1313  bool isPostfix() const { return isPostfix(getOpcode()); }
1314  bool isIncrementOp() const {
1315    return Opc == UO_PreInc || Opc == UO_PostInc;
1316  }
1317  bool isIncrementDecrementOp() const {
1318    return Opc <= UO_PreDec;
1319  }
1320  static bool isArithmeticOp(Opcode Op) {
1321    return Op >= UO_Plus && Op <= UO_LNot;
1322  }
1323  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1324
1325  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1326  /// corresponds to, e.g. "sizeof" or "[pre]++"
1327  static const char *getOpcodeStr(Opcode Op);
1328
1329  /// \brief Retrieve the unary opcode that corresponds to the given
1330  /// overloaded operator.
1331  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1332
1333  /// \brief Retrieve the overloaded operator kind that corresponds to
1334  /// the given unary opcode.
1335  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1336
1337  SourceRange getSourceRange() const {
1338    if (isPostfix())
1339      return SourceRange(Val->getLocStart(), Loc);
1340    else
1341      return SourceRange(Loc, Val->getLocEnd());
1342  }
1343  SourceLocation getExprLoc() const { return Loc; }
1344
1345  static bool classof(const Stmt *T) {
1346    return T->getStmtClass() == UnaryOperatorClass;
1347  }
1348  static bool classof(const UnaryOperator *) { return true; }
1349
1350  // Iterators
1351  child_range children() { return child_range(&Val, &Val+1); }
1352};
1353
1354/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1355/// offsetof(record-type, member-designator). For example, given:
1356/// @code
1357/// struct S {
1358///   float f;
1359///   double d;
1360/// };
1361/// struct T {
1362///   int i;
1363///   struct S s[10];
1364/// };
1365/// @endcode
1366/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1367
1368class OffsetOfExpr : public Expr {
1369public:
1370  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1371  class OffsetOfNode {
1372  public:
1373    /// \brief The kind of offsetof node we have.
1374    enum Kind {
1375      /// \brief An index into an array.
1376      Array = 0x00,
1377      /// \brief A field.
1378      Field = 0x01,
1379      /// \brief A field in a dependent type, known only by its name.
1380      Identifier = 0x02,
1381      /// \brief An implicit indirection through a C++ base class, when the
1382      /// field found is in a base class.
1383      Base = 0x03
1384    };
1385
1386  private:
1387    enum { MaskBits = 2, Mask = 0x03 };
1388
1389    /// \brief The source range that covers this part of the designator.
1390    SourceRange Range;
1391
1392    /// \brief The data describing the designator, which comes in three
1393    /// different forms, depending on the lower two bits.
1394    ///   - An unsigned index into the array of Expr*'s stored after this node
1395    ///     in memory, for [constant-expression] designators.
1396    ///   - A FieldDecl*, for references to a known field.
1397    ///   - An IdentifierInfo*, for references to a field with a given name
1398    ///     when the class type is dependent.
1399    ///   - A CXXBaseSpecifier*, for references that look at a field in a
1400    ///     base class.
1401    uintptr_t Data;
1402
1403  public:
1404    /// \brief Create an offsetof node that refers to an array element.
1405    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1406                 SourceLocation RBracketLoc)
1407      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1408
1409    /// \brief Create an offsetof node that refers to a field.
1410    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1411                 SourceLocation NameLoc)
1412      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1413        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1414
1415    /// \brief Create an offsetof node that refers to an identifier.
1416    OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1417                 SourceLocation NameLoc)
1418      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1419        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1420
1421    /// \brief Create an offsetof node that refers into a C++ base class.
1422    explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1423      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1424
1425    /// \brief Determine what kind of offsetof node this is.
1426    Kind getKind() const {
1427      return static_cast<Kind>(Data & Mask);
1428    }
1429
1430    /// \brief For an array element node, returns the index into the array
1431    /// of expressions.
1432    unsigned getArrayExprIndex() const {
1433      assert(getKind() == Array);
1434      return Data >> 2;
1435    }
1436
1437    /// \brief For a field offsetof node, returns the field.
1438    FieldDecl *getField() const {
1439      assert(getKind() == Field);
1440      return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1441    }
1442
1443    /// \brief For a field or identifier offsetof node, returns the name of
1444    /// the field.
1445    IdentifierInfo *getFieldName() const;
1446
1447    /// \brief For a base class node, returns the base specifier.
1448    CXXBaseSpecifier *getBase() const {
1449      assert(getKind() == Base);
1450      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1451    }
1452
1453    /// \brief Retrieve the source range that covers this offsetof node.
1454    ///
1455    /// For an array element node, the source range contains the locations of
1456    /// the square brackets. For a field or identifier node, the source range
1457    /// contains the location of the period (if there is one) and the
1458    /// identifier.
1459    SourceRange getRange() const { return Range; }
1460  };
1461
1462private:
1463
1464  SourceLocation OperatorLoc, RParenLoc;
1465  // Base type;
1466  TypeSourceInfo *TSInfo;
1467  // Number of sub-components (i.e. instances of OffsetOfNode).
1468  unsigned NumComps;
1469  // Number of sub-expressions (i.e. array subscript expressions).
1470  unsigned NumExprs;
1471
1472  OffsetOfExpr(ASTContext &C, QualType type,
1473               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1474               OffsetOfNode* compsPtr, unsigned numComps,
1475               Expr** exprsPtr, unsigned numExprs,
1476               SourceLocation RParenLoc);
1477
1478  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1479    : Expr(OffsetOfExprClass, EmptyShell()),
1480      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1481
1482public:
1483
1484  static OffsetOfExpr *Create(ASTContext &C, QualType type,
1485                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1486                              OffsetOfNode* compsPtr, unsigned numComps,
1487                              Expr** exprsPtr, unsigned numExprs,
1488                              SourceLocation RParenLoc);
1489
1490  static OffsetOfExpr *CreateEmpty(ASTContext &C,
1491                                   unsigned NumComps, unsigned NumExprs);
1492
1493  /// getOperatorLoc - Return the location of the operator.
1494  SourceLocation getOperatorLoc() const { return OperatorLoc; }
1495  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1496
1497  /// \brief Return the location of the right parentheses.
1498  SourceLocation getRParenLoc() const { return RParenLoc; }
1499  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1500
1501  TypeSourceInfo *getTypeSourceInfo() const {
1502    return TSInfo;
1503  }
1504  void setTypeSourceInfo(TypeSourceInfo *tsi) {
1505    TSInfo = tsi;
1506  }
1507
1508  const OffsetOfNode &getComponent(unsigned Idx) {
1509    assert(Idx < NumComps && "Subscript out of range");
1510    return reinterpret_cast<OffsetOfNode *> (this + 1)[Idx];
1511  }
1512
1513  void setComponent(unsigned Idx, OffsetOfNode ON) {
1514    assert(Idx < NumComps && "Subscript out of range");
1515    reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1516  }
1517
1518  unsigned getNumComponents() const {
1519    return NumComps;
1520  }
1521
1522  Expr* getIndexExpr(unsigned Idx) {
1523    assert(Idx < NumExprs && "Subscript out of range");
1524    return reinterpret_cast<Expr **>(
1525                    reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1526  }
1527
1528  void setIndexExpr(unsigned Idx, Expr* E) {
1529    assert(Idx < NumComps && "Subscript out of range");
1530    reinterpret_cast<Expr **>(
1531                reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1532  }
1533
1534  unsigned getNumExpressions() const {
1535    return NumExprs;
1536  }
1537
1538  SourceRange getSourceRange() const {
1539    return SourceRange(OperatorLoc, RParenLoc);
1540  }
1541
1542  static bool classof(const Stmt *T) {
1543    return T->getStmtClass() == OffsetOfExprClass;
1544  }
1545
1546  static bool classof(const OffsetOfExpr *) { return true; }
1547
1548  // Iterators
1549  child_range children() {
1550    Stmt **begin =
1551      reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1552                               + NumComps);
1553    return child_range(begin, begin + NumExprs);
1554  }
1555};
1556
1557/// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
1558/// types and expressions.
1559class SizeOfAlignOfExpr : public Expr {
1560  bool isSizeof : 1;  // true if sizeof, false if alignof.
1561  bool isType : 1;    // true if operand is a type, false if an expression
1562  union {
1563    TypeSourceInfo *Ty;
1564    Stmt *Ex;
1565  } Argument;
1566  SourceLocation OpLoc, RParenLoc;
1567
1568public:
1569  SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo,
1570                    QualType resultType, SourceLocation op,
1571                    SourceLocation rp) :
1572      Expr(SizeOfAlignOfExprClass, resultType, VK_RValue, OK_Ordinary,
1573           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1574           // Value-dependent if the argument is type-dependent.
1575           TInfo->getType()->isDependentType(),
1576           TInfo->getType()->containsUnexpandedParameterPack()),
1577      isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
1578    Argument.Ty = TInfo;
1579  }
1580
1581  SizeOfAlignOfExpr(bool issizeof, Expr *E,
1582                    QualType resultType, SourceLocation op,
1583                    SourceLocation rp) :
1584      Expr(SizeOfAlignOfExprClass, resultType, VK_RValue, OK_Ordinary,
1585           false, // Never type-dependent (C++ [temp.dep.expr]p3).
1586           // Value-dependent if the argument is type-dependent.
1587           E->isTypeDependent(),
1588           E->containsUnexpandedParameterPack()),
1589      isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
1590    Argument.Ex = E;
1591  }
1592
1593  /// \brief Construct an empty sizeof/alignof expression.
1594  explicit SizeOfAlignOfExpr(EmptyShell Empty)
1595    : Expr(SizeOfAlignOfExprClass, Empty) { }
1596
1597  bool isSizeOf() const { return isSizeof; }
1598  void setSizeof(bool S) { isSizeof = S; }
1599
1600  bool isArgumentType() const { return isType; }
1601  QualType getArgumentType() const {
1602    return getArgumentTypeInfo()->getType();
1603  }
1604  TypeSourceInfo *getArgumentTypeInfo() const {
1605    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1606    return Argument.Ty;
1607  }
1608  Expr *getArgumentExpr() {
1609    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1610    return static_cast<Expr*>(Argument.Ex);
1611  }
1612  const Expr *getArgumentExpr() const {
1613    return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
1614  }
1615
1616  void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1617  void setArgument(TypeSourceInfo *TInfo) {
1618    Argument.Ty = TInfo;
1619    isType = true;
1620  }
1621
1622  /// Gets the argument type, or the type of the argument expression, whichever
1623  /// is appropriate.
1624  QualType getTypeOfArgument() const {
1625    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1626  }
1627
1628  SourceLocation getOperatorLoc() const { return OpLoc; }
1629  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1630
1631  SourceLocation getRParenLoc() const { return RParenLoc; }
1632  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1633
1634  SourceRange getSourceRange() const {
1635    return SourceRange(OpLoc, RParenLoc);
1636  }
1637
1638  static bool classof(const Stmt *T) {
1639    return T->getStmtClass() == SizeOfAlignOfExprClass;
1640  }
1641  static bool classof(const SizeOfAlignOfExpr *) { return true; }
1642
1643  // Iterators
1644  child_range children();
1645};
1646
1647//===----------------------------------------------------------------------===//
1648// Postfix Operators.
1649//===----------------------------------------------------------------------===//
1650
1651/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1652class ArraySubscriptExpr : public Expr {
1653  enum { LHS, RHS, END_EXPR=2 };
1654  Stmt* SubExprs[END_EXPR];
1655  SourceLocation RBracketLoc;
1656public:
1657  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1658                     ExprValueKind VK, ExprObjectKind OK,
1659                     SourceLocation rbracketloc)
1660  : Expr(ArraySubscriptExprClass, t, VK, OK,
1661         lhs->isTypeDependent() || rhs->isTypeDependent(),
1662         lhs->isValueDependent() || rhs->isValueDependent(),
1663         (lhs->containsUnexpandedParameterPack() ||
1664          rhs->containsUnexpandedParameterPack())),
1665    RBracketLoc(rbracketloc) {
1666    SubExprs[LHS] = lhs;
1667    SubExprs[RHS] = rhs;
1668  }
1669
1670  /// \brief Create an empty array subscript expression.
1671  explicit ArraySubscriptExpr(EmptyShell Shell)
1672    : Expr(ArraySubscriptExprClass, Shell) { }
1673
1674  /// An array access can be written A[4] or 4[A] (both are equivalent).
1675  /// - getBase() and getIdx() always present the normalized view: A[4].
1676  ///    In this case getBase() returns "A" and getIdx() returns "4".
1677  /// - getLHS() and getRHS() present the syntactic view. e.g. for
1678  ///    4[A] getLHS() returns "4".
1679  /// Note: Because vector element access is also written A[4] we must
1680  /// predicate the format conversion in getBase and getIdx only on the
1681  /// the type of the RHS, as it is possible for the LHS to be a vector of
1682  /// integer type
1683  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1684  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1685  void setLHS(Expr *E) { SubExprs[LHS] = E; }
1686
1687  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1688  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1689  void setRHS(Expr *E) { SubExprs[RHS] = E; }
1690
1691  Expr *getBase() {
1692    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1693  }
1694
1695  const Expr *getBase() const {
1696    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1697  }
1698
1699  Expr *getIdx() {
1700    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1701  }
1702
1703  const Expr *getIdx() const {
1704    return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1705  }
1706
1707  SourceRange getSourceRange() const {
1708    return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1709  }
1710
1711  SourceLocation getRBracketLoc() const { return RBracketLoc; }
1712  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1713
1714  SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1715
1716  static bool classof(const Stmt *T) {
1717    return T->getStmtClass() == ArraySubscriptExprClass;
1718  }
1719  static bool classof(const ArraySubscriptExpr *) { return true; }
1720
1721  // Iterators
1722  child_range children() {
1723    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
1724  }
1725};
1726
1727
1728/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1729/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1730/// while its subclasses may represent alternative syntax that (semantically)
1731/// results in a function call. For example, CXXOperatorCallExpr is
1732/// a subclass for overloaded operator calls that use operator syntax, e.g.,
1733/// "str1 + str2" to resolve to a function call.
1734class CallExpr : public Expr {
1735  enum { FN=0, PREARGS_START=1 };
1736  Stmt **SubExprs;
1737  unsigned NumArgs;
1738  SourceLocation RParenLoc;
1739
1740protected:
1741  // These versions of the constructor are for derived classes.
1742  CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
1743           Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
1744           SourceLocation rparenloc);
1745  CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
1746
1747  Stmt *getPreArg(unsigned i) {
1748    assert(i < getNumPreArgs() && "Prearg access out of range!");
1749    return SubExprs[PREARGS_START+i];
1750  }
1751  const Stmt *getPreArg(unsigned i) const {
1752    assert(i < getNumPreArgs() && "Prearg access out of range!");
1753    return SubExprs[PREARGS_START+i];
1754  }
1755  void setPreArg(unsigned i, Stmt *PreArg) {
1756    assert(i < getNumPreArgs() && "Prearg access out of range!");
1757    SubExprs[PREARGS_START+i] = PreArg;
1758  }
1759
1760  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
1761
1762public:
1763  CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1764           ExprValueKind VK, SourceLocation rparenloc);
1765
1766  /// \brief Build an empty call expression.
1767  CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1768
1769  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1770  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1771  void setCallee(Expr *F) { SubExprs[FN] = F; }
1772
1773  Decl *getCalleeDecl();
1774  const Decl *getCalleeDecl() const {
1775    return const_cast<CallExpr*>(this)->getCalleeDecl();
1776  }
1777
1778  /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1779  FunctionDecl *getDirectCallee();
1780  const FunctionDecl *getDirectCallee() const {
1781    return const_cast<CallExpr*>(this)->getDirectCallee();
1782  }
1783
1784  /// getNumArgs - Return the number of actual arguments to this call.
1785  ///
1786  unsigned getNumArgs() const { return NumArgs; }
1787
1788  /// \brief Retrieve the call arguments.
1789  Expr **getArgs() {
1790    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
1791  }
1792
1793  /// getArg - Return the specified argument.
1794  Expr *getArg(unsigned Arg) {
1795    assert(Arg < NumArgs && "Arg access out of range!");
1796    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1797  }
1798  const Expr *getArg(unsigned Arg) const {
1799    assert(Arg < NumArgs && "Arg access out of range!");
1800    return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1801  }
1802
1803  /// setArg - Set the specified argument.
1804  void setArg(unsigned Arg, Expr *ArgExpr) {
1805    assert(Arg < NumArgs && "Arg access out of range!");
1806    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
1807  }
1808
1809  /// setNumArgs - This changes the number of arguments present in this call.
1810  /// Any orphaned expressions are deleted by this, and any new operands are set
1811  /// to null.
1812  void setNumArgs(ASTContext& C, unsigned NumArgs);
1813
1814  typedef ExprIterator arg_iterator;
1815  typedef ConstExprIterator const_arg_iterator;
1816
1817  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
1818  arg_iterator arg_end() {
1819    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1820  }
1821  const_arg_iterator arg_begin() const {
1822    return SubExprs+PREARGS_START+getNumPreArgs();
1823  }
1824  const_arg_iterator arg_end() const {
1825    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1826  }
1827
1828  /// getNumCommas - Return the number of commas that must have been present in
1829  /// this function call.
1830  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1831
1832  /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
1833  /// not, return 0.
1834  unsigned isBuiltinCall(const ASTContext &Context) const;
1835
1836  /// getCallReturnType - Get the return type of the call expr. This is not
1837  /// always the type of the expr itself, if the return type is a reference
1838  /// type.
1839  QualType getCallReturnType() const;
1840
1841  SourceLocation getRParenLoc() const { return RParenLoc; }
1842  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1843
1844  SourceRange getSourceRange() const;
1845
1846  static bool classof(const Stmt *T) {
1847    return T->getStmtClass() >= firstCallExprConstant &&
1848           T->getStmtClass() <= lastCallExprConstant;
1849  }
1850  static bool classof(const CallExpr *) { return true; }
1851
1852  // Iterators
1853  child_range children() {
1854    return child_range(&SubExprs[0],
1855                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
1856  }
1857};
1858
1859/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
1860///
1861class MemberExpr : public Expr {
1862  /// Extra data stored in some member expressions.
1863  struct MemberNameQualifier : public NameQualifier {
1864    DeclAccessPair FoundDecl;
1865  };
1866
1867  /// Base - the expression for the base pointer or structure references.  In
1868  /// X.F, this is "X".
1869  Stmt *Base;
1870
1871  /// MemberDecl - This is the decl being referenced by the field/member name.
1872  /// In X.F, this is the decl referenced by F.
1873  ValueDecl *MemberDecl;
1874
1875  /// MemberLoc - This is the location of the member name.
1876  SourceLocation MemberLoc;
1877
1878  /// MemberDNLoc - Provides source/type location info for the
1879  /// declaration name embedded in MemberDecl.
1880  DeclarationNameLoc MemberDNLoc;
1881
1882  /// IsArrow - True if this is "X->F", false if this is "X.F".
1883  bool IsArrow : 1;
1884
1885  /// \brief True if this member expression used a nested-name-specifier to
1886  /// refer to the member, e.g., "x->Base::f", or found its member via a using
1887  /// declaration.  When true, a MemberNameQualifier
1888  /// structure is allocated immediately after the MemberExpr.
1889  bool HasQualifierOrFoundDecl : 1;
1890
1891  /// \brief True if this member expression specified a template argument list
1892  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1893  /// structure (and its TemplateArguments) are allocated immediately after
1894  /// the MemberExpr or, if the member expression also has a qualifier, after
1895  /// the MemberNameQualifier structure.
1896  bool HasExplicitTemplateArgumentList : 1;
1897
1898  /// \brief Retrieve the qualifier that preceded the member name, if any.
1899  MemberNameQualifier *getMemberQualifier() {
1900    assert(HasQualifierOrFoundDecl);
1901    return reinterpret_cast<MemberNameQualifier *> (this + 1);
1902  }
1903
1904  /// \brief Retrieve the qualifier that preceded the member name, if any.
1905  const MemberNameQualifier *getMemberQualifier() const {
1906    return const_cast<MemberExpr *>(this)->getMemberQualifier();
1907  }
1908
1909public:
1910  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1911             const DeclarationNameInfo &NameInfo, QualType ty,
1912             ExprValueKind VK, ExprObjectKind OK)
1913    : Expr(MemberExprClass, ty, VK, OK,
1914           base->isTypeDependent(), base->isValueDependent(),
1915           base->containsUnexpandedParameterPack()),
1916      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
1917      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
1918      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {
1919    assert(memberdecl->getDeclName() == NameInfo.getName());
1920  }
1921
1922  // NOTE: this constructor should be used only when it is known that
1923  // the member name can not provide additional syntactic info
1924  // (i.e., source locations for C++ operator names or type source info
1925  // for constructors, destructors and conversion oeprators).
1926  MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1927             SourceLocation l, QualType ty,
1928             ExprValueKind VK, ExprObjectKind OK)
1929    : Expr(MemberExprClass, ty, VK, OK,
1930           base->isTypeDependent(), base->isValueDependent(),
1931           base->containsUnexpandedParameterPack()),
1932      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
1933      IsArrow(isarrow),
1934      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
1935
1936  static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
1937                            NestedNameSpecifierLoc QualifierLoc,
1938                            ValueDecl *memberdecl, DeclAccessPair founddecl,
1939                            DeclarationNameInfo MemberNameInfo,
1940                            const TemplateArgumentListInfo *targs,
1941                            QualType ty, ExprValueKind VK, ExprObjectKind OK);
1942
1943  void setBase(Expr *E) { Base = E; }
1944  Expr *getBase() const { return cast<Expr>(Base); }
1945
1946  /// \brief Retrieve the member declaration to which this expression refers.
1947  ///
1948  /// The returned declaration will either be a FieldDecl or (in C++)
1949  /// a CXXMethodDecl.
1950  ValueDecl *getMemberDecl() const { return MemberDecl; }
1951  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
1952
1953  /// \brief Retrieves the declaration found by lookup.
1954  DeclAccessPair getFoundDecl() const {
1955    if (!HasQualifierOrFoundDecl)
1956      return DeclAccessPair::make(getMemberDecl(),
1957                                  getMemberDecl()->getAccess());
1958    return getMemberQualifier()->FoundDecl;
1959  }
1960
1961  /// \brief Determines whether this member expression actually had
1962  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
1963  /// x->Base::foo.
1964  bool hasQualifier() const { return getQualifier() != 0; }
1965
1966  /// \brief If the member name was qualified, retrieves the
1967  /// nested-name-specifier that precedes the member name. Otherwise, returns
1968  /// NULL.
1969  NestedNameSpecifier *getQualifier() const {
1970    if (!HasQualifierOrFoundDecl)
1971      return 0;
1972
1973    return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
1974  }
1975
1976  /// \brief If the member name was qualified, retrieves the
1977  /// nested-name-specifier that precedes the member name, with source-location
1978  /// information.
1979  NestedNameSpecifierLoc getQualifierLoc() const {
1980    if (!hasQualifier())
1981      return NestedNameSpecifierLoc();
1982
1983    return getMemberQualifier()->QualifierLoc;
1984  }
1985
1986  /// \brief Determines whether this member expression actually had a C++
1987  /// template argument list explicitly specified, e.g., x.f<int>.
1988  bool hasExplicitTemplateArgs() const {
1989    return HasExplicitTemplateArgumentList;
1990  }
1991
1992  /// \brief Copies the template arguments (if present) into the given
1993  /// structure.
1994  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1995    if (hasExplicitTemplateArgs())
1996      getExplicitTemplateArgs().copyInto(List);
1997  }
1998
1999  /// \brief Retrieve the explicit template argument list that
2000  /// follow the member template name.  This must only be called on an
2001  /// expression with explicit template arguments.
2002  ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
2003    assert(HasExplicitTemplateArgumentList);
2004    if (!HasQualifierOrFoundDecl)
2005      return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
2006
2007    return *reinterpret_cast<ExplicitTemplateArgumentList *>(
2008                                                      getMemberQualifier() + 1);
2009  }
2010
2011  /// \brief Retrieve the explicit template argument list that
2012  /// followed the member template name.  This must only be called on
2013  /// an expression with explicit template arguments.
2014  const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
2015    return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2016  }
2017
2018  /// \brief Retrieves the optional explicit template arguments.
2019  /// This points to the same data as getExplicitTemplateArgs(), but
2020  /// returns null if there are no explicit template arguments.
2021  const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const {
2022    if (!hasExplicitTemplateArgs()) return 0;
2023    return &getExplicitTemplateArgs();
2024  }
2025
2026  /// \brief Retrieve the location of the left angle bracket following the
2027  /// member name ('<'), if any.
2028  SourceLocation getLAngleLoc() const {
2029    if (!HasExplicitTemplateArgumentList)
2030      return SourceLocation();
2031
2032    return getExplicitTemplateArgs().LAngleLoc;
2033  }
2034
2035  /// \brief Retrieve the template arguments provided as part of this
2036  /// template-id.
2037  const TemplateArgumentLoc *getTemplateArgs() const {
2038    if (!HasExplicitTemplateArgumentList)
2039      return 0;
2040
2041    return getExplicitTemplateArgs().getTemplateArgs();
2042  }
2043
2044  /// \brief Retrieve the number of template arguments provided as part of this
2045  /// template-id.
2046  unsigned getNumTemplateArgs() const {
2047    if (!HasExplicitTemplateArgumentList)
2048      return 0;
2049
2050    return getExplicitTemplateArgs().NumTemplateArgs;
2051  }
2052
2053  /// \brief Retrieve the location of the right angle bracket following the
2054  /// template arguments ('>').
2055  SourceLocation getRAngleLoc() const {
2056    if (!HasExplicitTemplateArgumentList)
2057      return SourceLocation();
2058
2059    return getExplicitTemplateArgs().RAngleLoc;
2060  }
2061
2062  /// \brief Retrieve the member declaration name info.
2063  DeclarationNameInfo getMemberNameInfo() const {
2064    return DeclarationNameInfo(MemberDecl->getDeclName(),
2065                               MemberLoc, MemberDNLoc);
2066  }
2067
2068  bool isArrow() const { return IsArrow; }
2069  void setArrow(bool A) { IsArrow = A; }
2070
2071  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2072  /// location of 'F'.
2073  SourceLocation getMemberLoc() const { return MemberLoc; }
2074  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2075
2076  SourceRange getSourceRange() const;
2077
2078  SourceLocation getExprLoc() const { return MemberLoc; }
2079
2080  /// \brief Determine whether the base of this explicit is implicit.
2081  bool isImplicitAccess() const {
2082    return getBase() && getBase()->isImplicitCXXThis();
2083  }
2084
2085  static bool classof(const Stmt *T) {
2086    return T->getStmtClass() == MemberExprClass;
2087  }
2088  static bool classof(const MemberExpr *) { return true; }
2089
2090  // Iterators
2091  child_range children() { return child_range(&Base, &Base+1); }
2092
2093  friend class ASTReader;
2094  friend class ASTStmtWriter;
2095};
2096
2097/// CompoundLiteralExpr - [C99 6.5.2.5]
2098///
2099class CompoundLiteralExpr : public Expr {
2100  /// LParenLoc - If non-null, this is the location of the left paren in a
2101  /// compound literal like "(int){4}".  This can be null if this is a
2102  /// synthesized compound expression.
2103  SourceLocation LParenLoc;
2104
2105  /// The type as written.  This can be an incomplete array type, in
2106  /// which case the actual expression type will be different.
2107  TypeSourceInfo *TInfo;
2108  Stmt *Init;
2109  bool FileScope;
2110public:
2111  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2112                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2113    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2114           tinfo->getType()->isDependentType(),
2115           init->isValueDependent(),
2116           init->containsUnexpandedParameterPack()),
2117      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
2118
2119  /// \brief Construct an empty compound literal.
2120  explicit CompoundLiteralExpr(EmptyShell Empty)
2121    : Expr(CompoundLiteralExprClass, Empty) { }
2122
2123  const Expr *getInitializer() const { return cast<Expr>(Init); }
2124  Expr *getInitializer() { return cast<Expr>(Init); }
2125  void setInitializer(Expr *E) { Init = E; }
2126
2127  bool isFileScope() const { return FileScope; }
2128  void setFileScope(bool FS) { FileScope = FS; }
2129
2130  SourceLocation getLParenLoc() const { return LParenLoc; }
2131  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2132
2133  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
2134  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
2135
2136  SourceRange getSourceRange() const {
2137    // FIXME: Init should never be null.
2138    if (!Init)
2139      return SourceRange();
2140    if (LParenLoc.isInvalid())
2141      return Init->getSourceRange();
2142    return SourceRange(LParenLoc, Init->getLocEnd());
2143  }
2144
2145  static bool classof(const Stmt *T) {
2146    return T->getStmtClass() == CompoundLiteralExprClass;
2147  }
2148  static bool classof(const CompoundLiteralExpr *) { return true; }
2149
2150  // Iterators
2151  child_range children() { return child_range(&Init, &Init+1); }
2152};
2153
2154/// CastExpr - Base class for type casts, including both implicit
2155/// casts (ImplicitCastExpr) and explicit casts that have some
2156/// representation in the source code (ExplicitCastExpr's derived
2157/// classes).
2158class CastExpr : public Expr {
2159public:
2160  typedef clang::CastKind CastKind;
2161
2162private:
2163  Stmt *Op;
2164
2165  void CheckCastConsistency() const {
2166#ifndef NDEBUG
2167    switch (getCastKind()) {
2168    case CK_DerivedToBase:
2169    case CK_UncheckedDerivedToBase:
2170    case CK_DerivedToBaseMemberPointer:
2171    case CK_BaseToDerived:
2172    case CK_BaseToDerivedMemberPointer:
2173      assert(!path_empty() && "Cast kind should have a base path!");
2174      break;
2175
2176    // These should not have an inheritance path.
2177    case CK_BitCast:
2178    case CK_Dynamic:
2179    case CK_ToUnion:
2180    case CK_ArrayToPointerDecay:
2181    case CK_FunctionToPointerDecay:
2182    case CK_NullToMemberPointer:
2183    case CK_NullToPointer:
2184    case CK_ConstructorConversion:
2185    case CK_IntegralToPointer:
2186    case CK_PointerToIntegral:
2187    case CK_ToVoid:
2188    case CK_VectorSplat:
2189    case CK_IntegralCast:
2190    case CK_IntegralToFloating:
2191    case CK_FloatingToIntegral:
2192    case CK_FloatingCast:
2193    case CK_AnyPointerToObjCPointerCast:
2194    case CK_AnyPointerToBlockPointerCast:
2195    case CK_ObjCObjectLValueCast:
2196    case CK_FloatingRealToComplex:
2197    case CK_FloatingComplexToReal:
2198    case CK_FloatingComplexCast:
2199    case CK_FloatingComplexToIntegralComplex:
2200    case CK_IntegralRealToComplex:
2201    case CK_IntegralComplexToReal:
2202    case CK_IntegralComplexCast:
2203    case CK_IntegralComplexToFloatingComplex:
2204      assert(!getType()->isBooleanType() && "unheralded conversion to bool");
2205      // fallthrough to check for null base path
2206
2207    case CK_Dependent:
2208    case CK_LValueToRValue:
2209    case CK_GetObjCProperty:
2210    case CK_NoOp:
2211    case CK_PointerToBoolean:
2212    case CK_IntegralToBoolean:
2213    case CK_FloatingToBoolean:
2214    case CK_MemberPointerToBoolean:
2215    case CK_FloatingComplexToBoolean:
2216    case CK_IntegralComplexToBoolean:
2217    case CK_LValueBitCast:            // -> bool&
2218    case CK_UserDefinedConversion:    // operator bool()
2219      assert(path_empty() && "Cast kind should not have a base path!");
2220      break;
2221    }
2222#endif
2223  }
2224
2225  const CXXBaseSpecifier * const *path_buffer() const {
2226    return const_cast<CastExpr*>(this)->path_buffer();
2227  }
2228  CXXBaseSpecifier **path_buffer();
2229
2230protected:
2231  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2232           const CastKind kind, Expr *op, unsigned BasePathSize) :
2233    Expr(SC, ty, VK, OK_Ordinary,
2234         // Cast expressions are type-dependent if the type is
2235         // dependent (C++ [temp.dep.expr]p3).
2236         ty->isDependentType(),
2237         // Cast expressions are value-dependent if the type is
2238         // dependent or if the subexpression is value-dependent.
2239         ty->isDependentType() || (op && op->isValueDependent()),
2240         (ty->containsUnexpandedParameterPack() ||
2241          op->containsUnexpandedParameterPack())),
2242    Op(op) {
2243    assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2244    CastExprBits.Kind = kind;
2245    CastExprBits.BasePathSize = BasePathSize;
2246    CheckCastConsistency();
2247  }
2248
2249  /// \brief Construct an empty cast.
2250  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2251    : Expr(SC, Empty) {
2252    CastExprBits.BasePathSize = BasePathSize;
2253  }
2254
2255public:
2256  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2257  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2258  const char *getCastKindName() const;
2259
2260  Expr *getSubExpr() { return cast<Expr>(Op); }
2261  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2262  void setSubExpr(Expr *E) { Op = E; }
2263
2264  /// \brief Retrieve the cast subexpression as it was written in the source
2265  /// code, looking through any implicit casts or other intermediate nodes
2266  /// introduced by semantic analysis.
2267  Expr *getSubExprAsWritten();
2268  const Expr *getSubExprAsWritten() const {
2269    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2270  }
2271
2272  typedef CXXBaseSpecifier **path_iterator;
2273  typedef const CXXBaseSpecifier * const *path_const_iterator;
2274  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2275  unsigned path_size() const { return CastExprBits.BasePathSize; }
2276  path_iterator path_begin() { return path_buffer(); }
2277  path_iterator path_end() { return path_buffer() + path_size(); }
2278  path_const_iterator path_begin() const { return path_buffer(); }
2279  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2280
2281  void setCastPath(const CXXCastPath &Path);
2282
2283  static bool classof(const Stmt *T) {
2284    return T->getStmtClass() >= firstCastExprConstant &&
2285           T->getStmtClass() <= lastCastExprConstant;
2286  }
2287  static bool classof(const CastExpr *) { return true; }
2288
2289  // Iterators
2290  child_range children() { return child_range(&Op, &Op+1); }
2291};
2292
2293/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2294/// conversions, which have no direct representation in the original
2295/// source code. For example: converting T[]->T*, void f()->void
2296/// (*f)(), float->double, short->int, etc.
2297///
2298/// In C, implicit casts always produce rvalues. However, in C++, an
2299/// implicit cast whose result is being bound to a reference will be
2300/// an lvalue or xvalue. For example:
2301///
2302/// @code
2303/// class Base { };
2304/// class Derived : public Base { };
2305/// Derived &&ref();
2306/// void f(Derived d) {
2307///   Base& b = d; // initializer is an ImplicitCastExpr
2308///                // to an lvalue of type Base
2309///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2310///                     // to an xvalue of type Base
2311/// }
2312/// @endcode
2313class ImplicitCastExpr : public CastExpr {
2314private:
2315  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2316                   unsigned BasePathLength, ExprValueKind VK)
2317    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2318  }
2319
2320  /// \brief Construct an empty implicit cast.
2321  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2322    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2323
2324public:
2325  enum OnStack_t { OnStack };
2326  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2327                   ExprValueKind VK)
2328    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2329  }
2330
2331  static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2332                                  CastKind Kind, Expr *Operand,
2333                                  const CXXCastPath *BasePath,
2334                                  ExprValueKind Cat);
2335
2336  static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2337
2338  SourceRange getSourceRange() const {
2339    return getSubExpr()->getSourceRange();
2340  }
2341
2342  static bool classof(const Stmt *T) {
2343    return T->getStmtClass() == ImplicitCastExprClass;
2344  }
2345  static bool classof(const ImplicitCastExpr *) { return true; }
2346};
2347
2348/// ExplicitCastExpr - An explicit cast written in the source
2349/// code.
2350///
2351/// This class is effectively an abstract class, because it provides
2352/// the basic representation of an explicitly-written cast without
2353/// specifying which kind of cast (C cast, functional cast, static
2354/// cast, etc.) was written; specific derived classes represent the
2355/// particular style of cast and its location information.
2356///
2357/// Unlike implicit casts, explicit cast nodes have two different
2358/// types: the type that was written into the source code, and the
2359/// actual type of the expression as determined by semantic
2360/// analysis. These types may differ slightly. For example, in C++ one
2361/// can cast to a reference type, which indicates that the resulting
2362/// expression will be an lvalue or xvalue. The reference type, however,
2363/// will not be used as the type of the expression.
2364class ExplicitCastExpr : public CastExpr {
2365  /// TInfo - Source type info for the (written) type
2366  /// this expression is casting to.
2367  TypeSourceInfo *TInfo;
2368
2369protected:
2370  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2371                   CastKind kind, Expr *op, unsigned PathSize,
2372                   TypeSourceInfo *writtenTy)
2373    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2374
2375  /// \brief Construct an empty explicit cast.
2376  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2377    : CastExpr(SC, Shell, PathSize) { }
2378
2379public:
2380  /// getTypeInfoAsWritten - Returns the type source info for the type
2381  /// that this expression is casting to.
2382  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2383  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2384
2385  /// getTypeAsWritten - Returns the type that this expression is
2386  /// casting to, as written in the source code.
2387  QualType getTypeAsWritten() const { return TInfo->getType(); }
2388
2389  static bool classof(const Stmt *T) {
2390     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2391            T->getStmtClass() <= lastExplicitCastExprConstant;
2392  }
2393  static bool classof(const ExplicitCastExpr *) { return true; }
2394};
2395
2396/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2397/// cast in C++ (C++ [expr.cast]), which uses the syntax
2398/// (Type)expr. For example: @c (int)f.
2399class CStyleCastExpr : public ExplicitCastExpr {
2400  SourceLocation LPLoc; // the location of the left paren
2401  SourceLocation RPLoc; // the location of the right paren
2402
2403  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2404                 unsigned PathSize, TypeSourceInfo *writtenTy,
2405                 SourceLocation l, SourceLocation r)
2406    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2407                       writtenTy), LPLoc(l), RPLoc(r) {}
2408
2409  /// \brief Construct an empty C-style explicit cast.
2410  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2411    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2412
2413public:
2414  static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2415                                ExprValueKind VK, CastKind K,
2416                                Expr *Op, const CXXCastPath *BasePath,
2417                                TypeSourceInfo *WrittenTy, SourceLocation L,
2418                                SourceLocation R);
2419
2420  static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2421
2422  SourceLocation getLParenLoc() const { return LPLoc; }
2423  void setLParenLoc(SourceLocation L) { LPLoc = L; }
2424
2425  SourceLocation getRParenLoc() const { return RPLoc; }
2426  void setRParenLoc(SourceLocation L) { RPLoc = L; }
2427
2428  SourceRange getSourceRange() const {
2429    return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2430  }
2431  static bool classof(const Stmt *T) {
2432    return T->getStmtClass() == CStyleCastExprClass;
2433  }
2434  static bool classof(const CStyleCastExpr *) { return true; }
2435};
2436
2437/// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2438///
2439/// This expression node kind describes a builtin binary operation,
2440/// such as "x + y" for integer values "x" and "y". The operands will
2441/// already have been converted to appropriate types (e.g., by
2442/// performing promotions or conversions).
2443///
2444/// In C++, where operators may be overloaded, a different kind of
2445/// expression node (CXXOperatorCallExpr) is used to express the
2446/// invocation of an overloaded operator with operator syntax. Within
2447/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2448/// used to store an expression "x + y" depends on the subexpressions
2449/// for x and y. If neither x or y is type-dependent, and the "+"
2450/// operator resolves to a built-in operation, BinaryOperator will be
2451/// used to express the computation (x and y may still be
2452/// value-dependent). If either x or y is type-dependent, or if the
2453/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2454/// be used to express the computation.
2455class BinaryOperator : public Expr {
2456public:
2457  typedef BinaryOperatorKind Opcode;
2458
2459private:
2460  unsigned Opc : 6;
2461  SourceLocation OpLoc;
2462
2463  enum { LHS, RHS, END_EXPR };
2464  Stmt* SubExprs[END_EXPR];
2465public:
2466
2467  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2468                 ExprValueKind VK, ExprObjectKind OK,
2469                 SourceLocation opLoc)
2470    : Expr(BinaryOperatorClass, ResTy, VK, OK,
2471           lhs->isTypeDependent() || rhs->isTypeDependent(),
2472           lhs->isValueDependent() || rhs->isValueDependent(),
2473           (lhs->containsUnexpandedParameterPack() ||
2474            rhs->containsUnexpandedParameterPack())),
2475      Opc(opc), OpLoc(opLoc) {
2476    SubExprs[LHS] = lhs;
2477    SubExprs[RHS] = rhs;
2478    assert(!isCompoundAssignmentOp() &&
2479           "Use ArithAssignBinaryOperator for compound assignments");
2480  }
2481
2482  /// \brief Construct an empty binary operator.
2483  explicit BinaryOperator(EmptyShell Empty)
2484    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2485
2486  SourceLocation getOperatorLoc() const { return OpLoc; }
2487  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2488
2489  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2490  void setOpcode(Opcode O) { Opc = O; }
2491
2492  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2493  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2494  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2495  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2496
2497  SourceRange getSourceRange() const {
2498    return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2499  }
2500
2501  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2502  /// corresponds to, e.g. "<<=".
2503  static const char *getOpcodeStr(Opcode Op);
2504
2505  const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2506
2507  /// \brief Retrieve the binary opcode that corresponds to the given
2508  /// overloaded operator.
2509  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2510
2511  /// \brief Retrieve the overloaded operator kind that corresponds to
2512  /// the given binary opcode.
2513  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2514
2515  /// predicates to categorize the respective opcodes.
2516  bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2517  bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2518  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2519  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2520  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2521  bool isShiftOp() const { return isShiftOp(getOpcode()); }
2522
2523  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2524  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2525
2526  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2527  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2528
2529  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2530  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2531
2532  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2533  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2534
2535  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2536  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2537
2538  static bool isAssignmentOp(Opcode Opc) {
2539    return Opc >= BO_Assign && Opc <= BO_OrAssign;
2540  }
2541  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2542
2543  static bool isCompoundAssignmentOp(Opcode Opc) {
2544    return Opc > BO_Assign && Opc <= BO_OrAssign;
2545  }
2546  bool isCompoundAssignmentOp() const {
2547    return isCompoundAssignmentOp(getOpcode());
2548  }
2549
2550  static bool isShiftAssignOp(Opcode Opc) {
2551    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2552  }
2553  bool isShiftAssignOp() const {
2554    return isShiftAssignOp(getOpcode());
2555  }
2556
2557  static bool classof(const Stmt *S) {
2558    return S->getStmtClass() >= firstBinaryOperatorConstant &&
2559           S->getStmtClass() <= lastBinaryOperatorConstant;
2560  }
2561  static bool classof(const BinaryOperator *) { return true; }
2562
2563  // Iterators
2564  child_range children() {
2565    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2566  }
2567
2568protected:
2569  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2570                 ExprValueKind VK, ExprObjectKind OK,
2571                 SourceLocation opLoc, bool dead)
2572    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
2573           lhs->isTypeDependent() || rhs->isTypeDependent(),
2574           lhs->isValueDependent() || rhs->isValueDependent(),
2575           (lhs->containsUnexpandedParameterPack() ||
2576            rhs->containsUnexpandedParameterPack())),
2577      Opc(opc), OpLoc(opLoc) {
2578    SubExprs[LHS] = lhs;
2579    SubExprs[RHS] = rhs;
2580  }
2581
2582  BinaryOperator(StmtClass SC, EmptyShell Empty)
2583    : Expr(SC, Empty), Opc(BO_MulAssign) { }
2584};
2585
2586/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2587/// track of the type the operation is performed in.  Due to the semantics of
2588/// these operators, the operands are promoted, the aritmetic performed, an
2589/// implicit conversion back to the result type done, then the assignment takes
2590/// place.  This captures the intermediate type which the computation is done
2591/// in.
2592class CompoundAssignOperator : public BinaryOperator {
2593  QualType ComputationLHSType;
2594  QualType ComputationResultType;
2595public:
2596  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
2597                         ExprValueKind VK, ExprObjectKind OK,
2598                         QualType CompLHSType, QualType CompResultType,
2599                         SourceLocation OpLoc)
2600    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true),
2601      ComputationLHSType(CompLHSType),
2602      ComputationResultType(CompResultType) {
2603    assert(isCompoundAssignmentOp() &&
2604           "Only should be used for compound assignments");
2605  }
2606
2607  /// \brief Build an empty compound assignment operator expression.
2608  explicit CompoundAssignOperator(EmptyShell Empty)
2609    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2610
2611  // The two computation types are the type the LHS is converted
2612  // to for the computation and the type of the result; the two are
2613  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2614  QualType getComputationLHSType() const { return ComputationLHSType; }
2615  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2616
2617  QualType getComputationResultType() const { return ComputationResultType; }
2618  void setComputationResultType(QualType T) { ComputationResultType = T; }
2619
2620  static bool classof(const CompoundAssignOperator *) { return true; }
2621  static bool classof(const Stmt *S) {
2622    return S->getStmtClass() == CompoundAssignOperatorClass;
2623  }
2624};
2625
2626/// AbstractConditionalOperator - An abstract base class for
2627/// ConditionalOperator and BinaryConditionalOperator.
2628class AbstractConditionalOperator : public Expr {
2629  SourceLocation QuestionLoc, ColonLoc;
2630  friend class ASTStmtReader;
2631
2632protected:
2633  AbstractConditionalOperator(StmtClass SC, QualType T,
2634                              ExprValueKind VK, ExprObjectKind OK,
2635                              bool TD, bool VD,
2636                              bool ContainsUnexpandedParameterPack,
2637                              SourceLocation qloc,
2638                              SourceLocation cloc)
2639    : Expr(SC, T, VK, OK, TD, VD, ContainsUnexpandedParameterPack),
2640      QuestionLoc(qloc), ColonLoc(cloc) {}
2641
2642  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
2643    : Expr(SC, Empty) { }
2644
2645public:
2646  // getCond - Return the expression representing the condition for
2647  //   the ?: operator.
2648  Expr *getCond() const;
2649
2650  // getTrueExpr - Return the subexpression representing the value of
2651  //   the expression if the condition evaluates to true.
2652  Expr *getTrueExpr() const;
2653
2654  // getFalseExpr - Return the subexpression representing the value of
2655  //   the expression if the condition evaluates to false.  This is
2656  //   the same as getRHS.
2657  Expr *getFalseExpr() const;
2658
2659  SourceLocation getQuestionLoc() const { return QuestionLoc; }
2660  SourceLocation getColonLoc() const { return ColonLoc; }
2661
2662  static bool classof(const Stmt *T) {
2663    return T->getStmtClass() == ConditionalOperatorClass ||
2664           T->getStmtClass() == BinaryConditionalOperatorClass;
2665  }
2666  static bool classof(const AbstractConditionalOperator *) { return true; }
2667};
2668
2669/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
2670/// middle" extension is a BinaryConditionalOperator.
2671class ConditionalOperator : public AbstractConditionalOperator {
2672  enum { COND, LHS, RHS, END_EXPR };
2673  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2674
2675  friend class ASTStmtReader;
2676public:
2677  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2678                      SourceLocation CLoc, Expr *rhs,
2679                      QualType t, ExprValueKind VK, ExprObjectKind OK)
2680    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
2681           // FIXME: the type of the conditional operator doesn't
2682           // depend on the type of the conditional, but the standard
2683           // seems to imply that it could. File a bug!
2684           (lhs->isTypeDependent() || rhs->isTypeDependent()),
2685           (cond->isValueDependent() || lhs->isValueDependent() ||
2686            rhs->isValueDependent()),
2687           (cond->containsUnexpandedParameterPack() ||
2688            lhs->containsUnexpandedParameterPack() ||
2689            rhs->containsUnexpandedParameterPack()),
2690                                  QLoc, CLoc) {
2691    SubExprs[COND] = cond;
2692    SubExprs[LHS] = lhs;
2693    SubExprs[RHS] = rhs;
2694  }
2695
2696  /// \brief Build an empty conditional operator.
2697  explicit ConditionalOperator(EmptyShell Empty)
2698    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
2699
2700  // getCond - Return the expression representing the condition for
2701  //   the ?: operator.
2702  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2703
2704  // getTrueExpr - Return the subexpression representing the value of
2705  //   the expression if the condition evaluates to true.
2706  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
2707
2708  // getFalseExpr - Return the subexpression representing the value of
2709  //   the expression if the condition evaluates to false.  This is
2710  //   the same as getRHS.
2711  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2712
2713  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2714  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2715
2716  SourceRange getSourceRange() const {
2717    return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2718  }
2719  static bool classof(const Stmt *T) {
2720    return T->getStmtClass() == ConditionalOperatorClass;
2721  }
2722  static bool classof(const ConditionalOperator *) { return true; }
2723
2724  // Iterators
2725  child_range children() {
2726    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2727  }
2728};
2729
2730/// BinaryConditionalOperator - The GNU extension to the conditional
2731/// operator which allows the middle operand to be omitted.
2732///
2733/// This is a different expression kind on the assumption that almost
2734/// every client ends up needing to know that these are different.
2735class BinaryConditionalOperator : public AbstractConditionalOperator {
2736  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
2737
2738  /// - the common condition/left-hand-side expression, which will be
2739  ///   evaluated as the opaque value
2740  /// - the condition, expressed in terms of the opaque value
2741  /// - the left-hand-side, expressed in terms of the opaque value
2742  /// - the right-hand-side
2743  Stmt *SubExprs[NUM_SUBEXPRS];
2744  OpaqueValueExpr *OpaqueValue;
2745
2746  friend class ASTStmtReader;
2747public:
2748  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
2749                            Expr *cond, Expr *lhs, Expr *rhs,
2750                            SourceLocation qloc, SourceLocation cloc,
2751                            QualType t, ExprValueKind VK, ExprObjectKind OK)
2752    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
2753           (common->isTypeDependent() || rhs->isTypeDependent()),
2754           (common->isValueDependent() || rhs->isValueDependent()),
2755           (common->containsUnexpandedParameterPack() ||
2756            rhs->containsUnexpandedParameterPack()),
2757                                  qloc, cloc),
2758      OpaqueValue(opaqueValue) {
2759    SubExprs[COMMON] = common;
2760    SubExprs[COND] = cond;
2761    SubExprs[LHS] = lhs;
2762    SubExprs[RHS] = rhs;
2763
2764    OpaqueValue->setSourceExpr(common);
2765  }
2766
2767  /// \brief Build an empty conditional operator.
2768  explicit BinaryConditionalOperator(EmptyShell Empty)
2769    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
2770
2771  /// \brief getCommon - Return the common expression, written to the
2772  ///   left of the condition.  The opaque value will be bound to the
2773  ///   result of this expression.
2774  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
2775
2776  /// \brief getOpaqueValue - Return the opaque value placeholder.
2777  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
2778
2779  /// \brief getCond - Return the condition expression; this is defined
2780  ///   in terms of the opaque value.
2781  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2782
2783  /// \brief getTrueExpr - Return the subexpression which will be
2784  ///   evaluated if the condition evaluates to true;  this is defined
2785  ///   in terms of the opaque value.
2786  Expr *getTrueExpr() const {
2787    return cast<Expr>(SubExprs[LHS]);
2788  }
2789
2790  /// \brief getFalseExpr - Return the subexpression which will be
2791  ///   evaluated if the condnition evaluates to false; this is
2792  ///   defined in terms of the opaque value.
2793  Expr *getFalseExpr() const {
2794    return cast<Expr>(SubExprs[RHS]);
2795  }
2796
2797  SourceRange getSourceRange() const {
2798    return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd());
2799  }
2800  static bool classof(const Stmt *T) {
2801    return T->getStmtClass() == BinaryConditionalOperatorClass;
2802  }
2803  static bool classof(const BinaryConditionalOperator *) { return true; }
2804
2805  // Iterators
2806  child_range children() {
2807    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
2808  }
2809};
2810
2811inline Expr *AbstractConditionalOperator::getCond() const {
2812  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2813    return co->getCond();
2814  return cast<BinaryConditionalOperator>(this)->getCond();
2815}
2816
2817inline Expr *AbstractConditionalOperator::getTrueExpr() const {
2818  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2819    return co->getTrueExpr();
2820  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
2821}
2822
2823inline Expr *AbstractConditionalOperator::getFalseExpr() const {
2824  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2825    return co->getFalseExpr();
2826  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
2827}
2828
2829/// AddrLabelExpr - The GNU address of label extension, representing &&label.
2830class AddrLabelExpr : public Expr {
2831  SourceLocation AmpAmpLoc, LabelLoc;
2832  LabelDecl *Label;
2833public:
2834  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
2835                QualType t)
2836    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false),
2837      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2838
2839  /// \brief Build an empty address of a label expression.
2840  explicit AddrLabelExpr(EmptyShell Empty)
2841    : Expr(AddrLabelExprClass, Empty) { }
2842
2843  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2844  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2845  SourceLocation getLabelLoc() const { return LabelLoc; }
2846  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2847
2848  SourceRange getSourceRange() const {
2849    return SourceRange(AmpAmpLoc, LabelLoc);
2850  }
2851
2852  LabelDecl *getLabel() const { return Label; }
2853  void setLabel(LabelDecl *L) { Label = L; }
2854
2855  static bool classof(const Stmt *T) {
2856    return T->getStmtClass() == AddrLabelExprClass;
2857  }
2858  static bool classof(const AddrLabelExpr *) { return true; }
2859
2860  // Iterators
2861  child_range children() { return child_range(); }
2862};
2863
2864/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2865/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2866/// takes the value of the last subexpression.
2867///
2868/// A StmtExpr is always an r-value; values "returned" out of a
2869/// StmtExpr will be copied.
2870class StmtExpr : public Expr {
2871  Stmt *SubStmt;
2872  SourceLocation LParenLoc, RParenLoc;
2873public:
2874  // FIXME: Does type-dependence need to be computed differently?
2875  StmtExpr(CompoundStmt *substmt, QualType T,
2876           SourceLocation lp, SourceLocation rp) :
2877    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
2878         T->isDependentType(), false, false),
2879    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2880
2881  /// \brief Build an empty statement expression.
2882  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2883
2884  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2885  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2886  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2887
2888  SourceRange getSourceRange() const {
2889    return SourceRange(LParenLoc, RParenLoc);
2890  }
2891
2892  SourceLocation getLParenLoc() const { return LParenLoc; }
2893  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2894  SourceLocation getRParenLoc() const { return RParenLoc; }
2895  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2896
2897  static bool classof(const Stmt *T) {
2898    return T->getStmtClass() == StmtExprClass;
2899  }
2900  static bool classof(const StmtExpr *) { return true; }
2901
2902  // Iterators
2903  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
2904};
2905
2906
2907/// ShuffleVectorExpr - clang-specific builtin-in function
2908/// __builtin_shufflevector.
2909/// This AST node represents a operator that does a constant
2910/// shuffle, similar to LLVM's shufflevector instruction. It takes
2911/// two vectors and a variable number of constant indices,
2912/// and returns the appropriately shuffled vector.
2913class ShuffleVectorExpr : public Expr {
2914  SourceLocation BuiltinLoc, RParenLoc;
2915
2916  // SubExprs - the list of values passed to the __builtin_shufflevector
2917  // function. The first two are vectors, and the rest are constant
2918  // indices.  The number of values in this list is always
2919  // 2+the number of indices in the vector type.
2920  Stmt **SubExprs;
2921  unsigned NumExprs;
2922
2923public:
2924  ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2925                    QualType Type, SourceLocation BLoc,
2926                    SourceLocation RP);
2927
2928  /// \brief Build an empty vector-shuffle expression.
2929  explicit ShuffleVectorExpr(EmptyShell Empty)
2930    : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2931
2932  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2933  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2934
2935  SourceLocation getRParenLoc() const { return RParenLoc; }
2936  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2937
2938  SourceRange getSourceRange() const {
2939    return SourceRange(BuiltinLoc, RParenLoc);
2940  }
2941  static bool classof(const Stmt *T) {
2942    return T->getStmtClass() == ShuffleVectorExprClass;
2943  }
2944  static bool classof(const ShuffleVectorExpr *) { return true; }
2945
2946  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
2947  /// constant expression, the actual arguments passed in, and the function
2948  /// pointers.
2949  unsigned getNumSubExprs() const { return NumExprs; }
2950
2951  /// \brief Retrieve the array of expressions.
2952  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
2953
2954  /// getExpr - Return the Expr at the specified index.
2955  Expr *getExpr(unsigned Index) {
2956    assert((Index < NumExprs) && "Arg access out of range!");
2957    return cast<Expr>(SubExprs[Index]);
2958  }
2959  const Expr *getExpr(unsigned Index) const {
2960    assert((Index < NumExprs) && "Arg access out of range!");
2961    return cast<Expr>(SubExprs[Index]);
2962  }
2963
2964  void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2965
2966  unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2967    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2968    return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2969  }
2970
2971  // Iterators
2972  child_range children() {
2973    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
2974  }
2975};
2976
2977/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2978/// This AST node is similar to the conditional operator (?:) in C, with
2979/// the following exceptions:
2980/// - the test expression must be a integer constant expression.
2981/// - the expression returned acts like the chosen subexpression in every
2982///   visible way: the type is the same as that of the chosen subexpression,
2983///   and all predicates (whether it's an l-value, whether it's an integer
2984///   constant expression, etc.) return the same result as for the chosen
2985///   sub-expression.
2986class ChooseExpr : public Expr {
2987  enum { COND, LHS, RHS, END_EXPR };
2988  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2989  SourceLocation BuiltinLoc, RParenLoc;
2990public:
2991  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
2992             QualType t, ExprValueKind VK, ExprObjectKind OK,
2993             SourceLocation RP, bool TypeDependent, bool ValueDependent)
2994    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
2995           (cond->containsUnexpandedParameterPack() ||
2996            lhs->containsUnexpandedParameterPack() ||
2997            rhs->containsUnexpandedParameterPack())),
2998      BuiltinLoc(BLoc), RParenLoc(RP) {
2999      SubExprs[COND] = cond;
3000      SubExprs[LHS] = lhs;
3001      SubExprs[RHS] = rhs;
3002    }
3003
3004  /// \brief Build an empty __builtin_choose_expr.
3005  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3006
3007  /// isConditionTrue - Return whether the condition is true (i.e. not
3008  /// equal to zero).
3009  bool isConditionTrue(const ASTContext &C) const;
3010
3011  /// getChosenSubExpr - Return the subexpression chosen according to the
3012  /// condition.
3013  Expr *getChosenSubExpr(const ASTContext &C) const {
3014    return isConditionTrue(C) ? getLHS() : getRHS();
3015  }
3016
3017  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3018  void setCond(Expr *E) { SubExprs[COND] = E; }
3019  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3020  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3021  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3022  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3023
3024  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3025  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3026
3027  SourceLocation getRParenLoc() const { return RParenLoc; }
3028  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3029
3030  SourceRange getSourceRange() const {
3031    return SourceRange(BuiltinLoc, RParenLoc);
3032  }
3033  static bool classof(const Stmt *T) {
3034    return T->getStmtClass() == ChooseExprClass;
3035  }
3036  static bool classof(const ChooseExpr *) { return true; }
3037
3038  // Iterators
3039  child_range children() {
3040    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3041  }
3042};
3043
3044/// GNUNullExpr - Implements the GNU __null extension, which is a name
3045/// for a null pointer constant that has integral type (e.g., int or
3046/// long) and is the same size and alignment as a pointer. The __null
3047/// extension is typically only used by system headers, which define
3048/// NULL as __null in C++ rather than using 0 (which is an integer
3049/// that may not match the size of a pointer).
3050class GNUNullExpr : public Expr {
3051  /// TokenLoc - The location of the __null keyword.
3052  SourceLocation TokenLoc;
3053
3054public:
3055  GNUNullExpr(QualType Ty, SourceLocation Loc)
3056    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false),
3057      TokenLoc(Loc) { }
3058
3059  /// \brief Build an empty GNU __null expression.
3060  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3061
3062  /// getTokenLocation - The location of the __null token.
3063  SourceLocation getTokenLocation() const { return TokenLoc; }
3064  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3065
3066  SourceRange getSourceRange() const {
3067    return SourceRange(TokenLoc);
3068  }
3069  static bool classof(const Stmt *T) {
3070    return T->getStmtClass() == GNUNullExprClass;
3071  }
3072  static bool classof(const GNUNullExpr *) { return true; }
3073
3074  // Iterators
3075  child_range children() { return child_range(); }
3076};
3077
3078/// VAArgExpr, used for the builtin function __builtin_va_arg.
3079class VAArgExpr : public Expr {
3080  Stmt *Val;
3081  TypeSourceInfo *TInfo;
3082  SourceLocation BuiltinLoc, RParenLoc;
3083public:
3084  VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3085            SourceLocation RPLoc, QualType t)
3086    : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3087           t->isDependentType(), false,
3088           (TInfo->getType()->containsUnexpandedParameterPack() ||
3089            e->containsUnexpandedParameterPack())),
3090      Val(e), TInfo(TInfo),
3091      BuiltinLoc(BLoc),
3092      RParenLoc(RPLoc) { }
3093
3094  /// \brief Create an empty __builtin_va_arg expression.
3095  explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3096
3097  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3098  Expr *getSubExpr() { return cast<Expr>(Val); }
3099  void setSubExpr(Expr *E) { Val = E; }
3100
3101  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3102  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3103
3104  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3105  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3106
3107  SourceLocation getRParenLoc() const { return RParenLoc; }
3108  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3109
3110  SourceRange getSourceRange() const {
3111    return SourceRange(BuiltinLoc, RParenLoc);
3112  }
3113  static bool classof(const Stmt *T) {
3114    return T->getStmtClass() == VAArgExprClass;
3115  }
3116  static bool classof(const VAArgExpr *) { return true; }
3117
3118  // Iterators
3119  child_range children() { return child_range(&Val, &Val+1); }
3120};
3121
3122/// @brief Describes an C or C++ initializer list.
3123///
3124/// InitListExpr describes an initializer list, which can be used to
3125/// initialize objects of different types, including
3126/// struct/class/union types, arrays, and vectors. For example:
3127///
3128/// @code
3129/// struct foo x = { 1, { 2, 3 } };
3130/// @endcode
3131///
3132/// Prior to semantic analysis, an initializer list will represent the
3133/// initializer list as written by the user, but will have the
3134/// placeholder type "void". This initializer list is called the
3135/// syntactic form of the initializer, and may contain C99 designated
3136/// initializers (represented as DesignatedInitExprs), initializations
3137/// of subobject members without explicit braces, and so on. Clients
3138/// interested in the original syntax of the initializer list should
3139/// use the syntactic form of the initializer list.
3140///
3141/// After semantic analysis, the initializer list will represent the
3142/// semantic form of the initializer, where the initializations of all
3143/// subobjects are made explicit with nested InitListExpr nodes and
3144/// C99 designators have been eliminated by placing the designated
3145/// initializations into the subobject they initialize. Additionally,
3146/// any "holes" in the initialization, where no initializer has been
3147/// specified for a particular subobject, will be replaced with
3148/// implicitly-generated ImplicitValueInitExpr expressions that
3149/// value-initialize the subobjects. Note, however, that the
3150/// initializer lists may still have fewer initializers than there are
3151/// elements to initialize within the object.
3152///
3153/// Given the semantic form of the initializer list, one can retrieve
3154/// the original syntactic form of that initializer list (if it
3155/// exists) using getSyntacticForm(). Since many initializer lists
3156/// have the same syntactic and semantic forms, getSyntacticForm() may
3157/// return NULL, indicating that the current initializer list also
3158/// serves as its syntactic form.
3159class InitListExpr : public Expr {
3160  // FIXME: Eliminate this vector in favor of ASTContext allocation
3161  typedef ASTVector<Stmt *> InitExprsTy;
3162  InitExprsTy InitExprs;
3163  SourceLocation LBraceLoc, RBraceLoc;
3164
3165  /// Contains the initializer list that describes the syntactic form
3166  /// written in the source code.
3167  InitListExpr *SyntacticForm;
3168
3169  /// If this initializer list initializes a union, specifies which
3170  /// field within the union will be initialized.
3171  FieldDecl *UnionFieldInit;
3172
3173  /// Whether this initializer list originally had a GNU array-range
3174  /// designator in it. This is a temporary marker used by CodeGen.
3175  bool HadArrayRangeDesignator;
3176
3177public:
3178  InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3179               Expr **initexprs, unsigned numinits,
3180               SourceLocation rbraceloc);
3181
3182  /// \brief Build an empty initializer list.
3183  explicit InitListExpr(ASTContext &C, EmptyShell Empty)
3184    : Expr(InitListExprClass, Empty), InitExprs(C) { }
3185
3186  unsigned getNumInits() const { return InitExprs.size(); }
3187
3188  /// \brief Retrieve the set of initializers.
3189  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3190
3191  const Expr *getInit(unsigned Init) const {
3192    assert(Init < getNumInits() && "Initializer access out of range!");
3193    return cast_or_null<Expr>(InitExprs[Init]);
3194  }
3195
3196  Expr *getInit(unsigned Init) {
3197    assert(Init < getNumInits() && "Initializer access out of range!");
3198    return cast_or_null<Expr>(InitExprs[Init]);
3199  }
3200
3201  void setInit(unsigned Init, Expr *expr) {
3202    assert(Init < getNumInits() && "Initializer access out of range!");
3203    InitExprs[Init] = expr;
3204  }
3205
3206  /// \brief Reserve space for some number of initializers.
3207  void reserveInits(ASTContext &C, unsigned NumInits);
3208
3209  /// @brief Specify the number of initializers
3210  ///
3211  /// If there are more than @p NumInits initializers, the remaining
3212  /// initializers will be destroyed. If there are fewer than @p
3213  /// NumInits initializers, NULL expressions will be added for the
3214  /// unknown initializers.
3215  void resizeInits(ASTContext &Context, unsigned NumInits);
3216
3217  /// @brief Updates the initializer at index @p Init with the new
3218  /// expression @p expr, and returns the old expression at that
3219  /// location.
3220  ///
3221  /// When @p Init is out of range for this initializer list, the
3222  /// initializer list will be extended with NULL expressions to
3223  /// accomodate the new entry.
3224  Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3225
3226  /// \brief If this initializes a union, specifies which field in the
3227  /// union to initialize.
3228  ///
3229  /// Typically, this field is the first named field within the
3230  /// union. However, a designated initializer can specify the
3231  /// initialization of a different field within the union.
3232  FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
3233  void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
3234
3235  // Explicit InitListExpr's originate from source code (and have valid source
3236  // locations). Implicit InitListExpr's are created by the semantic analyzer.
3237  bool isExplicit() {
3238    return LBraceLoc.isValid() && RBraceLoc.isValid();
3239  }
3240
3241  SourceLocation getLBraceLoc() const { return LBraceLoc; }
3242  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3243  SourceLocation getRBraceLoc() const { return RBraceLoc; }
3244  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3245
3246  /// @brief Retrieve the initializer list that describes the
3247  /// syntactic form of the initializer.
3248  ///
3249  ///
3250  InitListExpr *getSyntacticForm() const { return SyntacticForm; }
3251  void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
3252
3253  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
3254  void sawArrayRangeDesignator(bool ARD = true) {
3255    HadArrayRangeDesignator = ARD;
3256  }
3257
3258  SourceRange getSourceRange() const;
3259
3260  static bool classof(const Stmt *T) {
3261    return T->getStmtClass() == InitListExprClass;
3262  }
3263  static bool classof(const InitListExpr *) { return true; }
3264
3265  // Iterators
3266  child_range children() {
3267    if (InitExprs.empty()) return child_range();
3268    return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3269  }
3270
3271  typedef InitExprsTy::iterator iterator;
3272  typedef InitExprsTy::const_iterator const_iterator;
3273  typedef InitExprsTy::reverse_iterator reverse_iterator;
3274  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3275
3276  iterator begin() { return InitExprs.begin(); }
3277  const_iterator begin() const { return InitExprs.begin(); }
3278  iterator end() { return InitExprs.end(); }
3279  const_iterator end() const { return InitExprs.end(); }
3280  reverse_iterator rbegin() { return InitExprs.rbegin(); }
3281  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3282  reverse_iterator rend() { return InitExprs.rend(); }
3283  const_reverse_iterator rend() const { return InitExprs.rend(); }
3284};
3285
3286/// @brief Represents a C99 designated initializer expression.
3287///
3288/// A designated initializer expression (C99 6.7.8) contains one or
3289/// more designators (which can be field designators, array
3290/// designators, or GNU array-range designators) followed by an
3291/// expression that initializes the field or element(s) that the
3292/// designators refer to. For example, given:
3293///
3294/// @code
3295/// struct point {
3296///   double x;
3297///   double y;
3298/// };
3299/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3300/// @endcode
3301///
3302/// The InitListExpr contains three DesignatedInitExprs, the first of
3303/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3304/// designators, one array designator for @c [2] followed by one field
3305/// designator for @c .y. The initalization expression will be 1.0.
3306class DesignatedInitExpr : public Expr {
3307public:
3308  /// \brief Forward declaration of the Designator class.
3309  class Designator;
3310
3311private:
3312  /// The location of the '=' or ':' prior to the actual initializer
3313  /// expression.
3314  SourceLocation EqualOrColonLoc;
3315
3316  /// Whether this designated initializer used the GNU deprecated
3317  /// syntax rather than the C99 '=' syntax.
3318  bool GNUSyntax : 1;
3319
3320  /// The number of designators in this initializer expression.
3321  unsigned NumDesignators : 15;
3322
3323  /// \brief The designators in this designated initialization
3324  /// expression.
3325  Designator *Designators;
3326
3327  /// The number of subexpressions of this initializer expression,
3328  /// which contains both the initializer and any additional
3329  /// expressions used by array and array-range designators.
3330  unsigned NumSubExprs : 16;
3331
3332
3333  DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3334                     const Designator *Designators,
3335                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
3336                     Expr **IndexExprs, unsigned NumIndexExprs,
3337                     Expr *Init);
3338
3339  explicit DesignatedInitExpr(unsigned NumSubExprs)
3340    : Expr(DesignatedInitExprClass, EmptyShell()),
3341      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3342
3343public:
3344  /// A field designator, e.g., ".x".
3345  struct FieldDesignator {
3346    /// Refers to the field that is being initialized. The low bit
3347    /// of this field determines whether this is actually a pointer
3348    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3349    /// initially constructed, a field designator will store an
3350    /// IdentifierInfo*. After semantic analysis has resolved that
3351    /// name, the field designator will instead store a FieldDecl*.
3352    uintptr_t NameOrField;
3353
3354    /// The location of the '.' in the designated initializer.
3355    unsigned DotLoc;
3356
3357    /// The location of the field name in the designated initializer.
3358    unsigned FieldLoc;
3359  };
3360
3361  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3362  struct ArrayOrRangeDesignator {
3363    /// Location of the first index expression within the designated
3364    /// initializer expression's list of subexpressions.
3365    unsigned Index;
3366    /// The location of the '[' starting the array range designator.
3367    unsigned LBracketLoc;
3368    /// The location of the ellipsis separating the start and end
3369    /// indices. Only valid for GNU array-range designators.
3370    unsigned EllipsisLoc;
3371    /// The location of the ']' terminating the array range designator.
3372    unsigned RBracketLoc;
3373  };
3374
3375  /// @brief Represents a single C99 designator.
3376  ///
3377  /// @todo This class is infuriatingly similar to clang::Designator,
3378  /// but minor differences (storing indices vs. storing pointers)
3379  /// keep us from reusing it. Try harder, later, to rectify these
3380  /// differences.
3381  class Designator {
3382    /// @brief The kind of designator this describes.
3383    enum {
3384      FieldDesignator,
3385      ArrayDesignator,
3386      ArrayRangeDesignator
3387    } Kind;
3388
3389    union {
3390      /// A field designator, e.g., ".x".
3391      struct FieldDesignator Field;
3392      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3393      struct ArrayOrRangeDesignator ArrayOrRange;
3394    };
3395    friend class DesignatedInitExpr;
3396
3397  public:
3398    Designator() {}
3399
3400    /// @brief Initializes a field designator.
3401    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3402               SourceLocation FieldLoc)
3403      : Kind(FieldDesignator) {
3404      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3405      Field.DotLoc = DotLoc.getRawEncoding();
3406      Field.FieldLoc = FieldLoc.getRawEncoding();
3407    }
3408
3409    /// @brief Initializes an array designator.
3410    Designator(unsigned Index, SourceLocation LBracketLoc,
3411               SourceLocation RBracketLoc)
3412      : Kind(ArrayDesignator) {
3413      ArrayOrRange.Index = Index;
3414      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3415      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3416      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3417    }
3418
3419    /// @brief Initializes a GNU array-range designator.
3420    Designator(unsigned Index, SourceLocation LBracketLoc,
3421               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3422      : Kind(ArrayRangeDesignator) {
3423      ArrayOrRange.Index = Index;
3424      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3425      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3426      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3427    }
3428
3429    bool isFieldDesignator() const { return Kind == FieldDesignator; }
3430    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3431    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3432
3433    IdentifierInfo * getFieldName();
3434
3435    FieldDecl *getField() {
3436      assert(Kind == FieldDesignator && "Only valid on a field designator");
3437      if (Field.NameOrField & 0x01)
3438        return 0;
3439      else
3440        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3441    }
3442
3443    void setField(FieldDecl *FD) {
3444      assert(Kind == FieldDesignator && "Only valid on a field designator");
3445      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3446    }
3447
3448    SourceLocation getDotLoc() const {
3449      assert(Kind == FieldDesignator && "Only valid on a field designator");
3450      return SourceLocation::getFromRawEncoding(Field.DotLoc);
3451    }
3452
3453    SourceLocation getFieldLoc() const {
3454      assert(Kind == FieldDesignator && "Only valid on a field designator");
3455      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3456    }
3457
3458    SourceLocation getLBracketLoc() const {
3459      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3460             "Only valid on an array or array-range designator");
3461      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3462    }
3463
3464    SourceLocation getRBracketLoc() const {
3465      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3466             "Only valid on an array or array-range designator");
3467      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3468    }
3469
3470    SourceLocation getEllipsisLoc() const {
3471      assert(Kind == ArrayRangeDesignator &&
3472             "Only valid on an array-range designator");
3473      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3474    }
3475
3476    unsigned getFirstExprIndex() const {
3477      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3478             "Only valid on an array or array-range designator");
3479      return ArrayOrRange.Index;
3480    }
3481
3482    SourceLocation getStartLocation() const {
3483      if (Kind == FieldDesignator)
3484        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3485      else
3486        return getLBracketLoc();
3487    }
3488  };
3489
3490  static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3491                                    unsigned NumDesignators,
3492                                    Expr **IndexExprs, unsigned NumIndexExprs,
3493                                    SourceLocation EqualOrColonLoc,
3494                                    bool GNUSyntax, Expr *Init);
3495
3496  static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3497
3498  /// @brief Returns the number of designators in this initializer.
3499  unsigned size() const { return NumDesignators; }
3500
3501  // Iterator access to the designators.
3502  typedef Designator* designators_iterator;
3503  designators_iterator designators_begin() { return Designators; }
3504  designators_iterator designators_end() {
3505    return Designators + NumDesignators;
3506  }
3507
3508  typedef std::reverse_iterator<designators_iterator>
3509          reverse_designators_iterator;
3510  reverse_designators_iterator designators_rbegin() {
3511    return reverse_designators_iterator(designators_end());
3512  }
3513  reverse_designators_iterator designators_rend() {
3514    return reverse_designators_iterator(designators_begin());
3515  }
3516
3517  Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3518
3519  void setDesignators(ASTContext &C, const Designator *Desigs,
3520                      unsigned NumDesigs);
3521
3522  Expr *getArrayIndex(const Designator& D);
3523  Expr *getArrayRangeStart(const Designator& D);
3524  Expr *getArrayRangeEnd(const Designator& D);
3525
3526  /// @brief Retrieve the location of the '=' that precedes the
3527  /// initializer value itself, if present.
3528  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3529  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3530
3531  /// @brief Determines whether this designated initializer used the
3532  /// deprecated GNU syntax for designated initializers.
3533  bool usesGNUSyntax() const { return GNUSyntax; }
3534  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3535
3536  /// @brief Retrieve the initializer value.
3537  Expr *getInit() const {
3538    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3539  }
3540
3541  void setInit(Expr *init) {
3542    *child_begin() = init;
3543  }
3544
3545  /// \brief Retrieve the total number of subexpressions in this
3546  /// designated initializer expression, including the actual
3547  /// initialized value and any expressions that occur within array
3548  /// and array-range designators.
3549  unsigned getNumSubExprs() const { return NumSubExprs; }
3550
3551  Expr *getSubExpr(unsigned Idx) {
3552    assert(Idx < NumSubExprs && "Subscript out of range");
3553    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3554    Ptr += sizeof(DesignatedInitExpr);
3555    return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3556  }
3557
3558  void setSubExpr(unsigned Idx, Expr *E) {
3559    assert(Idx < NumSubExprs && "Subscript out of range");
3560    char* Ptr = static_cast<char*>(static_cast<void *>(this));
3561    Ptr += sizeof(DesignatedInitExpr);
3562    reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3563  }
3564
3565  /// \brief Replaces the designator at index @p Idx with the series
3566  /// of designators in [First, Last).
3567  void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3568                        const Designator *Last);
3569
3570  SourceRange getSourceRange() const;
3571
3572  static bool classof(const Stmt *T) {
3573    return T->getStmtClass() == DesignatedInitExprClass;
3574  }
3575  static bool classof(const DesignatedInitExpr *) { return true; }
3576
3577  // Iterators
3578  child_range children() {
3579    Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
3580    return child_range(begin, begin + NumSubExprs);
3581  }
3582};
3583
3584/// \brief Represents an implicitly-generated value initialization of
3585/// an object of a given type.
3586///
3587/// Implicit value initializations occur within semantic initializer
3588/// list expressions (InitListExpr) as placeholders for subobject
3589/// initializations not explicitly specified by the user.
3590///
3591/// \see InitListExpr
3592class ImplicitValueInitExpr : public Expr {
3593public:
3594  explicit ImplicitValueInitExpr(QualType ty)
3595    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
3596           false, false, false) { }
3597
3598  /// \brief Construct an empty implicit value initialization.
3599  explicit ImplicitValueInitExpr(EmptyShell Empty)
3600    : Expr(ImplicitValueInitExprClass, Empty) { }
3601
3602  static bool classof(const Stmt *T) {
3603    return T->getStmtClass() == ImplicitValueInitExprClass;
3604  }
3605  static bool classof(const ImplicitValueInitExpr *) { return true; }
3606
3607  SourceRange getSourceRange() const {
3608    return SourceRange();
3609  }
3610
3611  // Iterators
3612  child_range children() { return child_range(); }
3613};
3614
3615
3616class ParenListExpr : public Expr {
3617  Stmt **Exprs;
3618  unsigned NumExprs;
3619  SourceLocation LParenLoc, RParenLoc;
3620
3621public:
3622  ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3623                unsigned numexprs, SourceLocation rparenloc);
3624
3625  /// \brief Build an empty paren list.
3626  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3627
3628  unsigned getNumExprs() const { return NumExprs; }
3629
3630  const Expr* getExpr(unsigned Init) const {
3631    assert(Init < getNumExprs() && "Initializer access out of range!");
3632    return cast_or_null<Expr>(Exprs[Init]);
3633  }
3634
3635  Expr* getExpr(unsigned Init) {
3636    assert(Init < getNumExprs() && "Initializer access out of range!");
3637    return cast_or_null<Expr>(Exprs[Init]);
3638  }
3639
3640  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3641
3642  SourceLocation getLParenLoc() const { return LParenLoc; }
3643  SourceLocation getRParenLoc() const { return RParenLoc; }
3644
3645  SourceRange getSourceRange() const {
3646    return SourceRange(LParenLoc, RParenLoc);
3647  }
3648  static bool classof(const Stmt *T) {
3649    return T->getStmtClass() == ParenListExprClass;
3650  }
3651  static bool classof(const ParenListExpr *) { return true; }
3652
3653  // Iterators
3654  child_range children() {
3655    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
3656  }
3657
3658  friend class ASTStmtReader;
3659  friend class ASTStmtWriter;
3660};
3661
3662
3663//===----------------------------------------------------------------------===//
3664// Clang Extensions
3665//===----------------------------------------------------------------------===//
3666
3667
3668/// ExtVectorElementExpr - This represents access to specific elements of a
3669/// vector, and may occur on the left hand side or right hand side.  For example
3670/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
3671///
3672/// Note that the base may have either vector or pointer to vector type, just
3673/// like a struct field reference.
3674///
3675class ExtVectorElementExpr : public Expr {
3676  Stmt *Base;
3677  IdentifierInfo *Accessor;
3678  SourceLocation AccessorLoc;
3679public:
3680  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
3681                       IdentifierInfo &accessor, SourceLocation loc)
3682    : Expr(ExtVectorElementExprClass, ty, VK,
3683           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
3684           base->isTypeDependent(), base->isValueDependent(),
3685           base->containsUnexpandedParameterPack()),
3686      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3687
3688  /// \brief Build an empty vector element expression.
3689  explicit ExtVectorElementExpr(EmptyShell Empty)
3690    : Expr(ExtVectorElementExprClass, Empty) { }
3691
3692  const Expr *getBase() const { return cast<Expr>(Base); }
3693  Expr *getBase() { return cast<Expr>(Base); }
3694  void setBase(Expr *E) { Base = E; }
3695
3696  IdentifierInfo &getAccessor() const { return *Accessor; }
3697  void setAccessor(IdentifierInfo *II) { Accessor = II; }
3698
3699  SourceLocation getAccessorLoc() const { return AccessorLoc; }
3700  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3701
3702  /// getNumElements - Get the number of components being selected.
3703  unsigned getNumElements() const;
3704
3705  /// containsDuplicateElements - Return true if any element access is
3706  /// repeated.
3707  bool containsDuplicateElements() const;
3708
3709  /// getEncodedElementAccess - Encode the elements accessed into an llvm
3710  /// aggregate Constant of ConstantInt(s).
3711  void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3712
3713  SourceRange getSourceRange() const {
3714    return SourceRange(getBase()->getLocStart(), AccessorLoc);
3715  }
3716
3717  /// isArrow - Return true if the base expression is a pointer to vector,
3718  /// return false if the base expression is a vector.
3719  bool isArrow() const;
3720
3721  static bool classof(const Stmt *T) {
3722    return T->getStmtClass() == ExtVectorElementExprClass;
3723  }
3724  static bool classof(const ExtVectorElementExpr *) { return true; }
3725
3726  // Iterators
3727  child_range children() { return child_range(&Base, &Base+1); }
3728};
3729
3730
3731/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3732/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3733class BlockExpr : public Expr {
3734protected:
3735  BlockDecl *TheBlock;
3736public:
3737  BlockExpr(BlockDecl *BD, QualType ty)
3738    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
3739           ty->isDependentType(), false, false),
3740      TheBlock(BD) {}
3741
3742  /// \brief Build an empty block expression.
3743  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3744
3745  const BlockDecl *getBlockDecl() const { return TheBlock; }
3746  BlockDecl *getBlockDecl() { return TheBlock; }
3747  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3748
3749  // Convenience functions for probing the underlying BlockDecl.
3750  SourceLocation getCaretLocation() const;
3751  const Stmt *getBody() const;
3752  Stmt *getBody();
3753
3754  SourceRange getSourceRange() const {
3755    return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3756  }
3757
3758  /// getFunctionType - Return the underlying function type for this block.
3759  const FunctionType *getFunctionType() const;
3760
3761  static bool classof(const Stmt *T) {
3762    return T->getStmtClass() == BlockExprClass;
3763  }
3764  static bool classof(const BlockExpr *) { return true; }
3765
3766  // Iterators
3767  child_range children() { return child_range(); }
3768};
3769
3770/// BlockDeclRefExpr - A reference to a local variable declared in an
3771/// enclosing scope.
3772class BlockDeclRefExpr : public Expr {
3773  VarDecl *D;
3774  SourceLocation Loc;
3775  bool IsByRef : 1;
3776  bool ConstQualAdded : 1;
3777public:
3778  BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
3779                   SourceLocation l, bool ByRef, bool constAdded = false);
3780
3781  // \brief Build an empty reference to a declared variable in a
3782  // block.
3783  explicit BlockDeclRefExpr(EmptyShell Empty)
3784    : Expr(BlockDeclRefExprClass, Empty) { }
3785
3786  VarDecl *getDecl() { return D; }
3787  const VarDecl *getDecl() const { return D; }
3788  void setDecl(VarDecl *VD) { D = VD; }
3789
3790  SourceLocation getLocation() const { return Loc; }
3791  void setLocation(SourceLocation L) { Loc = L; }
3792
3793  SourceRange getSourceRange() const { return SourceRange(Loc); }
3794
3795  bool isByRef() const { return IsByRef; }
3796  void setByRef(bool BR) { IsByRef = BR; }
3797
3798  bool isConstQualAdded() const { return ConstQualAdded; }
3799  void setConstQualAdded(bool C) { ConstQualAdded = C; }
3800
3801  static bool classof(const Stmt *T) {
3802    return T->getStmtClass() == BlockDeclRefExprClass;
3803  }
3804  static bool classof(const BlockDeclRefExpr *) { return true; }
3805
3806  // Iterators
3807  child_range children() { return child_range(); }
3808};
3809
3810}  // end namespace clang
3811
3812#endif
3813