1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Expr interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_EXPR_H
15 #define LLVM_CLANG_AST_EXPR_H
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/OperationKinds.h"
22 #include "clang/AST/ASTVector.h"
23 #include "clang/AST/UsuallyTinyPtrVector.h"
24 #include "llvm/ADT/APSInt.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
39 class CXXBaseSpecifier;
40 class CXXOperatorCallExpr;
41 class CXXMemberCallExpr;
42 class TemplateArgumentLoc;
43 class TemplateArgumentListInfo;
45 /// \brief A simple array of base specifiers.
46 typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
48 /// Expr - This represents one expression. Note that Expr's are subclasses of
49 /// Stmt. This allows an expression to be transparently used any place a Stmt
52 class Expr : public Stmt {
55 virtual void ANCHOR(); // key function.
57 /// TypeDependent - Whether this expression is type-dependent
58 /// (C++ [temp.dep.expr]).
59 bool TypeDependent : 1;
61 /// ValueDependent - Whether this expression is value-dependent
62 /// (C++ [temp.dep.constexpr]).
63 bool ValueDependent : 1;
65 /// ValueKind - The value classification of this expression.
66 /// Only actually used by certain subclasses.
67 unsigned ValueKind : 2;
69 enum { BitsRemaining = 28 };
71 Expr(StmtClass SC, QualType T, bool TD, bool VD)
72 : Stmt(SC), TypeDependent(TD), ValueDependent(VD), ValueKind(0) {
76 /// \brief Construct an empty expression.
77 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
80 /// \brief Increases the reference count for this expression.
82 /// Invoke the Retain() operation when this expression
83 /// is being shared by another owner.
89 QualType getType() const { return TR; }
90 void setType(QualType t) {
91 // In C++, the type of an expression is always adjusted so that it
92 // will not have reference type an expression will never have
93 // reference type (C++ [expr]p6). Use
94 // QualType::getNonReferenceType() to retrieve the non-reference
95 // type. Additionally, inspect Expr::isLvalue to determine whether
96 // an expression that is adjusted in this manner should be
97 // considered an lvalue.
98 assert((t.isNull() || !t->isReferenceType()) &&
99 "Expressions can't have reference type");
104 /// isValueDependent - Determines whether this expression is
105 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
106 /// array bound of "Chars" in the following example is
109 /// template<int Size, char (&Chars)[Size]> struct meta_string;
111 bool isValueDependent() const { return ValueDependent; }
113 /// \brief Set whether this expression is value-dependent or not.
114 void setValueDependent(bool VD) { ValueDependent = VD; }
116 /// isTypeDependent - Determines whether this expression is
117 /// type-dependent (C++ [temp.dep.expr]), which means that its type
118 /// could change from one template instantiation to the next. For
119 /// example, the expressions "x" and "x + y" are type-dependent in
120 /// the following code, but "y" is not type-dependent:
122 /// template<typename T>
123 /// void add(T x, int y) {
127 bool isTypeDependent() const { return TypeDependent; }
129 /// \brief Set whether this expression is type-dependent or not.
130 void setTypeDependent(bool TD) { TypeDependent = TD; }
132 /// SourceLocation tokens are not useful in isolation - they are low level
133 /// value objects created/interpreted by SourceManager. We assume AST
134 /// clients will have a pointer to the respective SourceManager.
135 virtual SourceRange getSourceRange() const = 0;
137 /// getExprLoc - Return the preferred location for the arrow when diagnosing
138 /// a problem with a generic expression.
139 virtual SourceLocation getExprLoc() const { return getLocStart(); }
141 /// isUnusedResultAWarning - Return true if this immediate expression should
142 /// be warned about if the result is unused. If so, fill in Loc and Ranges
143 /// with location to warn on and the source range[s] to report with the
145 bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
146 SourceRange &R2, ASTContext &Ctx) const;
148 /// isLvalue - C99 6.3.2.1: an lvalue is an expression with an object type or
149 /// incomplete type other than void. Nonarray expressions that can be lvalues:
150 /// - name, where name must be a variable
152 /// - (e), where e must be an lvalue
153 /// - e.name, where e must be an lvalue
155 /// - *e, the type of e cannot be a function type
156 /// - string-constant
157 /// - reference type [C++ [expr]]
158 /// - b ? x : y, where x and y are lvalues of suitable types [C++]
160 enum isLvalueResult {
163 LV_IncompleteVoidType,
164 LV_DuplicateVectorComponents,
165 LV_InvalidExpression,
167 LV_SubObjCPropertySetting,
170 isLvalueResult isLvalue(ASTContext &Ctx) const;
172 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
173 /// does not have an incomplete type, does not have a const-qualified type,
174 /// and if it is a structure or union, does not have any member (including,
175 /// recursively, any member or element of all contained aggregates or unions)
176 /// with a const-qualified type.
178 /// \param Loc [in] [out] - A source location which *may* be filled
179 /// in with the location of the expression making this a
180 /// non-modifiable lvalue, if specified.
181 enum isModifiableLvalueResult {
184 MLV_IncompleteVoidType,
185 MLV_DuplicateVectorComponents,
186 MLV_InvalidExpression,
187 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
191 MLV_NotBlockQualified,
192 MLV_ReadonlyProperty,
193 MLV_NoSetterProperty,
195 MLV_SubObjCPropertySetting,
198 isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
199 SourceLocation *Loc = 0) const;
201 /// \brief The return type of classify(). Represents the C++0x expression
203 class Classification {
205 /// \brief The various classification results. Most of these mean prvalue.
209 CL_Function, // Functions cannot be lvalues in C.
210 CL_Void, // Void cannot be an lvalue in C.
211 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
212 CL_MemberFunction, // An expression referring to a member function
213 CL_SubObjCPropertySetting,
214 CL_ClassTemporary, // A prvalue of class type
215 CL_PRValue // A prvalue for any other reason, of any other type
217 /// \brief The results of modification testing.
218 enum ModifiableType {
219 CM_Untested, // testModifiable was false.
221 CM_RValue, // Not modifiable because it's an rvalue
222 CM_Function, // Not modifiable because it's a function; C++ only
223 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
224 CM_NotBlockQualified, // Not captured in the closure
225 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
235 unsigned short Modifiable;
237 explicit Classification(Kinds k, ModifiableType m)
238 : Kind(k), Modifiable(m)
244 Kinds getKind() const { return static_cast<Kinds>(Kind); }
245 ModifiableType getModifiable() const {
246 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
247 return static_cast<ModifiableType>(Modifiable);
249 bool isLValue() const { return Kind == CL_LValue; }
250 bool isXValue() const { return Kind == CL_XValue; }
251 bool isGLValue() const { return Kind <= CL_XValue; }
252 bool isPRValue() const { return Kind >= CL_Function; }
253 bool isRValue() const { return Kind >= CL_XValue; }
254 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
256 /// \brief classify - Classify this expression according to the C++0x
257 /// expression taxonomy.
259 /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the
260 /// old lvalue vs rvalue. This function determines the type of expression this
261 /// is. There are three expression types:
262 /// - lvalues are classical lvalues as in C++03.
263 /// - prvalues are equivalent to rvalues in C++03.
264 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
265 /// function returning an rvalue reference.
266 /// lvalues and xvalues are collectively referred to as glvalues, while
267 /// prvalues and xvalues together form rvalues.
268 Classification Classify(ASTContext &Ctx) const {
269 return ClassifyImpl(Ctx, 0);
272 /// \brief classifyModifiable - Classify this expression according to the
273 /// C++0x expression taxonomy, and see if it is valid on the left side
274 /// of an assignment.
276 /// This function extends classify in that it also tests whether the
277 /// expression is modifiable (C99 6.3.2.1p1).
278 /// \param Loc A source location that might be filled with a relevant location
279 /// if the expression is not modifiable.
280 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
281 return ClassifyImpl(Ctx, &Loc);
285 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
289 /// \brief If this expression refers to a bit-field, retrieve the
290 /// declaration of that bit-field.
291 FieldDecl *getBitField();
293 const FieldDecl *getBitField() const {
294 return const_cast<Expr*>(this)->getBitField();
297 /// \brief Returns whether this expression refers to a vector element.
298 bool refersToVectorElement() const;
300 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
301 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
302 /// but also int expressions which are produced by things like comparisons in
304 bool isKnownToHaveBooleanValue() const;
306 /// isIntegerConstantExpr - Return true if this expression is a valid integer
307 /// constant expression, and, if so, return its value in Result. If not a
308 /// valid i-c-e, return false and fill in Loc (if specified) with the location
309 /// of the invalid expression.
310 bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
311 SourceLocation *Loc = 0,
312 bool isEvaluated = true) const;
313 bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
315 return isIntegerConstantExpr(X, Ctx, Loc);
317 /// isConstantInitializer - Returns true if this expression is a constant
318 /// initializer, which can be emitted at compile-time.
319 bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
321 /// EvalResult is a struct with detailed info about an evaluated expression.
323 /// Val - This is the value the expression can be folded to.
326 /// HasSideEffects - Whether the evaluated expression has side effects.
327 /// For example, (f() && 0) can be folded, but it still has side effects.
330 /// Diag - If the expression is unfoldable, then Diag contains a note
331 /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
332 /// position for the error, and DiagExpr is the expression that caused
334 /// If the expression is foldable, but not an integer constant expression,
335 /// Diag contains a note diagnostic that describes why it isn't an integer
336 /// constant expression. If the expression *is* an integer constant
337 /// expression, then Diag will be zero.
339 const Expr *DiagExpr;
340 SourceLocation DiagLoc;
342 EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
344 // isGlobalLValue - Return true if the evaluated lvalue expression
346 bool isGlobalLValue() const;
347 // hasSideEffects - Return true if the evaluated expression has
349 bool hasSideEffects() const {
350 return HasSideEffects;
354 /// Evaluate - Return true if this is a constant which we can fold using
355 /// any crazy technique (that has nothing to do with language standards) that
356 /// we want to. If this function returns true, it returns the folded constant
358 bool Evaluate(EvalResult &Result, ASTContext &Ctx) const;
360 /// EvaluateAsBooleanCondition - Return true if this is a constant
361 /// which we we can fold and convert to a boolean condition using
362 /// any crazy technique that we want to.
363 bool EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const;
365 /// isEvaluatable - Call Evaluate to see if this expression can be constant
366 /// folded, but discard the result.
367 bool isEvaluatable(ASTContext &Ctx) const;
369 /// HasSideEffects - This routine returns true for all those expressions
370 /// which must be evaluated each time and must not be optimization away
371 /// or evaluated at compile time. Example is a function call, volatile
373 bool HasSideEffects(ASTContext &Ctx) const;
375 /// EvaluateAsInt - Call Evaluate and return the folded integer. This
376 /// must be called on an expression that constant folds to an integer.
377 llvm::APSInt EvaluateAsInt(ASTContext &Ctx) const;
379 /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
380 /// with link time known address.
381 bool EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const;
383 /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
384 bool EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const;
386 /// \brief Enumeration used to describe how \c isNullPointerConstant()
387 /// should cope with value-dependent expressions.
388 enum NullPointerConstantValueDependence {
389 /// \brief Specifies that the expression should never be value-dependent.
390 NPC_NeverValueDependent = 0,
392 /// \brief Specifies that a value-dependent expression of integral or
393 /// dependent type should be considered a null pointer constant.
394 NPC_ValueDependentIsNull,
396 /// \brief Specifies that a value-dependent expression should be considered
397 /// to never be a null pointer constant.
398 NPC_ValueDependentIsNotNull
401 /// isNullPointerConstant - C99 6.3.2.3p3 - Return true if this is either an
402 /// integer constant expression with the value zero, or if this is one that is
404 bool isNullPointerConstant(ASTContext &Ctx,
405 NullPointerConstantValueDependence NPC) const;
407 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
409 bool isOBJCGCCandidate(ASTContext &Ctx) const;
411 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
412 /// its subexpression. If that subexpression is also a ParenExpr,
413 /// then this method recursively returns its subexpression, and so forth.
414 /// Otherwise, the method returns the current Expr.
415 Expr *IgnoreParens();
417 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
418 /// or CastExprs, returning their operand.
419 Expr *IgnoreParenCasts();
421 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off any
422 /// ParenExpr or ImplicitCastExprs, returning their operand.
423 Expr *IgnoreParenImpCasts();
425 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
426 /// value (including ptr->int casts of the same size). Strip off any
427 /// ParenExpr or CastExprs, returning their operand.
428 Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
430 /// \brief Determine whether this expression is a default function argument.
432 /// Default arguments are implicitly generated in the abstract syntax tree
433 /// by semantic analysis for function calls, object constructions, etc. in
434 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
435 /// this routine also looks through any implicit casts to determine whether
436 /// the expression is a default argument.
437 bool isDefaultArgument() const;
439 /// \brief Determine whether this expression directly creates a
440 /// temporary object (of class type).
441 bool isTemporaryObject() const { return getTemporaryObject() != 0; }
443 /// \brief If this expression directly creates a temporary object of
444 /// class type, return the expression that actually constructs that
445 /// temporary object.
446 const Expr *getTemporaryObject() const;
448 const Expr *IgnoreParens() const {
449 return const_cast<Expr*>(this)->IgnoreParens();
451 const Expr *IgnoreParenCasts() const {
452 return const_cast<Expr*>(this)->IgnoreParenCasts();
454 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
455 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
458 static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
459 static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
461 static bool classof(const Stmt *T) {
462 return T->getStmtClass() >= firstExprConstant &&
463 T->getStmtClass() <= lastExprConstant;
465 static bool classof(const Expr *) { return true; }
469 //===----------------------------------------------------------------------===//
470 // Primary Expressions.
471 //===----------------------------------------------------------------------===//
473 /// \brief Represents the qualifier that may precede a C++ name, e.g., the
474 /// "std::" in "std::sort".
475 struct NameQualifier {
476 /// \brief The nested name specifier.
477 NestedNameSpecifier *NNS;
479 /// \brief The source range covered by the nested name specifier.
483 /// \brief Represents an explicit template argument list in C++, e.g.,
484 /// the "<int>" in "sort<int>".
485 struct ExplicitTemplateArgumentList {
486 /// \brief The source location of the left angle bracket ('<');
487 SourceLocation LAngleLoc;
489 /// \brief The source location of the right angle bracket ('>');
490 SourceLocation RAngleLoc;
492 /// \brief The number of template arguments in TemplateArgs.
493 /// The actual template arguments (if any) are stored after the
494 /// ExplicitTemplateArgumentList structure.
495 unsigned NumTemplateArgs;
497 /// \brief Retrieve the template arguments
498 TemplateArgumentLoc *getTemplateArgs() {
499 return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
502 /// \brief Retrieve the template arguments
503 const TemplateArgumentLoc *getTemplateArgs() const {
504 return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
507 void initializeFrom(const TemplateArgumentListInfo &List);
508 void copyInto(TemplateArgumentListInfo &List) const;
509 static std::size_t sizeFor(unsigned NumTemplateArgs);
510 static std::size_t sizeFor(const TemplateArgumentListInfo &List);
513 /// DeclRefExpr - [C99 6.5.1p2] - A reference to a declared variable, function,
515 class DeclRefExpr : public Expr {
517 // Flag on DecoratedD that specifies when this declaration reference
518 // expression has a C++ nested-name-specifier.
519 HasQualifierFlag = 0x01,
520 // Flag on DecoratedD that specifies when this declaration reference
521 // expression has an explicit C++ template argument list.
522 HasExplicitTemplateArgumentListFlag = 0x02
525 // DecoratedD - The declaration that we are referencing, plus two bits to
526 // indicate whether (1) the declaration's name was explicitly qualified and
527 // (2) the declaration's name was followed by an explicit template
529 llvm::PointerIntPair<ValueDecl *, 2> DecoratedD;
531 // Loc - The location of the declaration name itself.
534 /// DNLoc - Provides source/type location info for the
535 /// declaration name embedded in DecoratedD.
536 DeclarationNameLoc DNLoc;
538 /// \brief Retrieve the qualifier that preceded the declaration name, if any.
539 NameQualifier *getNameQualifier() {
540 if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
543 return reinterpret_cast<NameQualifier *> (this + 1);
546 /// \brief Retrieve the qualifier that preceded the member name, if any.
547 const NameQualifier *getNameQualifier() const {
548 return const_cast<DeclRefExpr *>(this)->getNameQualifier();
551 DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
552 ValueDecl *D, SourceLocation NameLoc,
553 const TemplateArgumentListInfo *TemplateArgs,
556 DeclRefExpr(NestedNameSpecifier *Qualifier, SourceRange QualifierRange,
557 ValueDecl *D, const DeclarationNameInfo &NameInfo,
558 const TemplateArgumentListInfo *TemplateArgs,
561 /// \brief Construct an empty declaration reference expression.
562 explicit DeclRefExpr(EmptyShell Empty)
563 : Expr(DeclRefExprClass, Empty) { }
565 /// \brief Computes the type- and value-dependence flags for this
566 /// declaration reference expression.
567 void computeDependence();
570 DeclRefExpr(ValueDecl *d, QualType t, SourceLocation l) :
571 Expr(DeclRefExprClass, t, false, false), DecoratedD(d, 0), Loc(l) {
575 static DeclRefExpr *Create(ASTContext &Context,
576 NestedNameSpecifier *Qualifier,
577 SourceRange QualifierRange,
579 SourceLocation NameLoc,
581 const TemplateArgumentListInfo *TemplateArgs = 0);
583 static DeclRefExpr *Create(ASTContext &Context,
584 NestedNameSpecifier *Qualifier,
585 SourceRange QualifierRange,
587 const DeclarationNameInfo &NameInfo,
589 const TemplateArgumentListInfo *TemplateArgs = 0);
591 /// \brief Construct an empty declaration reference expression.
592 static DeclRefExpr *CreateEmpty(ASTContext &Context,
593 bool HasQualifier, unsigned NumTemplateArgs);
595 ValueDecl *getDecl() { return DecoratedD.getPointer(); }
596 const ValueDecl *getDecl() const { return DecoratedD.getPointer(); }
597 void setDecl(ValueDecl *NewD) { DecoratedD.setPointer(NewD); }
599 DeclarationNameInfo getNameInfo() const {
600 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
603 SourceLocation getLocation() const { return Loc; }
604 void setLocation(SourceLocation L) { Loc = L; }
605 virtual SourceRange getSourceRange() const;
607 /// \brief Determine whether this declaration reference was preceded by a
608 /// C++ nested-name-specifier, e.g., \c N::foo.
609 bool hasQualifier() const { return DecoratedD.getInt() & HasQualifierFlag; }
611 /// \brief If the name was qualified, retrieves the source range of
612 /// the nested-name-specifier that precedes the name. Otherwise,
613 /// returns an empty source range.
614 SourceRange getQualifierRange() const {
616 return SourceRange();
618 return getNameQualifier()->Range;
621 /// \brief If the name was qualified, retrieves the nested-name-specifier
622 /// that precedes the name. Otherwise, returns NULL.
623 NestedNameSpecifier *getQualifier() const {
627 return getNameQualifier()->NNS;
630 bool hasExplicitTemplateArgs() const {
631 return (DecoratedD.getInt() & HasExplicitTemplateArgumentListFlag);
634 /// \brief Retrieve the explicit template argument list that followed the
635 /// member template name.
636 ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
637 assert(hasExplicitTemplateArgs());
639 if ((DecoratedD.getInt() & HasQualifierFlag) == 0)
640 return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
642 return *reinterpret_cast<ExplicitTemplateArgumentList *>(
643 getNameQualifier() + 1);
646 /// \brief Retrieve the explicit template argument list that followed the
647 /// member template name.
648 const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
649 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
652 /// \brief Retrieves the optional explicit template arguments.
653 /// This points to the same data as getExplicitTemplateArgs(), but
654 /// returns null if there are no explicit template arguments.
655 const ExplicitTemplateArgumentList *getExplicitTemplateArgsOpt() const {
656 if (!hasExplicitTemplateArgs()) return 0;
657 return &getExplicitTemplateArgs();
660 /// \brief Copies the template arguments (if present) into the given
662 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
663 if (hasExplicitTemplateArgs())
664 getExplicitTemplateArgs().copyInto(List);
667 /// \brief Retrieve the location of the left angle bracket following the
668 /// member name ('<'), if any.
669 SourceLocation getLAngleLoc() const {
670 if (!hasExplicitTemplateArgs())
671 return SourceLocation();
673 return getExplicitTemplateArgs().LAngleLoc;
676 /// \brief Retrieve the template arguments provided as part of this
678 const TemplateArgumentLoc *getTemplateArgs() const {
679 if (!hasExplicitTemplateArgs())
682 return getExplicitTemplateArgs().getTemplateArgs();
685 /// \brief Retrieve the number of template arguments provided as part of this
687 unsigned getNumTemplateArgs() const {
688 if (!hasExplicitTemplateArgs())
691 return getExplicitTemplateArgs().NumTemplateArgs;
694 /// \brief Retrieve the location of the right angle bracket following the
695 /// template arguments ('>').
696 SourceLocation getRAngleLoc() const {
697 if (!hasExplicitTemplateArgs())
698 return SourceLocation();
700 return getExplicitTemplateArgs().RAngleLoc;
703 static bool classof(const Stmt *T) {
704 return T->getStmtClass() == DeclRefExprClass;
706 static bool classof(const DeclRefExpr *) { return true; }
709 virtual child_iterator child_begin();
710 virtual child_iterator child_end();
712 friend class ASTStmtReader;
713 friend class ASTStmtWriter;
716 /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
717 class PredefinedExpr : public Expr {
723 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
724 /// 'virtual' keyword is omitted for virtual member functions.
725 PrettyFunctionNoVirtual
732 PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
733 : Expr(PredefinedExprClass, type, type->isDependentType(),
734 type->isDependentType()), Loc(l), Type(IT) {}
736 /// \brief Construct an empty predefined expression.
737 explicit PredefinedExpr(EmptyShell Empty)
738 : Expr(PredefinedExprClass, Empty) { }
740 IdentType getIdentType() const { return Type; }
741 void setIdentType(IdentType IT) { Type = IT; }
743 SourceLocation getLocation() const { return Loc; }
744 void setLocation(SourceLocation L) { Loc = L; }
746 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
748 virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
750 static bool classof(const Stmt *T) {
751 return T->getStmtClass() == PredefinedExprClass;
753 static bool classof(const PredefinedExpr *) { return true; }
756 virtual child_iterator child_begin();
757 virtual child_iterator child_end();
760 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
763 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
764 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
765 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
766 /// the APFloat/APInt values will never get freed. APNumericStorage uses
767 /// ASTContext's allocator for memory allocation.
768 class APNumericStorage {
771 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
772 uint64_t *pVal; ///< Used to store the >64 bits integer value.
775 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
777 APNumericStorage(const APNumericStorage&); // do not implement
778 APNumericStorage& operator=(const APNumericStorage&); // do not implement
781 APNumericStorage() : BitWidth(0), VAL(0) { }
783 llvm::APInt getIntValue() const {
784 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
786 return llvm::APInt(BitWidth, NumWords, pVal);
788 return llvm::APInt(BitWidth, VAL);
790 void setIntValue(ASTContext &C, const llvm::APInt &Val);
793 class APIntStorage : public APNumericStorage {
795 llvm::APInt getValue() const { return getIntValue(); }
796 void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); }
799 class APFloatStorage : public APNumericStorage {
801 llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); }
802 void setValue(ASTContext &C, const llvm::APFloat &Val) {
803 setIntValue(C, Val.bitcastToAPInt());
807 class IntegerLiteral : public Expr {
811 /// \brief Construct an empty integer literal.
812 explicit IntegerLiteral(EmptyShell Empty)
813 : Expr(IntegerLiteralClass, Empty) { }
816 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
817 // or UnsignedLongLongTy
818 IntegerLiteral(ASTContext &C, const llvm::APInt &V,
819 QualType type, SourceLocation l)
820 : Expr(IntegerLiteralClass, type, false, false), Loc(l) {
821 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
825 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
826 // or UnsignedLongLongTy
827 static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V,
828 QualType type, SourceLocation l);
829 static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
831 llvm::APInt getValue() const { return Num.getValue(); }
832 virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
834 /// \brief Retrieve the location of the literal.
835 SourceLocation getLocation() const { return Loc; }
837 void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); }
838 void setLocation(SourceLocation Location) { Loc = Location; }
840 static bool classof(const Stmt *T) {
841 return T->getStmtClass() == IntegerLiteralClass;
843 static bool classof(const IntegerLiteral *) { return true; }
846 virtual child_iterator child_begin();
847 virtual child_iterator child_end();
850 class CharacterLiteral : public Expr {
855 // type should be IntTy
856 CharacterLiteral(unsigned value, bool iswide, QualType type, SourceLocation l)
857 : Expr(CharacterLiteralClass, type, false, false), Value(value), Loc(l),
861 /// \brief Construct an empty character literal.
862 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
864 SourceLocation getLocation() const { return Loc; }
865 bool isWide() const { return IsWide; }
867 virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
869 unsigned getValue() const { return Value; }
871 void setLocation(SourceLocation Location) { Loc = Location; }
872 void setWide(bool W) { IsWide = W; }
873 void setValue(unsigned Val) { Value = Val; }
875 static bool classof(const Stmt *T) {
876 return T->getStmtClass() == CharacterLiteralClass;
878 static bool classof(const CharacterLiteral *) { return true; }
881 virtual child_iterator child_begin();
882 virtual child_iterator child_end();
885 class FloatingLiteral : public Expr {
890 FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
891 QualType Type, SourceLocation L)
892 : Expr(FloatingLiteralClass, Type, false, false),
893 IsExact(isexact), Loc(L) {
897 /// \brief Construct an empty floating-point literal.
898 explicit FloatingLiteral(EmptyShell Empty)
899 : Expr(FloatingLiteralClass, Empty), IsExact(false) { }
902 static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
903 bool isexact, QualType Type, SourceLocation L);
904 static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
906 llvm::APFloat getValue() const { return Num.getValue(); }
907 void setValue(ASTContext &C, const llvm::APFloat &Val) {
908 Num.setValue(C, Val);
911 bool isExact() const { return IsExact; }
912 void setExact(bool E) { IsExact = E; }
914 /// getValueAsApproximateDouble - This returns the value as an inaccurate
915 /// double. Note that this may cause loss of precision, but is useful for
916 /// debugging dumps, etc.
917 double getValueAsApproximateDouble() const;
919 SourceLocation getLocation() const { return Loc; }
920 void setLocation(SourceLocation L) { Loc = L; }
922 virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
924 static bool classof(const Stmt *T) {
925 return T->getStmtClass() == FloatingLiteralClass;
927 static bool classof(const FloatingLiteral *) { return true; }
930 virtual child_iterator child_begin();
931 virtual child_iterator child_end();
934 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
935 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
936 /// IntegerLiteral classes. Instances of this class always have a Complex type
937 /// whose element type matches the subexpression.
939 class ImaginaryLiteral : public Expr {
942 ImaginaryLiteral(Expr *val, QualType Ty)
943 : Expr(ImaginaryLiteralClass, Ty, false, false), Val(val) {}
945 /// \brief Build an empty imaginary literal.
946 explicit ImaginaryLiteral(EmptyShell Empty)
947 : Expr(ImaginaryLiteralClass, Empty) { }
949 const Expr *getSubExpr() const { return cast<Expr>(Val); }
950 Expr *getSubExpr() { return cast<Expr>(Val); }
951 void setSubExpr(Expr *E) { Val = E; }
953 virtual SourceRange getSourceRange() const { return Val->getSourceRange(); }
954 static bool classof(const Stmt *T) {
955 return T->getStmtClass() == ImaginaryLiteralClass;
957 static bool classof(const ImaginaryLiteral *) { return true; }
960 virtual child_iterator child_begin();
961 virtual child_iterator child_end();
964 /// StringLiteral - This represents a string literal expression, e.g. "foo"
965 /// or L"bar" (wide strings). The actual string is returned by getStrData()
966 /// is NOT null-terminated, and the length of the string is determined by
967 /// calling getByteLength(). The C type for a string is always a
968 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
971 /// Note that strings in C can be formed by concatenation of multiple string
972 /// literal pptokens in translation phase #6. This keeps track of the locations
973 /// of each of these pieces.
975 /// Strings in C can also be truncated and extended by assigning into arrays,
976 /// e.g. with constructs like:
977 /// char X[2] = "foobar";
978 /// In this case, getByteLength() will return 6, but the string literal will
979 /// have type "char[2]".
980 class StringLiteral : public Expr {
984 unsigned NumConcatenated;
985 SourceLocation TokLocs[1];
987 StringLiteral(QualType Ty) : Expr(StringLiteralClass, Ty, false, false) {}
990 /// This is the "fully general" constructor that allows representation of
991 /// strings formed from multiple concatenated tokens.
992 static StringLiteral *Create(ASTContext &C, const char *StrData,
993 unsigned ByteLength, bool Wide, QualType Ty,
994 const SourceLocation *Loc, unsigned NumStrs);
996 /// Simple constructor for string literals made from one token.
997 static StringLiteral *Create(ASTContext &C, const char *StrData,
999 bool Wide, QualType Ty, SourceLocation Loc) {
1000 return Create(C, StrData, ByteLength, Wide, Ty, &Loc, 1);
1003 /// \brief Construct an empty string literal.
1004 static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1006 llvm::StringRef getString() const {
1007 return llvm::StringRef(StrData, ByteLength);
1010 unsigned getByteLength() const { return ByteLength; }
1012 /// \brief Sets the string data to the given string data.
1013 void setString(ASTContext &C, llvm::StringRef Str);
1015 bool isWide() const { return IsWide; }
1016 void setWide(bool W) { IsWide = W; }
1018 bool containsNonAsciiOrNull() const {
1019 llvm::StringRef Str = getString();
1020 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1021 if (!isascii(Str[i]) || !Str[i])
1025 /// getNumConcatenated - Get the number of string literal tokens that were
1026 /// concatenated in translation phase #6 to form this string literal.
1027 unsigned getNumConcatenated() const { return NumConcatenated; }
1029 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1030 assert(TokNum < NumConcatenated && "Invalid tok number");
1031 return TokLocs[TokNum];
1033 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1034 assert(TokNum < NumConcatenated && "Invalid tok number");
1035 TokLocs[TokNum] = L;
1038 typedef const SourceLocation *tokloc_iterator;
1039 tokloc_iterator tokloc_begin() const { return TokLocs; }
1040 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1042 virtual SourceRange getSourceRange() const {
1043 return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1045 static bool classof(const Stmt *T) {
1046 return T->getStmtClass() == StringLiteralClass;
1048 static bool classof(const StringLiteral *) { return true; }
1051 virtual child_iterator child_begin();
1052 virtual child_iterator child_end();
1055 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1056 /// AST node is only formed if full location information is requested.
1057 class ParenExpr : public Expr {
1058 SourceLocation L, R;
1061 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1062 : Expr(ParenExprClass, val->getType(),
1063 val->isTypeDependent(), val->isValueDependent()),
1064 L(l), R(r), Val(val) {}
1066 /// \brief Construct an empty parenthesized expression.
1067 explicit ParenExpr(EmptyShell Empty)
1068 : Expr(ParenExprClass, Empty) { }
1070 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1071 Expr *getSubExpr() { return cast<Expr>(Val); }
1072 void setSubExpr(Expr *E) { Val = E; }
1074 virtual SourceRange getSourceRange() const { return SourceRange(L, R); }
1076 /// \brief Get the location of the left parentheses '('.
1077 SourceLocation getLParen() const { return L; }
1078 void setLParen(SourceLocation Loc) { L = Loc; }
1080 /// \brief Get the location of the right parentheses ')'.
1081 SourceLocation getRParen() const { return R; }
1082 void setRParen(SourceLocation Loc) { R = Loc; }
1084 static bool classof(const Stmt *T) {
1085 return T->getStmtClass() == ParenExprClass;
1087 static bool classof(const ParenExpr *) { return true; }
1090 virtual child_iterator child_begin();
1091 virtual child_iterator child_end();
1095 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1096 /// alignof), the postinc/postdec operators from postfix-expression, and various
1099 /// Notes on various nodes:
1101 /// Real/Imag - These return the real/imag part of a complex operand. If
1102 /// applied to a non-complex value, the former returns its operand and the
1103 /// later returns zero in the type of the operand.
1105 class UnaryOperator : public Expr {
1107 typedef UnaryOperatorKind Opcode;
1115 UnaryOperator(Expr *input, Opcode opc, QualType type, SourceLocation l)
1116 : Expr(UnaryOperatorClass, type,
1117 input->isTypeDependent() || type->isDependentType(),
1118 input->isValueDependent()),
1119 Opc(opc), Loc(l), Val(input) {}
1121 /// \brief Build an empty unary operator.
1122 explicit UnaryOperator(EmptyShell Empty)
1123 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1125 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1126 void setOpcode(Opcode O) { Opc = O; }
1128 Expr *getSubExpr() const { return cast<Expr>(Val); }
1129 void setSubExpr(Expr *E) { Val = E; }
1131 /// getOperatorLoc - Return the location of the operator.
1132 SourceLocation getOperatorLoc() const { return Loc; }
1133 void setOperatorLoc(SourceLocation L) { Loc = L; }
1135 /// isPostfix - Return true if this is a postfix operation, like x++.
1136 static bool isPostfix(Opcode Op) {
1137 return Op == UO_PostInc || Op == UO_PostDec;
1140 /// isPostfix - Return true if this is a prefix operation, like --x.
1141 static bool isPrefix(Opcode Op) {
1142 return Op == UO_PreInc || Op == UO_PreDec;
1145 bool isPrefix() const { return isPrefix(getOpcode()); }
1146 bool isPostfix() const { return isPostfix(getOpcode()); }
1147 bool isIncrementOp() const {
1148 return Opc == UO_PreInc || Opc == UO_PostInc;
1150 bool isIncrementDecrementOp() const {
1151 return Opc <= UO_PreDec;
1153 static bool isArithmeticOp(Opcode Op) {
1154 return Op >= UO_Plus && Op <= UO_LNot;
1156 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1158 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1159 /// corresponds to, e.g. "sizeof" or "[pre]++"
1160 static const char *getOpcodeStr(Opcode Op);
1162 /// \brief Retrieve the unary opcode that corresponds to the given
1163 /// overloaded operator.
1164 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1166 /// \brief Retrieve the overloaded operator kind that corresponds to
1167 /// the given unary opcode.
1168 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1170 virtual SourceRange getSourceRange() const {
1172 return SourceRange(Val->getLocStart(), Loc);
1174 return SourceRange(Loc, Val->getLocEnd());
1176 virtual SourceLocation getExprLoc() const { return Loc; }
1178 static bool classof(const Stmt *T) {
1179 return T->getStmtClass() == UnaryOperatorClass;
1181 static bool classof(const UnaryOperator *) { return true; }
1184 virtual child_iterator child_begin();
1185 virtual child_iterator child_end();
1188 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1189 /// offsetof(record-type, member-designator). For example, given:
1200 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1202 class OffsetOfExpr : public Expr {
1204 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1205 class OffsetOfNode {
1207 /// \brief The kind of offsetof node we have.
1209 /// \brief An index into an array.
1213 /// \brief A field in a dependent type, known only by its name.
1215 /// \brief An implicit indirection through a C++ base class, when the
1216 /// field found is in a base class.
1221 enum { MaskBits = 2, Mask = 0x03 };
1223 /// \brief The source range that covers this part of the designator.
1226 /// \brief The data describing the designator, which comes in three
1227 /// different forms, depending on the lower two bits.
1228 /// - An unsigned index into the array of Expr*'s stored after this node
1229 /// in memory, for [constant-expression] designators.
1230 /// - A FieldDecl*, for references to a known field.
1231 /// - An IdentifierInfo*, for references to a field with a given name
1232 /// when the class type is dependent.
1233 /// - A CXXBaseSpecifier*, for references that look at a field in a
1238 /// \brief Create an offsetof node that refers to an array element.
1239 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1240 SourceLocation RBracketLoc)
1241 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1243 /// \brief Create an offsetof node that refers to a field.
1244 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1245 SourceLocation NameLoc)
1246 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1247 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1249 /// \brief Create an offsetof node that refers to an identifier.
1250 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1251 SourceLocation NameLoc)
1252 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1253 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1255 /// \brief Create an offsetof node that refers into a C++ base class.
1256 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1257 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1259 /// \brief Determine what kind of offsetof node this is.
1260 Kind getKind() const {
1261 return static_cast<Kind>(Data & Mask);
1264 /// \brief For an array element node, returns the index into the array
1266 unsigned getArrayExprIndex() const {
1267 assert(getKind() == Array);
1271 /// \brief For a field offsetof node, returns the field.
1272 FieldDecl *getField() const {
1273 assert(getKind() == Field);
1274 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1277 /// \brief For a field or identifier offsetof node, returns the name of
1279 IdentifierInfo *getFieldName() const;
1281 /// \brief For a base class node, returns the base specifier.
1282 CXXBaseSpecifier *getBase() const {
1283 assert(getKind() == Base);
1284 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1287 /// \brief Retrieve the source range that covers this offsetof node.
1289 /// For an array element node, the source range contains the locations of
1290 /// the square brackets. For a field or identifier node, the source range
1291 /// contains the location of the period (if there is one) and the
1293 SourceRange getRange() const { return Range; }
1298 SourceLocation OperatorLoc, RParenLoc;
1300 TypeSourceInfo *TSInfo;
1301 // Number of sub-components (i.e. instances of OffsetOfNode).
1303 // Number of sub-expressions (i.e. array subscript expressions).
1306 OffsetOfExpr(ASTContext &C, QualType type,
1307 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1308 OffsetOfNode* compsPtr, unsigned numComps,
1309 Expr** exprsPtr, unsigned numExprs,
1310 SourceLocation RParenLoc);
1312 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1313 : Expr(OffsetOfExprClass, EmptyShell()),
1314 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1318 static OffsetOfExpr *Create(ASTContext &C, QualType type,
1319 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1320 OffsetOfNode* compsPtr, unsigned numComps,
1321 Expr** exprsPtr, unsigned numExprs,
1322 SourceLocation RParenLoc);
1324 static OffsetOfExpr *CreateEmpty(ASTContext &C,
1325 unsigned NumComps, unsigned NumExprs);
1327 /// getOperatorLoc - Return the location of the operator.
1328 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1329 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1331 /// \brief Return the location of the right parentheses.
1332 SourceLocation getRParenLoc() const { return RParenLoc; }
1333 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1335 TypeSourceInfo *getTypeSourceInfo() const {
1338 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1342 const OffsetOfNode &getComponent(unsigned Idx) {
1343 assert(Idx < NumComps && "Subscript out of range");
1344 return reinterpret_cast<OffsetOfNode *> (this + 1)[Idx];
1347 void setComponent(unsigned Idx, OffsetOfNode ON) {
1348 assert(Idx < NumComps && "Subscript out of range");
1349 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1352 unsigned getNumComponents() const {
1356 Expr* getIndexExpr(unsigned Idx) {
1357 assert(Idx < NumExprs && "Subscript out of range");
1358 return reinterpret_cast<Expr **>(
1359 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1362 void setIndexExpr(unsigned Idx, Expr* E) {
1363 assert(Idx < NumComps && "Subscript out of range");
1364 reinterpret_cast<Expr **>(
1365 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1368 unsigned getNumExpressions() const {
1372 virtual SourceRange getSourceRange() const {
1373 return SourceRange(OperatorLoc, RParenLoc);
1376 static bool classof(const Stmt *T) {
1377 return T->getStmtClass() == OffsetOfExprClass;
1380 static bool classof(const OffsetOfExpr *) { return true; }
1383 virtual child_iterator child_begin();
1384 virtual child_iterator child_end();
1387 /// SizeOfAlignOfExpr - [C99 6.5.3.4] - This is for sizeof/alignof, both of
1388 /// types and expressions.
1389 class SizeOfAlignOfExpr : public Expr {
1390 bool isSizeof : 1; // true if sizeof, false if alignof.
1391 bool isType : 1; // true if operand is a type, false if an expression
1396 SourceLocation OpLoc, RParenLoc;
1399 SizeOfAlignOfExpr(bool issizeof, TypeSourceInfo *TInfo,
1400 QualType resultType, SourceLocation op,
1401 SourceLocation rp) :
1402 Expr(SizeOfAlignOfExprClass, resultType,
1403 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1404 // Value-dependent if the argument is type-dependent.
1405 TInfo->getType()->isDependentType()),
1406 isSizeof(issizeof), isType(true), OpLoc(op), RParenLoc(rp) {
1407 Argument.Ty = TInfo;
1410 SizeOfAlignOfExpr(bool issizeof, Expr *E,
1411 QualType resultType, SourceLocation op,
1412 SourceLocation rp) :
1413 Expr(SizeOfAlignOfExprClass, resultType,
1414 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1415 // Value-dependent if the argument is type-dependent.
1416 E->isTypeDependent()),
1417 isSizeof(issizeof), isType(false), OpLoc(op), RParenLoc(rp) {
1421 /// \brief Construct an empty sizeof/alignof expression.
1422 explicit SizeOfAlignOfExpr(EmptyShell Empty)
1423 : Expr(SizeOfAlignOfExprClass, Empty) { }
1425 bool isSizeOf() const { return isSizeof; }
1426 void setSizeof(bool S) { isSizeof = S; }
1428 bool isArgumentType() const { return isType; }
1429 QualType getArgumentType() const {
1430 return getArgumentTypeInfo()->getType();
1432 TypeSourceInfo *getArgumentTypeInfo() const {
1433 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1436 Expr *getArgumentExpr() {
1437 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1438 return static_cast<Expr*>(Argument.Ex);
1440 const Expr *getArgumentExpr() const {
1441 return const_cast<SizeOfAlignOfExpr*>(this)->getArgumentExpr();
1444 void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1445 void setArgument(TypeSourceInfo *TInfo) {
1446 Argument.Ty = TInfo;
1450 /// Gets the argument type, or the type of the argument expression, whichever
1452 QualType getTypeOfArgument() const {
1453 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1456 SourceLocation getOperatorLoc() const { return OpLoc; }
1457 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1459 SourceLocation getRParenLoc() const { return RParenLoc; }
1460 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1462 virtual SourceRange getSourceRange() const {
1463 return SourceRange(OpLoc, RParenLoc);
1466 static bool classof(const Stmt *T) {
1467 return T->getStmtClass() == SizeOfAlignOfExprClass;
1469 static bool classof(const SizeOfAlignOfExpr *) { return true; }
1472 virtual child_iterator child_begin();
1473 virtual child_iterator child_end();
1476 //===----------------------------------------------------------------------===//
1477 // Postfix Operators.
1478 //===----------------------------------------------------------------------===//
1480 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1481 class ArraySubscriptExpr : public Expr {
1482 enum { LHS, RHS, END_EXPR=2 };
1483 Stmt* SubExprs[END_EXPR];
1484 SourceLocation RBracketLoc;
1486 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1487 SourceLocation rbracketloc)
1488 : Expr(ArraySubscriptExprClass, t,
1489 lhs->isTypeDependent() || rhs->isTypeDependent(),
1490 lhs->isValueDependent() || rhs->isValueDependent()),
1491 RBracketLoc(rbracketloc) {
1492 SubExprs[LHS] = lhs;
1493 SubExprs[RHS] = rhs;
1496 /// \brief Create an empty array subscript expression.
1497 explicit ArraySubscriptExpr(EmptyShell Shell)
1498 : Expr(ArraySubscriptExprClass, Shell) { }
1500 /// An array access can be written A[4] or 4[A] (both are equivalent).
1501 /// - getBase() and getIdx() always present the normalized view: A[4].
1502 /// In this case getBase() returns "A" and getIdx() returns "4".
1503 /// - getLHS() and getRHS() present the syntactic view. e.g. for
1504 /// 4[A] getLHS() returns "4".
1505 /// Note: Because vector element access is also written A[4] we must
1506 /// predicate the format conversion in getBase and getIdx only on the
1507 /// the type of the RHS, as it is possible for the LHS to be a vector of
1509 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1510 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1511 void setLHS(Expr *E) { SubExprs[LHS] = E; }
1513 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1514 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1515 void setRHS(Expr *E) { SubExprs[RHS] = E; }
1518 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1521 const Expr *getBase() const {
1522 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1526 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1529 const Expr *getIdx() const {
1530 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1533 virtual SourceRange getSourceRange() const {
1534 return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1537 SourceLocation getRBracketLoc() const { return RBracketLoc; }
1538 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1540 virtual SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1542 static bool classof(const Stmt *T) {
1543 return T->getStmtClass() == ArraySubscriptExprClass;
1545 static bool classof(const ArraySubscriptExpr *) { return true; }
1548 virtual child_iterator child_begin();
1549 virtual child_iterator child_end();
1553 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1554 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1555 /// while its subclasses may represent alternative syntax that (semantically)
1556 /// results in a function call. For example, CXXOperatorCallExpr is
1557 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
1558 /// "str1 + str2" to resolve to a function call.
1559 class CallExpr : public Expr {
1560 enum { FN=0, ARGS_START=1 };
1563 SourceLocation RParenLoc;
1566 // This version of the constructor is for derived classes.
1567 CallExpr(ASTContext& C, StmtClass SC, Expr *fn, Expr **args, unsigned numargs,
1568 QualType t, SourceLocation rparenloc);
1571 CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1572 SourceLocation rparenloc);
1574 /// \brief Build an empty call expression.
1575 CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1577 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1578 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1579 void setCallee(Expr *F) { SubExprs[FN] = F; }
1581 Decl *getCalleeDecl();
1582 const Decl *getCalleeDecl() const {
1583 return const_cast<CallExpr*>(this)->getCalleeDecl();
1586 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1587 FunctionDecl *getDirectCallee();
1588 const FunctionDecl *getDirectCallee() const {
1589 return const_cast<CallExpr*>(this)->getDirectCallee();
1592 /// getNumArgs - Return the number of actual arguments to this call.
1594 unsigned getNumArgs() const { return NumArgs; }
1596 /// getArg - Return the specified argument.
1597 Expr *getArg(unsigned Arg) {
1598 assert(Arg < NumArgs && "Arg access out of range!");
1599 return cast<Expr>(SubExprs[Arg+ARGS_START]);
1601 const Expr *getArg(unsigned Arg) const {
1602 assert(Arg < NumArgs && "Arg access out of range!");
1603 return cast<Expr>(SubExprs[Arg+ARGS_START]);
1606 /// setArg - Set the specified argument.
1607 void setArg(unsigned Arg, Expr *ArgExpr) {
1608 assert(Arg < NumArgs && "Arg access out of range!");
1609 SubExprs[Arg+ARGS_START] = ArgExpr;
1612 /// setNumArgs - This changes the number of arguments present in this call.
1613 /// Any orphaned expressions are deleted by this, and any new operands are set
1615 void setNumArgs(ASTContext& C, unsigned NumArgs);
1617 typedef ExprIterator arg_iterator;
1618 typedef ConstExprIterator const_arg_iterator;
1620 arg_iterator arg_begin() { return SubExprs+ARGS_START; }
1621 arg_iterator arg_end() { return SubExprs+ARGS_START+getNumArgs(); }
1622 const_arg_iterator arg_begin() const { return SubExprs+ARGS_START; }
1623 const_arg_iterator arg_end() const { return SubExprs+ARGS_START+getNumArgs();}
1625 /// getNumCommas - Return the number of commas that must have been present in
1626 /// this function call.
1627 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1629 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
1631 unsigned isBuiltinCall(ASTContext &Context) const;
1633 /// getCallReturnType - Get the return type of the call expr. This is not
1634 /// always the type of the expr itself, if the return type is a reference
1636 QualType getCallReturnType() const;
1638 SourceLocation getRParenLoc() const { return RParenLoc; }
1639 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1641 virtual SourceRange getSourceRange() const {
1642 return SourceRange(getCallee()->getLocStart(), RParenLoc);
1645 static bool classof(const Stmt *T) {
1646 return T->getStmtClass() >= firstCallExprConstant &&
1647 T->getStmtClass() <= lastCallExprConstant;
1649 static bool classof(const CallExpr *) { return true; }
1652 virtual child_iterator child_begin();
1653 virtual child_iterator child_end();
1656 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
1658 class MemberExpr : public Expr {
1659 /// Extra data stored in some member expressions.
1660 struct MemberNameQualifier : public NameQualifier {
1661 DeclAccessPair FoundDecl;
1664 /// Base - the expression for the base pointer or structure references. In
1665 /// X.F, this is "X".
1668 /// MemberDecl - This is the decl being referenced by the field/member name.
1669 /// In X.F, this is the decl referenced by F.
1670 ValueDecl *MemberDecl;
1672 /// MemberLoc - This is the location of the member name.
1673 SourceLocation MemberLoc;
1675 /// MemberDNLoc - Provides source/type location info for the
1676 /// declaration name embedded in MemberDecl.
1677 DeclarationNameLoc MemberDNLoc;
1679 /// IsArrow - True if this is "X->F", false if this is "X.F".
1682 /// \brief True if this member expression used a nested-name-specifier to
1683 /// refer to the member, e.g., "x->Base::f", or found its member via a using
1684 /// declaration. When true, a MemberNameQualifier
1685 /// structure is allocated immediately after the MemberExpr.
1686 bool HasQualifierOrFoundDecl : 1;
1688 /// \brief True if this member expression specified a template argument list
1689 /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
1690 /// structure (and its TemplateArguments) are allocated immediately after
1691 /// the MemberExpr or, if the member expression also has a qualifier, after
1692 /// the MemberNameQualifier structure.
1693 bool HasExplicitTemplateArgumentList : 1;
1695 /// \brief Retrieve the qualifier that preceded the member name, if any.
1696 MemberNameQualifier *getMemberQualifier() {
1697 assert(HasQualifierOrFoundDecl);
1698 return reinterpret_cast<MemberNameQualifier *> (this + 1);
1701 /// \brief Retrieve the qualifier that preceded the member name, if any.
1702 const MemberNameQualifier *getMemberQualifier() const {
1703 return const_cast<MemberExpr *>(this)->getMemberQualifier();
1707 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1708 const DeclarationNameInfo &NameInfo, QualType ty)
1709 : Expr(MemberExprClass, ty,
1710 base->isTypeDependent(), base->isValueDependent()),
1711 Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
1712 MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
1713 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {
1714 assert(memberdecl->getDeclName() == NameInfo.getName());
1717 // NOTE: this constructor should be used only when it is known that
1718 // the member name can not provide additional syntactic info
1719 // (i.e., source locations for C++ operator names or type source info
1720 // for constructors, destructors and conversion oeprators).
1721 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
1722 SourceLocation l, QualType ty)
1723 : Expr(MemberExprClass, ty,
1724 base->isTypeDependent(), base->isValueDependent()),
1725 Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
1727 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false) {}
1729 static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
1730 NestedNameSpecifier *qual, SourceRange qualrange,
1731 ValueDecl *memberdecl, DeclAccessPair founddecl,
1732 DeclarationNameInfo MemberNameInfo,
1733 const TemplateArgumentListInfo *targs,
1736 void setBase(Expr *E) { Base = E; }
1737 Expr *getBase() const { return cast<Expr>(Base); }
1739 /// \brief Retrieve the member declaration to which this expression refers.
1741 /// The returned declaration will either be a FieldDecl or (in C++)
1742 /// a CXXMethodDecl.
1743 ValueDecl *getMemberDecl() const { return MemberDecl; }
1744 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
1746 /// \brief Retrieves the declaration found by lookup.
1747 DeclAccessPair getFoundDecl() const {
1748 if (!HasQualifierOrFoundDecl)
1749 return DeclAccessPair::make(getMemberDecl(),
1750 getMemberDecl()->getAccess());
1751 return getMemberQualifier()->FoundDecl;
1754 /// \brief Determines whether this member expression actually had
1755 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
1757 bool hasQualifier() const { return getQualifier() != 0; }
1759 /// \brief If the member name was qualified, retrieves the source range of
1760 /// the nested-name-specifier that precedes the member name. Otherwise,
1761 /// returns an empty source range.
1762 SourceRange getQualifierRange() const {
1763 if (!HasQualifierOrFoundDecl)
1764 return SourceRange();
1766 return getMemberQualifier()->Range;
1769 /// \brief If the member name was qualified, retrieves the
1770 /// nested-name-specifier that precedes the member name. Otherwise, returns
1772 NestedNameSpecifier *getQualifier() const {
1773 if (!HasQualifierOrFoundDecl)
1776 return getMemberQualifier()->NNS;
1779 /// \brief Determines whether this member expression actually had a C++
1780 /// template argument list explicitly specified, e.g., x.f<int>.
1781 bool hasExplicitTemplateArgs() const {
1782 return HasExplicitTemplateArgumentList;
1785 /// \brief Copies the template arguments (if present) into the given
1787 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1788 if (hasExplicitTemplateArgs())
1789 getExplicitTemplateArgs().copyInto(List);
1792 /// \brief Retrieve the explicit template argument list that
1793 /// follow the member template name. This must only be called on an
1794 /// expression with explicit template arguments.
1795 ExplicitTemplateArgumentList &getExplicitTemplateArgs() {
1796 assert(HasExplicitTemplateArgumentList);
1797 if (!HasQualifierOrFoundDecl)
1798 return *reinterpret_cast<ExplicitTemplateArgumentList *>(this + 1);
1800 return *reinterpret_cast<ExplicitTemplateArgumentList *>(
1801 getMemberQualifier() + 1);
1804 /// \brief Retrieve the explicit template argument list that
1805 /// followed the member template name. This must only be called on
1806 /// an expression with explicit template arguments.
1807 const ExplicitTemplateArgumentList &getExplicitTemplateArgs() const {
1808 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
1811 /// \brief Retrieves the optional explicit template arguments.
1812 /// This points to the same data as getExplicitTemplateArgs(), but
1813 /// returns null if there are no explicit template arguments.
1814 const ExplicitTemplateArgumentList *getOptionalExplicitTemplateArgs() const {
1815 if (!hasExplicitTemplateArgs()) return 0;
1816 return &getExplicitTemplateArgs();
1819 /// \brief Retrieve the location of the left angle bracket following the
1820 /// member name ('<'), if any.
1821 SourceLocation getLAngleLoc() const {
1822 if (!HasExplicitTemplateArgumentList)
1823 return SourceLocation();
1825 return getExplicitTemplateArgs().LAngleLoc;
1828 /// \brief Retrieve the template arguments provided as part of this
1830 const TemplateArgumentLoc *getTemplateArgs() const {
1831 if (!HasExplicitTemplateArgumentList)
1834 return getExplicitTemplateArgs().getTemplateArgs();
1837 /// \brief Retrieve the number of template arguments provided as part of this
1839 unsigned getNumTemplateArgs() const {
1840 if (!HasExplicitTemplateArgumentList)
1843 return getExplicitTemplateArgs().NumTemplateArgs;
1846 /// \brief Retrieve the location of the right angle bracket following the
1847 /// template arguments ('>').
1848 SourceLocation getRAngleLoc() const {
1849 if (!HasExplicitTemplateArgumentList)
1850 return SourceLocation();
1852 return getExplicitTemplateArgs().RAngleLoc;
1855 /// \brief Retrieve the member declaration name info.
1856 DeclarationNameInfo getMemberNameInfo() const {
1857 return DeclarationNameInfo(MemberDecl->getDeclName(),
1858 MemberLoc, MemberDNLoc);
1861 bool isArrow() const { return IsArrow; }
1862 void setArrow(bool A) { IsArrow = A; }
1864 /// getMemberLoc - Return the location of the "member", in X->F, it is the
1865 /// location of 'F'.
1866 SourceLocation getMemberLoc() const { return MemberLoc; }
1867 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
1869 virtual SourceRange getSourceRange() const {
1870 // If we have an implicit base (like a C++ implicit this),
1871 // make sure not to return its location
1872 SourceLocation EndLoc = (HasExplicitTemplateArgumentList)
1873 ? getRAngleLoc() : getMemberNameInfo().getEndLoc();
1875 SourceLocation BaseLoc = getBase()->getLocStart();
1876 if (BaseLoc.isInvalid())
1877 return SourceRange(MemberLoc, EndLoc);
1878 return SourceRange(BaseLoc, EndLoc);
1881 virtual SourceLocation getExprLoc() const { return MemberLoc; }
1883 static bool classof(const Stmt *T) {
1884 return T->getStmtClass() == MemberExprClass;
1886 static bool classof(const MemberExpr *) { return true; }
1889 virtual child_iterator child_begin();
1890 virtual child_iterator child_end();
1893 /// CompoundLiteralExpr - [C99 6.5.2.5]
1895 class CompoundLiteralExpr : public Expr {
1896 /// LParenLoc - If non-null, this is the location of the left paren in a
1897 /// compound literal like "(int){4}". This can be null if this is a
1898 /// synthesized compound expression.
1899 SourceLocation LParenLoc;
1901 /// The type as written. This can be an incomplete array type, in
1902 /// which case the actual expression type will be different.
1903 TypeSourceInfo *TInfo;
1907 // FIXME: Can compound literals be value-dependent?
1908 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
1909 QualType T, Expr *init, bool fileScope)
1910 : Expr(CompoundLiteralExprClass, T,
1911 tinfo->getType()->isDependentType(), false),
1912 LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
1914 /// \brief Construct an empty compound literal.
1915 explicit CompoundLiteralExpr(EmptyShell Empty)
1916 : Expr(CompoundLiteralExprClass, Empty) { }
1918 const Expr *getInitializer() const { return cast<Expr>(Init); }
1919 Expr *getInitializer() { return cast<Expr>(Init); }
1920 void setInitializer(Expr *E) { Init = E; }
1922 bool isFileScope() const { return FileScope; }
1923 void setFileScope(bool FS) { FileScope = FS; }
1925 SourceLocation getLParenLoc() const { return LParenLoc; }
1926 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1928 TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
1929 void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
1931 virtual SourceRange getSourceRange() const {
1932 // FIXME: Init should never be null.
1934 return SourceRange();
1935 if (LParenLoc.isInvalid())
1936 return Init->getSourceRange();
1937 return SourceRange(LParenLoc, Init->getLocEnd());
1940 static bool classof(const Stmt *T) {
1941 return T->getStmtClass() == CompoundLiteralExprClass;
1943 static bool classof(const CompoundLiteralExpr *) { return true; }
1946 virtual child_iterator child_begin();
1947 virtual child_iterator child_end();
1950 /// CastExpr - Base class for type casts, including both implicit
1951 /// casts (ImplicitCastExpr) and explicit casts that have some
1952 /// representation in the source code (ExplicitCastExpr's derived
1954 class CastExpr : public Expr {
1956 typedef clang::CastKind CastKind;
1960 unsigned BasePathSize : BitsRemaining - 5;
1963 void CheckBasePath() const {
1965 switch (getCastKind()) {
1966 case CK_DerivedToBase:
1967 case CK_UncheckedDerivedToBase:
1968 case CK_DerivedToBaseMemberPointer:
1969 case CK_BaseToDerived:
1970 case CK_BaseToDerivedMemberPointer:
1971 assert(!path_empty() && "Cast kind should have a base path!");
1974 // These should not have an inheritance path.
1977 case CK_LValueBitCast:
1981 case CK_ArrayToPointerDecay:
1982 case CK_FunctionToPointerDecay:
1983 case CK_NullToMemberPointer:
1984 case CK_UserDefinedConversion:
1985 case CK_ConstructorConversion:
1986 case CK_IntegralToPointer:
1987 case CK_PointerToIntegral:
1989 case CK_VectorSplat:
1990 case CK_IntegralCast:
1991 case CK_IntegralToFloating:
1992 case CK_FloatingToIntegral:
1993 case CK_FloatingCast:
1994 case CK_MemberPointerToBoolean:
1995 case CK_AnyPointerToObjCPointerCast:
1996 case CK_AnyPointerToBlockPointerCast:
1997 case CK_ObjCObjectLValueCast:
1998 assert(path_empty() && "Cast kind should not have a base path!");
2004 const CXXBaseSpecifier * const *path_buffer() const {
2005 return const_cast<CastExpr*>(this)->path_buffer();
2007 CXXBaseSpecifier **path_buffer();
2010 CastExpr(StmtClass SC, QualType ty, const CastKind kind, Expr *op,
2011 unsigned BasePathSize) :
2013 // Cast expressions are type-dependent if the type is
2014 // dependent (C++ [temp.dep.expr]p3).
2015 ty->isDependentType(),
2016 // Cast expressions are value-dependent if the type is
2017 // dependent or if the subexpression is value-dependent.
2018 ty->isDependentType() || (op && op->isValueDependent())),
2019 Kind(kind), BasePathSize(BasePathSize), Op(op) {
2023 /// \brief Construct an empty cast.
2024 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2025 : Expr(SC, Empty), BasePathSize(BasePathSize) { }
2028 CastKind getCastKind() const { return static_cast<CastKind>(Kind); }
2029 void setCastKind(CastKind K) { Kind = K; }
2030 const char *getCastKindName() const;
2032 Expr *getSubExpr() { return cast<Expr>(Op); }
2033 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2034 void setSubExpr(Expr *E) { Op = E; }
2036 /// \brief Retrieve the cast subexpression as it was written in the source
2037 /// code, looking through any implicit casts or other intermediate nodes
2038 /// introduced by semantic analysis.
2039 Expr *getSubExprAsWritten();
2040 const Expr *getSubExprAsWritten() const {
2041 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2044 typedef CXXBaseSpecifier **path_iterator;
2045 typedef const CXXBaseSpecifier * const *path_const_iterator;
2046 bool path_empty() const { return BasePathSize == 0; }
2047 unsigned path_size() const { return BasePathSize; }
2048 path_iterator path_begin() { return path_buffer(); }
2049 path_iterator path_end() { return path_buffer() + path_size(); }
2050 path_const_iterator path_begin() const { return path_buffer(); }
2051 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2053 void setCastPath(const CXXCastPath &Path);
2055 static bool classof(const Stmt *T) {
2056 return T->getStmtClass() >= firstCastExprConstant &&
2057 T->getStmtClass() <= lastCastExprConstant;
2059 static bool classof(const CastExpr *) { return true; }
2062 virtual child_iterator child_begin();
2063 virtual child_iterator child_end();
2066 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2067 /// conversions, which have no direct representation in the original
2068 /// source code. For example: converting T[]->T*, void f()->void
2069 /// (*f)(), float->double, short->int, etc.
2071 /// In C, implicit casts always produce rvalues. However, in C++, an
2072 /// implicit cast whose result is being bound to a reference will be
2073 /// an lvalue or xvalue. For example:
2077 /// class Derived : public Base { };
2078 /// Derived &&ref();
2079 /// void f(Derived d) {
2080 /// Base& b = d; // initializer is an ImplicitCastExpr
2081 /// // to an lvalue of type Base
2082 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2083 /// // to an xvalue of type Base
2086 class ImplicitCastExpr : public CastExpr {
2088 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2089 unsigned BasePathLength, ExprValueKind VK)
2090 : CastExpr(ImplicitCastExprClass, ty, kind, op, BasePathLength) {
2094 /// \brief Construct an empty implicit cast.
2095 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2096 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2099 enum OnStack_t { OnStack };
2100 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2102 : CastExpr(ImplicitCastExprClass, ty, kind, op, 0) {
2106 static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2107 CastKind Kind, Expr *Operand,
2108 const CXXCastPath *BasePath,
2111 static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2113 virtual SourceRange getSourceRange() const {
2114 return getSubExpr()->getSourceRange();
2117 /// getValueKind - The value kind that this cast produces.
2118 ExprValueKind getValueKind() const {
2119 return static_cast<ExprValueKind>(ValueKind);
2122 /// setValueKind - Set the value kind this cast produces.
2123 void setValueKind(ExprValueKind Cat) { ValueKind = Cat; }
2125 static bool classof(const Stmt *T) {
2126 return T->getStmtClass() == ImplicitCastExprClass;
2128 static bool classof(const ImplicitCastExpr *) { return true; }
2131 /// ExplicitCastExpr - An explicit cast written in the source
2134 /// This class is effectively an abstract class, because it provides
2135 /// the basic representation of an explicitly-written cast without
2136 /// specifying which kind of cast (C cast, functional cast, static
2137 /// cast, etc.) was written; specific derived classes represent the
2138 /// particular style of cast and its location information.
2140 /// Unlike implicit casts, explicit cast nodes have two different
2141 /// types: the type that was written into the source code, and the
2142 /// actual type of the expression as determined by semantic
2143 /// analysis. These types may differ slightly. For example, in C++ one
2144 /// can cast to a reference type, which indicates that the resulting
2145 /// expression will be an lvalue or xvalue. The reference type, however,
2146 /// will not be used as the type of the expression.
2147 class ExplicitCastExpr : public CastExpr {
2148 /// TInfo - Source type info for the (written) type
2149 /// this expression is casting to.
2150 TypeSourceInfo *TInfo;
2153 ExplicitCastExpr(StmtClass SC, QualType exprTy, CastKind kind,
2154 Expr *op, unsigned PathSize, TypeSourceInfo *writtenTy)
2155 : CastExpr(SC, exprTy, kind, op, PathSize), TInfo(writtenTy) {}
2157 /// \brief Construct an empty explicit cast.
2158 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2159 : CastExpr(SC, Shell, PathSize) { }
2162 /// getTypeInfoAsWritten - Returns the type source info for the type
2163 /// that this expression is casting to.
2164 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2165 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2167 /// getTypeAsWritten - Returns the type that this expression is
2168 /// casting to, as written in the source code.
2169 QualType getTypeAsWritten() const { return TInfo->getType(); }
2171 static bool classof(const Stmt *T) {
2172 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2173 T->getStmtClass() <= lastExplicitCastExprConstant;
2175 static bool classof(const ExplicitCastExpr *) { return true; }
2178 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2179 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2180 /// (Type)expr. For example: @c (int)f.
2181 class CStyleCastExpr : public ExplicitCastExpr {
2182 SourceLocation LPLoc; // the location of the left paren
2183 SourceLocation RPLoc; // the location of the right paren
2185 CStyleCastExpr(QualType exprTy, CastKind kind, Expr *op,
2186 unsigned PathSize, TypeSourceInfo *writtenTy,
2187 SourceLocation l, SourceLocation r)
2188 : ExplicitCastExpr(CStyleCastExprClass, exprTy, kind, op, PathSize,
2189 writtenTy), LPLoc(l), RPLoc(r) {}
2191 /// \brief Construct an empty C-style explicit cast.
2192 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2193 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2196 static CStyleCastExpr *Create(ASTContext &Context, QualType T, CastKind K,
2197 Expr *Op, const CXXCastPath *BasePath,
2198 TypeSourceInfo *WrittenTy, SourceLocation L,
2201 static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2203 SourceLocation getLParenLoc() const { return LPLoc; }
2204 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2206 SourceLocation getRParenLoc() const { return RPLoc; }
2207 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2209 virtual SourceRange getSourceRange() const {
2210 return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2212 static bool classof(const Stmt *T) {
2213 return T->getStmtClass() == CStyleCastExprClass;
2215 static bool classof(const CStyleCastExpr *) { return true; }
2218 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2220 /// This expression node kind describes a builtin binary operation,
2221 /// such as "x + y" for integer values "x" and "y". The operands will
2222 /// already have been converted to appropriate types (e.g., by
2223 /// performing promotions or conversions).
2225 /// In C++, where operators may be overloaded, a different kind of
2226 /// expression node (CXXOperatorCallExpr) is used to express the
2227 /// invocation of an overloaded operator with operator syntax. Within
2228 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2229 /// used to store an expression "x + y" depends on the subexpressions
2230 /// for x and y. If neither x or y is type-dependent, and the "+"
2231 /// operator resolves to a built-in operation, BinaryOperator will be
2232 /// used to express the computation (x and y may still be
2233 /// value-dependent). If either x or y is type-dependent, or if the
2234 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2235 /// be used to express the computation.
2236 class BinaryOperator : public Expr {
2238 typedef BinaryOperatorKind Opcode;
2242 SourceLocation OpLoc;
2244 enum { LHS, RHS, END_EXPR };
2245 Stmt* SubExprs[END_EXPR];
2248 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2249 SourceLocation opLoc)
2250 : Expr(BinaryOperatorClass, ResTy,
2251 lhs->isTypeDependent() || rhs->isTypeDependent(),
2252 lhs->isValueDependent() || rhs->isValueDependent()),
2253 Opc(opc), OpLoc(opLoc) {
2254 SubExprs[LHS] = lhs;
2255 SubExprs[RHS] = rhs;
2256 assert(!isCompoundAssignmentOp() &&
2257 "Use ArithAssignBinaryOperator for compound assignments");
2260 /// \brief Construct an empty binary operator.
2261 explicit BinaryOperator(EmptyShell Empty)
2262 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2264 SourceLocation getOperatorLoc() const { return OpLoc; }
2265 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2267 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2268 void setOpcode(Opcode O) { Opc = O; }
2270 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2271 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2272 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2273 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2275 virtual SourceRange getSourceRange() const {
2276 return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2279 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2280 /// corresponds to, e.g. "<<=".
2281 static const char *getOpcodeStr(Opcode Op);
2283 const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2285 /// \brief Retrieve the binary opcode that corresponds to the given
2286 /// overloaded operator.
2287 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2289 /// \brief Retrieve the overloaded operator kind that corresponds to
2290 /// the given binary opcode.
2291 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2293 /// predicates to categorize the respective opcodes.
2294 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2295 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2296 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2297 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2298 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2300 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2301 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2303 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2304 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2306 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2307 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2309 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2310 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2312 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2313 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2315 bool isAssignmentOp() const { return Opc >= BO_Assign && Opc <= BO_OrAssign; }
2316 bool isCompoundAssignmentOp() const {
2317 return Opc > BO_Assign && Opc <= BO_OrAssign;
2319 bool isShiftAssignOp() const {
2320 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2323 static bool classof(const Stmt *S) {
2324 return S->getStmtClass() >= firstBinaryOperatorConstant &&
2325 S->getStmtClass() <= lastBinaryOperatorConstant;
2327 static bool classof(const BinaryOperator *) { return true; }
2330 virtual child_iterator child_begin();
2331 virtual child_iterator child_end();
2334 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2335 SourceLocation opLoc, bool dead)
2336 : Expr(CompoundAssignOperatorClass, ResTy,
2337 lhs->isTypeDependent() || rhs->isTypeDependent(),
2338 lhs->isValueDependent() || rhs->isValueDependent()),
2339 Opc(opc), OpLoc(opLoc) {
2340 SubExprs[LHS] = lhs;
2341 SubExprs[RHS] = rhs;
2344 BinaryOperator(StmtClass SC, EmptyShell Empty)
2345 : Expr(SC, Empty), Opc(BO_MulAssign) { }
2348 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2349 /// track of the type the operation is performed in. Due to the semantics of
2350 /// these operators, the operands are promoted, the aritmetic performed, an
2351 /// implicit conversion back to the result type done, then the assignment takes
2352 /// place. This captures the intermediate type which the computation is done
2354 class CompoundAssignOperator : public BinaryOperator {
2355 QualType ComputationLHSType;
2356 QualType ComputationResultType;
2358 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc,
2359 QualType ResType, QualType CompLHSType,
2360 QualType CompResultType,
2361 SourceLocation OpLoc)
2362 : BinaryOperator(lhs, rhs, opc, ResType, OpLoc, true),
2363 ComputationLHSType(CompLHSType),
2364 ComputationResultType(CompResultType) {
2365 assert(isCompoundAssignmentOp() &&
2366 "Only should be used for compound assignments");
2369 /// \brief Build an empty compound assignment operator expression.
2370 explicit CompoundAssignOperator(EmptyShell Empty)
2371 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2373 // The two computation types are the type the LHS is converted
2374 // to for the computation and the type of the result; the two are
2375 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2376 QualType getComputationLHSType() const { return ComputationLHSType; }
2377 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2379 QualType getComputationResultType() const { return ComputationResultType; }
2380 void setComputationResultType(QualType T) { ComputationResultType = T; }
2382 static bool classof(const CompoundAssignOperator *) { return true; }
2383 static bool classof(const Stmt *S) {
2384 return S->getStmtClass() == CompoundAssignOperatorClass;
2388 /// ConditionalOperator - The ?: operator. Note that LHS may be null when the
2389 /// GNU "missing LHS" extension is in use.
2391 class ConditionalOperator : public Expr {
2392 enum { COND, LHS, RHS, END_EXPR };
2393 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2395 SourceLocation QuestionLoc, ColonLoc;
2397 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2398 SourceLocation CLoc, Expr *rhs, Expr *save, QualType t)
2399 : Expr(ConditionalOperatorClass, t,
2400 // FIXME: the type of the conditional operator doesn't
2401 // depend on the type of the conditional, but the standard
2402 // seems to imply that it could. File a bug!
2403 ((lhs && lhs->isTypeDependent()) || (rhs && rhs->isTypeDependent())),
2404 (cond->isValueDependent() ||
2405 (lhs && lhs->isValueDependent()) ||
2406 (rhs && rhs->isValueDependent()))),
2409 SubExprs[COND] = cond;
2410 SubExprs[LHS] = lhs;
2411 SubExprs[RHS] = rhs;
2415 /// \brief Build an empty conditional operator.
2416 explicit ConditionalOperator(EmptyShell Empty)
2417 : Expr(ConditionalOperatorClass, Empty) { }
2419 // getCond - Return the expression representing the condition for
2421 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2422 void setCond(Expr *E) { SubExprs[COND] = E; }
2424 // getTrueExpr - Return the subexpression representing the value of the ?:
2425 // expression if the condition evaluates to true.
2426 Expr *getTrueExpr() const {
2427 return cast<Expr>(!Save ? SubExprs[LHS] : SubExprs[COND]);
2430 // getFalseExpr - Return the subexpression representing the value of the ?:
2431 // expression if the condition evaluates to false. This is the same as getRHS.
2432 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2434 // getSaveExpr - In most cases this value will be null. Except a GCC extension
2435 // allows the left subexpression to be omitted, and instead of that condition
2436 // be returned. e.g: x ?: y is shorthand for x ? x : y, except that the
2437 // expression "x" is only evaluated once. Under this senario, this function
2438 // returns the original, non-converted condition expression for the ?:operator
2439 Expr *getSaveExpr() const { return Save? cast<Expr>(Save) : (Expr*)0; }
2441 Expr *getLHS() const { return Save ? 0 : cast<Expr>(SubExprs[LHS]); }
2442 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2444 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2445 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2447 Expr *getSAVE() const { return Save? cast<Expr>(Save) : (Expr*)0; }
2448 void setSAVE(Expr *E) { Save = E; }
2450 SourceLocation getQuestionLoc() const { return QuestionLoc; }
2451 void setQuestionLoc(SourceLocation L) { QuestionLoc = L; }
2453 SourceLocation getColonLoc() const { return ColonLoc; }
2454 void setColonLoc(SourceLocation L) { ColonLoc = L; }
2456 virtual SourceRange getSourceRange() const {
2457 return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2459 static bool classof(const Stmt *T) {
2460 return T->getStmtClass() == ConditionalOperatorClass;
2462 static bool classof(const ConditionalOperator *) { return true; }
2465 virtual child_iterator child_begin();
2466 virtual child_iterator child_end();
2469 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
2470 class AddrLabelExpr : public Expr {
2471 SourceLocation AmpAmpLoc, LabelLoc;
2474 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelStmt *L,
2476 : Expr(AddrLabelExprClass, t, false, false),
2477 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2479 /// \brief Build an empty address of a label expression.
2480 explicit AddrLabelExpr(EmptyShell Empty)
2481 : Expr(AddrLabelExprClass, Empty) { }
2483 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2484 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2485 SourceLocation getLabelLoc() const { return LabelLoc; }
2486 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2488 virtual SourceRange getSourceRange() const {
2489 return SourceRange(AmpAmpLoc, LabelLoc);
2492 LabelStmt *getLabel() const { return Label; }
2493 void setLabel(LabelStmt *S) { Label = S; }
2495 static bool classof(const Stmt *T) {
2496 return T->getStmtClass() == AddrLabelExprClass;
2498 static bool classof(const AddrLabelExpr *) { return true; }
2501 virtual child_iterator child_begin();
2502 virtual child_iterator child_end();
2505 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
2506 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
2507 /// takes the value of the last subexpression.
2508 class StmtExpr : public Expr {
2510 SourceLocation LParenLoc, RParenLoc;
2512 // FIXME: Does type-dependence need to be computed differently?
2513 StmtExpr(CompoundStmt *substmt, QualType T,
2514 SourceLocation lp, SourceLocation rp) :
2515 Expr(StmtExprClass, T, T->isDependentType(), false),
2516 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
2518 /// \brief Build an empty statement expression.
2519 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
2521 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
2522 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
2523 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
2525 virtual SourceRange getSourceRange() const {
2526 return SourceRange(LParenLoc, RParenLoc);
2529 SourceLocation getLParenLoc() const { return LParenLoc; }
2530 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2531 SourceLocation getRParenLoc() const { return RParenLoc; }
2532 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2534 static bool classof(const Stmt *T) {
2535 return T->getStmtClass() == StmtExprClass;
2537 static bool classof(const StmtExpr *) { return true; }
2540 virtual child_iterator child_begin();
2541 virtual child_iterator child_end();
2544 /// TypesCompatibleExpr - GNU builtin-in function __builtin_types_compatible_p.
2545 /// This AST node represents a function that returns 1 if two *types* (not
2546 /// expressions) are compatible. The result of this built-in function can be
2547 /// used in integer constant expressions.
2548 class TypesCompatibleExpr : public Expr {
2549 TypeSourceInfo *TInfo1;
2550 TypeSourceInfo *TInfo2;
2551 SourceLocation BuiltinLoc, RParenLoc;
2553 TypesCompatibleExpr(QualType ReturnType, SourceLocation BLoc,
2554 TypeSourceInfo *tinfo1, TypeSourceInfo *tinfo2,
2555 SourceLocation RP) :
2556 Expr(TypesCompatibleExprClass, ReturnType, false, false),
2557 TInfo1(tinfo1), TInfo2(tinfo2), BuiltinLoc(BLoc), RParenLoc(RP) {}
2559 /// \brief Build an empty __builtin_type_compatible_p expression.
2560 explicit TypesCompatibleExpr(EmptyShell Empty)
2561 : Expr(TypesCompatibleExprClass, Empty) { }
2563 TypeSourceInfo *getArgTInfo1() const { return TInfo1; }
2564 void setArgTInfo1(TypeSourceInfo *TInfo) { TInfo1 = TInfo; }
2565 TypeSourceInfo *getArgTInfo2() const { return TInfo2; }
2566 void setArgTInfo2(TypeSourceInfo *TInfo) { TInfo2 = TInfo; }
2568 QualType getArgType1() const { return TInfo1->getType(); }
2569 QualType getArgType2() const { return TInfo2->getType(); }
2571 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2572 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2574 SourceLocation getRParenLoc() const { return RParenLoc; }
2575 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2577 virtual SourceRange getSourceRange() const {
2578 return SourceRange(BuiltinLoc, RParenLoc);
2580 static bool classof(const Stmt *T) {
2581 return T->getStmtClass() == TypesCompatibleExprClass;
2583 static bool classof(const TypesCompatibleExpr *) { return true; }
2586 virtual child_iterator child_begin();
2587 virtual child_iterator child_end();
2590 /// ShuffleVectorExpr - clang-specific builtin-in function
2591 /// __builtin_shufflevector.
2592 /// This AST node represents a operator that does a constant
2593 /// shuffle, similar to LLVM's shufflevector instruction. It takes
2594 /// two vectors and a variable number of constant indices,
2595 /// and returns the appropriately shuffled vector.
2596 class ShuffleVectorExpr : public Expr {
2597 SourceLocation BuiltinLoc, RParenLoc;
2599 // SubExprs - the list of values passed to the __builtin_shufflevector
2600 // function. The first two are vectors, and the rest are constant
2601 // indices. The number of values in this list is always
2602 // 2+the number of indices in the vector type.
2607 // FIXME: Can a shufflevector be value-dependent? Does type-dependence need
2608 // to be computed differently?
2609 ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2610 QualType Type, SourceLocation BLoc,
2611 SourceLocation RP) :
2612 Expr(ShuffleVectorExprClass, Type, Type->isDependentType(), false),
2613 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr) {
2615 SubExprs = new (C) Stmt*[nexpr];
2616 for (unsigned i = 0; i < nexpr; i++)
2617 SubExprs[i] = args[i];
2620 /// \brief Build an empty vector-shuffle expression.
2621 explicit ShuffleVectorExpr(EmptyShell Empty)
2622 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
2624 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2625 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2627 SourceLocation getRParenLoc() const { return RParenLoc; }
2628 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2630 virtual SourceRange getSourceRange() const {
2631 return SourceRange(BuiltinLoc, RParenLoc);
2633 static bool classof(const Stmt *T) {
2634 return T->getStmtClass() == ShuffleVectorExprClass;
2636 static bool classof(const ShuffleVectorExpr *) { return true; }
2638 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
2639 /// constant expression, the actual arguments passed in, and the function
2641 unsigned getNumSubExprs() const { return NumExprs; }
2643 /// getExpr - Return the Expr at the specified index.
2644 Expr *getExpr(unsigned Index) {
2645 assert((Index < NumExprs) && "Arg access out of range!");
2646 return cast<Expr>(SubExprs[Index]);
2648 const Expr *getExpr(unsigned Index) const {
2649 assert((Index < NumExprs) && "Arg access out of range!");
2650 return cast<Expr>(SubExprs[Index]);
2653 void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
2655 unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
2656 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
2657 return getExpr(N+2)->EvaluateAsInt(Ctx).getZExtValue();
2661 virtual child_iterator child_begin();
2662 virtual child_iterator child_end();
2665 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
2666 /// This AST node is similar to the conditional operator (?:) in C, with
2667 /// the following exceptions:
2668 /// - the test expression must be a integer constant expression.
2669 /// - the expression returned acts like the chosen subexpression in every
2670 /// visible way: the type is the same as that of the chosen subexpression,
2671 /// and all predicates (whether it's an l-value, whether it's an integer
2672 /// constant expression, etc.) return the same result as for the chosen
2674 class ChooseExpr : public Expr {
2675 enum { COND, LHS, RHS, END_EXPR };
2676 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2677 SourceLocation BuiltinLoc, RParenLoc;
2679 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
2680 SourceLocation RP, bool TypeDependent, bool ValueDependent)
2681 : Expr(ChooseExprClass, t, TypeDependent, ValueDependent),
2682 BuiltinLoc(BLoc), RParenLoc(RP) {
2683 SubExprs[COND] = cond;
2684 SubExprs[LHS] = lhs;
2685 SubExprs[RHS] = rhs;
2688 /// \brief Build an empty __builtin_choose_expr.
2689 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
2691 /// isConditionTrue - Return whether the condition is true (i.e. not
2693 bool isConditionTrue(ASTContext &C) const;
2695 /// getChosenSubExpr - Return the subexpression chosen according to the
2697 Expr *getChosenSubExpr(ASTContext &C) const {
2698 return isConditionTrue(C) ? getLHS() : getRHS();
2701 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2702 void setCond(Expr *E) { SubExprs[COND] = E; }
2703 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2704 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2705 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2706 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2708 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2709 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2711 SourceLocation getRParenLoc() const { return RParenLoc; }
2712 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2714 virtual SourceRange getSourceRange() const {
2715 return SourceRange(BuiltinLoc, RParenLoc);
2717 static bool classof(const Stmt *T) {
2718 return T->getStmtClass() == ChooseExprClass;
2720 static bool classof(const ChooseExpr *) { return true; }
2723 virtual child_iterator child_begin();
2724 virtual child_iterator child_end();
2727 /// GNUNullExpr - Implements the GNU __null extension, which is a name
2728 /// for a null pointer constant that has integral type (e.g., int or
2729 /// long) and is the same size and alignment as a pointer. The __null
2730 /// extension is typically only used by system headers, which define
2731 /// NULL as __null in C++ rather than using 0 (which is an integer
2732 /// that may not match the size of a pointer).
2733 class GNUNullExpr : public Expr {
2734 /// TokenLoc - The location of the __null keyword.
2735 SourceLocation TokenLoc;
2738 GNUNullExpr(QualType Ty, SourceLocation Loc)
2739 : Expr(GNUNullExprClass, Ty, false, false), TokenLoc(Loc) { }
2741 /// \brief Build an empty GNU __null expression.
2742 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
2744 /// getTokenLocation - The location of the __null token.
2745 SourceLocation getTokenLocation() const { return TokenLoc; }
2746 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
2748 virtual SourceRange getSourceRange() const {
2749 return SourceRange(TokenLoc);
2751 static bool classof(const Stmt *T) {
2752 return T->getStmtClass() == GNUNullExprClass;
2754 static bool classof(const GNUNullExpr *) { return true; }
2757 virtual child_iterator child_begin();
2758 virtual child_iterator child_end();
2761 /// VAArgExpr, used for the builtin function __builtin_va_arg.
2762 class VAArgExpr : public Expr {
2764 TypeSourceInfo *TInfo;
2765 SourceLocation BuiltinLoc, RParenLoc;
2767 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
2768 SourceLocation RPLoc, QualType t)
2769 : Expr(VAArgExprClass, t, t->isDependentType(), false),
2770 Val(e), TInfo(TInfo),
2772 RParenLoc(RPLoc) { }
2774 /// \brief Create an empty __builtin_va_arg expression.
2775 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
2777 const Expr *getSubExpr() const { return cast<Expr>(Val); }
2778 Expr *getSubExpr() { return cast<Expr>(Val); }
2779 void setSubExpr(Expr *E) { Val = E; }
2781 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
2782 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
2784 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
2785 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
2787 SourceLocation getRParenLoc() const { return RParenLoc; }
2788 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2790 virtual SourceRange getSourceRange() const {
2791 return SourceRange(BuiltinLoc, RParenLoc);
2793 static bool classof(const Stmt *T) {
2794 return T->getStmtClass() == VAArgExprClass;
2796 static bool classof(const VAArgExpr *) { return true; }
2799 virtual child_iterator child_begin();
2800 virtual child_iterator child_end();
2803 /// @brief Describes an C or C++ initializer list.
2805 /// InitListExpr describes an initializer list, which can be used to
2806 /// initialize objects of different types, including
2807 /// struct/class/union types, arrays, and vectors. For example:
2810 /// struct foo x = { 1, { 2, 3 } };
2813 /// Prior to semantic analysis, an initializer list will represent the
2814 /// initializer list as written by the user, but will have the
2815 /// placeholder type "void". This initializer list is called the
2816 /// syntactic form of the initializer, and may contain C99 designated
2817 /// initializers (represented as DesignatedInitExprs), initializations
2818 /// of subobject members without explicit braces, and so on. Clients
2819 /// interested in the original syntax of the initializer list should
2820 /// use the syntactic form of the initializer list.
2822 /// After semantic analysis, the initializer list will represent the
2823 /// semantic form of the initializer, where the initializations of all
2824 /// subobjects are made explicit with nested InitListExpr nodes and
2825 /// C99 designators have been eliminated by placing the designated
2826 /// initializations into the subobject they initialize. Additionally,
2827 /// any "holes" in the initialization, where no initializer has been
2828 /// specified for a particular subobject, will be replaced with
2829 /// implicitly-generated ImplicitValueInitExpr expressions that
2830 /// value-initialize the subobjects. Note, however, that the
2831 /// initializer lists may still have fewer initializers than there are
2832 /// elements to initialize within the object.
2834 /// Given the semantic form of the initializer list, one can retrieve
2835 /// the original syntactic form of that initializer list (if it
2836 /// exists) using getSyntacticForm(). Since many initializer lists
2837 /// have the same syntactic and semantic forms, getSyntacticForm() may
2838 /// return NULL, indicating that the current initializer list also
2839 /// serves as its syntactic form.
2840 class InitListExpr : public Expr {
2841 // FIXME: Eliminate this vector in favor of ASTContext allocation
2842 typedef ASTVector<Stmt *> InitExprsTy;
2843 InitExprsTy InitExprs;
2844 SourceLocation LBraceLoc, RBraceLoc;
2846 /// Contains the initializer list that describes the syntactic form
2847 /// written in the source code.
2848 InitListExpr *SyntacticForm;
2850 /// If this initializer list initializes a union, specifies which
2851 /// field within the union will be initialized.
2852 FieldDecl *UnionFieldInit;
2854 /// Whether this initializer list originally had a GNU array-range
2855 /// designator in it. This is a temporary marker used by CodeGen.
2856 bool HadArrayRangeDesignator;
2859 InitListExpr(ASTContext &C, SourceLocation lbraceloc,
2860 Expr **initexprs, unsigned numinits,
2861 SourceLocation rbraceloc);
2863 /// \brief Build an empty initializer list.
2864 explicit InitListExpr(ASTContext &C, EmptyShell Empty)
2865 : Expr(InitListExprClass, Empty), InitExprs(C) { }
2867 unsigned getNumInits() const { return InitExprs.size(); }
2869 const Expr* getInit(unsigned Init) const {
2870 assert(Init < getNumInits() && "Initializer access out of range!");
2871 return cast_or_null<Expr>(InitExprs[Init]);
2874 Expr* getInit(unsigned Init) {
2875 assert(Init < getNumInits() && "Initializer access out of range!");
2876 return cast_or_null<Expr>(InitExprs[Init]);
2879 void setInit(unsigned Init, Expr *expr) {
2880 assert(Init < getNumInits() && "Initializer access out of range!");
2881 InitExprs[Init] = expr;
2884 /// \brief Reserve space for some number of initializers.
2885 void reserveInits(ASTContext &C, unsigned NumInits);
2887 /// @brief Specify the number of initializers
2889 /// If there are more than @p NumInits initializers, the remaining
2890 /// initializers will be destroyed. If there are fewer than @p
2891 /// NumInits initializers, NULL expressions will be added for the
2892 /// unknown initializers.
2893 void resizeInits(ASTContext &Context, unsigned NumInits);
2895 /// @brief Updates the initializer at index @p Init with the new
2896 /// expression @p expr, and returns the old expression at that
2899 /// When @p Init is out of range for this initializer list, the
2900 /// initializer list will be extended with NULL expressions to
2901 /// accomodate the new entry.
2902 Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
2904 /// \brief If this initializes a union, specifies which field in the
2905 /// union to initialize.
2907 /// Typically, this field is the first named field within the
2908 /// union. However, a designated initializer can specify the
2909 /// initialization of a different field within the union.
2910 FieldDecl *getInitializedFieldInUnion() { return UnionFieldInit; }
2911 void setInitializedFieldInUnion(FieldDecl *FD) { UnionFieldInit = FD; }
2913 // Explicit InitListExpr's originate from source code (and have valid source
2914 // locations). Implicit InitListExpr's are created by the semantic analyzer.
2916 return LBraceLoc.isValid() && RBraceLoc.isValid();
2919 SourceLocation getLBraceLoc() const { return LBraceLoc; }
2920 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
2921 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2922 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
2924 /// @brief Retrieve the initializer list that describes the
2925 /// syntactic form of the initializer.
2928 InitListExpr *getSyntacticForm() const { return SyntacticForm; }
2929 void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
2931 bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
2932 void sawArrayRangeDesignator(bool ARD = true) {
2933 HadArrayRangeDesignator = ARD;
2936 virtual SourceRange getSourceRange() const {
2937 return SourceRange(LBraceLoc, RBraceLoc);
2939 static bool classof(const Stmt *T) {
2940 return T->getStmtClass() == InitListExprClass;
2942 static bool classof(const InitListExpr *) { return true; }
2945 virtual child_iterator child_begin();
2946 virtual child_iterator child_end();
2948 typedef InitExprsTy::iterator iterator;
2949 typedef InitExprsTy::const_iterator const_iterator;
2950 typedef InitExprsTy::reverse_iterator reverse_iterator;
2951 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
2953 iterator begin() { return InitExprs.begin(); }
2954 const_iterator begin() const { return InitExprs.begin(); }
2955 iterator end() { return InitExprs.end(); }
2956 const_iterator end() const { return InitExprs.end(); }
2957 reverse_iterator rbegin() { return InitExprs.rbegin(); }
2958 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
2959 reverse_iterator rend() { return InitExprs.rend(); }
2960 const_reverse_iterator rend() const { return InitExprs.rend(); }
2963 /// @brief Represents a C99 designated initializer expression.
2965 /// A designated initializer expression (C99 6.7.8) contains one or
2966 /// more designators (which can be field designators, array
2967 /// designators, or GNU array-range designators) followed by an
2968 /// expression that initializes the field or element(s) that the
2969 /// designators refer to. For example, given:
2976 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
2979 /// The InitListExpr contains three DesignatedInitExprs, the first of
2980 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
2981 /// designators, one array designator for @c [2] followed by one field
2982 /// designator for @c .y. The initalization expression will be 1.0.
2983 class DesignatedInitExpr : public Expr {
2985 /// \brief Forward declaration of the Designator class.
2989 /// The location of the '=' or ':' prior to the actual initializer
2991 SourceLocation EqualOrColonLoc;
2993 /// Whether this designated initializer used the GNU deprecated
2994 /// syntax rather than the C99 '=' syntax.
2997 /// The number of designators in this initializer expression.
2998 unsigned NumDesignators : 15;
3000 /// \brief The designators in this designated initialization
3002 Designator *Designators;
3004 /// The number of subexpressions of this initializer expression,
3005 /// which contains both the initializer and any additional
3006 /// expressions used by array and array-range designators.
3007 unsigned NumSubExprs : 16;
3010 DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3011 const Designator *Designators,
3012 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3013 Expr **IndexExprs, unsigned NumIndexExprs,
3016 explicit DesignatedInitExpr(unsigned NumSubExprs)
3017 : Expr(DesignatedInitExprClass, EmptyShell()),
3018 NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3021 /// A field designator, e.g., ".x".
3022 struct FieldDesignator {
3023 /// Refers to the field that is being initialized. The low bit
3024 /// of this field determines whether this is actually a pointer
3025 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3026 /// initially constructed, a field designator will store an
3027 /// IdentifierInfo*. After semantic analysis has resolved that
3028 /// name, the field designator will instead store a FieldDecl*.
3029 uintptr_t NameOrField;
3031 /// The location of the '.' in the designated initializer.
3034 /// The location of the field name in the designated initializer.
3038 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3039 struct ArrayOrRangeDesignator {
3040 /// Location of the first index expression within the designated
3041 /// initializer expression's list of subexpressions.
3043 /// The location of the '[' starting the array range designator.
3044 unsigned LBracketLoc;
3045 /// The location of the ellipsis separating the start and end
3046 /// indices. Only valid for GNU array-range designators.
3047 unsigned EllipsisLoc;
3048 /// The location of the ']' terminating the array range designator.
3049 unsigned RBracketLoc;
3052 /// @brief Represents a single C99 designator.
3054 /// @todo This class is infuriatingly similar to clang::Designator,
3055 /// but minor differences (storing indices vs. storing pointers)
3056 /// keep us from reusing it. Try harder, later, to rectify these
3059 /// @brief The kind of designator this describes.
3063 ArrayRangeDesignator
3067 /// A field designator, e.g., ".x".
3068 struct FieldDesignator Field;
3069 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3070 struct ArrayOrRangeDesignator ArrayOrRange;
3072 friend class DesignatedInitExpr;
3077 /// @brief Initializes a field designator.
3078 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3079 SourceLocation FieldLoc)
3080 : Kind(FieldDesignator) {
3081 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3082 Field.DotLoc = DotLoc.getRawEncoding();
3083 Field.FieldLoc = FieldLoc.getRawEncoding();
3086 /// @brief Initializes an array designator.
3087 Designator(unsigned Index, SourceLocation LBracketLoc,
3088 SourceLocation RBracketLoc)
3089 : Kind(ArrayDesignator) {
3090 ArrayOrRange.Index = Index;
3091 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3092 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3093 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3096 /// @brief Initializes a GNU array-range designator.
3097 Designator(unsigned Index, SourceLocation LBracketLoc,
3098 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3099 : Kind(ArrayRangeDesignator) {
3100 ArrayOrRange.Index = Index;
3101 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3102 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3103 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3106 bool isFieldDesignator() const { return Kind == FieldDesignator; }
3107 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3108 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3110 IdentifierInfo * getFieldName();
3112 FieldDecl *getField() {
3113 assert(Kind == FieldDesignator && "Only valid on a field designator");
3114 if (Field.NameOrField & 0x01)
3117 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3120 void setField(FieldDecl *FD) {
3121 assert(Kind == FieldDesignator && "Only valid on a field designator");
3122 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3125 SourceLocation getDotLoc() const {
3126 assert(Kind == FieldDesignator && "Only valid on a field designator");
3127 return SourceLocation::getFromRawEncoding(Field.DotLoc);
3130 SourceLocation getFieldLoc() const {
3131 assert(Kind == FieldDesignator && "Only valid on a field designator");
3132 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3135 SourceLocation getLBracketLoc() const {
3136 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3137 "Only valid on an array or array-range designator");
3138 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3141 SourceLocation getRBracketLoc() const {
3142 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3143 "Only valid on an array or array-range designator");
3144 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3147 SourceLocation getEllipsisLoc() const {
3148 assert(Kind == ArrayRangeDesignator &&
3149 "Only valid on an array-range designator");
3150 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3153 unsigned getFirstExprIndex() const {
3154 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3155 "Only valid on an array or array-range designator");
3156 return ArrayOrRange.Index;
3159 SourceLocation getStartLocation() const {
3160 if (Kind == FieldDesignator)
3161 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3163 return getLBracketLoc();
3167 static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3168 unsigned NumDesignators,
3169 Expr **IndexExprs, unsigned NumIndexExprs,
3170 SourceLocation EqualOrColonLoc,
3171 bool GNUSyntax, Expr *Init);
3173 static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3175 /// @brief Returns the number of designators in this initializer.
3176 unsigned size() const { return NumDesignators; }
3178 // Iterator access to the designators.
3179 typedef Designator* designators_iterator;
3180 designators_iterator designators_begin() { return Designators; }
3181 designators_iterator designators_end() {
3182 return Designators + NumDesignators;
3185 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3187 void setDesignators(ASTContext &C, const Designator *Desigs,
3188 unsigned NumDesigs);
3190 Expr *getArrayIndex(const Designator& D);
3191 Expr *getArrayRangeStart(const Designator& D);
3192 Expr *getArrayRangeEnd(const Designator& D);
3194 /// @brief Retrieve the location of the '=' that precedes the
3195 /// initializer value itself, if present.
3196 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3197 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3199 /// @brief Determines whether this designated initializer used the
3200 /// deprecated GNU syntax for designated initializers.
3201 bool usesGNUSyntax() const { return GNUSyntax; }
3202 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3204 /// @brief Retrieve the initializer value.
3205 Expr *getInit() const {
3206 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3209 void setInit(Expr *init) {
3210 *child_begin() = init;
3213 /// \brief Retrieve the total number of subexpressions in this
3214 /// designated initializer expression, including the actual
3215 /// initialized value and any expressions that occur within array
3216 /// and array-range designators.
3217 unsigned getNumSubExprs() const { return NumSubExprs; }
3219 Expr *getSubExpr(unsigned Idx) {
3220 assert(Idx < NumSubExprs && "Subscript out of range");
3221 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3222 Ptr += sizeof(DesignatedInitExpr);
3223 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3226 void setSubExpr(unsigned Idx, Expr *E) {
3227 assert(Idx < NumSubExprs && "Subscript out of range");
3228 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3229 Ptr += sizeof(DesignatedInitExpr);
3230 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3233 /// \brief Replaces the designator at index @p Idx with the series
3234 /// of designators in [First, Last).
3235 void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3236 const Designator *Last);
3238 virtual SourceRange getSourceRange() const;
3240 static bool classof(const Stmt *T) {
3241 return T->getStmtClass() == DesignatedInitExprClass;
3243 static bool classof(const DesignatedInitExpr *) { return true; }
3246 virtual child_iterator child_begin();
3247 virtual child_iterator child_end();
3250 /// \brief Represents an implicitly-generated value initialization of
3251 /// an object of a given type.
3253 /// Implicit value initializations occur within semantic initializer
3254 /// list expressions (InitListExpr) as placeholders for subobject
3255 /// initializations not explicitly specified by the user.
3257 /// \see InitListExpr
3258 class ImplicitValueInitExpr : public Expr {
3260 explicit ImplicitValueInitExpr(QualType ty)
3261 : Expr(ImplicitValueInitExprClass, ty, false, false) { }
3263 /// \brief Construct an empty implicit value initialization.
3264 explicit ImplicitValueInitExpr(EmptyShell Empty)
3265 : Expr(ImplicitValueInitExprClass, Empty) { }
3267 static bool classof(const Stmt *T) {
3268 return T->getStmtClass() == ImplicitValueInitExprClass;
3270 static bool classof(const ImplicitValueInitExpr *) { return true; }
3272 virtual SourceRange getSourceRange() const {
3273 return SourceRange();
3277 virtual child_iterator child_begin();
3278 virtual child_iterator child_end();
3282 class ParenListExpr : public Expr {
3285 SourceLocation LParenLoc, RParenLoc;
3288 ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3289 unsigned numexprs, SourceLocation rparenloc);
3291 /// \brief Build an empty paren list.
3292 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3294 unsigned getNumExprs() const { return NumExprs; }
3296 const Expr* getExpr(unsigned Init) const {
3297 assert(Init < getNumExprs() && "Initializer access out of range!");
3298 return cast_or_null<Expr>(Exprs[Init]);
3301 Expr* getExpr(unsigned Init) {
3302 assert(Init < getNumExprs() && "Initializer access out of range!");
3303 return cast_or_null<Expr>(Exprs[Init]);
3306 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3308 SourceLocation getLParenLoc() const { return LParenLoc; }
3309 SourceLocation getRParenLoc() const { return RParenLoc; }
3311 virtual SourceRange getSourceRange() const {
3312 return SourceRange(LParenLoc, RParenLoc);
3314 static bool classof(const Stmt *T) {
3315 return T->getStmtClass() == ParenListExprClass;
3317 static bool classof(const ParenListExpr *) { return true; }
3320 virtual child_iterator child_begin();
3321 virtual child_iterator child_end();
3323 friend class ASTStmtReader;
3324 friend class ASTStmtWriter;
3328 //===----------------------------------------------------------------------===//
3330 //===----------------------------------------------------------------------===//
3333 /// ExtVectorElementExpr - This represents access to specific elements of a
3334 /// vector, and may occur on the left hand side or right hand side. For example
3335 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
3337 /// Note that the base may have either vector or pointer to vector type, just
3338 /// like a struct field reference.
3340 class ExtVectorElementExpr : public Expr {
3342 IdentifierInfo *Accessor;
3343 SourceLocation AccessorLoc;
3345 ExtVectorElementExpr(QualType ty, Expr *base, IdentifierInfo &accessor,
3347 : Expr(ExtVectorElementExprClass, ty, base->isTypeDependent(),
3348 base->isValueDependent()),
3349 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3351 /// \brief Build an empty vector element expression.
3352 explicit ExtVectorElementExpr(EmptyShell Empty)
3353 : Expr(ExtVectorElementExprClass, Empty) { }
3355 const Expr *getBase() const { return cast<Expr>(Base); }
3356 Expr *getBase() { return cast<Expr>(Base); }
3357 void setBase(Expr *E) { Base = E; }
3359 IdentifierInfo &getAccessor() const { return *Accessor; }
3360 void setAccessor(IdentifierInfo *II) { Accessor = II; }
3362 SourceLocation getAccessorLoc() const { return AccessorLoc; }
3363 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
3365 /// getNumElements - Get the number of components being selected.
3366 unsigned getNumElements() const;
3368 /// containsDuplicateElements - Return true if any element access is
3370 bool containsDuplicateElements() const;
3372 /// getEncodedElementAccess - Encode the elements accessed into an llvm
3373 /// aggregate Constant of ConstantInt(s).
3374 void getEncodedElementAccess(llvm::SmallVectorImpl<unsigned> &Elts) const;
3376 virtual SourceRange getSourceRange() const {
3377 return SourceRange(getBase()->getLocStart(), AccessorLoc);
3380 /// isArrow - Return true if the base expression is a pointer to vector,
3381 /// return false if the base expression is a vector.
3382 bool isArrow() const;
3384 static bool classof(const Stmt *T) {
3385 return T->getStmtClass() == ExtVectorElementExprClass;
3387 static bool classof(const ExtVectorElementExpr *) { return true; }
3390 virtual child_iterator child_begin();
3391 virtual child_iterator child_end();
3395 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
3396 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3397 class BlockExpr : public Expr {
3399 BlockDecl *TheBlock;
3400 bool HasBlockDeclRefExprs;
3402 BlockExpr(BlockDecl *BD, QualType ty, bool hasBlockDeclRefExprs)
3403 : Expr(BlockExprClass, ty, ty->isDependentType(), false),
3404 TheBlock(BD), HasBlockDeclRefExprs(hasBlockDeclRefExprs) {}
3406 /// \brief Build an empty block expression.
3407 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
3409 const BlockDecl *getBlockDecl() const { return TheBlock; }
3410 BlockDecl *getBlockDecl() { return TheBlock; }
3411 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
3413 // Convenience functions for probing the underlying BlockDecl.
3414 SourceLocation getCaretLocation() const;
3415 const Stmt *getBody() const;
3418 virtual SourceRange getSourceRange() const {
3419 return SourceRange(getCaretLocation(), getBody()->getLocEnd());
3422 /// getFunctionType - Return the underlying function type for this block.
3423 const FunctionType *getFunctionType() const;
3425 /// hasBlockDeclRefExprs - Return true iff the block has BlockDeclRefExpr
3426 /// inside of the block that reference values outside the block.
3427 bool hasBlockDeclRefExprs() const { return HasBlockDeclRefExprs; }
3428 void setHasBlockDeclRefExprs(bool BDRE) { HasBlockDeclRefExprs = BDRE; }
3430 static bool classof(const Stmt *T) {
3431 return T->getStmtClass() == BlockExprClass;
3433 static bool classof(const BlockExpr *) { return true; }
3436 virtual child_iterator child_begin();
3437 virtual child_iterator child_end();
3440 /// BlockDeclRefExpr - A reference to a declared variable, function,
3442 class BlockDeclRefExpr : public Expr {
3446 bool ConstQualAdded : 1;
3447 Stmt *CopyConstructorVal;
3449 // FIXME: Fix type/value dependence!
3450 BlockDeclRefExpr(ValueDecl *d, QualType t, SourceLocation l, bool ByRef,
3451 bool constAdded = false,
3452 Stmt *copyConstructorVal = 0)
3453 : Expr(BlockDeclRefExprClass, t, (!t.isNull() && t->isDependentType()),false),
3454 D(d), Loc(l), IsByRef(ByRef),
3455 ConstQualAdded(constAdded), CopyConstructorVal(copyConstructorVal) {}
3457 // \brief Build an empty reference to a declared variable in a
3459 explicit BlockDeclRefExpr(EmptyShell Empty)
3460 : Expr(BlockDeclRefExprClass, Empty) { }
3462 ValueDecl *getDecl() { return D; }
3463 const ValueDecl *getDecl() const { return D; }
3464 void setDecl(ValueDecl *VD) { D = VD; }
3466 SourceLocation getLocation() const { return Loc; }
3467 void setLocation(SourceLocation L) { Loc = L; }
3469 virtual SourceRange getSourceRange() const { return SourceRange(Loc); }
3471 bool isByRef() const { return IsByRef; }
3472 void setByRef(bool BR) { IsByRef = BR; }
3474 bool isConstQualAdded() const { return ConstQualAdded; }
3475 void setConstQualAdded(bool C) { ConstQualAdded = C; }
3477 const Expr *getCopyConstructorExpr() const
3478 { return cast_or_null<Expr>(CopyConstructorVal); }
3479 Expr *getCopyConstructorExpr()
3480 { return cast_or_null<Expr>(CopyConstructorVal); }
3481 void setCopyConstructorExpr(Expr *E) { CopyConstructorVal = E; }
3483 static bool classof(const Stmt *T) {
3484 return T->getStmtClass() == BlockDeclRefExprClass;
3486 static bool classof(const BlockDeclRefExpr *) { return true; }
3489 virtual child_iterator child_begin();
3490 virtual child_iterator child_end();
3493 } // end namespace clang