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