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