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