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