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/TemplateBase.h"
24 #include "clang/AST/UsuallyTinyPtrVector.h"
25 #include "clang/Basic/TypeTraits.h"
26 #include "llvm/ADT/APSInt.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.h"
41 class CXXBaseSpecifier;
42 class CXXOperatorCallExpr;
43 class CXXMemberCallExpr;
44 class ObjCPropertyRefExpr;
45 class OpaqueValueExpr;
47 /// \brief A simple array of base specifiers.
48 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
50 /// Expr - This represents one expression. Note that Expr's are subclasses of
51 /// Stmt. This allows an expression to be transparently used any place a Stmt
54 class Expr : public Stmt {
58 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
59 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
62 ExprBits.TypeDependent = TD;
63 ExprBits.ValueDependent = VD;
64 ExprBits.InstantiationDependent = ID;
65 ExprBits.ValueKind = VK;
66 ExprBits.ObjectKind = OK;
67 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
71 /// \brief Construct an empty expression.
72 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
75 QualType getType() const { return TR; }
76 void setType(QualType t) {
77 // In C++, the type of an expression is always adjusted so that it
78 // will not have reference type an expression will never have
79 // reference type (C++ [expr]p6). Use
80 // QualType::getNonReferenceType() to retrieve the non-reference
81 // type. Additionally, inspect Expr::isLvalue to determine whether
82 // an expression that is adjusted in this manner should be
83 // considered an lvalue.
84 assert((t.isNull() || !t->isReferenceType()) &&
85 "Expressions can't have reference type");
90 /// isValueDependent - Determines whether this expression is
91 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
92 /// array bound of "Chars" in the following example is
95 /// template<int Size, char (&Chars)[Size]> struct meta_string;
97 bool isValueDependent() const { return ExprBits.ValueDependent; }
99 /// \brief Set whether this expression is value-dependent or not.
100 void setValueDependent(bool VD) {
101 ExprBits.ValueDependent = VD;
103 ExprBits.InstantiationDependent = true;
106 /// isTypeDependent - Determines whether this expression is
107 /// type-dependent (C++ [temp.dep.expr]), which means that its type
108 /// could change from one template instantiation to the next. For
109 /// example, the expressions "x" and "x + y" are type-dependent in
110 /// the following code, but "y" is not type-dependent:
112 /// template<typename T>
113 /// void add(T x, int y) {
117 bool isTypeDependent() const { return ExprBits.TypeDependent; }
119 /// \brief Set whether this expression is type-dependent or not.
120 void setTypeDependent(bool TD) {
121 ExprBits.TypeDependent = TD;
123 ExprBits.InstantiationDependent = true;
126 /// \brief Whether this expression is instantiation-dependent, meaning that
127 /// it depends in some way on a template parameter, even if neither its type
128 /// nor (constant) value can change due to the template instantiation.
130 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
131 /// instantiation-dependent (since it involves a template parameter \c T), but
132 /// is neither type- nor value-dependent, since the type of the inner
133 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
134 /// \c sizeof is known.
137 /// template<typename T>
138 /// void f(T x, T y) {
139 /// sizeof(sizeof(T() + T());
143 bool isInstantiationDependent() const {
144 return ExprBits.InstantiationDependent;
147 /// \brief Set whether this expression is instantiation-dependent or not.
148 void setInstantiationDependent(bool ID) {
149 ExprBits.InstantiationDependent = ID;
152 /// \brief Whether this expression contains an unexpanded parameter
153 /// pack (for C++0x variadic templates).
155 /// Given the following function template:
158 /// template<typename F, typename ...Types>
159 /// void forward(const F &f, Types &&...args) {
160 /// f(static_cast<Types&&>(args)...);
164 /// The expressions \c args and \c static_cast<Types&&>(args) both
165 /// contain parameter packs.
166 bool containsUnexpandedParameterPack() const {
167 return ExprBits.ContainsUnexpandedParameterPack;
170 /// \brief Set the bit that describes whether this expression
171 /// contains an unexpanded parameter pack.
172 void setContainsUnexpandedParameterPack(bool PP = true) {
173 ExprBits.ContainsUnexpandedParameterPack = PP;
176 /// getExprLoc - Return the preferred location for the arrow when diagnosing
177 /// a problem with a generic expression.
178 SourceLocation getExprLoc() const;
180 /// isUnusedResultAWarning - Return true if this immediate expression should
181 /// be warned about if the result is unused. If so, fill in Loc and Ranges
182 /// with location to warn on and the source range[s] to report with the
184 bool isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
185 SourceRange &R2, ASTContext &Ctx) const;
187 /// isLValue - True if this expression is an "l-value" according to
188 /// the rules of the current language. C and C++ give somewhat
189 /// different rules for this concept, but in general, the result of
190 /// an l-value expression identifies a specific object whereas the
191 /// result of an r-value expression is a value detached from any
192 /// specific storage.
194 /// C++0x divides the concept of "r-value" into pure r-values
195 /// ("pr-values") and so-called expiring values ("x-values"), which
196 /// identify specific objects that can be safely cannibalized for
197 /// their resources. This is an unfortunate abuse of terminology on
198 /// the part of the C++ committee. In Clang, when we say "r-value",
199 /// we generally mean a pr-value.
200 bool isLValue() const { return getValueKind() == VK_LValue; }
201 bool isRValue() const { return getValueKind() == VK_RValue; }
202 bool isXValue() const { return getValueKind() == VK_XValue; }
203 bool isGLValue() const { return getValueKind() != VK_RValue; }
205 enum LValueClassification {
208 LV_IncompleteVoidType,
209 LV_DuplicateVectorComponents,
210 LV_InvalidExpression,
211 LV_InvalidMessageExpression,
213 LV_SubObjCPropertySetting,
216 /// Reasons why an expression might not be an l-value.
217 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
219 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
220 /// does not have an incomplete type, does not have a const-qualified type,
221 /// and if it is a structure or union, does not have any member (including,
222 /// recursively, any member or element of all contained aggregates or unions)
223 /// with a const-qualified type.
225 /// \param Loc [in] [out] - A source location which *may* be filled
226 /// in with the location of the expression making this a
227 /// non-modifiable lvalue, if specified.
228 enum isModifiableLvalueResult {
231 MLV_IncompleteVoidType,
232 MLV_DuplicateVectorComponents,
233 MLV_InvalidExpression,
234 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
238 MLV_NotBlockQualified,
239 MLV_ReadonlyProperty,
240 MLV_NoSetterProperty,
242 MLV_SubObjCPropertySetting,
243 MLV_InvalidMessageExpression,
246 isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
247 SourceLocation *Loc = 0) const;
249 /// \brief The return type of classify(). Represents the C++0x expression
251 class Classification {
253 /// \brief The various classification results. Most of these mean prvalue.
257 CL_Function, // Functions cannot be lvalues in C.
258 CL_Void, // Void cannot be an lvalue in C.
259 CL_AddressableVoid, // Void expression whose address can be taken in C.
260 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
261 CL_MemberFunction, // An expression referring to a member function
262 CL_SubObjCPropertySetting,
263 CL_ClassTemporary, // A prvalue of class type
264 CL_ObjCMessageRValue, // ObjC message is an rvalue
265 CL_PRValue // A prvalue for any other reason, of any other type
267 /// \brief The results of modification testing.
268 enum ModifiableType {
269 CM_Untested, // testModifiable was false.
271 CM_RValue, // Not modifiable because it's an rvalue
272 CM_Function, // Not modifiable because it's a function; C++ only
273 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
274 CM_NotBlockQualified, // Not captured in the closure
275 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
285 unsigned short Modifiable;
287 explicit Classification(Kinds k, ModifiableType m)
288 : Kind(k), Modifiable(m)
294 Kinds getKind() const { return static_cast<Kinds>(Kind); }
295 ModifiableType getModifiable() const {
296 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
297 return static_cast<ModifiableType>(Modifiable);
299 bool isLValue() const { return Kind == CL_LValue; }
300 bool isXValue() const { return Kind == CL_XValue; }
301 bool isGLValue() const { return Kind <= CL_XValue; }
302 bool isPRValue() const { return Kind >= CL_Function; }
303 bool isRValue() const { return Kind >= CL_XValue; }
304 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
306 /// \brief Create a simple, modifiably lvalue
307 static Classification makeSimpleLValue() {
308 return Classification(CL_LValue, CM_Modifiable);
312 /// \brief Classify - Classify this expression according to the C++0x
313 /// expression taxonomy.
315 /// C++0x defines ([basic.lval]) a new taxonomy of expressions to replace the
316 /// old lvalue vs rvalue. This function determines the type of expression this
317 /// is. There are three expression types:
318 /// - lvalues are classical lvalues as in C++03.
319 /// - prvalues are equivalent to rvalues in C++03.
320 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
321 /// function returning an rvalue reference.
322 /// lvalues and xvalues are collectively referred to as glvalues, while
323 /// prvalues and xvalues together form rvalues.
324 Classification Classify(ASTContext &Ctx) const {
325 return ClassifyImpl(Ctx, 0);
328 /// \brief ClassifyModifiable - Classify this expression according to the
329 /// C++0x expression taxonomy, and see if it is valid on the left side
330 /// of an assignment.
332 /// This function extends classify in that it also tests whether the
333 /// expression is modifiable (C99 6.3.2.1p1).
334 /// \param Loc A source location that might be filled with a relevant location
335 /// if the expression is not modifiable.
336 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
337 return ClassifyImpl(Ctx, &Loc);
340 /// getValueKindForType - Given a formal return or parameter type,
341 /// give its value kind.
342 static ExprValueKind getValueKindForType(QualType T) {
343 if (const ReferenceType *RT = T->getAs<ReferenceType>())
344 return (isa<LValueReferenceType>(RT)
346 : (RT->getPointeeType()->isFunctionType()
347 ? VK_LValue : VK_XValue));
351 /// getValueKind - The value kind that this expression produces.
352 ExprValueKind getValueKind() const {
353 return static_cast<ExprValueKind>(ExprBits.ValueKind);
356 /// getObjectKind - The object kind that this expression produces.
357 /// Object kinds are meaningful only for expressions that yield an
358 /// l-value or x-value.
359 ExprObjectKind getObjectKind() const {
360 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
363 bool isOrdinaryOrBitFieldObject() const {
364 ExprObjectKind OK = getObjectKind();
365 return (OK == OK_Ordinary || OK == OK_BitField);
368 /// setValueKind - Set the value kind produced by this expression.
369 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
371 /// setObjectKind - Set the object kind produced by this expression.
372 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
375 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
379 /// \brief If this expression refers to a bit-field, retrieve the
380 /// declaration of that bit-field.
381 FieldDecl *getBitField();
383 const FieldDecl *getBitField() const {
384 return const_cast<Expr*>(this)->getBitField();
387 /// \brief If this expression is an l-value for an Objective C
388 /// property, find the underlying property reference expression.
389 const ObjCPropertyRefExpr *getObjCProperty() const;
391 /// \brief Returns whether this expression refers to a vector element.
392 bool refersToVectorElement() const;
394 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
395 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
396 /// but also int expressions which are produced by things like comparisons in
398 bool isKnownToHaveBooleanValue() const;
400 /// isIntegerConstantExpr - Return true if this expression is a valid integer
401 /// constant expression, and, if so, return its value in Result. If not a
402 /// valid i-c-e, return false and fill in Loc (if specified) with the location
403 /// of the invalid expression.
404 bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
405 SourceLocation *Loc = 0,
406 bool isEvaluated = true) const;
407 bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc = 0) const {
409 return isIntegerConstantExpr(X, Ctx, Loc);
411 /// isConstantInitializer - Returns true if this expression is a constant
412 /// initializer, which can be emitted at compile-time.
413 bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
415 /// EvalResult is a struct with detailed info about an evaluated expression.
417 /// Val - This is the value the expression can be folded to.
420 /// HasSideEffects - Whether the evaluated expression has side effects.
421 /// For example, (f() && 0) can be folded, but it still has side effects.
424 /// Diag - If the expression is unfoldable, then Diag contains a note
425 /// diagnostic indicating why it's not foldable. DiagLoc indicates a caret
426 /// position for the error, and DiagExpr is the expression that caused
428 /// If the expression is foldable, but not an integer constant expression,
429 /// Diag contains a note diagnostic that describes why it isn't an integer
430 /// constant expression. If the expression *is* an integer constant
431 /// expression, then Diag will be zero.
433 const Expr *DiagExpr;
434 SourceLocation DiagLoc;
436 EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
438 // isGlobalLValue - Return true if the evaluated lvalue expression
440 bool isGlobalLValue() const;
441 // hasSideEffects - Return true if the evaluated expression has
443 bool hasSideEffects() const {
444 return HasSideEffects;
448 /// Evaluate - Return true if this is a constant which we can fold using
449 /// any crazy technique (that has nothing to do with language standards) that
450 /// we want to. If this function returns true, it returns the folded constant
452 bool Evaluate(EvalResult &Result, const ASTContext &Ctx) const;
454 /// EvaluateAsBooleanCondition - Return true if this is a constant
455 /// which we we can fold and convert to a boolean condition using
456 /// any crazy technique that we want to, even if the expression has
458 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
460 /// EvaluateAsInt - Return true if this is a constant which we can fold and
461 /// convert to an integer using any crazy technique that we want to.
462 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx) const;
464 /// isEvaluatable - Call Evaluate to see if this expression can be constant
465 /// folded, but discard the result.
466 bool isEvaluatable(const ASTContext &Ctx) const;
468 /// HasSideEffects - This routine returns true for all those expressions
469 /// which must be evaluated each time and must not be optimized away
470 /// or evaluated at compile time. Example is a function call, volatile
472 bool HasSideEffects(const ASTContext &Ctx) const;
474 /// EvaluateKnownConstInt - Call Evaluate and return the folded integer. This
475 /// must be called on an expression that constant folds to an integer.
476 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const;
478 /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
479 /// with link time known address.
480 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
482 /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
483 bool EvaluateAsAnyLValue(EvalResult &Result, const ASTContext &Ctx) const;
485 /// \brief Enumeration used to describe the kind of Null pointer constant
486 /// returned from \c isNullPointerConstant().
487 enum NullPointerConstantKind {
488 /// \brief Expression is not a Null pointer constant.
491 /// \brief Expression is a Null pointer constant built from a zero integer.
494 /// \brief Expression is a C++0X nullptr.
497 /// \brief Expression is a GNU-style __null constant.
501 /// \brief Enumeration used to describe how \c isNullPointerConstant()
502 /// should cope with value-dependent expressions.
503 enum NullPointerConstantValueDependence {
504 /// \brief Specifies that the expression should never be value-dependent.
505 NPC_NeverValueDependent = 0,
507 /// \brief Specifies that a value-dependent expression of integral or
508 /// dependent type should be considered a null pointer constant.
509 NPC_ValueDependentIsNull,
511 /// \brief Specifies that a value-dependent expression should be considered
512 /// to never be a null pointer constant.
513 NPC_ValueDependentIsNotNull
516 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
517 /// a Null pointer constant. The return value can further distinguish the
518 /// kind of NULL pointer constant that was detected.
519 NullPointerConstantKind isNullPointerConstant(
521 NullPointerConstantValueDependence NPC) const;
523 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
525 bool isOBJCGCCandidate(ASTContext &Ctx) const;
527 /// \brief Returns true if this expression is a bound member function.
528 bool isBoundMemberFunction(ASTContext &Ctx) const;
530 /// \brief Given an expression of bound-member type, find the type
531 /// of the member. Returns null if this is an *overloaded* bound
532 /// member expression.
533 static QualType findBoundMemberType(const Expr *expr);
535 /// \brief Result type of CanThrow().
536 enum CanThrowResult {
541 /// \brief Test if this expression, if evaluated, might throw, according to
542 /// the rules of C++ [expr.unary.noexcept].
543 CanThrowResult CanThrow(ASTContext &C) const;
545 /// IgnoreImpCasts - Skip past any implicit casts which might
546 /// surround this expression. Only skips ImplicitCastExprs.
547 Expr *IgnoreImpCasts();
549 /// IgnoreImplicit - Skip past any implicit AST nodes which might
550 /// surround this expression.
551 Expr *IgnoreImplicit() { return cast<Expr>(Stmt::IgnoreImplicit()); }
553 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
554 /// its subexpression. If that subexpression is also a ParenExpr,
555 /// then this method recursively returns its subexpression, and so forth.
556 /// Otherwise, the method returns the current Expr.
557 Expr *IgnoreParens();
559 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
560 /// or CastExprs, returning their operand.
561 Expr *IgnoreParenCasts();
563 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off any
564 /// ParenExpr or ImplicitCastExprs, returning their operand.
565 Expr *IgnoreParenImpCasts();
567 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
568 /// call to a conversion operator, return the argument.
569 Expr *IgnoreConversionOperator();
571 const Expr *IgnoreConversionOperator() const {
572 return const_cast<Expr*>(this)->IgnoreConversionOperator();
575 const Expr *IgnoreParenImpCasts() const {
576 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
579 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
580 /// CastExprs that represent lvalue casts, returning their operand.
581 Expr *IgnoreParenLValueCasts();
583 const Expr *IgnoreParenLValueCasts() const {
584 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
587 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
588 /// value (including ptr->int casts of the same size). Strip off any
589 /// ParenExpr or CastExprs, returning their operand.
590 Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
592 /// \brief Determine whether this expression is a default function argument.
594 /// Default arguments are implicitly generated in the abstract syntax tree
595 /// by semantic analysis for function calls, object constructions, etc. in
596 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
597 /// this routine also looks through any implicit casts to determine whether
598 /// the expression is a default argument.
599 bool isDefaultArgument() const;
601 /// \brief Determine whether the result of this expression is a
602 /// temporary object of the given class type.
603 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
605 /// \brief Whether this expression is an implicit reference to 'this' in C++.
606 bool isImplicitCXXThis() const;
608 const Expr *IgnoreImpCasts() const {
609 return const_cast<Expr*>(this)->IgnoreImpCasts();
611 const Expr *IgnoreParens() const {
612 return const_cast<Expr*>(this)->IgnoreParens();
614 const Expr *IgnoreParenCasts() const {
615 return const_cast<Expr*>(this)->IgnoreParenCasts();
617 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
618 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
621 static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs);
622 static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs);
624 static bool classof(const Stmt *T) {
625 return T->getStmtClass() >= firstExprConstant &&
626 T->getStmtClass() <= lastExprConstant;
628 static bool classof(const Expr *) { return true; }
632 //===----------------------------------------------------------------------===//
633 // Primary Expressions.
634 //===----------------------------------------------------------------------===//
636 /// OpaqueValueExpr - An expression referring to an opaque object of a
637 /// fixed type and value class. These don't correspond to concrete
638 /// syntax; instead they're used to express operations (usually copy
639 /// operations) on values whose source is generally obvious from
641 class OpaqueValueExpr : public Expr {
642 friend class ASTStmtReader;
647 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
648 ExprObjectKind OK = OK_Ordinary)
649 : Expr(OpaqueValueExprClass, T, VK, OK,
650 T->isDependentType(), T->isDependentType(),
651 T->isInstantiationDependentType(),
653 SourceExpr(0), Loc(Loc) {
656 /// Given an expression which invokes a copy constructor --- i.e. a
657 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
658 /// find the OpaqueValueExpr that's the source of the construction.
659 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
661 explicit OpaqueValueExpr(EmptyShell Empty)
662 : Expr(OpaqueValueExprClass, Empty) { }
664 /// \brief Retrieve the location of this expression.
665 SourceLocation getLocation() const { return Loc; }
667 SourceRange getSourceRange() const {
668 if (SourceExpr) return SourceExpr->getSourceRange();
671 SourceLocation getExprLoc() const {
672 if (SourceExpr) return SourceExpr->getExprLoc();
676 child_range children() { return child_range(); }
678 /// The source expression of an opaque value expression is the
679 /// expression which originally generated the value. This is
680 /// provided as a convenience for analyses that don't wish to
681 /// precisely model the execution behavior of the program.
683 /// The source expression is typically set when building the
684 /// expression which binds the opaque value expression in the first
686 Expr *getSourceExpr() const { return SourceExpr; }
687 void setSourceExpr(Expr *e) { SourceExpr = e; }
689 static bool classof(const Stmt *T) {
690 return T->getStmtClass() == OpaqueValueExprClass;
692 static bool classof(const OpaqueValueExpr *) { return true; }
695 /// \brief A reference to a declared variable, function, enum, etc.
698 /// This encodes all the information about how a declaration is referenced
699 /// within an expression.
701 /// There are several optional constructs attached to DeclRefExprs only when
702 /// they apply in order to conserve memory. These are laid out past the end of
703 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
705 /// DeclRefExprBits.HasQualifier:
706 /// Specifies when this declaration reference expression has a C++
707 /// nested-name-specifier.
708 /// DeclRefExprBits.HasFoundDecl:
709 /// Specifies when this declaration reference expression has a record of
710 /// a NamedDecl (different from the referenced ValueDecl) which was found
711 /// during name lookup and/or overload resolution.
712 /// DeclRefExprBits.HasExplicitTemplateArgs:
713 /// Specifies when this declaration reference expression has an explicit
714 /// C++ template argument list.
715 class DeclRefExpr : public Expr {
716 /// \brief The declaration that we are referencing.
719 /// \brief The location of the declaration name itself.
722 /// \brief Provides source/type location info for the declaration name
724 DeclarationNameLoc DNLoc;
726 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
727 NestedNameSpecifierLoc &getInternalQualifierLoc() {
728 assert(hasQualifier());
729 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
732 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
733 const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
734 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
737 /// \brief Test whether there is a distinct FoundDecl attached to the end of
739 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
741 /// \brief Helper to retrieve the optional NamedDecl through which this
742 /// reference occured.
743 NamedDecl *&getInternalFoundDecl() {
744 assert(hasFoundDecl());
746 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
747 return *reinterpret_cast<NamedDecl **>(this + 1);
750 /// \brief Helper to retrieve the optional NamedDecl through which this
751 /// reference occured.
752 NamedDecl *getInternalFoundDecl() const {
753 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
756 DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
757 ValueDecl *D, const DeclarationNameInfo &NameInfo,
759 const TemplateArgumentListInfo *TemplateArgs,
760 QualType T, ExprValueKind VK);
762 /// \brief Construct an empty declaration reference expression.
763 explicit DeclRefExpr(EmptyShell Empty)
764 : Expr(DeclRefExprClass, Empty) { }
766 /// \brief Computes the type- and value-dependence flags for this
767 /// declaration reference expression.
768 void computeDependence();
771 DeclRefExpr(ValueDecl *D, QualType T, ExprValueKind VK, SourceLocation L,
772 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
773 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
774 D(D), Loc(L), DNLoc(LocInfo) {
775 DeclRefExprBits.HasQualifier = 0;
776 DeclRefExprBits.HasExplicitTemplateArgs = 0;
777 DeclRefExprBits.HasFoundDecl = 0;
778 DeclRefExprBits.HadMultipleCandidates = 0;
782 static DeclRefExpr *Create(ASTContext &Context,
783 NestedNameSpecifierLoc QualifierLoc,
785 SourceLocation NameLoc,
786 QualType T, ExprValueKind VK,
787 NamedDecl *FoundD = 0,
788 const TemplateArgumentListInfo *TemplateArgs = 0);
790 static DeclRefExpr *Create(ASTContext &Context,
791 NestedNameSpecifierLoc QualifierLoc,
793 const DeclarationNameInfo &NameInfo,
794 QualType T, ExprValueKind VK,
795 NamedDecl *FoundD = 0,
796 const TemplateArgumentListInfo *TemplateArgs = 0);
798 /// \brief Construct an empty declaration reference expression.
799 static DeclRefExpr *CreateEmpty(ASTContext &Context,
802 bool HasExplicitTemplateArgs,
803 unsigned NumTemplateArgs);
805 ValueDecl *getDecl() { return D; }
806 const ValueDecl *getDecl() const { return D; }
807 void setDecl(ValueDecl *NewD) { D = NewD; }
809 DeclarationNameInfo getNameInfo() const {
810 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
813 SourceLocation getLocation() const { return Loc; }
814 void setLocation(SourceLocation L) { Loc = L; }
815 SourceRange getSourceRange() const;
817 /// \brief Determine whether this declaration reference was preceded by a
818 /// C++ nested-name-specifier, e.g., \c N::foo.
819 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
821 /// \brief If the name was qualified, retrieves the nested-name-specifier
822 /// that precedes the name. Otherwise, returns NULL.
823 NestedNameSpecifier *getQualifier() const {
827 return getInternalQualifierLoc().getNestedNameSpecifier();
830 /// \brief If the name was qualified, retrieves the nested-name-specifier
831 /// that precedes the name, with source-location information.
832 NestedNameSpecifierLoc getQualifierLoc() const {
834 return NestedNameSpecifierLoc();
836 return getInternalQualifierLoc();
839 /// \brief Get the NamedDecl through which this reference occured.
841 /// This Decl may be different from the ValueDecl actually referred to in the
842 /// presence of using declarations, etc. It always returns non-NULL, and may
843 /// simple return the ValueDecl when appropriate.
844 NamedDecl *getFoundDecl() {
845 return hasFoundDecl() ? getInternalFoundDecl() : D;
848 /// \brief Get the NamedDecl through which this reference occurred.
849 /// See non-const variant.
850 const NamedDecl *getFoundDecl() const {
851 return hasFoundDecl() ? getInternalFoundDecl() : D;
854 /// \brief Determines whether this declaration reference was followed by an
855 /// explict template argument list.
856 bool hasExplicitTemplateArgs() const {
857 return DeclRefExprBits.HasExplicitTemplateArgs;
860 /// \brief Retrieve the explicit template argument list that followed the
861 /// member template name.
862 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
863 assert(hasExplicitTemplateArgs());
865 return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
866 &getInternalFoundDecl() + 1);
869 return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
870 &getInternalQualifierLoc() + 1);
872 return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
875 /// \brief Retrieve the explicit template argument list that followed the
876 /// member template name.
877 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
878 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
881 /// \brief Retrieves the optional explicit template arguments.
882 /// This points to the same data as getExplicitTemplateArgs(), but
883 /// returns null if there are no explicit template arguments.
884 const ASTTemplateArgumentListInfo *getExplicitTemplateArgsOpt() const {
885 if (!hasExplicitTemplateArgs()) return 0;
886 return &getExplicitTemplateArgs();
889 /// \brief Copies the template arguments (if present) into the given
891 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
892 if (hasExplicitTemplateArgs())
893 getExplicitTemplateArgs().copyInto(List);
896 /// \brief Retrieve the location of the left angle bracket following the
897 /// member name ('<'), if any.
898 SourceLocation getLAngleLoc() const {
899 if (!hasExplicitTemplateArgs())
900 return SourceLocation();
902 return getExplicitTemplateArgs().LAngleLoc;
905 /// \brief Retrieve the template arguments provided as part of this
907 const TemplateArgumentLoc *getTemplateArgs() const {
908 if (!hasExplicitTemplateArgs())
911 return getExplicitTemplateArgs().getTemplateArgs();
914 /// \brief Retrieve the number of template arguments provided as part of this
916 unsigned getNumTemplateArgs() const {
917 if (!hasExplicitTemplateArgs())
920 return getExplicitTemplateArgs().NumTemplateArgs;
923 /// \brief Retrieve the location of the right angle bracket following the
924 /// template arguments ('>').
925 SourceLocation getRAngleLoc() const {
926 if (!hasExplicitTemplateArgs())
927 return SourceLocation();
929 return getExplicitTemplateArgs().RAngleLoc;
932 /// \brief Returns true if this expression refers to a function that
933 /// was resolved from an overloaded set having size greater than 1.
934 bool hadMultipleCandidates() const {
935 return DeclRefExprBits.HadMultipleCandidates;
937 /// \brief Sets the flag telling whether this expression refers to
938 /// a function that was resolved from an overloaded set having size
940 void setHadMultipleCandidates(bool V = true) {
941 DeclRefExprBits.HadMultipleCandidates = V;
944 static bool classof(const Stmt *T) {
945 return T->getStmtClass() == DeclRefExprClass;
947 static bool classof(const DeclRefExpr *) { return true; }
950 child_range children() { return child_range(); }
952 friend class ASTStmtReader;
953 friend class ASTStmtWriter;
956 /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
957 class PredefinedExpr : public Expr {
963 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
964 /// 'virtual' keyword is omitted for virtual member functions.
965 PrettyFunctionNoVirtual
972 PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
973 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
974 type->isDependentType(), type->isDependentType(),
975 type->isInstantiationDependentType(),
976 /*ContainsUnexpandedParameterPack=*/false),
979 /// \brief Construct an empty predefined expression.
980 explicit PredefinedExpr(EmptyShell Empty)
981 : Expr(PredefinedExprClass, Empty) { }
983 IdentType getIdentType() const { return Type; }
984 void setIdentType(IdentType IT) { Type = IT; }
986 SourceLocation getLocation() const { return Loc; }
987 void setLocation(SourceLocation L) { Loc = L; }
989 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
991 SourceRange getSourceRange() const { return SourceRange(Loc); }
993 static bool classof(const Stmt *T) {
994 return T->getStmtClass() == PredefinedExprClass;
996 static bool classof(const PredefinedExpr *) { return true; }
999 child_range children() { return child_range(); }
1002 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1005 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1006 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1007 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1008 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1009 /// ASTContext's allocator for memory allocation.
1010 class APNumericStorage {
1013 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1014 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1017 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1019 APNumericStorage(const APNumericStorage&); // do not implement
1020 APNumericStorage& operator=(const APNumericStorage&); // do not implement
1023 APNumericStorage() : BitWidth(0), VAL(0) { }
1025 llvm::APInt getIntValue() const {
1026 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1028 return llvm::APInt(BitWidth, NumWords, pVal);
1030 return llvm::APInt(BitWidth, VAL);
1032 void setIntValue(ASTContext &C, const llvm::APInt &Val);
1035 class APIntStorage : public APNumericStorage {
1037 llvm::APInt getValue() const { return getIntValue(); }
1038 void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Val); }
1041 class APFloatStorage : public APNumericStorage {
1043 llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); }
1044 void setValue(ASTContext &C, const llvm::APFloat &Val) {
1045 setIntValue(C, Val.bitcastToAPInt());
1049 class IntegerLiteral : public Expr {
1053 /// \brief Construct an empty integer literal.
1054 explicit IntegerLiteral(EmptyShell Empty)
1055 : Expr(IntegerLiteralClass, Empty) { }
1058 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1059 // or UnsignedLongLongTy
1060 IntegerLiteral(ASTContext &C, const llvm::APInt &V,
1061 QualType type, SourceLocation l)
1062 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1065 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
1066 assert(V.getBitWidth() == C.getIntWidth(type) &&
1067 "Integer type is not the correct size for constant.");
1071 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1072 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1073 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1074 /// \param V - the value that the returned integer literal contains.
1075 static IntegerLiteral *Create(ASTContext &C, const llvm::APInt &V,
1076 QualType type, SourceLocation l);
1077 /// \brief Returns a new empty integer literal.
1078 static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
1080 llvm::APInt getValue() const { return Num.getValue(); }
1081 SourceRange getSourceRange() const { return SourceRange(Loc); }
1083 /// \brief Retrieve the location of the literal.
1084 SourceLocation getLocation() const { return Loc; }
1086 void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, Val); }
1087 void setLocation(SourceLocation Location) { Loc = Location; }
1089 static bool classof(const Stmt *T) {
1090 return T->getStmtClass() == IntegerLiteralClass;
1092 static bool classof(const IntegerLiteral *) { return true; }
1095 child_range children() { return child_range(); }
1098 class CharacterLiteral : public Expr {
1100 enum CharacterKind {
1112 // type should be IntTy
1113 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1115 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1117 Value(value), Loc(l), Kind(kind) {
1120 /// \brief Construct an empty character literal.
1121 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1123 SourceLocation getLocation() const { return Loc; }
1124 CharacterKind getKind() const { return static_cast<CharacterKind>(Kind); }
1126 SourceRange getSourceRange() const { return SourceRange(Loc); }
1128 unsigned getValue() const { return Value; }
1130 void setLocation(SourceLocation Location) { Loc = Location; }
1131 void setKind(CharacterKind kind) { Kind = kind; }
1132 void setValue(unsigned Val) { Value = Val; }
1134 static bool classof(const Stmt *T) {
1135 return T->getStmtClass() == CharacterLiteralClass;
1137 static bool classof(const CharacterLiteral *) { return true; }
1140 child_range children() { return child_range(); }
1143 class FloatingLiteral : public Expr {
1148 FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
1149 QualType Type, SourceLocation L)
1150 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
1152 IsExact(isexact), Loc(L) {
1156 /// \brief Construct an empty floating-point literal.
1157 explicit FloatingLiteral(EmptyShell Empty)
1158 : Expr(FloatingLiteralClass, Empty), IsExact(false) { }
1161 static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
1162 bool isexact, QualType Type, SourceLocation L);
1163 static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
1165 llvm::APFloat getValue() const { return Num.getValue(); }
1166 void setValue(ASTContext &C, const llvm::APFloat &Val) {
1167 Num.setValue(C, Val);
1170 bool isExact() const { return IsExact; }
1171 void setExact(bool E) { IsExact = E; }
1173 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1174 /// double. Note that this may cause loss of precision, but is useful for
1175 /// debugging dumps, etc.
1176 double getValueAsApproximateDouble() const;
1178 SourceLocation getLocation() const { return Loc; }
1179 void setLocation(SourceLocation L) { Loc = L; }
1181 SourceRange getSourceRange() const { return SourceRange(Loc); }
1183 static bool classof(const Stmt *T) {
1184 return T->getStmtClass() == FloatingLiteralClass;
1186 static bool classof(const FloatingLiteral *) { return true; }
1189 child_range children() { return child_range(); }
1192 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1193 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1194 /// IntegerLiteral classes. Instances of this class always have a Complex type
1195 /// whose element type matches the subexpression.
1197 class ImaginaryLiteral : public Expr {
1200 ImaginaryLiteral(Expr *val, QualType Ty)
1201 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1205 /// \brief Build an empty imaginary literal.
1206 explicit ImaginaryLiteral(EmptyShell Empty)
1207 : Expr(ImaginaryLiteralClass, Empty) { }
1209 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1210 Expr *getSubExpr() { return cast<Expr>(Val); }
1211 void setSubExpr(Expr *E) { Val = E; }
1213 SourceRange getSourceRange() const { return Val->getSourceRange(); }
1214 static bool classof(const Stmt *T) {
1215 return T->getStmtClass() == ImaginaryLiteralClass;
1217 static bool classof(const ImaginaryLiteral *) { return true; }
1220 child_range children() { return child_range(&Val, &Val+1); }
1223 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1224 /// or L"bar" (wide strings). The actual string is returned by getStrData()
1225 /// is NOT null-terminated, and the length of the string is determined by
1226 /// calling getByteLength(). The C type for a string is always a
1227 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1230 /// Note that strings in C can be formed by concatenation of multiple string
1231 /// literal pptokens in translation phase #6. This keeps track of the locations
1232 /// of each of these pieces.
1234 /// Strings in C can also be truncated and extended by assigning into arrays,
1235 /// e.g. with constructs like:
1236 /// char X[2] = "foobar";
1237 /// In this case, getByteLength() will return 6, but the string literal will
1238 /// have type "char[2]".
1239 class StringLiteral : public Expr {
1250 friend class ASTStmtReader;
1252 const char *StrData;
1253 unsigned ByteLength;
1254 unsigned NumConcatenated;
1257 SourceLocation TokLocs[1];
1259 StringLiteral(QualType Ty) :
1260 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1264 /// This is the "fully general" constructor that allows representation of
1265 /// strings formed from multiple concatenated tokens.
1266 static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1267 bool Pascal, QualType Ty,
1268 const SourceLocation *Loc, unsigned NumStrs);
1270 /// Simple constructor for string literals made from one token.
1271 static StringLiteral *Create(ASTContext &C, StringRef Str, StringKind Kind,
1272 bool Pascal, QualType Ty,
1273 SourceLocation Loc) {
1274 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1277 /// \brief Construct an empty string literal.
1278 static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
1280 StringRef getString() const {
1281 return StringRef(StrData, ByteLength);
1284 unsigned getByteLength() const { return ByteLength; }
1286 /// \brief Sets the string data to the given string data.
1287 void setString(ASTContext &C, StringRef Str);
1289 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1290 bool isAscii() const { return Kind == Ascii; }
1291 bool isWide() const { return Kind == Wide; }
1292 bool isUTF8() const { return Kind == UTF8; }
1293 bool isUTF16() const { return Kind == UTF16; }
1294 bool isUTF32() const { return Kind == UTF32; }
1295 bool isPascal() const { return IsPascal; }
1297 bool containsNonAsciiOrNull() const {
1298 StringRef Str = getString();
1299 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1300 if (!isascii(Str[i]) || !Str[i])
1304 /// getNumConcatenated - Get the number of string literal tokens that were
1305 /// concatenated in translation phase #6 to form this string literal.
1306 unsigned getNumConcatenated() const { return NumConcatenated; }
1308 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1309 assert(TokNum < NumConcatenated && "Invalid tok number");
1310 return TokLocs[TokNum];
1312 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1313 assert(TokNum < NumConcatenated && "Invalid tok number");
1314 TokLocs[TokNum] = L;
1317 /// getLocationOfByte - Return a source location that points to the specified
1318 /// byte of this string literal.
1320 /// Strings are amazingly complex. They can be formed from multiple tokens
1321 /// and can have escape sequences in them in addition to the usual trigraph
1322 /// and escaped newline business. This routine handles this complexity.
1324 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1325 const LangOptions &Features,
1326 const TargetInfo &Target) const;
1328 typedef const SourceLocation *tokloc_iterator;
1329 tokloc_iterator tokloc_begin() const { return TokLocs; }
1330 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1332 SourceRange getSourceRange() const {
1333 return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
1335 static bool classof(const Stmt *T) {
1336 return T->getStmtClass() == StringLiteralClass;
1338 static bool classof(const StringLiteral *) { return true; }
1341 child_range children() { return child_range(); }
1344 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1345 /// AST node is only formed if full location information is requested.
1346 class ParenExpr : public Expr {
1347 SourceLocation L, R;
1350 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1351 : Expr(ParenExprClass, val->getType(),
1352 val->getValueKind(), val->getObjectKind(),
1353 val->isTypeDependent(), val->isValueDependent(),
1354 val->isInstantiationDependent(),
1355 val->containsUnexpandedParameterPack()),
1356 L(l), R(r), Val(val) {}
1358 /// \brief Construct an empty parenthesized expression.
1359 explicit ParenExpr(EmptyShell Empty)
1360 : Expr(ParenExprClass, Empty) { }
1362 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1363 Expr *getSubExpr() { return cast<Expr>(Val); }
1364 void setSubExpr(Expr *E) { Val = E; }
1366 SourceRange getSourceRange() const { return SourceRange(L, R); }
1368 /// \brief Get the location of the left parentheses '('.
1369 SourceLocation getLParen() const { return L; }
1370 void setLParen(SourceLocation Loc) { L = Loc; }
1372 /// \brief Get the location of the right parentheses ')'.
1373 SourceLocation getRParen() const { return R; }
1374 void setRParen(SourceLocation Loc) { R = Loc; }
1376 static bool classof(const Stmt *T) {
1377 return T->getStmtClass() == ParenExprClass;
1379 static bool classof(const ParenExpr *) { return true; }
1382 child_range children() { return child_range(&Val, &Val+1); }
1386 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1387 /// alignof), the postinc/postdec operators from postfix-expression, and various
1390 /// Notes on various nodes:
1392 /// Real/Imag - These return the real/imag part of a complex operand. If
1393 /// applied to a non-complex value, the former returns its operand and the
1394 /// later returns zero in the type of the operand.
1396 class UnaryOperator : public Expr {
1398 typedef UnaryOperatorKind Opcode;
1406 UnaryOperator(Expr *input, Opcode opc, QualType type,
1407 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1408 : Expr(UnaryOperatorClass, type, VK, OK,
1409 input->isTypeDependent() || type->isDependentType(),
1410 input->isValueDependent(),
1411 (input->isInstantiationDependent() ||
1412 type->isInstantiationDependentType()),
1413 input->containsUnexpandedParameterPack()),
1414 Opc(opc), Loc(l), Val(input) {}
1416 /// \brief Build an empty unary operator.
1417 explicit UnaryOperator(EmptyShell Empty)
1418 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1420 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1421 void setOpcode(Opcode O) { Opc = O; }
1423 Expr *getSubExpr() const { return cast<Expr>(Val); }
1424 void setSubExpr(Expr *E) { Val = E; }
1426 /// getOperatorLoc - Return the location of the operator.
1427 SourceLocation getOperatorLoc() const { return Loc; }
1428 void setOperatorLoc(SourceLocation L) { Loc = L; }
1430 /// isPostfix - Return true if this is a postfix operation, like x++.
1431 static bool isPostfix(Opcode Op) {
1432 return Op == UO_PostInc || Op == UO_PostDec;
1435 /// isPrefix - Return true if this is a prefix operation, like --x.
1436 static bool isPrefix(Opcode Op) {
1437 return Op == UO_PreInc || Op == UO_PreDec;
1440 bool isPrefix() const { return isPrefix(getOpcode()); }
1441 bool isPostfix() const { return isPostfix(getOpcode()); }
1442 bool isIncrementOp() const {
1443 return Opc == UO_PreInc || Opc == UO_PostInc;
1445 bool isIncrementDecrementOp() const {
1446 return Opc <= UO_PreDec;
1448 static bool isArithmeticOp(Opcode Op) {
1449 return Op >= UO_Plus && Op <= UO_LNot;
1451 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1453 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1454 /// corresponds to, e.g. "sizeof" or "[pre]++"
1455 static const char *getOpcodeStr(Opcode Op);
1457 /// \brief Retrieve the unary opcode that corresponds to the given
1458 /// overloaded operator.
1459 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1461 /// \brief Retrieve the overloaded operator kind that corresponds to
1462 /// the given unary opcode.
1463 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1465 SourceRange getSourceRange() const {
1467 return SourceRange(Val->getLocStart(), Loc);
1469 return SourceRange(Loc, Val->getLocEnd());
1471 SourceLocation getExprLoc() const { return Loc; }
1473 static bool classof(const Stmt *T) {
1474 return T->getStmtClass() == UnaryOperatorClass;
1476 static bool classof(const UnaryOperator *) { return true; }
1479 child_range children() { return child_range(&Val, &Val+1); }
1482 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1483 /// offsetof(record-type, member-designator). For example, given:
1494 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1496 class OffsetOfExpr : public Expr {
1498 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1499 class OffsetOfNode {
1501 /// \brief The kind of offsetof node we have.
1503 /// \brief An index into an array.
1507 /// \brief A field in a dependent type, known only by its name.
1509 /// \brief An implicit indirection through a C++ base class, when the
1510 /// field found is in a base class.
1515 enum { MaskBits = 2, Mask = 0x03 };
1517 /// \brief The source range that covers this part of the designator.
1520 /// \brief The data describing the designator, which comes in three
1521 /// different forms, depending on the lower two bits.
1522 /// - An unsigned index into the array of Expr*'s stored after this node
1523 /// in memory, for [constant-expression] designators.
1524 /// - A FieldDecl*, for references to a known field.
1525 /// - An IdentifierInfo*, for references to a field with a given name
1526 /// when the class type is dependent.
1527 /// - A CXXBaseSpecifier*, for references that look at a field in a
1532 /// \brief Create an offsetof node that refers to an array element.
1533 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1534 SourceLocation RBracketLoc)
1535 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1537 /// \brief Create an offsetof node that refers to a field.
1538 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1539 SourceLocation NameLoc)
1540 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1541 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1543 /// \brief Create an offsetof node that refers to an identifier.
1544 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1545 SourceLocation NameLoc)
1546 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1547 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1549 /// \brief Create an offsetof node that refers into a C++ base class.
1550 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1551 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1553 /// \brief Determine what kind of offsetof node this is.
1554 Kind getKind() const {
1555 return static_cast<Kind>(Data & Mask);
1558 /// \brief For an array element node, returns the index into the array
1560 unsigned getArrayExprIndex() const {
1561 assert(getKind() == Array);
1565 /// \brief For a field offsetof node, returns the field.
1566 FieldDecl *getField() const {
1567 assert(getKind() == Field);
1568 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1571 /// \brief For a field or identifier offsetof node, returns the name of
1573 IdentifierInfo *getFieldName() const;
1575 /// \brief For a base class node, returns the base specifier.
1576 CXXBaseSpecifier *getBase() const {
1577 assert(getKind() == Base);
1578 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1581 /// \brief Retrieve the source range that covers this offsetof node.
1583 /// For an array element node, the source range contains the locations of
1584 /// the square brackets. For a field or identifier node, the source range
1585 /// contains the location of the period (if there is one) and the
1587 SourceRange getSourceRange() const { return Range; }
1592 SourceLocation OperatorLoc, RParenLoc;
1594 TypeSourceInfo *TSInfo;
1595 // Number of sub-components (i.e. instances of OffsetOfNode).
1597 // Number of sub-expressions (i.e. array subscript expressions).
1600 OffsetOfExpr(ASTContext &C, QualType type,
1601 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1602 OffsetOfNode* compsPtr, unsigned numComps,
1603 Expr** exprsPtr, unsigned numExprs,
1604 SourceLocation RParenLoc);
1606 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1607 : Expr(OffsetOfExprClass, EmptyShell()),
1608 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1612 static OffsetOfExpr *Create(ASTContext &C, QualType type,
1613 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1614 OffsetOfNode* compsPtr, unsigned numComps,
1615 Expr** exprsPtr, unsigned numExprs,
1616 SourceLocation RParenLoc);
1618 static OffsetOfExpr *CreateEmpty(ASTContext &C,
1619 unsigned NumComps, unsigned NumExprs);
1621 /// getOperatorLoc - Return the location of the operator.
1622 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1623 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1625 /// \brief Return the location of the right parentheses.
1626 SourceLocation getRParenLoc() const { return RParenLoc; }
1627 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1629 TypeSourceInfo *getTypeSourceInfo() const {
1632 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1636 const OffsetOfNode &getComponent(unsigned Idx) const {
1637 assert(Idx < NumComps && "Subscript out of range");
1638 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1641 void setComponent(unsigned Idx, OffsetOfNode ON) {
1642 assert(Idx < NumComps && "Subscript out of range");
1643 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1646 unsigned getNumComponents() const {
1650 Expr* getIndexExpr(unsigned Idx) {
1651 assert(Idx < NumExprs && "Subscript out of range");
1652 return reinterpret_cast<Expr **>(
1653 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1655 const Expr *getIndexExpr(unsigned Idx) const {
1656 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1659 void setIndexExpr(unsigned Idx, Expr* E) {
1660 assert(Idx < NumComps && "Subscript out of range");
1661 reinterpret_cast<Expr **>(
1662 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1665 unsigned getNumExpressions() const {
1669 SourceRange getSourceRange() const {
1670 return SourceRange(OperatorLoc, RParenLoc);
1673 static bool classof(const Stmt *T) {
1674 return T->getStmtClass() == OffsetOfExprClass;
1677 static bool classof(const OffsetOfExpr *) { return true; }
1680 child_range children() {
1682 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1684 return child_range(begin, begin + NumExprs);
1688 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1689 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1690 /// vec_step (OpenCL 1.1 6.11.12).
1691 class UnaryExprOrTypeTraitExpr : public Expr {
1693 bool isType : 1; // true if operand is a type, false if an expression
1698 SourceLocation OpLoc, RParenLoc;
1701 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1702 QualType resultType, SourceLocation op,
1703 SourceLocation rp) :
1704 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1705 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1706 // Value-dependent if the argument is type-dependent.
1707 TInfo->getType()->isDependentType(),
1708 TInfo->getType()->isInstantiationDependentType(),
1709 TInfo->getType()->containsUnexpandedParameterPack()),
1710 Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) {
1711 Argument.Ty = TInfo;
1714 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1715 QualType resultType, SourceLocation op,
1716 SourceLocation rp) :
1717 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1718 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1719 // Value-dependent if the argument is type-dependent.
1720 E->isTypeDependent(),
1721 E->isInstantiationDependent(),
1722 E->containsUnexpandedParameterPack()),
1723 Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) {
1727 /// \brief Construct an empty sizeof/alignof expression.
1728 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1729 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1731 UnaryExprOrTypeTrait getKind() const {
1732 return static_cast<UnaryExprOrTypeTrait>(Kind);
1734 void setKind(UnaryExprOrTypeTrait K) { Kind = K; }
1736 bool isArgumentType() const { return isType; }
1737 QualType getArgumentType() const {
1738 return getArgumentTypeInfo()->getType();
1740 TypeSourceInfo *getArgumentTypeInfo() const {
1741 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1744 Expr *getArgumentExpr() {
1745 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
1746 return static_cast<Expr*>(Argument.Ex);
1748 const Expr *getArgumentExpr() const {
1749 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
1752 void setArgument(Expr *E) { Argument.Ex = E; isType = false; }
1753 void setArgument(TypeSourceInfo *TInfo) {
1754 Argument.Ty = TInfo;
1758 /// Gets the argument type, or the type of the argument expression, whichever
1760 QualType getTypeOfArgument() const {
1761 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
1764 SourceLocation getOperatorLoc() const { return OpLoc; }
1765 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
1767 SourceLocation getRParenLoc() const { return RParenLoc; }
1768 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1770 SourceRange getSourceRange() const {
1771 return SourceRange(OpLoc, RParenLoc);
1774 static bool classof(const Stmt *T) {
1775 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
1777 static bool classof(const UnaryExprOrTypeTraitExpr *) { return true; }
1780 child_range children();
1783 //===----------------------------------------------------------------------===//
1784 // Postfix Operators.
1785 //===----------------------------------------------------------------------===//
1787 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
1788 class ArraySubscriptExpr : public Expr {
1789 enum { LHS, RHS, END_EXPR=2 };
1790 Stmt* SubExprs[END_EXPR];
1791 SourceLocation RBracketLoc;
1793 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
1794 ExprValueKind VK, ExprObjectKind OK,
1795 SourceLocation rbracketloc)
1796 : Expr(ArraySubscriptExprClass, t, VK, OK,
1797 lhs->isTypeDependent() || rhs->isTypeDependent(),
1798 lhs->isValueDependent() || rhs->isValueDependent(),
1799 (lhs->isInstantiationDependent() ||
1800 rhs->isInstantiationDependent()),
1801 (lhs->containsUnexpandedParameterPack() ||
1802 rhs->containsUnexpandedParameterPack())),
1803 RBracketLoc(rbracketloc) {
1804 SubExprs[LHS] = lhs;
1805 SubExprs[RHS] = rhs;
1808 /// \brief Create an empty array subscript expression.
1809 explicit ArraySubscriptExpr(EmptyShell Shell)
1810 : Expr(ArraySubscriptExprClass, Shell) { }
1812 /// An array access can be written A[4] or 4[A] (both are equivalent).
1813 /// - getBase() and getIdx() always present the normalized view: A[4].
1814 /// In this case getBase() returns "A" and getIdx() returns "4".
1815 /// - getLHS() and getRHS() present the syntactic view. e.g. for
1816 /// 4[A] getLHS() returns "4".
1817 /// Note: Because vector element access is also written A[4] we must
1818 /// predicate the format conversion in getBase and getIdx only on the
1819 /// the type of the RHS, as it is possible for the LHS to be a vector of
1821 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
1822 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
1823 void setLHS(Expr *E) { SubExprs[LHS] = E; }
1825 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
1826 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
1827 void setRHS(Expr *E) { SubExprs[RHS] = E; }
1830 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1833 const Expr *getBase() const {
1834 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
1838 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1841 const Expr *getIdx() const {
1842 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
1845 SourceRange getSourceRange() const {
1846 return SourceRange(getLHS()->getLocStart(), RBracketLoc);
1849 SourceLocation getRBracketLoc() const { return RBracketLoc; }
1850 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1852 SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
1854 static bool classof(const Stmt *T) {
1855 return T->getStmtClass() == ArraySubscriptExprClass;
1857 static bool classof(const ArraySubscriptExpr *) { return true; }
1860 child_range children() {
1861 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
1866 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
1867 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
1868 /// while its subclasses may represent alternative syntax that (semantically)
1869 /// results in a function call. For example, CXXOperatorCallExpr is
1870 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
1871 /// "str1 + str2" to resolve to a function call.
1872 class CallExpr : public Expr {
1873 enum { FN=0, PREARGS_START=1 };
1876 SourceLocation RParenLoc;
1879 // These versions of the constructor are for derived classes.
1880 CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
1881 Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
1882 SourceLocation rparenloc);
1883 CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs, EmptyShell Empty);
1885 Stmt *getPreArg(unsigned i) {
1886 assert(i < getNumPreArgs() && "Prearg access out of range!");
1887 return SubExprs[PREARGS_START+i];
1889 const Stmt *getPreArg(unsigned i) const {
1890 assert(i < getNumPreArgs() && "Prearg access out of range!");
1891 return SubExprs[PREARGS_START+i];
1893 void setPreArg(unsigned i, Stmt *PreArg) {
1894 assert(i < getNumPreArgs() && "Prearg access out of range!");
1895 SubExprs[PREARGS_START+i] = PreArg;
1898 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
1901 CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs, QualType t,
1902 ExprValueKind VK, SourceLocation rparenloc);
1904 /// \brief Build an empty call expression.
1905 CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty);
1907 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
1908 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
1909 void setCallee(Expr *F) { SubExprs[FN] = F; }
1911 Decl *getCalleeDecl();
1912 const Decl *getCalleeDecl() const {
1913 return const_cast<CallExpr*>(this)->getCalleeDecl();
1916 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
1917 FunctionDecl *getDirectCallee();
1918 const FunctionDecl *getDirectCallee() const {
1919 return const_cast<CallExpr*>(this)->getDirectCallee();
1922 /// getNumArgs - Return the number of actual arguments to this call.
1924 unsigned getNumArgs() const { return NumArgs; }
1926 /// \brief Retrieve the call arguments.
1928 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
1931 /// getArg - Return the specified argument.
1932 Expr *getArg(unsigned Arg) {
1933 assert(Arg < NumArgs && "Arg access out of range!");
1934 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1936 const Expr *getArg(unsigned Arg) const {
1937 assert(Arg < NumArgs && "Arg access out of range!");
1938 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
1941 /// setArg - Set the specified argument.
1942 void setArg(unsigned Arg, Expr *ArgExpr) {
1943 assert(Arg < NumArgs && "Arg access out of range!");
1944 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
1947 /// setNumArgs - This changes the number of arguments present in this call.
1948 /// Any orphaned expressions are deleted by this, and any new operands are set
1950 void setNumArgs(ASTContext& C, unsigned NumArgs);
1952 typedef ExprIterator arg_iterator;
1953 typedef ConstExprIterator const_arg_iterator;
1955 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
1956 arg_iterator arg_end() {
1957 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1959 const_arg_iterator arg_begin() const {
1960 return SubExprs+PREARGS_START+getNumPreArgs();
1962 const_arg_iterator arg_end() const {
1963 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
1966 /// getNumCommas - Return the number of commas that must have been present in
1967 /// this function call.
1968 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
1970 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
1972 unsigned isBuiltinCall(const ASTContext &Context) const;
1974 /// getCallReturnType - Get the return type of the call expr. This is not
1975 /// always the type of the expr itself, if the return type is a reference
1977 QualType getCallReturnType() const;
1979 SourceLocation getRParenLoc() const { return RParenLoc; }
1980 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1982 SourceRange getSourceRange() const;
1984 static bool classof(const Stmt *T) {
1985 return T->getStmtClass() >= firstCallExprConstant &&
1986 T->getStmtClass() <= lastCallExprConstant;
1988 static bool classof(const CallExpr *) { return true; }
1991 child_range children() {
1992 return child_range(&SubExprs[0],
1993 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
1997 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
1999 class MemberExpr : public Expr {
2000 /// Extra data stored in some member expressions.
2001 struct MemberNameQualifier {
2002 /// \brief The nested-name-specifier that qualifies the name, including
2003 /// source-location information.
2004 NestedNameSpecifierLoc QualifierLoc;
2006 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2007 /// name qualifiers.
2008 DeclAccessPair FoundDecl;
2011 /// Base - the expression for the base pointer or structure references. In
2012 /// X.F, this is "X".
2015 /// MemberDecl - This is the decl being referenced by the field/member name.
2016 /// In X.F, this is the decl referenced by F.
2017 ValueDecl *MemberDecl;
2019 /// MemberLoc - This is the location of the member name.
2020 SourceLocation MemberLoc;
2022 /// MemberDNLoc - Provides source/type location info for the
2023 /// declaration name embedded in MemberDecl.
2024 DeclarationNameLoc MemberDNLoc;
2026 /// IsArrow - True if this is "X->F", false if this is "X.F".
2029 /// \brief True if this member expression used a nested-name-specifier to
2030 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2031 /// declaration. When true, a MemberNameQualifier
2032 /// structure is allocated immediately after the MemberExpr.
2033 bool HasQualifierOrFoundDecl : 1;
2035 /// \brief True if this member expression specified a template argument list
2036 /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentList
2037 /// structure (and its TemplateArguments) are allocated immediately after
2038 /// the MemberExpr or, if the member expression also has a qualifier, after
2039 /// the MemberNameQualifier structure.
2040 bool HasExplicitTemplateArgumentList : 1;
2042 /// \brief True if this member expression refers to a method that
2043 /// was resolved from an overloaded set having size greater than 1.
2044 bool HadMultipleCandidates : 1;
2046 /// \brief Retrieve the qualifier that preceded the member name, if any.
2047 MemberNameQualifier *getMemberQualifier() {
2048 assert(HasQualifierOrFoundDecl);
2049 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2052 /// \brief Retrieve the qualifier that preceded the member name, if any.
2053 const MemberNameQualifier *getMemberQualifier() const {
2054 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2058 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2059 const DeclarationNameInfo &NameInfo, QualType ty,
2060 ExprValueKind VK, ExprObjectKind OK)
2061 : Expr(MemberExprClass, ty, VK, OK,
2062 base->isTypeDependent(),
2063 base->isValueDependent(),
2064 base->isInstantiationDependent(),
2065 base->containsUnexpandedParameterPack()),
2066 Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
2067 MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
2068 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false),
2069 HadMultipleCandidates(false) {
2070 assert(memberdecl->getDeclName() == NameInfo.getName());
2073 // NOTE: this constructor should be used only when it is known that
2074 // the member name can not provide additional syntactic info
2075 // (i.e., source locations for C++ operator names or type source info
2076 // for constructors, destructors and conversion oeprators).
2077 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2078 SourceLocation l, QualType ty,
2079 ExprValueKind VK, ExprObjectKind OK)
2080 : Expr(MemberExprClass, ty, VK, OK,
2081 base->isTypeDependent(), base->isValueDependent(),
2082 base->isInstantiationDependent(),
2083 base->containsUnexpandedParameterPack()),
2084 Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
2086 HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(false),
2087 HadMultipleCandidates(false) {}
2089 static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
2090 NestedNameSpecifierLoc QualifierLoc,
2091 ValueDecl *memberdecl, DeclAccessPair founddecl,
2092 DeclarationNameInfo MemberNameInfo,
2093 const TemplateArgumentListInfo *targs,
2094 QualType ty, ExprValueKind VK, ExprObjectKind OK);
2096 void setBase(Expr *E) { Base = E; }
2097 Expr *getBase() const { return cast<Expr>(Base); }
2099 /// \brief Retrieve the member declaration to which this expression refers.
2101 /// The returned declaration will either be a FieldDecl or (in C++)
2102 /// a CXXMethodDecl.
2103 ValueDecl *getMemberDecl() const { return MemberDecl; }
2104 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2106 /// \brief Retrieves the declaration found by lookup.
2107 DeclAccessPair getFoundDecl() const {
2108 if (!HasQualifierOrFoundDecl)
2109 return DeclAccessPair::make(getMemberDecl(),
2110 getMemberDecl()->getAccess());
2111 return getMemberQualifier()->FoundDecl;
2114 /// \brief Determines whether this member expression actually had
2115 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2117 bool hasQualifier() const { return getQualifier() != 0; }
2119 /// \brief If the member name was qualified, retrieves the
2120 /// nested-name-specifier that precedes the member name. Otherwise, returns
2122 NestedNameSpecifier *getQualifier() const {
2123 if (!HasQualifierOrFoundDecl)
2126 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2129 /// \brief If the member name was qualified, retrieves the
2130 /// nested-name-specifier that precedes the member name, with source-location
2132 NestedNameSpecifierLoc getQualifierLoc() const {
2133 if (!hasQualifier())
2134 return NestedNameSpecifierLoc();
2136 return getMemberQualifier()->QualifierLoc;
2139 /// \brief Determines whether this member expression actually had a C++
2140 /// template argument list explicitly specified, e.g., x.f<int>.
2141 bool hasExplicitTemplateArgs() const {
2142 return HasExplicitTemplateArgumentList;
2145 /// \brief Copies the template arguments (if present) into the given
2147 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2148 if (hasExplicitTemplateArgs())
2149 getExplicitTemplateArgs().copyInto(List);
2152 /// \brief Retrieve the explicit template argument list that
2153 /// follow the member template name. This must only be called on an
2154 /// expression with explicit template arguments.
2155 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2156 assert(HasExplicitTemplateArgumentList);
2157 if (!HasQualifierOrFoundDecl)
2158 return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
2160 return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
2161 getMemberQualifier() + 1);
2164 /// \brief Retrieve the explicit template argument list that
2165 /// followed the member template name. This must only be called on
2166 /// an expression with explicit template arguments.
2167 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2168 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2171 /// \brief Retrieves the optional explicit template arguments.
2172 /// This points to the same data as getExplicitTemplateArgs(), but
2173 /// returns null if there are no explicit template arguments.
2174 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2175 if (!hasExplicitTemplateArgs()) return 0;
2176 return &getExplicitTemplateArgs();
2179 /// \brief Retrieve the location of the left angle bracket following the
2180 /// member name ('<'), if any.
2181 SourceLocation getLAngleLoc() const {
2182 if (!HasExplicitTemplateArgumentList)
2183 return SourceLocation();
2185 return getExplicitTemplateArgs().LAngleLoc;
2188 /// \brief Retrieve the template arguments provided as part of this
2190 const TemplateArgumentLoc *getTemplateArgs() const {
2191 if (!HasExplicitTemplateArgumentList)
2194 return getExplicitTemplateArgs().getTemplateArgs();
2197 /// \brief Retrieve the number of template arguments provided as part of this
2199 unsigned getNumTemplateArgs() const {
2200 if (!HasExplicitTemplateArgumentList)
2203 return getExplicitTemplateArgs().NumTemplateArgs;
2206 /// \brief Retrieve the location of the right angle bracket following the
2207 /// template arguments ('>').
2208 SourceLocation getRAngleLoc() const {
2209 if (!HasExplicitTemplateArgumentList)
2210 return SourceLocation();
2212 return getExplicitTemplateArgs().RAngleLoc;
2215 /// \brief Retrieve the member declaration name info.
2216 DeclarationNameInfo getMemberNameInfo() const {
2217 return DeclarationNameInfo(MemberDecl->getDeclName(),
2218 MemberLoc, MemberDNLoc);
2221 bool isArrow() const { return IsArrow; }
2222 void setArrow(bool A) { IsArrow = A; }
2224 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2225 /// location of 'F'.
2226 SourceLocation getMemberLoc() const { return MemberLoc; }
2227 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2229 SourceRange getSourceRange() const;
2231 SourceLocation getExprLoc() const { return MemberLoc; }
2233 /// \brief Determine whether the base of this explicit is implicit.
2234 bool isImplicitAccess() const {
2235 return getBase() && getBase()->isImplicitCXXThis();
2238 /// \brief Returns true if this member expression refers to a method that
2239 /// was resolved from an overloaded set having size greater than 1.
2240 bool hadMultipleCandidates() const {
2241 return HadMultipleCandidates;
2243 /// \brief Sets the flag telling whether this expression refers to
2244 /// a method that was resolved from an overloaded set having size
2246 void setHadMultipleCandidates(bool V = true) {
2247 HadMultipleCandidates = V;
2250 static bool classof(const Stmt *T) {
2251 return T->getStmtClass() == MemberExprClass;
2253 static bool classof(const MemberExpr *) { return true; }
2256 child_range children() { return child_range(&Base, &Base+1); }
2258 friend class ASTReader;
2259 friend class ASTStmtWriter;
2262 /// CompoundLiteralExpr - [C99 6.5.2.5]
2264 class CompoundLiteralExpr : public Expr {
2265 /// LParenLoc - If non-null, this is the location of the left paren in a
2266 /// compound literal like "(int){4}". This can be null if this is a
2267 /// synthesized compound expression.
2268 SourceLocation LParenLoc;
2270 /// The type as written. This can be an incomplete array type, in
2271 /// which case the actual expression type will be different.
2272 TypeSourceInfo *TInfo;
2276 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2277 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2278 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2279 tinfo->getType()->isDependentType(),
2280 init->isValueDependent(),
2281 (init->isInstantiationDependent() ||
2282 tinfo->getType()->isInstantiationDependentType()),
2283 init->containsUnexpandedParameterPack()),
2284 LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope) {}
2286 /// \brief Construct an empty compound literal.
2287 explicit CompoundLiteralExpr(EmptyShell Empty)
2288 : Expr(CompoundLiteralExprClass, Empty) { }
2290 const Expr *getInitializer() const { return cast<Expr>(Init); }
2291 Expr *getInitializer() { return cast<Expr>(Init); }
2292 void setInitializer(Expr *E) { Init = E; }
2294 bool isFileScope() const { return FileScope; }
2295 void setFileScope(bool FS) { FileScope = FS; }
2297 SourceLocation getLParenLoc() const { return LParenLoc; }
2298 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2300 TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
2301 void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo = tinfo; }
2303 SourceRange getSourceRange() const {
2304 // FIXME: Init should never be null.
2306 return SourceRange();
2307 if (LParenLoc.isInvalid())
2308 return Init->getSourceRange();
2309 return SourceRange(LParenLoc, Init->getLocEnd());
2312 static bool classof(const Stmt *T) {
2313 return T->getStmtClass() == CompoundLiteralExprClass;
2315 static bool classof(const CompoundLiteralExpr *) { return true; }
2318 child_range children() { return child_range(&Init, &Init+1); }
2321 /// CastExpr - Base class for type casts, including both implicit
2322 /// casts (ImplicitCastExpr) and explicit casts that have some
2323 /// representation in the source code (ExplicitCastExpr's derived
2325 class CastExpr : public Expr {
2327 typedef clang::CastKind CastKind;
2332 void CheckCastConsistency() const;
2334 const CXXBaseSpecifier * const *path_buffer() const {
2335 return const_cast<CastExpr*>(this)->path_buffer();
2337 CXXBaseSpecifier **path_buffer();
2339 void setBasePathSize(unsigned basePathSize) {
2340 CastExprBits.BasePathSize = basePathSize;
2341 assert(CastExprBits.BasePathSize == basePathSize &&
2342 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2346 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2347 const CastKind kind, Expr *op, unsigned BasePathSize) :
2348 Expr(SC, ty, VK, OK_Ordinary,
2349 // Cast expressions are type-dependent if the type is
2350 // dependent (C++ [temp.dep.expr]p3).
2351 ty->isDependentType(),
2352 // Cast expressions are value-dependent if the type is
2353 // dependent or if the subexpression is value-dependent.
2354 ty->isDependentType() || (op && op->isValueDependent()),
2355 (ty->isInstantiationDependentType() ||
2356 (op && op->isInstantiationDependent())),
2357 (ty->containsUnexpandedParameterPack() ||
2358 op->containsUnexpandedParameterPack())),
2360 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2361 CastExprBits.Kind = kind;
2362 setBasePathSize(BasePathSize);
2364 CheckCastConsistency();
2368 /// \brief Construct an empty cast.
2369 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2371 setBasePathSize(BasePathSize);
2375 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2376 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2377 const char *getCastKindName() const;
2379 Expr *getSubExpr() { return cast<Expr>(Op); }
2380 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2381 void setSubExpr(Expr *E) { Op = E; }
2383 /// \brief Retrieve the cast subexpression as it was written in the source
2384 /// code, looking through any implicit casts or other intermediate nodes
2385 /// introduced by semantic analysis.
2386 Expr *getSubExprAsWritten();
2387 const Expr *getSubExprAsWritten() const {
2388 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2391 typedef CXXBaseSpecifier **path_iterator;
2392 typedef const CXXBaseSpecifier * const *path_const_iterator;
2393 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2394 unsigned path_size() const { return CastExprBits.BasePathSize; }
2395 path_iterator path_begin() { return path_buffer(); }
2396 path_iterator path_end() { return path_buffer() + path_size(); }
2397 path_const_iterator path_begin() const { return path_buffer(); }
2398 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2400 void setCastPath(const CXXCastPath &Path);
2402 static bool classof(const Stmt *T) {
2403 return T->getStmtClass() >= firstCastExprConstant &&
2404 T->getStmtClass() <= lastCastExprConstant;
2406 static bool classof(const CastExpr *) { return true; }
2409 child_range children() { return child_range(&Op, &Op+1); }
2412 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2413 /// conversions, which have no direct representation in the original
2414 /// source code. For example: converting T[]->T*, void f()->void
2415 /// (*f)(), float->double, short->int, etc.
2417 /// In C, implicit casts always produce rvalues. However, in C++, an
2418 /// implicit cast whose result is being bound to a reference will be
2419 /// an lvalue or xvalue. For example:
2423 /// class Derived : public Base { };
2424 /// Derived &&ref();
2425 /// void f(Derived d) {
2426 /// Base& b = d; // initializer is an ImplicitCastExpr
2427 /// // to an lvalue of type Base
2428 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2429 /// // to an xvalue of type Base
2432 class ImplicitCastExpr : public CastExpr {
2434 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2435 unsigned BasePathLength, ExprValueKind VK)
2436 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2439 /// \brief Construct an empty implicit cast.
2440 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2441 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2444 enum OnStack_t { OnStack };
2445 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2447 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2450 static ImplicitCastExpr *Create(ASTContext &Context, QualType T,
2451 CastKind Kind, Expr *Operand,
2452 const CXXCastPath *BasePath,
2455 static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2457 SourceRange getSourceRange() const {
2458 return getSubExpr()->getSourceRange();
2461 static bool classof(const Stmt *T) {
2462 return T->getStmtClass() == ImplicitCastExprClass;
2464 static bool classof(const ImplicitCastExpr *) { return true; }
2467 inline Expr *Expr::IgnoreImpCasts() {
2469 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2470 e = ice->getSubExpr();
2474 /// ExplicitCastExpr - An explicit cast written in the source
2477 /// This class is effectively an abstract class, because it provides
2478 /// the basic representation of an explicitly-written cast without
2479 /// specifying which kind of cast (C cast, functional cast, static
2480 /// cast, etc.) was written; specific derived classes represent the
2481 /// particular style of cast and its location information.
2483 /// Unlike implicit casts, explicit cast nodes have two different
2484 /// types: the type that was written into the source code, and the
2485 /// actual type of the expression as determined by semantic
2486 /// analysis. These types may differ slightly. For example, in C++ one
2487 /// can cast to a reference type, which indicates that the resulting
2488 /// expression will be an lvalue or xvalue. The reference type, however,
2489 /// will not be used as the type of the expression.
2490 class ExplicitCastExpr : public CastExpr {
2491 /// TInfo - Source type info for the (written) type
2492 /// this expression is casting to.
2493 TypeSourceInfo *TInfo;
2496 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2497 CastKind kind, Expr *op, unsigned PathSize,
2498 TypeSourceInfo *writtenTy)
2499 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2501 /// \brief Construct an empty explicit cast.
2502 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2503 : CastExpr(SC, Shell, PathSize) { }
2506 /// getTypeInfoAsWritten - Returns the type source info for the type
2507 /// that this expression is casting to.
2508 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2509 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2511 /// getTypeAsWritten - Returns the type that this expression is
2512 /// casting to, as written in the source code.
2513 QualType getTypeAsWritten() const { return TInfo->getType(); }
2515 static bool classof(const Stmt *T) {
2516 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2517 T->getStmtClass() <= lastExplicitCastExprConstant;
2519 static bool classof(const ExplicitCastExpr *) { return true; }
2522 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2523 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2524 /// (Type)expr. For example: @c (int)f.
2525 class CStyleCastExpr : public ExplicitCastExpr {
2526 SourceLocation LPLoc; // the location of the left paren
2527 SourceLocation RPLoc; // the location of the right paren
2529 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2530 unsigned PathSize, TypeSourceInfo *writtenTy,
2531 SourceLocation l, SourceLocation r)
2532 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2533 writtenTy), LPLoc(l), RPLoc(r) {}
2535 /// \brief Construct an empty C-style explicit cast.
2536 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2537 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2540 static CStyleCastExpr *Create(ASTContext &Context, QualType T,
2541 ExprValueKind VK, CastKind K,
2542 Expr *Op, const CXXCastPath *BasePath,
2543 TypeSourceInfo *WrittenTy, SourceLocation L,
2546 static CStyleCastExpr *CreateEmpty(ASTContext &Context, unsigned PathSize);
2548 SourceLocation getLParenLoc() const { return LPLoc; }
2549 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2551 SourceLocation getRParenLoc() const { return RPLoc; }
2552 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2554 SourceRange getSourceRange() const {
2555 return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
2557 static bool classof(const Stmt *T) {
2558 return T->getStmtClass() == CStyleCastExprClass;
2560 static bool classof(const CStyleCastExpr *) { return true; }
2563 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2565 /// This expression node kind describes a builtin binary operation,
2566 /// such as "x + y" for integer values "x" and "y". The operands will
2567 /// already have been converted to appropriate types (e.g., by
2568 /// performing promotions or conversions).
2570 /// In C++, where operators may be overloaded, a different kind of
2571 /// expression node (CXXOperatorCallExpr) is used to express the
2572 /// invocation of an overloaded operator with operator syntax. Within
2573 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2574 /// used to store an expression "x + y" depends on the subexpressions
2575 /// for x and y. If neither x or y is type-dependent, and the "+"
2576 /// operator resolves to a built-in operation, BinaryOperator will be
2577 /// used to express the computation (x and y may still be
2578 /// value-dependent). If either x or y is type-dependent, or if the
2579 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2580 /// be used to express the computation.
2581 class BinaryOperator : public Expr {
2583 typedef BinaryOperatorKind Opcode;
2587 SourceLocation OpLoc;
2589 enum { LHS, RHS, END_EXPR };
2590 Stmt* SubExprs[END_EXPR];
2593 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2594 ExprValueKind VK, ExprObjectKind OK,
2595 SourceLocation opLoc)
2596 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2597 lhs->isTypeDependent() || rhs->isTypeDependent(),
2598 lhs->isValueDependent() || rhs->isValueDependent(),
2599 (lhs->isInstantiationDependent() ||
2600 rhs->isInstantiationDependent()),
2601 (lhs->containsUnexpandedParameterPack() ||
2602 rhs->containsUnexpandedParameterPack())),
2603 Opc(opc), OpLoc(opLoc) {
2604 SubExprs[LHS] = lhs;
2605 SubExprs[RHS] = rhs;
2606 assert(!isCompoundAssignmentOp() &&
2607 "Use ArithAssignBinaryOperator for compound assignments");
2610 /// \brief Construct an empty binary operator.
2611 explicit BinaryOperator(EmptyShell Empty)
2612 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2614 SourceLocation getOperatorLoc() const { return OpLoc; }
2615 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2617 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2618 void setOpcode(Opcode O) { Opc = O; }
2620 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2621 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2622 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2623 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2625 SourceRange getSourceRange() const {
2626 return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
2629 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2630 /// corresponds to, e.g. "<<=".
2631 static const char *getOpcodeStr(Opcode Op);
2633 const char *getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2635 /// \brief Retrieve the binary opcode that corresponds to the given
2636 /// overloaded operator.
2637 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2639 /// \brief Retrieve the overloaded operator kind that corresponds to
2640 /// the given binary opcode.
2641 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2643 /// predicates to categorize the respective opcodes.
2644 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2645 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2646 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2647 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2648 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2649 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2651 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2652 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2654 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2655 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2657 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2658 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2660 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2661 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2663 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2664 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2666 static bool isAssignmentOp(Opcode Opc) {
2667 return Opc >= BO_Assign && Opc <= BO_OrAssign;
2669 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
2671 static bool isCompoundAssignmentOp(Opcode Opc) {
2672 return Opc > BO_Assign && Opc <= BO_OrAssign;
2674 bool isCompoundAssignmentOp() const {
2675 return isCompoundAssignmentOp(getOpcode());
2678 static bool isShiftAssignOp(Opcode Opc) {
2679 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
2681 bool isShiftAssignOp() const {
2682 return isShiftAssignOp(getOpcode());
2685 static bool classof(const Stmt *S) {
2686 return S->getStmtClass() >= firstBinaryOperatorConstant &&
2687 S->getStmtClass() <= lastBinaryOperatorConstant;
2689 static bool classof(const BinaryOperator *) { return true; }
2692 child_range children() {
2693 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2697 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2698 ExprValueKind VK, ExprObjectKind OK,
2699 SourceLocation opLoc, bool dead)
2700 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
2701 lhs->isTypeDependent() || rhs->isTypeDependent(),
2702 lhs->isValueDependent() || rhs->isValueDependent(),
2703 (lhs->isInstantiationDependent() ||
2704 rhs->isInstantiationDependent()),
2705 (lhs->containsUnexpandedParameterPack() ||
2706 rhs->containsUnexpandedParameterPack())),
2707 Opc(opc), OpLoc(opLoc) {
2708 SubExprs[LHS] = lhs;
2709 SubExprs[RHS] = rhs;
2712 BinaryOperator(StmtClass SC, EmptyShell Empty)
2713 : Expr(SC, Empty), Opc(BO_MulAssign) { }
2716 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
2717 /// track of the type the operation is performed in. Due to the semantics of
2718 /// these operators, the operands are promoted, the arithmetic performed, an
2719 /// implicit conversion back to the result type done, then the assignment takes
2720 /// place. This captures the intermediate type which the computation is done
2722 class CompoundAssignOperator : public BinaryOperator {
2723 QualType ComputationLHSType;
2724 QualType ComputationResultType;
2726 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
2727 ExprValueKind VK, ExprObjectKind OK,
2728 QualType CompLHSType, QualType CompResultType,
2729 SourceLocation OpLoc)
2730 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, true),
2731 ComputationLHSType(CompLHSType),
2732 ComputationResultType(CompResultType) {
2733 assert(isCompoundAssignmentOp() &&
2734 "Only should be used for compound assignments");
2737 /// \brief Build an empty compound assignment operator expression.
2738 explicit CompoundAssignOperator(EmptyShell Empty)
2739 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
2741 // The two computation types are the type the LHS is converted
2742 // to for the computation and the type of the result; the two are
2743 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
2744 QualType getComputationLHSType() const { return ComputationLHSType; }
2745 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
2747 QualType getComputationResultType() const { return ComputationResultType; }
2748 void setComputationResultType(QualType T) { ComputationResultType = T; }
2750 static bool classof(const CompoundAssignOperator *) { return true; }
2751 static bool classof(const Stmt *S) {
2752 return S->getStmtClass() == CompoundAssignOperatorClass;
2756 /// AbstractConditionalOperator - An abstract base class for
2757 /// ConditionalOperator and BinaryConditionalOperator.
2758 class AbstractConditionalOperator : public Expr {
2759 SourceLocation QuestionLoc, ColonLoc;
2760 friend class ASTStmtReader;
2763 AbstractConditionalOperator(StmtClass SC, QualType T,
2764 ExprValueKind VK, ExprObjectKind OK,
2765 bool TD, bool VD, bool ID,
2766 bool ContainsUnexpandedParameterPack,
2767 SourceLocation qloc,
2768 SourceLocation cloc)
2769 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
2770 QuestionLoc(qloc), ColonLoc(cloc) {}
2772 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
2773 : Expr(SC, Empty) { }
2776 // getCond - Return the expression representing the condition for
2778 Expr *getCond() const;
2780 // getTrueExpr - Return the subexpression representing the value of
2781 // the expression if the condition evaluates to true.
2782 Expr *getTrueExpr() const;
2784 // getFalseExpr - Return the subexpression representing the value of
2785 // the expression if the condition evaluates to false. This is
2786 // the same as getRHS.
2787 Expr *getFalseExpr() const;
2789 SourceLocation getQuestionLoc() const { return QuestionLoc; }
2790 SourceLocation getColonLoc() const { return ColonLoc; }
2792 static bool classof(const Stmt *T) {
2793 return T->getStmtClass() == ConditionalOperatorClass ||
2794 T->getStmtClass() == BinaryConditionalOperatorClass;
2796 static bool classof(const AbstractConditionalOperator *) { return true; }
2799 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
2800 /// middle" extension is a BinaryConditionalOperator.
2801 class ConditionalOperator : public AbstractConditionalOperator {
2802 enum { COND, LHS, RHS, END_EXPR };
2803 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
2805 friend class ASTStmtReader;
2807 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
2808 SourceLocation CLoc, Expr *rhs,
2809 QualType t, ExprValueKind VK, ExprObjectKind OK)
2810 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
2811 // FIXME: the type of the conditional operator doesn't
2812 // depend on the type of the conditional, but the standard
2813 // seems to imply that it could. File a bug!
2814 (lhs->isTypeDependent() || rhs->isTypeDependent()),
2815 (cond->isValueDependent() || lhs->isValueDependent() ||
2816 rhs->isValueDependent()),
2817 (cond->isInstantiationDependent() ||
2818 lhs->isInstantiationDependent() ||
2819 rhs->isInstantiationDependent()),
2820 (cond->containsUnexpandedParameterPack() ||
2821 lhs->containsUnexpandedParameterPack() ||
2822 rhs->containsUnexpandedParameterPack()),
2824 SubExprs[COND] = cond;
2825 SubExprs[LHS] = lhs;
2826 SubExprs[RHS] = rhs;
2829 /// \brief Build an empty conditional operator.
2830 explicit ConditionalOperator(EmptyShell Empty)
2831 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
2833 // getCond - Return the expression representing the condition for
2835 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2837 // getTrueExpr - Return the subexpression representing the value of
2838 // the expression if the condition evaluates to true.
2839 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
2841 // getFalseExpr - Return the subexpression representing the value of
2842 // the expression if the condition evaluates to false. This is
2843 // the same as getRHS.
2844 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
2846 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2847 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2849 SourceRange getSourceRange() const {
2850 return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
2852 static bool classof(const Stmt *T) {
2853 return T->getStmtClass() == ConditionalOperatorClass;
2855 static bool classof(const ConditionalOperator *) { return true; }
2858 child_range children() {
2859 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2863 /// BinaryConditionalOperator - The GNU extension to the conditional
2864 /// operator which allows the middle operand to be omitted.
2866 /// This is a different expression kind on the assumption that almost
2867 /// every client ends up needing to know that these are different.
2868 class BinaryConditionalOperator : public AbstractConditionalOperator {
2869 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
2871 /// - the common condition/left-hand-side expression, which will be
2872 /// evaluated as the opaque value
2873 /// - the condition, expressed in terms of the opaque value
2874 /// - the left-hand-side, expressed in terms of the opaque value
2875 /// - the right-hand-side
2876 Stmt *SubExprs[NUM_SUBEXPRS];
2877 OpaqueValueExpr *OpaqueValue;
2879 friend class ASTStmtReader;
2881 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
2882 Expr *cond, Expr *lhs, Expr *rhs,
2883 SourceLocation qloc, SourceLocation cloc,
2884 QualType t, ExprValueKind VK, ExprObjectKind OK)
2885 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
2886 (common->isTypeDependent() || rhs->isTypeDependent()),
2887 (common->isValueDependent() || rhs->isValueDependent()),
2888 (common->isInstantiationDependent() ||
2889 rhs->isInstantiationDependent()),
2890 (common->containsUnexpandedParameterPack() ||
2891 rhs->containsUnexpandedParameterPack()),
2893 OpaqueValue(opaqueValue) {
2894 SubExprs[COMMON] = common;
2895 SubExprs[COND] = cond;
2896 SubExprs[LHS] = lhs;
2897 SubExprs[RHS] = rhs;
2899 OpaqueValue->setSourceExpr(common);
2902 /// \brief Build an empty conditional operator.
2903 explicit BinaryConditionalOperator(EmptyShell Empty)
2904 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
2906 /// \brief getCommon - Return the common expression, written to the
2907 /// left of the condition. The opaque value will be bound to the
2908 /// result of this expression.
2909 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
2911 /// \brief getOpaqueValue - Return the opaque value placeholder.
2912 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
2914 /// \brief getCond - Return the condition expression; this is defined
2915 /// in terms of the opaque value.
2916 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
2918 /// \brief getTrueExpr - Return the subexpression which will be
2919 /// evaluated if the condition evaluates to true; this is defined
2920 /// in terms of the opaque value.
2921 Expr *getTrueExpr() const {
2922 return cast<Expr>(SubExprs[LHS]);
2925 /// \brief getFalseExpr - Return the subexpression which will be
2926 /// evaluated if the condnition evaluates to false; this is
2927 /// defined in terms of the opaque value.
2928 Expr *getFalseExpr() const {
2929 return cast<Expr>(SubExprs[RHS]);
2932 SourceRange getSourceRange() const {
2933 return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocEnd());
2935 static bool classof(const Stmt *T) {
2936 return T->getStmtClass() == BinaryConditionalOperatorClass;
2938 static bool classof(const BinaryConditionalOperator *) { return true; }
2941 child_range children() {
2942 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
2946 inline Expr *AbstractConditionalOperator::getCond() const {
2947 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2948 return co->getCond();
2949 return cast<BinaryConditionalOperator>(this)->getCond();
2952 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
2953 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2954 return co->getTrueExpr();
2955 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
2958 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
2959 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
2960 return co->getFalseExpr();
2961 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
2964 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
2965 class AddrLabelExpr : public Expr {
2966 SourceLocation AmpAmpLoc, LabelLoc;
2969 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
2971 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
2973 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
2975 /// \brief Build an empty address of a label expression.
2976 explicit AddrLabelExpr(EmptyShell Empty)
2977 : Expr(AddrLabelExprClass, Empty) { }
2979 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
2980 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
2981 SourceLocation getLabelLoc() const { return LabelLoc; }
2982 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
2984 SourceRange getSourceRange() const {
2985 return SourceRange(AmpAmpLoc, LabelLoc);
2988 LabelDecl *getLabel() const { return Label; }
2989 void setLabel(LabelDecl *L) { Label = L; }
2991 static bool classof(const Stmt *T) {
2992 return T->getStmtClass() == AddrLabelExprClass;
2994 static bool classof(const AddrLabelExpr *) { return true; }
2997 child_range children() { return child_range(); }
3000 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3001 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3002 /// takes the value of the last subexpression.
3004 /// A StmtExpr is always an r-value; values "returned" out of a
3005 /// StmtExpr will be copied.
3006 class StmtExpr : public Expr {
3008 SourceLocation LParenLoc, RParenLoc;
3010 // FIXME: Does type-dependence need to be computed differently?
3011 // FIXME: Do we need to compute instantiation instantiation-dependence for
3012 // statements? (ugh!)
3013 StmtExpr(CompoundStmt *substmt, QualType T,
3014 SourceLocation lp, SourceLocation rp) :
3015 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3016 T->isDependentType(), false, false, false),
3017 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3019 /// \brief Build an empty statement expression.
3020 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3022 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3023 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3024 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3026 SourceRange getSourceRange() const {
3027 return SourceRange(LParenLoc, RParenLoc);
3030 SourceLocation getLParenLoc() const { return LParenLoc; }
3031 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3032 SourceLocation getRParenLoc() const { return RParenLoc; }
3033 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3035 static bool classof(const Stmt *T) {
3036 return T->getStmtClass() == StmtExprClass;
3038 static bool classof(const StmtExpr *) { return true; }
3041 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3045 /// ShuffleVectorExpr - clang-specific builtin-in function
3046 /// __builtin_shufflevector.
3047 /// This AST node represents a operator that does a constant
3048 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3049 /// two vectors and a variable number of constant indices,
3050 /// and returns the appropriately shuffled vector.
3051 class ShuffleVectorExpr : public Expr {
3052 SourceLocation BuiltinLoc, RParenLoc;
3054 // SubExprs - the list of values passed to the __builtin_shufflevector
3055 // function. The first two are vectors, and the rest are constant
3056 // indices. The number of values in this list is always
3057 // 2+the number of indices in the vector type.
3062 ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3063 QualType Type, SourceLocation BLoc,
3066 /// \brief Build an empty vector-shuffle expression.
3067 explicit ShuffleVectorExpr(EmptyShell Empty)
3068 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3070 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3071 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3073 SourceLocation getRParenLoc() const { return RParenLoc; }
3074 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3076 SourceRange getSourceRange() const {
3077 return SourceRange(BuiltinLoc, RParenLoc);
3079 static bool classof(const Stmt *T) {
3080 return T->getStmtClass() == ShuffleVectorExprClass;
3082 static bool classof(const ShuffleVectorExpr *) { return true; }
3084 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3085 /// constant expression, the actual arguments passed in, and the function
3087 unsigned getNumSubExprs() const { return NumExprs; }
3089 /// \brief Retrieve the array of expressions.
3090 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3092 /// getExpr - Return the Expr at the specified index.
3093 Expr *getExpr(unsigned Index) {
3094 assert((Index < NumExprs) && "Arg access out of range!");
3095 return cast<Expr>(SubExprs[Index]);
3097 const Expr *getExpr(unsigned Index) const {
3098 assert((Index < NumExprs) && "Arg access out of range!");
3099 return cast<Expr>(SubExprs[Index]);
3102 void setExprs(ASTContext &C, Expr ** Exprs, unsigned NumExprs);
3104 unsigned getShuffleMaskIdx(ASTContext &Ctx, unsigned N) {
3105 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3106 return getExpr(N+2)->EvaluateKnownConstInt(Ctx).getZExtValue();
3110 child_range children() {
3111 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3115 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3116 /// This AST node is similar to the conditional operator (?:) in C, with
3117 /// the following exceptions:
3118 /// - the test expression must be a integer constant expression.
3119 /// - the expression returned acts like the chosen subexpression in every
3120 /// visible way: the type is the same as that of the chosen subexpression,
3121 /// and all predicates (whether it's an l-value, whether it's an integer
3122 /// constant expression, etc.) return the same result as for the chosen
3124 class ChooseExpr : public Expr {
3125 enum { COND, LHS, RHS, END_EXPR };
3126 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3127 SourceLocation BuiltinLoc, RParenLoc;
3129 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3130 QualType t, ExprValueKind VK, ExprObjectKind OK,
3131 SourceLocation RP, bool TypeDependent, bool ValueDependent)
3132 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3133 (cond->isInstantiationDependent() ||
3134 lhs->isInstantiationDependent() ||
3135 rhs->isInstantiationDependent()),
3136 (cond->containsUnexpandedParameterPack() ||
3137 lhs->containsUnexpandedParameterPack() ||
3138 rhs->containsUnexpandedParameterPack())),
3139 BuiltinLoc(BLoc), RParenLoc(RP) {
3140 SubExprs[COND] = cond;
3141 SubExprs[LHS] = lhs;
3142 SubExprs[RHS] = rhs;
3145 /// \brief Build an empty __builtin_choose_expr.
3146 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3148 /// isConditionTrue - Return whether the condition is true (i.e. not
3150 bool isConditionTrue(const ASTContext &C) const;
3152 /// getChosenSubExpr - Return the subexpression chosen according to the
3154 Expr *getChosenSubExpr(const ASTContext &C) const {
3155 return isConditionTrue(C) ? getLHS() : getRHS();
3158 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3159 void setCond(Expr *E) { SubExprs[COND] = E; }
3160 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3161 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3162 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3163 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3165 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3166 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3168 SourceLocation getRParenLoc() const { return RParenLoc; }
3169 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3171 SourceRange getSourceRange() const {
3172 return SourceRange(BuiltinLoc, RParenLoc);
3174 static bool classof(const Stmt *T) {
3175 return T->getStmtClass() == ChooseExprClass;
3177 static bool classof(const ChooseExpr *) { return true; }
3180 child_range children() {
3181 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3185 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3186 /// for a null pointer constant that has integral type (e.g., int or
3187 /// long) and is the same size and alignment as a pointer. The __null
3188 /// extension is typically only used by system headers, which define
3189 /// NULL as __null in C++ rather than using 0 (which is an integer
3190 /// that may not match the size of a pointer).
3191 class GNUNullExpr : public Expr {
3192 /// TokenLoc - The location of the __null keyword.
3193 SourceLocation TokenLoc;
3196 GNUNullExpr(QualType Ty, SourceLocation Loc)
3197 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3201 /// \brief Build an empty GNU __null expression.
3202 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3204 /// getTokenLocation - The location of the __null token.
3205 SourceLocation getTokenLocation() const { return TokenLoc; }
3206 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3208 SourceRange getSourceRange() const {
3209 return SourceRange(TokenLoc);
3211 static bool classof(const Stmt *T) {
3212 return T->getStmtClass() == GNUNullExprClass;
3214 static bool classof(const GNUNullExpr *) { return true; }
3217 child_range children() { return child_range(); }
3220 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3221 class VAArgExpr : public Expr {
3223 TypeSourceInfo *TInfo;
3224 SourceLocation BuiltinLoc, RParenLoc;
3226 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3227 SourceLocation RPLoc, QualType t)
3228 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3229 t->isDependentType(), false,
3230 (TInfo->getType()->isInstantiationDependentType() ||
3231 e->isInstantiationDependent()),
3232 (TInfo->getType()->containsUnexpandedParameterPack() ||
3233 e->containsUnexpandedParameterPack())),
3234 Val(e), TInfo(TInfo),
3236 RParenLoc(RPLoc) { }
3238 /// \brief Create an empty __builtin_va_arg expression.
3239 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3241 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3242 Expr *getSubExpr() { return cast<Expr>(Val); }
3243 void setSubExpr(Expr *E) { Val = E; }
3245 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3246 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3248 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3249 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3251 SourceLocation getRParenLoc() const { return RParenLoc; }
3252 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3254 SourceRange getSourceRange() const {
3255 return SourceRange(BuiltinLoc, RParenLoc);
3257 static bool classof(const Stmt *T) {
3258 return T->getStmtClass() == VAArgExprClass;
3260 static bool classof(const VAArgExpr *) { return true; }
3263 child_range children() { return child_range(&Val, &Val+1); }
3266 /// @brief Describes an C or C++ initializer list.
3268 /// InitListExpr describes an initializer list, which can be used to
3269 /// initialize objects of different types, including
3270 /// struct/class/union types, arrays, and vectors. For example:
3273 /// struct foo x = { 1, { 2, 3 } };
3276 /// Prior to semantic analysis, an initializer list will represent the
3277 /// initializer list as written by the user, but will have the
3278 /// placeholder type "void". This initializer list is called the
3279 /// syntactic form of the initializer, and may contain C99 designated
3280 /// initializers (represented as DesignatedInitExprs), initializations
3281 /// of subobject members without explicit braces, and so on. Clients
3282 /// interested in the original syntax of the initializer list should
3283 /// use the syntactic form of the initializer list.
3285 /// After semantic analysis, the initializer list will represent the
3286 /// semantic form of the initializer, where the initializations of all
3287 /// subobjects are made explicit with nested InitListExpr nodes and
3288 /// C99 designators have been eliminated by placing the designated
3289 /// initializations into the subobject they initialize. Additionally,
3290 /// any "holes" in the initialization, where no initializer has been
3291 /// specified for a particular subobject, will be replaced with
3292 /// implicitly-generated ImplicitValueInitExpr expressions that
3293 /// value-initialize the subobjects. Note, however, that the
3294 /// initializer lists may still have fewer initializers than there are
3295 /// elements to initialize within the object.
3297 /// Given the semantic form of the initializer list, one can retrieve
3298 /// the original syntactic form of that initializer list (if it
3299 /// exists) using getSyntacticForm(). Since many initializer lists
3300 /// have the same syntactic and semantic forms, getSyntacticForm() may
3301 /// return NULL, indicating that the current initializer list also
3302 /// serves as its syntactic form.
3303 class InitListExpr : public Expr {
3304 // FIXME: Eliminate this vector in favor of ASTContext allocation
3305 typedef ASTVector<Stmt *> InitExprsTy;
3306 InitExprsTy InitExprs;
3307 SourceLocation LBraceLoc, RBraceLoc;
3309 /// Contains the initializer list that describes the syntactic form
3310 /// written in the source code.
3311 InitListExpr *SyntacticForm;
3314 /// If this initializer list initializes an array with more elements than
3315 /// there are initializers in the list, specifies an expression to be used
3316 /// for value initialization of the rest of the elements.
3318 /// If this initializer list initializes a union, specifies which
3319 /// field within the union will be initialized.
3320 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3322 /// Whether this initializer list originally had a GNU array-range
3323 /// designator in it. This is a temporary marker used by CodeGen.
3324 bool HadArrayRangeDesignator;
3327 InitListExpr(ASTContext &C, SourceLocation lbraceloc,
3328 Expr **initexprs, unsigned numinits,
3329 SourceLocation rbraceloc);
3331 /// \brief Build an empty initializer list.
3332 explicit InitListExpr(ASTContext &C, EmptyShell Empty)
3333 : Expr(InitListExprClass, Empty), InitExprs(C) { }
3335 unsigned getNumInits() const { return InitExprs.size(); }
3337 /// \brief Retrieve the set of initializers.
3338 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3340 const Expr *getInit(unsigned Init) const {
3341 assert(Init < getNumInits() && "Initializer access out of range!");
3342 return cast_or_null<Expr>(InitExprs[Init]);
3345 Expr *getInit(unsigned Init) {
3346 assert(Init < getNumInits() && "Initializer access out of range!");
3347 return cast_or_null<Expr>(InitExprs[Init]);
3350 void setInit(unsigned Init, Expr *expr) {
3351 assert(Init < getNumInits() && "Initializer access out of range!");
3352 InitExprs[Init] = expr;
3355 /// \brief Reserve space for some number of initializers.
3356 void reserveInits(ASTContext &C, unsigned NumInits);
3358 /// @brief Specify the number of initializers
3360 /// If there are more than @p NumInits initializers, the remaining
3361 /// initializers will be destroyed. If there are fewer than @p
3362 /// NumInits initializers, NULL expressions will be added for the
3363 /// unknown initializers.
3364 void resizeInits(ASTContext &Context, unsigned NumInits);
3366 /// @brief Updates the initializer at index @p Init with the new
3367 /// expression @p expr, and returns the old expression at that
3370 /// When @p Init is out of range for this initializer list, the
3371 /// initializer list will be extended with NULL expressions to
3372 /// accommodate the new entry.
3373 Expr *updateInit(ASTContext &C, unsigned Init, Expr *expr);
3375 /// \brief If this initializer list initializes an array with more elements
3376 /// than there are initializers in the list, specifies an expression to be
3377 /// used for value initialization of the rest of the elements.
3378 Expr *getArrayFiller() {
3379 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3381 const Expr *getArrayFiller() const {
3382 return const_cast<InitListExpr *>(this)->getArrayFiller();
3384 void setArrayFiller(Expr *filler);
3386 /// \brief If this initializes a union, specifies which field in the
3387 /// union to initialize.
3389 /// Typically, this field is the first named field within the
3390 /// union. However, a designated initializer can specify the
3391 /// initialization of a different field within the union.
3392 FieldDecl *getInitializedFieldInUnion() {
3393 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3395 const FieldDecl *getInitializedFieldInUnion() const {
3396 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3398 void setInitializedFieldInUnion(FieldDecl *FD) {
3399 ArrayFillerOrUnionFieldInit = FD;
3402 // Explicit InitListExpr's originate from source code (and have valid source
3403 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3405 return LBraceLoc.isValid() && RBraceLoc.isValid();
3408 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3409 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3410 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3411 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3413 /// @brief Retrieve the initializer list that describes the
3414 /// syntactic form of the initializer.
3417 InitListExpr *getSyntacticForm() const { return SyntacticForm; }
3418 void setSyntacticForm(InitListExpr *Init) { SyntacticForm = Init; }
3420 bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
3421 void sawArrayRangeDesignator(bool ARD = true) {
3422 HadArrayRangeDesignator = ARD;
3425 SourceRange getSourceRange() const;
3427 static bool classof(const Stmt *T) {
3428 return T->getStmtClass() == InitListExprClass;
3430 static bool classof(const InitListExpr *) { return true; }
3433 child_range children() {
3434 if (InitExprs.empty()) return child_range();
3435 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3438 typedef InitExprsTy::iterator iterator;
3439 typedef InitExprsTy::const_iterator const_iterator;
3440 typedef InitExprsTy::reverse_iterator reverse_iterator;
3441 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3443 iterator begin() { return InitExprs.begin(); }
3444 const_iterator begin() const { return InitExprs.begin(); }
3445 iterator end() { return InitExprs.end(); }
3446 const_iterator end() const { return InitExprs.end(); }
3447 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3448 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3449 reverse_iterator rend() { return InitExprs.rend(); }
3450 const_reverse_iterator rend() const { return InitExprs.rend(); }
3452 friend class ASTStmtReader;
3453 friend class ASTStmtWriter;
3456 /// @brief Represents a C99 designated initializer expression.
3458 /// A designated initializer expression (C99 6.7.8) contains one or
3459 /// more designators (which can be field designators, array
3460 /// designators, or GNU array-range designators) followed by an
3461 /// expression that initializes the field or element(s) that the
3462 /// designators refer to. For example, given:
3469 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3472 /// The InitListExpr contains three DesignatedInitExprs, the first of
3473 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3474 /// designators, one array designator for @c [2] followed by one field
3475 /// designator for @c .y. The initalization expression will be 1.0.
3476 class DesignatedInitExpr : public Expr {
3478 /// \brief Forward declaration of the Designator class.
3482 /// The location of the '=' or ':' prior to the actual initializer
3484 SourceLocation EqualOrColonLoc;
3486 /// Whether this designated initializer used the GNU deprecated
3487 /// syntax rather than the C99 '=' syntax.
3490 /// The number of designators in this initializer expression.
3491 unsigned NumDesignators : 15;
3493 /// \brief The designators in this designated initialization
3495 Designator *Designators;
3497 /// The number of subexpressions of this initializer expression,
3498 /// which contains both the initializer and any additional
3499 /// expressions used by array and array-range designators.
3500 unsigned NumSubExprs : 16;
3503 DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
3504 const Designator *Designators,
3505 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3506 Expr **IndexExprs, unsigned NumIndexExprs,
3509 explicit DesignatedInitExpr(unsigned NumSubExprs)
3510 : Expr(DesignatedInitExprClass, EmptyShell()),
3511 NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
3514 /// A field designator, e.g., ".x".
3515 struct FieldDesignator {
3516 /// Refers to the field that is being initialized. The low bit
3517 /// of this field determines whether this is actually a pointer
3518 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3519 /// initially constructed, a field designator will store an
3520 /// IdentifierInfo*. After semantic analysis has resolved that
3521 /// name, the field designator will instead store a FieldDecl*.
3522 uintptr_t NameOrField;
3524 /// The location of the '.' in the designated initializer.
3527 /// The location of the field name in the designated initializer.
3531 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3532 struct ArrayOrRangeDesignator {
3533 /// Location of the first index expression within the designated
3534 /// initializer expression's list of subexpressions.
3536 /// The location of the '[' starting the array range designator.
3537 unsigned LBracketLoc;
3538 /// The location of the ellipsis separating the start and end
3539 /// indices. Only valid for GNU array-range designators.
3540 unsigned EllipsisLoc;
3541 /// The location of the ']' terminating the array range designator.
3542 unsigned RBracketLoc;
3545 /// @brief Represents a single C99 designator.
3547 /// @todo This class is infuriatingly similar to clang::Designator,
3548 /// but minor differences (storing indices vs. storing pointers)
3549 /// keep us from reusing it. Try harder, later, to rectify these
3552 /// @brief The kind of designator this describes.
3556 ArrayRangeDesignator
3560 /// A field designator, e.g., ".x".
3561 struct FieldDesignator Field;
3562 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3563 struct ArrayOrRangeDesignator ArrayOrRange;
3565 friend class DesignatedInitExpr;
3570 /// @brief Initializes a field designator.
3571 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
3572 SourceLocation FieldLoc)
3573 : Kind(FieldDesignator) {
3574 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
3575 Field.DotLoc = DotLoc.getRawEncoding();
3576 Field.FieldLoc = FieldLoc.getRawEncoding();
3579 /// @brief Initializes an array designator.
3580 Designator(unsigned Index, SourceLocation LBracketLoc,
3581 SourceLocation RBracketLoc)
3582 : Kind(ArrayDesignator) {
3583 ArrayOrRange.Index = Index;
3584 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3585 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
3586 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3589 /// @brief Initializes a GNU array-range designator.
3590 Designator(unsigned Index, SourceLocation LBracketLoc,
3591 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
3592 : Kind(ArrayRangeDesignator) {
3593 ArrayOrRange.Index = Index;
3594 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
3595 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
3596 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
3599 bool isFieldDesignator() const { return Kind == FieldDesignator; }
3600 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
3601 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
3603 IdentifierInfo *getFieldName() const;
3605 FieldDecl *getField() const {
3606 assert(Kind == FieldDesignator && "Only valid on a field designator");
3607 if (Field.NameOrField & 0x01)
3610 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
3613 void setField(FieldDecl *FD) {
3614 assert(Kind == FieldDesignator && "Only valid on a field designator");
3615 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
3618 SourceLocation getDotLoc() const {
3619 assert(Kind == FieldDesignator && "Only valid on a field designator");
3620 return SourceLocation::getFromRawEncoding(Field.DotLoc);
3623 SourceLocation getFieldLoc() const {
3624 assert(Kind == FieldDesignator && "Only valid on a field designator");
3625 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
3628 SourceLocation getLBracketLoc() const {
3629 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3630 "Only valid on an array or array-range designator");
3631 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
3634 SourceLocation getRBracketLoc() const {
3635 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3636 "Only valid on an array or array-range designator");
3637 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
3640 SourceLocation getEllipsisLoc() const {
3641 assert(Kind == ArrayRangeDesignator &&
3642 "Only valid on an array-range designator");
3643 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
3646 unsigned getFirstExprIndex() const {
3647 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
3648 "Only valid on an array or array-range designator");
3649 return ArrayOrRange.Index;
3652 SourceLocation getStartLocation() const {
3653 if (Kind == FieldDesignator)
3654 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
3656 return getLBracketLoc();
3658 SourceLocation getEndLocation() const {
3659 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
3661 SourceRange getSourceRange() const {
3662 return SourceRange(getStartLocation(), getEndLocation());
3666 static DesignatedInitExpr *Create(ASTContext &C, Designator *Designators,
3667 unsigned NumDesignators,
3668 Expr **IndexExprs, unsigned NumIndexExprs,
3669 SourceLocation EqualOrColonLoc,
3670 bool GNUSyntax, Expr *Init);
3672 static DesignatedInitExpr *CreateEmpty(ASTContext &C, unsigned NumIndexExprs);
3674 /// @brief Returns the number of designators in this initializer.
3675 unsigned size() const { return NumDesignators; }
3677 // Iterator access to the designators.
3678 typedef Designator *designators_iterator;
3679 designators_iterator designators_begin() { return Designators; }
3680 designators_iterator designators_end() {
3681 return Designators + NumDesignators;
3684 typedef const Designator *const_designators_iterator;
3685 const_designators_iterator designators_begin() const { return Designators; }
3686 const_designators_iterator designators_end() const {
3687 return Designators + NumDesignators;
3690 typedef std::reverse_iterator<designators_iterator>
3691 reverse_designators_iterator;
3692 reverse_designators_iterator designators_rbegin() {
3693 return reverse_designators_iterator(designators_end());
3695 reverse_designators_iterator designators_rend() {
3696 return reverse_designators_iterator(designators_begin());
3699 typedef std::reverse_iterator<const_designators_iterator>
3700 const_reverse_designators_iterator;
3701 const_reverse_designators_iterator designators_rbegin() const {
3702 return const_reverse_designators_iterator(designators_end());
3704 const_reverse_designators_iterator designators_rend() const {
3705 return const_reverse_designators_iterator(designators_begin());
3708 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
3710 void setDesignators(ASTContext &C, const Designator *Desigs,
3711 unsigned NumDesigs);
3713 Expr *getArrayIndex(const Designator& D);
3714 Expr *getArrayRangeStart(const Designator& D);
3715 Expr *getArrayRangeEnd(const Designator& D);
3717 /// @brief Retrieve the location of the '=' that precedes the
3718 /// initializer value itself, if present.
3719 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
3720 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
3722 /// @brief Determines whether this designated initializer used the
3723 /// deprecated GNU syntax for designated initializers.
3724 bool usesGNUSyntax() const { return GNUSyntax; }
3725 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
3727 /// @brief Retrieve the initializer value.
3728 Expr *getInit() const {
3729 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
3732 void setInit(Expr *init) {
3733 *child_begin() = init;
3736 /// \brief Retrieve the total number of subexpressions in this
3737 /// designated initializer expression, including the actual
3738 /// initialized value and any expressions that occur within array
3739 /// and array-range designators.
3740 unsigned getNumSubExprs() const { return NumSubExprs; }
3742 Expr *getSubExpr(unsigned Idx) {
3743 assert(Idx < NumSubExprs && "Subscript out of range");
3744 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3745 Ptr += sizeof(DesignatedInitExpr);
3746 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
3749 void setSubExpr(unsigned Idx, Expr *E) {
3750 assert(Idx < NumSubExprs && "Subscript out of range");
3751 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3752 Ptr += sizeof(DesignatedInitExpr);
3753 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
3756 /// \brief Replaces the designator at index @p Idx with the series
3757 /// of designators in [First, Last).
3758 void ExpandDesignator(ASTContext &C, unsigned Idx, const Designator *First,
3759 const Designator *Last);
3761 SourceRange getDesignatorsSourceRange() const;
3763 SourceRange getSourceRange() const;
3765 static bool classof(const Stmt *T) {
3766 return T->getStmtClass() == DesignatedInitExprClass;
3768 static bool classof(const DesignatedInitExpr *) { return true; }
3771 child_range children() {
3772 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
3773 return child_range(begin, begin + NumSubExprs);
3777 /// \brief Represents an implicitly-generated value initialization of
3778 /// an object of a given type.
3780 /// Implicit value initializations occur within semantic initializer
3781 /// list expressions (InitListExpr) as placeholders for subobject
3782 /// initializations not explicitly specified by the user.
3784 /// \see InitListExpr
3785 class ImplicitValueInitExpr : public Expr {
3787 explicit ImplicitValueInitExpr(QualType ty)
3788 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
3789 false, false, ty->isInstantiationDependentType(), false) { }
3791 /// \brief Construct an empty implicit value initialization.
3792 explicit ImplicitValueInitExpr(EmptyShell Empty)
3793 : Expr(ImplicitValueInitExprClass, Empty) { }
3795 static bool classof(const Stmt *T) {
3796 return T->getStmtClass() == ImplicitValueInitExprClass;
3798 static bool classof(const ImplicitValueInitExpr *) { return true; }
3800 SourceRange getSourceRange() const {
3801 return SourceRange();
3805 child_range children() { return child_range(); }
3809 class ParenListExpr : public Expr {
3812 SourceLocation LParenLoc, RParenLoc;
3815 ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
3816 unsigned numexprs, SourceLocation rparenloc, QualType T);
3818 /// \brief Build an empty paren list.
3819 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
3821 unsigned getNumExprs() const { return NumExprs; }
3823 const Expr* getExpr(unsigned Init) const {
3824 assert(Init < getNumExprs() && "Initializer access out of range!");
3825 return cast_or_null<Expr>(Exprs[Init]);
3828 Expr* getExpr(unsigned Init) {
3829 assert(Init < getNumExprs() && "Initializer access out of range!");
3830 return cast_or_null<Expr>(Exprs[Init]);
3833 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
3835 SourceLocation getLParenLoc() const { return LParenLoc; }
3836 SourceLocation getRParenLoc() const { return RParenLoc; }
3838 SourceRange getSourceRange() const {
3839 return SourceRange(LParenLoc, RParenLoc);
3841 static bool classof(const Stmt *T) {
3842 return T->getStmtClass() == ParenListExprClass;
3844 static bool classof(const ParenListExpr *) { return true; }
3847 child_range children() {
3848 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
3851 friend class ASTStmtReader;
3852 friend class ASTStmtWriter;
3856 /// \brief Represents a C1X generic selection.
3858 /// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling
3859 /// expression, followed by one or more generic associations. Each generic
3860 /// association specifies a type name and an expression, or "default" and an
3861 /// expression (in which case it is known as a default generic association).
3862 /// The type and value of the generic selection are identical to those of its
3863 /// result expression, which is defined as the expression in the generic
3864 /// association with a type name that is compatible with the type of the
3865 /// controlling expression, or the expression in the default generic association
3866 /// if no types are compatible. For example:
3869 /// _Generic(X, double: 1, float: 2, default: 3)
3872 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
3873 /// or 3 if "hello".
3875 /// As an extension, generic selections are allowed in C++, where the following
3876 /// additional semantics apply:
3878 /// Any generic selection whose controlling expression is type-dependent or
3879 /// which names a dependent type in its association list is result-dependent,
3880 /// which means that the choice of result expression is dependent.
3881 /// Result-dependent generic associations are both type- and value-dependent.
3882 class GenericSelectionExpr : public Expr {
3883 enum { CONTROLLING, END_EXPR };
3884 TypeSourceInfo **AssocTypes;
3886 unsigned NumAssocs, ResultIndex;
3887 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
3890 GenericSelectionExpr(ASTContext &Context,
3891 SourceLocation GenericLoc, Expr *ControllingExpr,
3892 TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3893 unsigned NumAssocs, SourceLocation DefaultLoc,
3894 SourceLocation RParenLoc,
3895 bool ContainsUnexpandedParameterPack,
3896 unsigned ResultIndex);
3898 /// This constructor is used in the result-dependent case.
3899 GenericSelectionExpr(ASTContext &Context,
3900 SourceLocation GenericLoc, Expr *ControllingExpr,
3901 TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3902 unsigned NumAssocs, SourceLocation DefaultLoc,
3903 SourceLocation RParenLoc,
3904 bool ContainsUnexpandedParameterPack);
3906 explicit GenericSelectionExpr(EmptyShell Empty)
3907 : Expr(GenericSelectionExprClass, Empty) { }
3909 unsigned getNumAssocs() const { return NumAssocs; }
3911 SourceLocation getGenericLoc() const { return GenericLoc; }
3912 SourceLocation getDefaultLoc() const { return DefaultLoc; }
3913 SourceLocation getRParenLoc() const { return RParenLoc; }
3915 const Expr *getAssocExpr(unsigned i) const {
3916 return cast<Expr>(SubExprs[END_EXPR+i]);
3918 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
3920 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
3921 return AssocTypes[i];
3923 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
3925 QualType getAssocType(unsigned i) const {
3926 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
3927 return TS->getType();
3932 const Expr *getControllingExpr() const {
3933 return cast<Expr>(SubExprs[CONTROLLING]);
3935 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
3937 /// Whether this generic selection is result-dependent.
3938 bool isResultDependent() const { return ResultIndex == -1U; }
3940 /// The zero-based index of the result expression's generic association in
3941 /// the generic selection's association list. Defined only if the
3942 /// generic selection is not result-dependent.
3943 unsigned getResultIndex() const {
3944 assert(!isResultDependent() && "Generic selection is result-dependent");
3948 /// The generic selection's result expression. Defined only if the
3949 /// generic selection is not result-dependent.
3950 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
3951 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
3953 SourceRange getSourceRange() const {
3954 return SourceRange(GenericLoc, RParenLoc);
3956 static bool classof(const Stmt *T) {
3957 return T->getStmtClass() == GenericSelectionExprClass;
3959 static bool classof(const GenericSelectionExpr *) { return true; }
3961 child_range children() {
3962 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
3965 friend class ASTStmtReader;
3968 //===----------------------------------------------------------------------===//
3970 //===----------------------------------------------------------------------===//
3973 /// ExtVectorElementExpr - This represents access to specific elements of a
3974 /// vector, and may occur on the left hand side or right hand side. For example
3975 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
3977 /// Note that the base may have either vector or pointer to vector type, just
3978 /// like a struct field reference.
3980 class ExtVectorElementExpr : public Expr {
3982 IdentifierInfo *Accessor;
3983 SourceLocation AccessorLoc;
3985 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
3986 IdentifierInfo &accessor, SourceLocation loc)
3987 : Expr(ExtVectorElementExprClass, ty, VK,
3988 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
3989 base->isTypeDependent(), base->isValueDependent(),
3990 base->isInstantiationDependent(),
3991 base->containsUnexpandedParameterPack()),
3992 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
3994 /// \brief Build an empty vector element expression.
3995 explicit ExtVectorElementExpr(EmptyShell Empty)
3996 : Expr(ExtVectorElementExprClass, Empty) { }
3998 const Expr *getBase() const { return cast<Expr>(Base); }
3999 Expr *getBase() { return cast<Expr>(Base); }
4000 void setBase(Expr *E) { Base = E; }
4002 IdentifierInfo &getAccessor() const { return *Accessor; }
4003 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4005 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4006 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4008 /// getNumElements - Get the number of components being selected.
4009 unsigned getNumElements() const;
4011 /// containsDuplicateElements - Return true if any element access is
4013 bool containsDuplicateElements() const;
4015 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4016 /// aggregate Constant of ConstantInt(s).
4017 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4019 SourceRange getSourceRange() const {
4020 return SourceRange(getBase()->getLocStart(), AccessorLoc);
4023 /// isArrow - Return true if the base expression is a pointer to vector,
4024 /// return false if the base expression is a vector.
4025 bool isArrow() const;
4027 static bool classof(const Stmt *T) {
4028 return T->getStmtClass() == ExtVectorElementExprClass;
4030 static bool classof(const ExtVectorElementExpr *) { return true; }
4033 child_range children() { return child_range(&Base, &Base+1); }
4037 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4038 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4039 class BlockExpr : public Expr {
4041 BlockDecl *TheBlock;
4043 BlockExpr(BlockDecl *BD, QualType ty)
4044 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4045 ty->isDependentType(), false,
4046 // FIXME: Check for instantiate-dependence in the statement?
4047 ty->isInstantiationDependentType(),
4051 /// \brief Build an empty block expression.
4052 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4054 const BlockDecl *getBlockDecl() const { return TheBlock; }
4055 BlockDecl *getBlockDecl() { return TheBlock; }
4056 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4058 // Convenience functions for probing the underlying BlockDecl.
4059 SourceLocation getCaretLocation() const;
4060 const Stmt *getBody() const;
4063 SourceRange getSourceRange() const {
4064 return SourceRange(getCaretLocation(), getBody()->getLocEnd());
4067 /// getFunctionType - Return the underlying function type for this block.
4068 const FunctionType *getFunctionType() const;
4070 static bool classof(const Stmt *T) {
4071 return T->getStmtClass() == BlockExprClass;
4073 static bool classof(const BlockExpr *) { return true; }
4076 child_range children() { return child_range(); }
4079 /// BlockDeclRefExpr - A reference to a local variable declared in an
4080 /// enclosing scope.
4081 class BlockDeclRefExpr : public Expr {
4085 bool ConstQualAdded : 1;
4087 BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
4088 SourceLocation l, bool ByRef, bool constAdded = false);
4090 // \brief Build an empty reference to a declared variable in a
4092 explicit BlockDeclRefExpr(EmptyShell Empty)
4093 : Expr(BlockDeclRefExprClass, Empty) { }
4095 VarDecl *getDecl() { return D; }
4096 const VarDecl *getDecl() const { return D; }
4097 void setDecl(VarDecl *VD) { D = VD; }
4099 SourceLocation getLocation() const { return Loc; }
4100 void setLocation(SourceLocation L) { Loc = L; }
4102 SourceRange getSourceRange() const { return SourceRange(Loc); }
4104 bool isByRef() const { return IsByRef; }
4105 void setByRef(bool BR) { IsByRef = BR; }
4107 bool isConstQualAdded() const { return ConstQualAdded; }
4108 void setConstQualAdded(bool C) { ConstQualAdded = C; }
4110 static bool classof(const Stmt *T) {
4111 return T->getStmtClass() == BlockDeclRefExprClass;
4113 static bool classof(const BlockDeclRefExpr *) { return true; }
4116 child_range children() { return child_range(); }
4119 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4120 /// This AST node provides support for reinterpreting a type to another
4121 /// type of the same size.
4122 class AsTypeExpr : public Expr { // Should this be an ExplicitCastExpr?
4125 SourceLocation BuiltinLoc, RParenLoc;
4127 friend class ASTReader;
4128 friend class ASTStmtReader;
4129 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4132 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4133 ExprValueKind VK, ExprObjectKind OK,
4134 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4135 : Expr(AsTypeExprClass, DstType, VK, OK,
4136 DstType->isDependentType(),
4137 DstType->isDependentType() || SrcExpr->isValueDependent(),
4138 (DstType->isInstantiationDependentType() ||
4139 SrcExpr->isInstantiationDependent()),
4140 (DstType->containsUnexpandedParameterPack() ||
4141 SrcExpr->containsUnexpandedParameterPack())),
4142 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4144 /// getSrcExpr - Return the Expr to be converted.
4145 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4147 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4148 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4150 /// getRParenLoc - Return the location of final right parenthesis.
4151 SourceLocation getRParenLoc() const { return RParenLoc; }
4153 SourceRange getSourceRange() const {
4154 return SourceRange(BuiltinLoc, RParenLoc);
4157 static bool classof(const Stmt *T) {
4158 return T->getStmtClass() == AsTypeExprClass;
4160 static bool classof(const AsTypeExpr *) { return true; }
4163 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4166 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4167 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4168 /// similarly-named C++0x instructions. All of these instructions take one
4169 /// primary pointer and at least one memory order.
4170 class AtomicExpr : public Expr {
4172 enum AtomicOp { Load, Store, CmpXchgStrong, CmpXchgWeak, Xchg,
4173 Add, Sub, And, Or, Xor };
4175 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, END_EXPR };
4176 Stmt* SubExprs[END_EXPR];
4177 unsigned NumSubExprs;
4178 SourceLocation BuiltinLoc, RParenLoc;
4182 AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, QualType t,
4183 AtomicOp op, SourceLocation RP);
4185 /// \brief Build an empty AtomicExpr.
4186 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4188 Expr *getPtr() const {
4189 return cast<Expr>(SubExprs[PTR]);
4191 void setPtr(Expr *E) {
4194 Expr *getOrder() const {
4195 return cast<Expr>(SubExprs[ORDER]);
4197 void setOrder(Expr *E) {
4198 SubExprs[ORDER] = E;
4200 Expr *getVal1() const {
4201 assert(NumSubExprs >= 3);
4202 return cast<Expr>(SubExprs[VAL1]);
4204 void setVal1(Expr *E) {
4205 assert(NumSubExprs >= 3);
4208 Expr *getOrderFail() const {
4209 assert(NumSubExprs == 5);
4210 return cast<Expr>(SubExprs[ORDER_FAIL]);
4212 void setOrderFail(Expr *E) {
4213 assert(NumSubExprs == 5);
4214 SubExprs[ORDER_FAIL] = E;
4216 Expr *getVal2() const {
4217 assert(NumSubExprs == 5);
4218 return cast<Expr>(SubExprs[VAL2]);
4220 void setVal2(Expr *E) {
4221 assert(NumSubExprs == 5);
4225 AtomicOp getOp() const { return Op; }
4226 void setOp(AtomicOp op) { Op = op; }
4227 unsigned getNumSubExprs() { return NumSubExprs; }
4228 void setNumSubExprs(unsigned num) { NumSubExprs = num; }
4230 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4232 bool isVolatile() const {
4233 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4236 bool isCmpXChg() const {
4237 return getOp() == AtomicExpr::CmpXchgStrong ||
4238 getOp() == AtomicExpr::CmpXchgWeak;
4241 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4242 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4244 SourceLocation getRParenLoc() const { return RParenLoc; }
4245 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4247 SourceRange getSourceRange() const {
4248 return SourceRange(BuiltinLoc, RParenLoc);
4250 static bool classof(const Stmt *T) {
4251 return T->getStmtClass() == AtomicExprClass;
4253 static bool classof(const AtomicExpr *) { return true; }
4256 child_range children() {
4257 return child_range(SubExprs, SubExprs+NumSubExprs);
4260 } // end namespace clang