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