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