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