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/ASTVector.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/OperationKinds.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/TypeTraits.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APSInt.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Compiler.h"
37 class CXXBaseSpecifier;
38 class CXXMemberCallExpr;
39 class CXXOperatorCallExpr;
43 class MaterializeTemporaryExpr;
45 class ObjCPropertyRefExpr;
46 class OpaqueValueExpr;
51 /// \brief A simple array of base specifiers.
52 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
54 /// \brief An adjustment to be made to the temporary created when emitting a
55 /// reference binding, which accesses a particular subobject of that temporary.
56 struct SubobjectAdjustment {
58 DerivedToBaseAdjustment,
60 MemberPointerAdjustment
65 const CastExpr *BasePath;
66 const CXXRecordDecl *DerivedClass;
70 const MemberPointerType *MPT;
75 struct DTB DerivedToBase;
80 SubobjectAdjustment(const CastExpr *BasePath,
81 const CXXRecordDecl *DerivedClass)
82 : Kind(DerivedToBaseAdjustment) {
83 DerivedToBase.BasePath = BasePath;
84 DerivedToBase.DerivedClass = DerivedClass;
87 SubobjectAdjustment(FieldDecl *Field)
88 : Kind(FieldAdjustment) {
92 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
93 : Kind(MemberPointerAdjustment) {
99 /// Expr - This represents one expression. Note that Expr's are subclasses of
100 /// Stmt. This allows an expression to be transparently used any place a Stmt
103 class Expr : public Stmt {
107 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
108 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
111 ExprBits.TypeDependent = TD;
112 ExprBits.ValueDependent = VD;
113 ExprBits.InstantiationDependent = ID;
114 ExprBits.ValueKind = VK;
115 ExprBits.ObjectKind = OK;
116 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
120 /// \brief Construct an empty expression.
121 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
124 QualType getType() const { return TR; }
125 void setType(QualType t) {
126 // In C++, the type of an expression is always adjusted so that it
127 // will not have reference type an expression will never have
128 // reference type (C++ [expr]p6). Use
129 // QualType::getNonReferenceType() to retrieve the non-reference
130 // type. Additionally, inspect Expr::isLvalue to determine whether
131 // an expression that is adjusted in this manner should be
132 // considered an lvalue.
133 assert((t.isNull() || !t->isReferenceType()) &&
134 "Expressions can't have reference type");
139 /// isValueDependent - Determines whether this expression is
140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
141 /// array bound of "Chars" in the following example is
144 /// template<int Size, char (&Chars)[Size]> struct meta_string;
146 bool isValueDependent() const { return ExprBits.ValueDependent; }
148 /// \brief Set whether this expression is value-dependent or not.
149 void setValueDependent(bool VD) {
150 ExprBits.ValueDependent = VD;
152 ExprBits.InstantiationDependent = true;
155 /// isTypeDependent - Determines whether this expression is
156 /// type-dependent (C++ [temp.dep.expr]), which means that its type
157 /// could change from one template instantiation to the next. For
158 /// example, the expressions "x" and "x + y" are type-dependent in
159 /// the following code, but "y" is not type-dependent:
161 /// template<typename T>
162 /// void add(T x, int y) {
166 bool isTypeDependent() const { return ExprBits.TypeDependent; }
168 /// \brief Set whether this expression is type-dependent or not.
169 void setTypeDependent(bool TD) {
170 ExprBits.TypeDependent = TD;
172 ExprBits.InstantiationDependent = true;
175 /// \brief Whether this expression is instantiation-dependent, meaning that
176 /// it depends in some way on a template parameter, even if neither its type
177 /// nor (constant) value can change due to the template instantiation.
179 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
180 /// instantiation-dependent (since it involves a template parameter \c T), but
181 /// is neither type- nor value-dependent, since the type of the inner
182 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
183 /// \c sizeof is known.
186 /// template<typename T>
187 /// void f(T x, T y) {
188 /// sizeof(sizeof(T() + T());
192 bool isInstantiationDependent() const {
193 return ExprBits.InstantiationDependent;
196 /// \brief Set whether this expression is instantiation-dependent or not.
197 void setInstantiationDependent(bool ID) {
198 ExprBits.InstantiationDependent = ID;
201 /// \brief Whether this expression contains an unexpanded parameter
202 /// pack (for C++11 variadic templates).
204 /// Given the following function template:
207 /// template<typename F, typename ...Types>
208 /// void forward(const F &f, Types &&...args) {
209 /// f(static_cast<Types&&>(args)...);
213 /// The expressions \c args and \c static_cast<Types&&>(args) both
214 /// contain parameter packs.
215 bool containsUnexpandedParameterPack() const {
216 return ExprBits.ContainsUnexpandedParameterPack;
219 /// \brief Set the bit that describes whether this expression
220 /// contains an unexpanded parameter pack.
221 void setContainsUnexpandedParameterPack(bool PP = true) {
222 ExprBits.ContainsUnexpandedParameterPack = PP;
225 /// getExprLoc - Return the preferred location for the arrow when diagnosing
226 /// a problem with a generic expression.
227 SourceLocation getExprLoc() const LLVM_READONLY;
229 /// isUnusedResultAWarning - Return true if this immediate expression should
230 /// be warned about if the result is unused. If so, fill in expr, location,
231 /// and ranges with expr to warn on and source locations/ranges appropriate
233 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
234 SourceRange &R1, SourceRange &R2,
235 ASTContext &Ctx) const;
237 /// isLValue - True if this expression is an "l-value" according to
238 /// the rules of the current language. C and C++ give somewhat
239 /// different rules for this concept, but in general, the result of
240 /// an l-value expression identifies a specific object whereas the
241 /// result of an r-value expression is a value detached from any
242 /// specific storage.
244 /// C++11 divides the concept of "r-value" into pure r-values
245 /// ("pr-values") and so-called expiring values ("x-values"), which
246 /// identify specific objects that can be safely cannibalized for
247 /// their resources. This is an unfortunate abuse of terminology on
248 /// the part of the C++ committee. In Clang, when we say "r-value",
249 /// we generally mean a pr-value.
250 bool isLValue() const { return getValueKind() == VK_LValue; }
251 bool isRValue() const { return getValueKind() == VK_RValue; }
252 bool isXValue() const { return getValueKind() == VK_XValue; }
253 bool isGLValue() const { return getValueKind() != VK_RValue; }
255 enum LValueClassification {
258 LV_IncompleteVoidType,
259 LV_DuplicateVectorComponents,
260 LV_InvalidExpression,
261 LV_InvalidMessageExpression,
263 LV_SubObjCPropertySetting,
267 /// Reasons why an expression might not be an l-value.
268 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
270 enum isModifiableLvalueResult {
273 MLV_IncompleteVoidType,
274 MLV_DuplicateVectorComponents,
275 MLV_InvalidExpression,
276 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
280 MLV_NoSetterProperty,
282 MLV_SubObjCPropertySetting,
283 MLV_InvalidMessageExpression,
287 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
288 /// does not have an incomplete type, does not have a const-qualified type,
289 /// and if it is a structure or union, does not have any member (including,
290 /// recursively, any member or element of all contained aggregates or unions)
291 /// with a const-qualified type.
293 /// \param Loc [in,out] - A source location which *may* be filled
294 /// in with the location of the expression making this a
295 /// non-modifiable lvalue, if specified.
296 isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx,
297 SourceLocation *Loc = 0) const;
299 /// \brief The return type of classify(). Represents the C++11 expression
301 class Classification {
303 /// \brief The various classification results. Most of these mean prvalue.
307 CL_Function, // Functions cannot be lvalues in C.
308 CL_Void, // Void cannot be an lvalue in C.
309 CL_AddressableVoid, // Void expression whose address can be taken in C.
310 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
311 CL_MemberFunction, // An expression referring to a member function
312 CL_SubObjCPropertySetting,
313 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
314 CL_ArrayTemporary, // A temporary of array type.
315 CL_ObjCMessageRValue, // ObjC message is an rvalue
316 CL_PRValue // A prvalue for any other reason, of any other type
318 /// \brief The results of modification testing.
319 enum ModifiableType {
320 CM_Untested, // testModifiable was false.
322 CM_RValue, // Not modifiable because it's an rvalue
323 CM_Function, // Not modifiable because it's a function; C++ only
324 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
325 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
335 unsigned short Modifiable;
337 explicit Classification(Kinds k, ModifiableType m)
338 : Kind(k), Modifiable(m)
344 Kinds getKind() const { return static_cast<Kinds>(Kind); }
345 ModifiableType getModifiable() const {
346 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
347 return static_cast<ModifiableType>(Modifiable);
349 bool isLValue() const { return Kind == CL_LValue; }
350 bool isXValue() const { return Kind == CL_XValue; }
351 bool isGLValue() const { return Kind <= CL_XValue; }
352 bool isPRValue() const { return Kind >= CL_Function; }
353 bool isRValue() const { return Kind >= CL_XValue; }
354 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
356 /// \brief Create a simple, modifiably lvalue
357 static Classification makeSimpleLValue() {
358 return Classification(CL_LValue, CM_Modifiable);
362 /// \brief Classify - Classify this expression according to the C++11
363 /// expression taxonomy.
365 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
366 /// old lvalue vs rvalue. This function determines the type of expression this
367 /// is. There are three expression types:
368 /// - lvalues are classical lvalues as in C++03.
369 /// - prvalues are equivalent to rvalues in C++03.
370 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
371 /// function returning an rvalue reference.
372 /// lvalues and xvalues are collectively referred to as glvalues, while
373 /// prvalues and xvalues together form rvalues.
374 Classification Classify(ASTContext &Ctx) const {
375 return ClassifyImpl(Ctx, 0);
378 /// \brief ClassifyModifiable - Classify this expression according to the
379 /// C++11 expression taxonomy, and see if it is valid on the left side
380 /// of an assignment.
382 /// This function extends classify in that it also tests whether the
383 /// expression is modifiable (C99 6.3.2.1p1).
384 /// \param Loc A source location that might be filled with a relevant location
385 /// if the expression is not modifiable.
386 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
387 return ClassifyImpl(Ctx, &Loc);
390 /// getValueKindForType - Given a formal return or parameter type,
391 /// give its value kind.
392 static ExprValueKind getValueKindForType(QualType T) {
393 if (const ReferenceType *RT = T->getAs<ReferenceType>())
394 return (isa<LValueReferenceType>(RT)
396 : (RT->getPointeeType()->isFunctionType()
397 ? VK_LValue : VK_XValue));
401 /// getValueKind - The value kind that this expression produces.
402 ExprValueKind getValueKind() const {
403 return static_cast<ExprValueKind>(ExprBits.ValueKind);
406 /// getObjectKind - The object kind that this expression produces.
407 /// Object kinds are meaningful only for expressions that yield an
408 /// l-value or x-value.
409 ExprObjectKind getObjectKind() const {
410 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
413 bool isOrdinaryOrBitFieldObject() const {
414 ExprObjectKind OK = getObjectKind();
415 return (OK == OK_Ordinary || OK == OK_BitField);
418 /// setValueKind - Set the value kind produced by this expression.
419 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
421 /// setObjectKind - Set the object kind produced by this expression.
422 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
425 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429 /// \brief Returns true if this expression is a gl-value that
430 /// potentially refers to a bit-field.
432 /// In C++, whether a gl-value refers to a bitfield is essentially
433 /// an aspect of the value-kind type system.
434 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
436 /// \brief If this expression refers to a bit-field, retrieve the
437 /// declaration of that bit-field.
439 /// Note that this returns a non-null pointer in subtly different
440 /// places than refersToBitField returns true. In particular, this can
441 /// return a non-null pointer even for r-values loaded from
442 /// bit-fields, but it will return null for a conditional bit-field.
443 FieldDecl *getSourceBitField();
445 const FieldDecl *getSourceBitField() const {
446 return const_cast<Expr*>(this)->getSourceBitField();
449 /// \brief If this expression is an l-value for an Objective C
450 /// property, find the underlying property reference expression.
451 const ObjCPropertyRefExpr *getObjCProperty() const;
453 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
454 bool isObjCSelfExpr() const;
456 /// \brief Returns whether this expression refers to a vector element.
457 bool refersToVectorElement() const;
459 /// \brief Returns whether this expression has a placeholder type.
460 bool hasPlaceholderType() const {
461 return getType()->isPlaceholderType();
464 /// \brief Returns whether this expression has a specific placeholder type.
465 bool hasPlaceholderType(BuiltinType::Kind K) const {
466 assert(BuiltinType::isPlaceholderTypeKind(K));
467 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
468 return BT->getKind() == K;
472 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
473 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
474 /// but also int expressions which are produced by things like comparisons in
476 bool isKnownToHaveBooleanValue() const;
478 /// isIntegerConstantExpr - Return true if this expression is a valid integer
479 /// constant expression, and, if so, return its value in Result. If not a
480 /// valid i-c-e, return false and fill in Loc (if specified) with the location
481 /// of the invalid expression.
483 /// Note: This does not perform the implicit conversions required by C++11
485 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
486 SourceLocation *Loc = 0,
487 bool isEvaluated = true) const;
488 bool isIntegerConstantExpr(const ASTContext &Ctx,
489 SourceLocation *Loc = 0) const;
491 /// isCXX98IntegralConstantExpr - Return true if this expression is an
492 /// integral constant expression in C++98. Can only be used in C++.
493 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
495 /// isCXX11ConstantExpr - Return true if this expression is a constant
496 /// expression in C++11. Can only be used in C++.
498 /// Note: This does not perform the implicit conversions required by C++11
500 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = 0,
501 SourceLocation *Loc = 0) const;
503 /// isPotentialConstantExpr - Return true if this function's definition
504 /// might be usable in a constant expression in C++11, if it were marked
505 /// constexpr. Return false if the function can never produce a constant
506 /// expression, along with diagnostics describing why not.
507 static bool isPotentialConstantExpr(const FunctionDecl *FD,
509 PartialDiagnosticAt> &Diags);
511 /// isConstantInitializer - Returns true if this expression can be emitted to
512 /// IR as a constant, and thus can be used as a constant initializer in C.
513 bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
515 /// EvalStatus is a struct with detailed info about an evaluation in progress.
517 /// HasSideEffects - Whether the evaluated expression has side effects.
518 /// For example, (f() && 0) can be folded, but it still has side effects.
521 /// Diag - If this is non-null, it will be filled in with a stack of notes
522 /// indicating why evaluation failed (or why it failed to produce a constant
524 /// If the expression is unfoldable, the notes will indicate why it's not
525 /// foldable. If the expression is foldable, but not a constant expression,
526 /// the notes will describes why it isn't a constant expression. If the
527 /// expression *is* a constant expression, no notes will be produced.
528 SmallVectorImpl<PartialDiagnosticAt> *Diag;
530 EvalStatus() : HasSideEffects(false), Diag(0) {}
532 // hasSideEffects - Return true if the evaluated expression has
534 bool hasSideEffects() const {
535 return HasSideEffects;
539 /// EvalResult is a struct with detailed info about an evaluated expression.
540 struct EvalResult : EvalStatus {
541 /// Val - This is the value the expression can be folded to.
544 // isGlobalLValue - Return true if the evaluated lvalue expression
546 bool isGlobalLValue() const;
549 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
550 /// an rvalue using any crazy technique (that has nothing to do with language
551 /// standards) that we want to, even if the expression has side-effects. If
552 /// this function returns true, it returns the folded constant in Result. If
553 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
555 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
557 /// EvaluateAsBooleanCondition - Return true if this is a constant
558 /// which we we can fold and convert to a boolean condition using
559 /// any crazy technique that we want to, even if the expression has
561 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
563 enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
565 /// EvaluateAsInt - Return true if this is a constant which we can fold and
566 /// convert to an integer, using any crazy technique that we want to.
567 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
568 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
570 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
571 /// constant folded without side-effects, but discard the result.
572 bool isEvaluatable(const ASTContext &Ctx) const;
574 /// HasSideEffects - This routine returns true for all those expressions
575 /// which have any effect other than producing a value. Example is a function
576 /// call, volatile variable read, or throwing an exception.
577 bool HasSideEffects(const ASTContext &Ctx) const;
579 /// \brief Determine whether this expression involves a call to any function
580 /// that is not trivial.
581 bool hasNonTrivialCall(ASTContext &Ctx);
583 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
584 /// integer. This must be called on an expression that constant folds to an
586 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
587 SmallVectorImpl<PartialDiagnosticAt> *Diag=0) const;
589 void EvaluateForOverflow(const ASTContext &Ctx) const;
591 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
592 /// lvalue with link time known address, with no side-effects.
593 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
595 /// EvaluateAsInitializer - Evaluate an expression as if it were the
596 /// initializer of the given declaration. Returns true if the initializer
597 /// can be folded to a constant, and produces any relevant notes. In C++11,
598 /// notes will be produced if the expression is not a constant expression.
599 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
601 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
603 /// \brief Enumeration used to describe the kind of Null pointer constant
604 /// returned from \c isNullPointerConstant().
605 enum NullPointerConstantKind {
606 /// \brief Expression is not a Null pointer constant.
609 /// \brief Expression is a Null pointer constant built from a zero integer
610 /// expression that is not a simple, possibly parenthesized, zero literal.
611 /// C++ Core Issue 903 will classify these expressions as "not pointers"
612 /// once it is adopted.
613 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
616 /// \brief Expression is a Null pointer constant built from a literal zero.
619 /// \brief Expression is a C++11 nullptr.
622 /// \brief Expression is a GNU-style __null constant.
626 /// \brief Enumeration used to describe how \c isNullPointerConstant()
627 /// should cope with value-dependent expressions.
628 enum NullPointerConstantValueDependence {
629 /// \brief Specifies that the expression should never be value-dependent.
630 NPC_NeverValueDependent = 0,
632 /// \brief Specifies that a value-dependent expression of integral or
633 /// dependent type should be considered a null pointer constant.
634 NPC_ValueDependentIsNull,
636 /// \brief Specifies that a value-dependent expression should be considered
637 /// to never be a null pointer constant.
638 NPC_ValueDependentIsNotNull
641 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
642 /// a Null pointer constant. The return value can further distinguish the
643 /// kind of NULL pointer constant that was detected.
644 NullPointerConstantKind isNullPointerConstant(
646 NullPointerConstantValueDependence NPC) const;
648 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
650 bool isOBJCGCCandidate(ASTContext &Ctx) const;
652 /// \brief Returns true if this expression is a bound member function.
653 bool isBoundMemberFunction(ASTContext &Ctx) const;
655 /// \brief Given an expression of bound-member type, find the type
656 /// of the member. Returns null if this is an *overloaded* bound
657 /// member expression.
658 static QualType findBoundMemberType(const Expr *expr);
660 /// IgnoreImpCasts - Skip past any implicit casts which might
661 /// surround this expression. Only skips ImplicitCastExprs.
662 Expr *IgnoreImpCasts() LLVM_READONLY;
664 /// IgnoreImplicit - Skip past any implicit AST nodes which might
665 /// surround this expression.
666 Expr *IgnoreImplicit() LLVM_READONLY {
667 return cast<Expr>(Stmt::IgnoreImplicit());
670 const Expr *IgnoreImplicit() const LLVM_READONLY {
671 return const_cast<Expr*>(this)->IgnoreImplicit();
674 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
675 /// its subexpression. If that subexpression is also a ParenExpr,
676 /// then this method recursively returns its subexpression, and so forth.
677 /// Otherwise, the method returns the current Expr.
678 Expr *IgnoreParens() LLVM_READONLY;
680 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
681 /// or CastExprs, returning their operand.
682 Expr *IgnoreParenCasts() LLVM_READONLY;
684 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
685 /// any ParenExpr or ImplicitCastExprs, returning their operand.
686 Expr *IgnoreParenImpCasts() LLVM_READONLY;
688 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
689 /// call to a conversion operator, return the argument.
690 Expr *IgnoreConversionOperator() LLVM_READONLY;
692 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
693 return const_cast<Expr*>(this)->IgnoreConversionOperator();
696 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
697 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
700 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
701 /// CastExprs that represent lvalue casts, returning their operand.
702 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
704 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
705 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
708 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
709 /// value (including ptr->int casts of the same size). Strip off any
710 /// ParenExpr or CastExprs, returning their operand.
711 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
713 /// Ignore parentheses and derived-to-base casts.
714 Expr *ignoreParenBaseCasts() LLVM_READONLY;
716 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
717 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
720 /// \brief Determine whether this expression is a default function argument.
722 /// Default arguments are implicitly generated in the abstract syntax tree
723 /// by semantic analysis for function calls, object constructions, etc. in
724 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
725 /// this routine also looks through any implicit casts to determine whether
726 /// the expression is a default argument.
727 bool isDefaultArgument() const;
729 /// \brief Determine whether the result of this expression is a
730 /// temporary object of the given class type.
731 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
733 /// \brief Whether this expression is an implicit reference to 'this' in C++.
734 bool isImplicitCXXThis() const;
736 const Expr *IgnoreImpCasts() const LLVM_READONLY {
737 return const_cast<Expr*>(this)->IgnoreImpCasts();
739 const Expr *IgnoreParens() const LLVM_READONLY {
740 return const_cast<Expr*>(this)->IgnoreParens();
742 const Expr *IgnoreParenCasts() const LLVM_READONLY {
743 return const_cast<Expr*>(this)->IgnoreParenCasts();
745 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
746 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
749 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
751 /// \brief For an expression of class type or pointer to class type,
752 /// return the most derived class decl the expression is known to refer to.
754 /// If this expression is a cast, this method looks through it to find the
755 /// most derived decl that can be inferred from the expression.
756 /// This is valid because derived-to-base conversions have undefined
757 /// behavior if the object isn't dynamically of the derived type.
758 const CXXRecordDecl *getBestDynamicClassType() const;
760 /// Walk outwards from an expression we want to bind a reference to and
761 /// find the expression whose lifetime needs to be extended. Record
762 /// the LHSs of comma expressions and adjustments needed along the path.
763 const Expr *skipRValueSubobjectAdjustments(
764 SmallVectorImpl<const Expr *> &CommaLHS,
765 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
767 /// Skip irrelevant expressions to find what should be materialize for
768 /// binding with a reference.
770 findMaterializedTemporary(const MaterializeTemporaryExpr *&MTE) const;
772 static bool classof(const Stmt *T) {
773 return T->getStmtClass() >= firstExprConstant &&
774 T->getStmtClass() <= lastExprConstant;
779 //===----------------------------------------------------------------------===//
780 // Primary Expressions.
781 //===----------------------------------------------------------------------===//
783 /// OpaqueValueExpr - An expression referring to an opaque object of a
784 /// fixed type and value class. These don't correspond to concrete
785 /// syntax; instead they're used to express operations (usually copy
786 /// operations) on values whose source is generally obvious from
788 class OpaqueValueExpr : public Expr {
789 friend class ASTStmtReader;
794 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
795 ExprObjectKind OK = OK_Ordinary,
796 Expr *SourceExpr = 0)
797 : Expr(OpaqueValueExprClass, T, VK, OK,
798 T->isDependentType(),
799 T->isDependentType() ||
800 (SourceExpr && SourceExpr->isValueDependent()),
801 T->isInstantiationDependentType(),
803 SourceExpr(SourceExpr), Loc(Loc) {
806 /// Given an expression which invokes a copy constructor --- i.e. a
807 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
808 /// find the OpaqueValueExpr that's the source of the construction.
809 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
811 explicit OpaqueValueExpr(EmptyShell Empty)
812 : Expr(OpaqueValueExprClass, Empty) { }
814 /// \brief Retrieve the location of this expression.
815 SourceLocation getLocation() const { return Loc; }
817 SourceLocation getLocStart() const LLVM_READONLY {
818 return SourceExpr ? SourceExpr->getLocStart() : Loc;
820 SourceLocation getLocEnd() const LLVM_READONLY {
821 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
823 SourceLocation getExprLoc() const LLVM_READONLY {
824 if (SourceExpr) return SourceExpr->getExprLoc();
828 child_range children() { return child_range(); }
830 /// The source expression of an opaque value expression is the
831 /// expression which originally generated the value. This is
832 /// provided as a convenience for analyses that don't wish to
833 /// precisely model the execution behavior of the program.
835 /// The source expression is typically set when building the
836 /// expression which binds the opaque value expression in the first
838 Expr *getSourceExpr() const { return SourceExpr; }
840 static bool classof(const Stmt *T) {
841 return T->getStmtClass() == OpaqueValueExprClass;
845 /// \brief A reference to a declared variable, function, enum, etc.
848 /// This encodes all the information about how a declaration is referenced
849 /// within an expression.
851 /// There are several optional constructs attached to DeclRefExprs only when
852 /// they apply in order to conserve memory. These are laid out past the end of
853 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
855 /// DeclRefExprBits.HasQualifier:
856 /// Specifies when this declaration reference expression has a C++
857 /// nested-name-specifier.
858 /// DeclRefExprBits.HasFoundDecl:
859 /// Specifies when this declaration reference expression has a record of
860 /// a NamedDecl (different from the referenced ValueDecl) which was found
861 /// during name lookup and/or overload resolution.
862 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
863 /// Specifies when this declaration reference expression has an explicit
864 /// C++ template keyword and/or template argument list.
865 /// DeclRefExprBits.RefersToEnclosingLocal
866 /// Specifies when this declaration reference expression (validly)
867 /// refers to a local variable from a different function.
868 class DeclRefExpr : public Expr {
869 /// \brief The declaration that we are referencing.
872 /// \brief The location of the declaration name itself.
875 /// \brief Provides source/type location info for the declaration name
877 DeclarationNameLoc DNLoc;
879 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
880 NestedNameSpecifierLoc &getInternalQualifierLoc() {
881 assert(hasQualifier());
882 return *reinterpret_cast<NestedNameSpecifierLoc *>(this + 1);
885 /// \brief Helper to retrieve the optional NestedNameSpecifierLoc.
886 const NestedNameSpecifierLoc &getInternalQualifierLoc() const {
887 return const_cast<DeclRefExpr *>(this)->getInternalQualifierLoc();
890 /// \brief Test whether there is a distinct FoundDecl attached to the end of
892 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
894 /// \brief Helper to retrieve the optional NamedDecl through which this
895 /// reference occurred.
896 NamedDecl *&getInternalFoundDecl() {
897 assert(hasFoundDecl());
899 return *reinterpret_cast<NamedDecl **>(&getInternalQualifierLoc() + 1);
900 return *reinterpret_cast<NamedDecl **>(this + 1);
903 /// \brief Helper to retrieve the optional NamedDecl through which this
904 /// reference occurred.
905 NamedDecl *getInternalFoundDecl() const {
906 return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
909 DeclRefExpr(const ASTContext &Ctx,
910 NestedNameSpecifierLoc QualifierLoc,
911 SourceLocation TemplateKWLoc,
912 ValueDecl *D, bool refersToEnclosingLocal,
913 const DeclarationNameInfo &NameInfo,
915 const TemplateArgumentListInfo *TemplateArgs,
916 QualType T, ExprValueKind VK);
918 /// \brief Construct an empty declaration reference expression.
919 explicit DeclRefExpr(EmptyShell Empty)
920 : Expr(DeclRefExprClass, Empty) { }
922 /// \brief Computes the type- and value-dependence flags for this
923 /// declaration reference expression.
924 void computeDependence(const ASTContext &C);
927 DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T,
928 ExprValueKind VK, SourceLocation L,
929 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
930 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
931 D(D), Loc(L), DNLoc(LocInfo) {
932 DeclRefExprBits.HasQualifier = 0;
933 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
934 DeclRefExprBits.HasFoundDecl = 0;
935 DeclRefExprBits.HadMultipleCandidates = 0;
936 DeclRefExprBits.RefersToEnclosingLocal = refersToEnclosingLocal;
937 computeDependence(D->getASTContext());
940 static DeclRefExpr *Create(const ASTContext &Context,
941 NestedNameSpecifierLoc QualifierLoc,
942 SourceLocation TemplateKWLoc,
944 bool isEnclosingLocal,
945 SourceLocation NameLoc,
946 QualType T, ExprValueKind VK,
947 NamedDecl *FoundD = 0,
948 const TemplateArgumentListInfo *TemplateArgs = 0);
950 static DeclRefExpr *Create(const ASTContext &Context,
951 NestedNameSpecifierLoc QualifierLoc,
952 SourceLocation TemplateKWLoc,
954 bool isEnclosingLocal,
955 const DeclarationNameInfo &NameInfo,
956 QualType T, ExprValueKind VK,
957 NamedDecl *FoundD = 0,
958 const TemplateArgumentListInfo *TemplateArgs = 0);
960 /// \brief Construct an empty declaration reference expression.
961 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
964 bool HasTemplateKWAndArgsInfo,
965 unsigned NumTemplateArgs);
967 ValueDecl *getDecl() { return D; }
968 const ValueDecl *getDecl() const { return D; }
969 void setDecl(ValueDecl *NewD) { D = NewD; }
971 DeclarationNameInfo getNameInfo() const {
972 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
975 SourceLocation getLocation() const { return Loc; }
976 void setLocation(SourceLocation L) { Loc = L; }
977 SourceLocation getLocStart() const LLVM_READONLY;
978 SourceLocation getLocEnd() const LLVM_READONLY;
980 /// \brief Determine whether this declaration reference was preceded by a
981 /// C++ nested-name-specifier, e.g., \c N::foo.
982 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
984 /// \brief If the name was qualified, retrieves the nested-name-specifier
985 /// that precedes the name. Otherwise, returns NULL.
986 NestedNameSpecifier *getQualifier() const {
990 return getInternalQualifierLoc().getNestedNameSpecifier();
993 /// \brief If the name was qualified, retrieves the nested-name-specifier
994 /// that precedes the name, with source-location information.
995 NestedNameSpecifierLoc getQualifierLoc() const {
997 return NestedNameSpecifierLoc();
999 return getInternalQualifierLoc();
1002 /// \brief Get the NamedDecl through which this reference occurred.
1004 /// This Decl may be different from the ValueDecl actually referred to in the
1005 /// presence of using declarations, etc. It always returns non-NULL, and may
1006 /// simple return the ValueDecl when appropriate.
1007 NamedDecl *getFoundDecl() {
1008 return hasFoundDecl() ? getInternalFoundDecl() : D;
1011 /// \brief Get the NamedDecl through which this reference occurred.
1012 /// See non-const variant.
1013 const NamedDecl *getFoundDecl() const {
1014 return hasFoundDecl() ? getInternalFoundDecl() : D;
1017 bool hasTemplateKWAndArgsInfo() const {
1018 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1021 /// \brief Return the optional template keyword and arguments info.
1022 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
1023 if (!hasTemplateKWAndArgsInfo())
1027 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1028 &getInternalFoundDecl() + 1);
1031 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
1032 &getInternalQualifierLoc() + 1);
1034 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
1037 /// \brief Return the optional template keyword and arguments info.
1038 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
1039 return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
1042 /// \brief Retrieve the location of the template keyword preceding
1043 /// this name, if any.
1044 SourceLocation getTemplateKeywordLoc() const {
1045 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1046 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
1049 /// \brief Retrieve the location of the left angle bracket starting the
1050 /// explicit template argument list following the name, if any.
1051 SourceLocation getLAngleLoc() const {
1052 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1053 return getTemplateKWAndArgsInfo()->LAngleLoc;
1056 /// \brief Retrieve the location of the right angle bracket ending the
1057 /// explicit template argument list following the name, if any.
1058 SourceLocation getRAngleLoc() const {
1059 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1060 return getTemplateKWAndArgsInfo()->RAngleLoc;
1063 /// \brief Determines whether the name in this declaration reference
1064 /// was preceded by the template keyword.
1065 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1067 /// \brief Determines whether this declaration reference was followed by an
1068 /// explicit template argument list.
1069 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1071 /// \brief Retrieve the explicit template argument list that followed the
1072 /// member template name.
1073 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
1074 assert(hasExplicitTemplateArgs());
1075 return *getTemplateKWAndArgsInfo();
1078 /// \brief Retrieve the explicit template argument list that followed the
1079 /// member template name.
1080 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
1081 return const_cast<DeclRefExpr *>(this)->getExplicitTemplateArgs();
1084 /// \brief Retrieves the optional explicit template arguments.
1085 /// This points to the same data as getExplicitTemplateArgs(), but
1086 /// returns null if there are no explicit template arguments.
1087 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
1088 if (!hasExplicitTemplateArgs()) return 0;
1089 return &getExplicitTemplateArgs();
1092 /// \brief Copies the template arguments (if present) into the given
1094 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1095 if (hasExplicitTemplateArgs())
1096 getExplicitTemplateArgs().copyInto(List);
1099 /// \brief Retrieve the template arguments provided as part of this
1101 const TemplateArgumentLoc *getTemplateArgs() const {
1102 if (!hasExplicitTemplateArgs())
1105 return getExplicitTemplateArgs().getTemplateArgs();
1108 /// \brief Retrieve the number of template arguments provided as part of this
1110 unsigned getNumTemplateArgs() const {
1111 if (!hasExplicitTemplateArgs())
1114 return getExplicitTemplateArgs().NumTemplateArgs;
1117 /// \brief Returns true if this expression refers to a function that
1118 /// was resolved from an overloaded set having size greater than 1.
1119 bool hadMultipleCandidates() const {
1120 return DeclRefExprBits.HadMultipleCandidates;
1122 /// \brief Sets the flag telling whether this expression refers to
1123 /// a function that was resolved from an overloaded set having size
1125 void setHadMultipleCandidates(bool V = true) {
1126 DeclRefExprBits.HadMultipleCandidates = V;
1129 /// Does this DeclRefExpr refer to a local declaration from an
1130 /// enclosing function scope?
1131 bool refersToEnclosingLocal() const {
1132 return DeclRefExprBits.RefersToEnclosingLocal;
1135 static bool classof(const Stmt *T) {
1136 return T->getStmtClass() == DeclRefExprClass;
1140 child_range children() { return child_range(); }
1142 friend class ASTStmtReader;
1143 friend class ASTStmtWriter;
1146 /// PredefinedExpr - [C99 6.4.2.2] - A predefined identifier such as __func__.
1147 class PredefinedExpr : public Expr {
1152 LFunction, // Same as Function, but as wide string.
1155 /// PrettyFunctionNoVirtual - The same as PrettyFunction, except that the
1156 /// 'virtual' keyword is omitted for virtual member functions.
1157 PrettyFunctionNoVirtual
1164 PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
1165 : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
1166 type->isDependentType(), type->isDependentType(),
1167 type->isInstantiationDependentType(),
1168 /*ContainsUnexpandedParameterPack=*/false),
1171 /// \brief Construct an empty predefined expression.
1172 explicit PredefinedExpr(EmptyShell Empty)
1173 : Expr(PredefinedExprClass, Empty) { }
1175 IdentType getIdentType() const { return Type; }
1176 void setIdentType(IdentType IT) { Type = IT; }
1178 SourceLocation getLocation() const { return Loc; }
1179 void setLocation(SourceLocation L) { Loc = L; }
1181 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1183 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1184 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1186 static bool classof(const Stmt *T) {
1187 return T->getStmtClass() == PredefinedExprClass;
1191 child_range children() { return child_range(); }
1194 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1197 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1198 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1199 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1200 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1201 /// ASTContext's allocator for memory allocation.
1202 class APNumericStorage {
1204 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1205 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1209 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1211 APNumericStorage(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1212 void operator=(const APNumericStorage &) LLVM_DELETED_FUNCTION;
1215 APNumericStorage() : VAL(0), BitWidth(0) { }
1217 llvm::APInt getIntValue() const {
1218 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1220 return llvm::APInt(BitWidth, NumWords, pVal);
1222 return llvm::APInt(BitWidth, VAL);
1224 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1227 class APIntStorage : private APNumericStorage {
1229 llvm::APInt getValue() const { return getIntValue(); }
1230 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1231 setIntValue(C, Val);
1235 class APFloatStorage : private APNumericStorage {
1237 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1238 return llvm::APFloat(Semantics, getIntValue());
1240 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1241 setIntValue(C, Val.bitcastToAPInt());
1245 class IntegerLiteral : public Expr, public APIntStorage {
1248 /// \brief Construct an empty integer literal.
1249 explicit IntegerLiteral(EmptyShell Empty)
1250 : Expr(IntegerLiteralClass, Empty) { }
1253 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1254 // or UnsignedLongLongTy
1255 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1258 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1259 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1260 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1261 /// \param V - the value that the returned integer literal contains.
1262 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1263 QualType type, SourceLocation l);
1264 /// \brief Returns a new empty integer literal.
1265 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1267 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1268 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1270 /// \brief Retrieve the location of the literal.
1271 SourceLocation getLocation() const { return Loc; }
1273 void setLocation(SourceLocation Location) { Loc = Location; }
1275 static bool classof(const Stmt *T) {
1276 return T->getStmtClass() == IntegerLiteralClass;
1280 child_range children() { return child_range(); }
1283 class CharacterLiteral : public Expr {
1285 enum CharacterKind {
1296 // type should be IntTy
1297 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1299 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1301 Value(value), Loc(l) {
1302 CharacterLiteralBits.Kind = kind;
1305 /// \brief Construct an empty character literal.
1306 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1308 SourceLocation getLocation() const { return Loc; }
1309 CharacterKind getKind() const {
1310 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1313 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1314 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1316 unsigned getValue() const { return Value; }
1318 void setLocation(SourceLocation Location) { Loc = Location; }
1319 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1320 void setValue(unsigned Val) { Value = Val; }
1322 static bool classof(const Stmt *T) {
1323 return T->getStmtClass() == CharacterLiteralClass;
1327 child_range children() { return child_range(); }
1330 class FloatingLiteral : public Expr, private APFloatStorage {
1333 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1334 QualType Type, SourceLocation L);
1336 /// \brief Construct an empty floating-point literal.
1337 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1340 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1341 bool isexact, QualType Type, SourceLocation L);
1342 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1344 llvm::APFloat getValue() const {
1345 return APFloatStorage::getValue(getSemantics());
1347 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1348 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1349 APFloatStorage::setValue(C, Val);
1352 /// Get a raw enumeration value representing the floating-point semantics of
1353 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1354 APFloatSemantics getRawSemantics() const {
1355 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1358 /// Set the raw enumeration value representing the floating-point semantics of
1359 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1360 void setRawSemantics(APFloatSemantics Sem) {
1361 FloatingLiteralBits.Semantics = Sem;
1364 /// Return the APFloat semantics this literal uses.
1365 const llvm::fltSemantics &getSemantics() const;
1367 /// Set the APFloat semantics this literal uses.
1368 void setSemantics(const llvm::fltSemantics &Sem);
1370 bool isExact() const { return FloatingLiteralBits.IsExact; }
1371 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1373 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1374 /// double. Note that this may cause loss of precision, but is useful for
1375 /// debugging dumps, etc.
1376 double getValueAsApproximateDouble() const;
1378 SourceLocation getLocation() const { return Loc; }
1379 void setLocation(SourceLocation L) { Loc = L; }
1381 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1382 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1384 static bool classof(const Stmt *T) {
1385 return T->getStmtClass() == FloatingLiteralClass;
1389 child_range children() { return child_range(); }
1392 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1393 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1394 /// IntegerLiteral classes. Instances of this class always have a Complex type
1395 /// whose element type matches the subexpression.
1397 class ImaginaryLiteral : public Expr {
1400 ImaginaryLiteral(Expr *val, QualType Ty)
1401 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1405 /// \brief Build an empty imaginary literal.
1406 explicit ImaginaryLiteral(EmptyShell Empty)
1407 : Expr(ImaginaryLiteralClass, Empty) { }
1409 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1410 Expr *getSubExpr() { return cast<Expr>(Val); }
1411 void setSubExpr(Expr *E) { Val = E; }
1413 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1414 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1416 static bool classof(const Stmt *T) {
1417 return T->getStmtClass() == ImaginaryLiteralClass;
1421 child_range children() { return child_range(&Val, &Val+1); }
1424 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1425 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1426 /// is NOT null-terminated, and the length of the string is determined by
1427 /// calling getByteLength(). The C type for a string is always a
1428 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1431 /// Note that strings in C can be formed by concatenation of multiple string
1432 /// literal pptokens in translation phase #6. This keeps track of the locations
1433 /// of each of these pieces.
1435 /// Strings in C can also be truncated and extended by assigning into arrays,
1436 /// e.g. with constructs like:
1437 /// char X[2] = "foobar";
1438 /// In this case, getByteLength() will return 6, but the string literal will
1439 /// have type "char[2]".
1440 class StringLiteral : public Expr {
1451 friend class ASTStmtReader;
1455 const uint16_t *asUInt16;
1456 const uint32_t *asUInt32;
1459 unsigned CharByteWidth : 4;
1461 unsigned IsPascal : 1;
1462 unsigned NumConcatenated;
1463 SourceLocation TokLocs[1];
1465 StringLiteral(QualType Ty) :
1466 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1469 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1472 /// This is the "fully general" constructor that allows representation of
1473 /// strings formed from multiple concatenated tokens.
1474 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1475 StringKind Kind, bool Pascal, QualType Ty,
1476 const SourceLocation *Loc, unsigned NumStrs);
1478 /// Simple constructor for string literals made from one token.
1479 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1480 StringKind Kind, bool Pascal, QualType Ty,
1481 SourceLocation Loc) {
1482 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1485 /// \brief Construct an empty string literal.
1486 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1488 StringRef getString() const {
1489 assert(CharByteWidth==1
1490 && "This function is used in places that assume strings use char");
1491 return StringRef(StrData.asChar, getByteLength());
1494 /// Allow access to clients that need the byte representation, such as
1495 /// ASTWriterStmt::VisitStringLiteral().
1496 StringRef getBytes() const {
1497 // FIXME: StringRef may not be the right type to use as a result for this.
1498 if (CharByteWidth == 1)
1499 return StringRef(StrData.asChar, getByteLength());
1500 if (CharByteWidth == 4)
1501 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1503 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1504 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1508 void outputString(raw_ostream &OS) const;
1510 uint32_t getCodeUnit(size_t i) const {
1511 assert(i < Length && "out of bounds access");
1512 if (CharByteWidth == 1)
1513 return static_cast<unsigned char>(StrData.asChar[i]);
1514 if (CharByteWidth == 4)
1515 return StrData.asUInt32[i];
1516 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1517 return StrData.asUInt16[i];
1520 unsigned getByteLength() const { return CharByteWidth*Length; }
1521 unsigned getLength() const { return Length; }
1522 unsigned getCharByteWidth() const { return CharByteWidth; }
1524 /// \brief Sets the string data to the given string data.
1525 void setString(const ASTContext &C, StringRef Str,
1526 StringKind Kind, bool IsPascal);
1528 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1531 bool isAscii() const { return Kind == Ascii; }
1532 bool isWide() const { return Kind == Wide; }
1533 bool isUTF8() const { return Kind == UTF8; }
1534 bool isUTF16() const { return Kind == UTF16; }
1535 bool isUTF32() const { return Kind == UTF32; }
1536 bool isPascal() const { return IsPascal; }
1538 bool containsNonAsciiOrNull() const {
1539 StringRef Str = getString();
1540 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1541 if (!isASCII(Str[i]) || !Str[i])
1546 /// getNumConcatenated - Get the number of string literal tokens that were
1547 /// concatenated in translation phase #6 to form this string literal.
1548 unsigned getNumConcatenated() const { return NumConcatenated; }
1550 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1551 assert(TokNum < NumConcatenated && "Invalid tok number");
1552 return TokLocs[TokNum];
1554 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1555 assert(TokNum < NumConcatenated && "Invalid tok number");
1556 TokLocs[TokNum] = L;
1559 /// getLocationOfByte - Return a source location that points to the specified
1560 /// byte of this string literal.
1562 /// Strings are amazingly complex. They can be formed from multiple tokens
1563 /// and can have escape sequences in them in addition to the usual trigraph
1564 /// and escaped newline business. This routine handles this complexity.
1566 SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1567 const LangOptions &Features,
1568 const TargetInfo &Target) const;
1570 typedef const SourceLocation *tokloc_iterator;
1571 tokloc_iterator tokloc_begin() const { return TokLocs; }
1572 tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
1574 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1575 SourceLocation getLocEnd() const LLVM_READONLY {
1576 return TokLocs[NumConcatenated - 1];
1579 static bool classof(const Stmt *T) {
1580 return T->getStmtClass() == StringLiteralClass;
1584 child_range children() { return child_range(); }
1587 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1588 /// AST node is only formed if full location information is requested.
1589 class ParenExpr : public Expr {
1590 SourceLocation L, R;
1593 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1594 : Expr(ParenExprClass, val->getType(),
1595 val->getValueKind(), val->getObjectKind(),
1596 val->isTypeDependent(), val->isValueDependent(),
1597 val->isInstantiationDependent(),
1598 val->containsUnexpandedParameterPack()),
1599 L(l), R(r), Val(val) {}
1601 /// \brief Construct an empty parenthesized expression.
1602 explicit ParenExpr(EmptyShell Empty)
1603 : Expr(ParenExprClass, Empty) { }
1605 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1606 Expr *getSubExpr() { return cast<Expr>(Val); }
1607 void setSubExpr(Expr *E) { Val = E; }
1609 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1610 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1612 /// \brief Get the location of the left parentheses '('.
1613 SourceLocation getLParen() const { return L; }
1614 void setLParen(SourceLocation Loc) { L = Loc; }
1616 /// \brief Get the location of the right parentheses ')'.
1617 SourceLocation getRParen() const { return R; }
1618 void setRParen(SourceLocation Loc) { R = Loc; }
1620 static bool classof(const Stmt *T) {
1621 return T->getStmtClass() == ParenExprClass;
1625 child_range children() { return child_range(&Val, &Val+1); }
1629 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1630 /// alignof), the postinc/postdec operators from postfix-expression, and various
1633 /// Notes on various nodes:
1635 /// Real/Imag - These return the real/imag part of a complex operand. If
1636 /// applied to a non-complex value, the former returns its operand and the
1637 /// later returns zero in the type of the operand.
1639 class UnaryOperator : public Expr {
1641 typedef UnaryOperatorKind Opcode;
1649 UnaryOperator(Expr *input, Opcode opc, QualType type,
1650 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1651 : Expr(UnaryOperatorClass, type, VK, OK,
1652 input->isTypeDependent() || type->isDependentType(),
1653 input->isValueDependent(),
1654 (input->isInstantiationDependent() ||
1655 type->isInstantiationDependentType()),
1656 input->containsUnexpandedParameterPack()),
1657 Opc(opc), Loc(l), Val(input) {}
1659 /// \brief Build an empty unary operator.
1660 explicit UnaryOperator(EmptyShell Empty)
1661 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1663 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1664 void setOpcode(Opcode O) { Opc = O; }
1666 Expr *getSubExpr() const { return cast<Expr>(Val); }
1667 void setSubExpr(Expr *E) { Val = E; }
1669 /// getOperatorLoc - Return the location of the operator.
1670 SourceLocation getOperatorLoc() const { return Loc; }
1671 void setOperatorLoc(SourceLocation L) { Loc = L; }
1673 /// isPostfix - Return true if this is a postfix operation, like x++.
1674 static bool isPostfix(Opcode Op) {
1675 return Op == UO_PostInc || Op == UO_PostDec;
1678 /// isPrefix - Return true if this is a prefix operation, like --x.
1679 static bool isPrefix(Opcode Op) {
1680 return Op == UO_PreInc || Op == UO_PreDec;
1683 bool isPrefix() const { return isPrefix(getOpcode()); }
1684 bool isPostfix() const { return isPostfix(getOpcode()); }
1686 static bool isIncrementOp(Opcode Op) {
1687 return Op == UO_PreInc || Op == UO_PostInc;
1689 bool isIncrementOp() const {
1690 return isIncrementOp(getOpcode());
1693 static bool isDecrementOp(Opcode Op) {
1694 return Op == UO_PreDec || Op == UO_PostDec;
1696 bool isDecrementOp() const {
1697 return isDecrementOp(getOpcode());
1700 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1701 bool isIncrementDecrementOp() const {
1702 return isIncrementDecrementOp(getOpcode());
1705 static bool isArithmeticOp(Opcode Op) {
1706 return Op >= UO_Plus && Op <= UO_LNot;
1708 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1710 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1711 /// corresponds to, e.g. "sizeof" or "[pre]++"
1712 static StringRef getOpcodeStr(Opcode Op);
1714 /// \brief Retrieve the unary opcode that corresponds to the given
1715 /// overloaded operator.
1716 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1718 /// \brief Retrieve the overloaded operator kind that corresponds to
1719 /// the given unary opcode.
1720 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1722 SourceLocation getLocStart() const LLVM_READONLY {
1723 return isPostfix() ? Val->getLocStart() : Loc;
1725 SourceLocation getLocEnd() const LLVM_READONLY {
1726 return isPostfix() ? Loc : Val->getLocEnd();
1728 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1730 static bool classof(const Stmt *T) {
1731 return T->getStmtClass() == UnaryOperatorClass;
1735 child_range children() { return child_range(&Val, &Val+1); }
1738 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1739 /// offsetof(record-type, member-designator). For example, given:
1750 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1752 class OffsetOfExpr : public Expr {
1754 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1755 class OffsetOfNode {
1757 /// \brief The kind of offsetof node we have.
1759 /// \brief An index into an array.
1763 /// \brief A field in a dependent type, known only by its name.
1765 /// \brief An implicit indirection through a C++ base class, when the
1766 /// field found is in a base class.
1771 enum { MaskBits = 2, Mask = 0x03 };
1773 /// \brief The source range that covers this part of the designator.
1776 /// \brief The data describing the designator, which comes in three
1777 /// different forms, depending on the lower two bits.
1778 /// - An unsigned index into the array of Expr*'s stored after this node
1779 /// in memory, for [constant-expression] designators.
1780 /// - A FieldDecl*, for references to a known field.
1781 /// - An IdentifierInfo*, for references to a field with a given name
1782 /// when the class type is dependent.
1783 /// - A CXXBaseSpecifier*, for references that look at a field in a
1788 /// \brief Create an offsetof node that refers to an array element.
1789 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1790 SourceLocation RBracketLoc)
1791 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
1793 /// \brief Create an offsetof node that refers to a field.
1794 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
1795 SourceLocation NameLoc)
1796 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1797 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
1799 /// \brief Create an offsetof node that refers to an identifier.
1800 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1801 SourceLocation NameLoc)
1802 : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
1803 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
1805 /// \brief Create an offsetof node that refers into a C++ base class.
1806 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1807 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1809 /// \brief Determine what kind of offsetof node this is.
1810 Kind getKind() const {
1811 return static_cast<Kind>(Data & Mask);
1814 /// \brief For an array element node, returns the index into the array
1816 unsigned getArrayExprIndex() const {
1817 assert(getKind() == Array);
1821 /// \brief For a field offsetof node, returns the field.
1822 FieldDecl *getField() const {
1823 assert(getKind() == Field);
1824 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1827 /// \brief For a field or identifier offsetof node, returns the name of
1829 IdentifierInfo *getFieldName() const;
1831 /// \brief For a base class node, returns the base specifier.
1832 CXXBaseSpecifier *getBase() const {
1833 assert(getKind() == Base);
1834 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1837 /// \brief Retrieve the source range that covers this offsetof node.
1839 /// For an array element node, the source range contains the locations of
1840 /// the square brackets. For a field or identifier node, the source range
1841 /// contains the location of the period (if there is one) and the
1843 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1844 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1845 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1850 SourceLocation OperatorLoc, RParenLoc;
1852 TypeSourceInfo *TSInfo;
1853 // Number of sub-components (i.e. instances of OffsetOfNode).
1855 // Number of sub-expressions (i.e. array subscript expressions).
1858 OffsetOfExpr(const ASTContext &C, QualType type,
1859 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1860 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1861 SourceLocation RParenLoc);
1863 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1864 : Expr(OffsetOfExprClass, EmptyShell()),
1865 TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
1869 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1870 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1871 ArrayRef<OffsetOfNode> comps,
1872 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1874 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1875 unsigned NumComps, unsigned NumExprs);
1877 /// getOperatorLoc - Return the location of the operator.
1878 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1879 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1881 /// \brief Return the location of the right parentheses.
1882 SourceLocation getRParenLoc() const { return RParenLoc; }
1883 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1885 TypeSourceInfo *getTypeSourceInfo() const {
1888 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1892 const OffsetOfNode &getComponent(unsigned Idx) const {
1893 assert(Idx < NumComps && "Subscript out of range");
1894 return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
1897 void setComponent(unsigned Idx, OffsetOfNode ON) {
1898 assert(Idx < NumComps && "Subscript out of range");
1899 reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] = ON;
1902 unsigned getNumComponents() const {
1906 Expr* getIndexExpr(unsigned Idx) {
1907 assert(Idx < NumExprs && "Subscript out of range");
1908 return reinterpret_cast<Expr **>(
1909 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx];
1911 const Expr *getIndexExpr(unsigned Idx) const {
1912 return const_cast<OffsetOfExpr*>(this)->getIndexExpr(Idx);
1915 void setIndexExpr(unsigned Idx, Expr* E) {
1916 assert(Idx < NumComps && "Subscript out of range");
1917 reinterpret_cast<Expr **>(
1918 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] = E;
1921 unsigned getNumExpressions() const {
1925 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1926 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1928 static bool classof(const Stmt *T) {
1929 return T->getStmtClass() == OffsetOfExprClass;
1933 child_range children() {
1935 reinterpret_cast<Stmt**>(reinterpret_cast<OffsetOfNode*>(this + 1)
1937 return child_range(begin, begin + NumExprs);
1941 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1942 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1943 /// vec_step (OpenCL 1.1 6.11.12).
1944 class UnaryExprOrTypeTraitExpr : public Expr {
1949 SourceLocation OpLoc, RParenLoc;
1952 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1953 QualType resultType, SourceLocation op,
1954 SourceLocation rp) :
1955 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1956 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1957 // Value-dependent if the argument is type-dependent.
1958 TInfo->getType()->isDependentType(),
1959 TInfo->getType()->isInstantiationDependentType(),
1960 TInfo->getType()->containsUnexpandedParameterPack()),
1961 OpLoc(op), RParenLoc(rp) {
1962 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1963 UnaryExprOrTypeTraitExprBits.IsType = true;
1964 Argument.Ty = TInfo;
1967 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1968 QualType resultType, SourceLocation op,
1969 SourceLocation rp) :
1970 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1971 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1972 // Value-dependent if the argument is type-dependent.
1973 E->isTypeDependent(),
1974 E->isInstantiationDependent(),
1975 E->containsUnexpandedParameterPack()),
1976 OpLoc(op), RParenLoc(rp) {
1977 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1978 UnaryExprOrTypeTraitExprBits.IsType = false;
1982 /// \brief Construct an empty sizeof/alignof expression.
1983 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1984 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1986 UnaryExprOrTypeTrait getKind() const {
1987 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
1989 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
1991 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
1992 QualType getArgumentType() const {
1993 return getArgumentTypeInfo()->getType();
1995 TypeSourceInfo *getArgumentTypeInfo() const {
1996 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
1999 Expr *getArgumentExpr() {
2000 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2001 return static_cast<Expr*>(Argument.Ex);
2003 const Expr *getArgumentExpr() const {
2004 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2007 void setArgument(Expr *E) {
2009 UnaryExprOrTypeTraitExprBits.IsType = false;
2011 void setArgument(TypeSourceInfo *TInfo) {
2012 Argument.Ty = TInfo;
2013 UnaryExprOrTypeTraitExprBits.IsType = true;
2016 /// Gets the argument type, or the type of the argument expression, whichever
2018 QualType getTypeOfArgument() const {
2019 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2022 SourceLocation getOperatorLoc() const { return OpLoc; }
2023 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2025 SourceLocation getRParenLoc() const { return RParenLoc; }
2026 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2028 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2029 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2031 static bool classof(const Stmt *T) {
2032 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2036 child_range children();
2039 //===----------------------------------------------------------------------===//
2040 // Postfix Operators.
2041 //===----------------------------------------------------------------------===//
2043 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2044 class ArraySubscriptExpr : public Expr {
2045 enum { LHS, RHS, END_EXPR=2 };
2046 Stmt* SubExprs[END_EXPR];
2047 SourceLocation RBracketLoc;
2049 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2050 ExprValueKind VK, ExprObjectKind OK,
2051 SourceLocation rbracketloc)
2052 : Expr(ArraySubscriptExprClass, t, VK, OK,
2053 lhs->isTypeDependent() || rhs->isTypeDependent(),
2054 lhs->isValueDependent() || rhs->isValueDependent(),
2055 (lhs->isInstantiationDependent() ||
2056 rhs->isInstantiationDependent()),
2057 (lhs->containsUnexpandedParameterPack() ||
2058 rhs->containsUnexpandedParameterPack())),
2059 RBracketLoc(rbracketloc) {
2060 SubExprs[LHS] = lhs;
2061 SubExprs[RHS] = rhs;
2064 /// \brief Create an empty array subscript expression.
2065 explicit ArraySubscriptExpr(EmptyShell Shell)
2066 : Expr(ArraySubscriptExprClass, Shell) { }
2068 /// An array access can be written A[4] or 4[A] (both are equivalent).
2069 /// - getBase() and getIdx() always present the normalized view: A[4].
2070 /// In this case getBase() returns "A" and getIdx() returns "4".
2071 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2072 /// 4[A] getLHS() returns "4".
2073 /// Note: Because vector element access is also written A[4] we must
2074 /// predicate the format conversion in getBase and getIdx only on the
2075 /// the type of the RHS, as it is possible for the LHS to be a vector of
2077 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2078 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2079 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2081 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2082 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2083 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2086 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2089 const Expr *getBase() const {
2090 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2094 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2097 const Expr *getIdx() const {
2098 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2101 SourceLocation getLocStart() const LLVM_READONLY {
2102 return getLHS()->getLocStart();
2104 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2106 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2107 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2109 SourceLocation getExprLoc() const LLVM_READONLY {
2110 return getBase()->getExprLoc();
2113 static bool classof(const Stmt *T) {
2114 return T->getStmtClass() == ArraySubscriptExprClass;
2118 child_range children() {
2119 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2124 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2125 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2126 /// while its subclasses may represent alternative syntax that (semantically)
2127 /// results in a function call. For example, CXXOperatorCallExpr is
2128 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2129 /// "str1 + str2" to resolve to a function call.
2130 class CallExpr : public Expr {
2131 enum { FN=0, PREARGS_START=1 };
2134 SourceLocation RParenLoc;
2137 // These versions of the constructor are for derived classes.
2138 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2139 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2140 SourceLocation rparenloc);
2141 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2144 Stmt *getPreArg(unsigned i) {
2145 assert(i < getNumPreArgs() && "Prearg access out of range!");
2146 return SubExprs[PREARGS_START+i];
2148 const Stmt *getPreArg(unsigned i) const {
2149 assert(i < getNumPreArgs() && "Prearg access out of range!");
2150 return SubExprs[PREARGS_START+i];
2152 void setPreArg(unsigned i, Stmt *PreArg) {
2153 assert(i < getNumPreArgs() && "Prearg access out of range!");
2154 SubExprs[PREARGS_START+i] = PreArg;
2157 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2160 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2161 ExprValueKind VK, SourceLocation rparenloc);
2163 /// \brief Build an empty call expression.
2164 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2166 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2167 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2168 void setCallee(Expr *F) { SubExprs[FN] = F; }
2170 Decl *getCalleeDecl();
2171 const Decl *getCalleeDecl() const {
2172 return const_cast<CallExpr*>(this)->getCalleeDecl();
2175 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2176 FunctionDecl *getDirectCallee();
2177 const FunctionDecl *getDirectCallee() const {
2178 return const_cast<CallExpr*>(this)->getDirectCallee();
2181 /// getNumArgs - Return the number of actual arguments to this call.
2183 unsigned getNumArgs() const { return NumArgs; }
2185 /// \brief Retrieve the call arguments.
2187 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2189 const Expr *const *getArgs() const {
2190 return const_cast<CallExpr*>(this)->getArgs();
2193 /// getArg - Return the specified argument.
2194 Expr *getArg(unsigned Arg) {
2195 assert(Arg < NumArgs && "Arg access out of range!");
2196 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2198 const Expr *getArg(unsigned Arg) const {
2199 assert(Arg < NumArgs && "Arg access out of range!");
2200 return cast<Expr>(SubExprs[Arg+getNumPreArgs()+PREARGS_START]);
2203 /// setArg - Set the specified argument.
2204 void setArg(unsigned Arg, Expr *ArgExpr) {
2205 assert(Arg < NumArgs && "Arg access out of range!");
2206 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2209 /// setNumArgs - This changes the number of arguments present in this call.
2210 /// Any orphaned expressions are deleted by this, and any new operands are set
2212 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2214 typedef ExprIterator arg_iterator;
2215 typedef ConstExprIterator const_arg_iterator;
2217 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2218 arg_iterator arg_end() {
2219 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2221 const_arg_iterator arg_begin() const {
2222 return SubExprs+PREARGS_START+getNumPreArgs();
2224 const_arg_iterator arg_end() const {
2225 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2228 /// This method provides fast access to all the subexpressions of
2229 /// a CallExpr without going through the slower virtual child_iterator
2230 /// interface. This provides efficient reverse iteration of the
2231 /// subexpressions. This is currently used for CFG construction.
2232 ArrayRef<Stmt*> getRawSubExprs() {
2233 return ArrayRef<Stmt*>(SubExprs,
2234 getNumPreArgs() + PREARGS_START + getNumArgs());
2237 /// getNumCommas - Return the number of commas that must have been present in
2238 /// this function call.
2239 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2241 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
2243 unsigned isBuiltinCall() const;
2245 /// \brief Returns \c true if this is a call to a builtin which does not
2246 /// evaluate side-effects within its arguments.
2247 bool isUnevaluatedBuiltinCall(ASTContext &Ctx) const;
2249 /// getCallReturnType - Get the return type of the call expr. This is not
2250 /// always the type of the expr itself, if the return type is a reference
2252 QualType getCallReturnType() const;
2254 SourceLocation getRParenLoc() const { return RParenLoc; }
2255 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2257 SourceLocation getLocStart() const LLVM_READONLY;
2258 SourceLocation getLocEnd() const LLVM_READONLY;
2260 static bool classof(const Stmt *T) {
2261 return T->getStmtClass() >= firstCallExprConstant &&
2262 T->getStmtClass() <= lastCallExprConstant;
2266 child_range children() {
2267 return child_range(&SubExprs[0],
2268 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2272 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2274 class MemberExpr : public Expr {
2275 /// Extra data stored in some member expressions.
2276 struct MemberNameQualifier {
2277 /// \brief The nested-name-specifier that qualifies the name, including
2278 /// source-location information.
2279 NestedNameSpecifierLoc QualifierLoc;
2281 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2282 /// name qualifiers.
2283 DeclAccessPair FoundDecl;
2286 /// Base - the expression for the base pointer or structure references. In
2287 /// X.F, this is "X".
2290 /// MemberDecl - This is the decl being referenced by the field/member name.
2291 /// In X.F, this is the decl referenced by F.
2292 ValueDecl *MemberDecl;
2294 /// MemberDNLoc - Provides source/type location info for the
2295 /// declaration name embedded in MemberDecl.
2296 DeclarationNameLoc MemberDNLoc;
2298 /// MemberLoc - This is the location of the member name.
2299 SourceLocation MemberLoc;
2301 /// IsArrow - True if this is "X->F", false if this is "X.F".
2304 /// \brief True if this member expression used a nested-name-specifier to
2305 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2306 /// declaration. When true, a MemberNameQualifier
2307 /// structure is allocated immediately after the MemberExpr.
2308 bool HasQualifierOrFoundDecl : 1;
2310 /// \brief True if this member expression specified a template keyword
2311 /// and/or a template argument list explicitly, e.g., x->f<int>,
2312 /// x->template f, x->template f<int>.
2313 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2314 /// TemplateArguments (if any) are allocated immediately after
2315 /// the MemberExpr or, if the member expression also has a qualifier,
2316 /// after the MemberNameQualifier structure.
2317 bool HasTemplateKWAndArgsInfo : 1;
2319 /// \brief True if this member expression refers to a method that
2320 /// was resolved from an overloaded set having size greater than 1.
2321 bool HadMultipleCandidates : 1;
2323 /// \brief Retrieve the qualifier that preceded the member name, if any.
2324 MemberNameQualifier *getMemberQualifier() {
2325 assert(HasQualifierOrFoundDecl);
2326 return reinterpret_cast<MemberNameQualifier *> (this + 1);
2329 /// \brief Retrieve the qualifier that preceded the member name, if any.
2330 const MemberNameQualifier *getMemberQualifier() const {
2331 return const_cast<MemberExpr *>(this)->getMemberQualifier();
2335 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2336 const DeclarationNameInfo &NameInfo, QualType ty,
2337 ExprValueKind VK, ExprObjectKind OK)
2338 : Expr(MemberExprClass, ty, VK, OK,
2339 base->isTypeDependent(),
2340 base->isValueDependent(),
2341 base->isInstantiationDependent(),
2342 base->containsUnexpandedParameterPack()),
2343 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2344 MemberLoc(NameInfo.getLoc()), IsArrow(isarrow),
2345 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2346 HadMultipleCandidates(false) {
2347 assert(memberdecl->getDeclName() == NameInfo.getName());
2350 // NOTE: this constructor should be used only when it is known that
2351 // the member name can not provide additional syntactic info
2352 // (i.e., source locations for C++ operator names or type source info
2353 // for constructors, destructors and conversion operators).
2354 MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
2355 SourceLocation l, QualType ty,
2356 ExprValueKind VK, ExprObjectKind OK)
2357 : Expr(MemberExprClass, ty, VK, OK,
2358 base->isTypeDependent(), base->isValueDependent(),
2359 base->isInstantiationDependent(),
2360 base->containsUnexpandedParameterPack()),
2361 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2363 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2364 HadMultipleCandidates(false) {}
2366 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2367 NestedNameSpecifierLoc QualifierLoc,
2368 SourceLocation TemplateKWLoc,
2369 ValueDecl *memberdecl, DeclAccessPair founddecl,
2370 DeclarationNameInfo MemberNameInfo,
2371 const TemplateArgumentListInfo *targs,
2372 QualType ty, ExprValueKind VK, ExprObjectKind OK);
2374 void setBase(Expr *E) { Base = E; }
2375 Expr *getBase() const { return cast<Expr>(Base); }
2377 /// \brief Retrieve the member declaration to which this expression refers.
2379 /// The returned declaration will either be a FieldDecl or (in C++)
2380 /// a CXXMethodDecl.
2381 ValueDecl *getMemberDecl() const { return MemberDecl; }
2382 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2384 /// \brief Retrieves the declaration found by lookup.
2385 DeclAccessPair getFoundDecl() const {
2386 if (!HasQualifierOrFoundDecl)
2387 return DeclAccessPair::make(getMemberDecl(),
2388 getMemberDecl()->getAccess());
2389 return getMemberQualifier()->FoundDecl;
2392 /// \brief Determines whether this member expression actually had
2393 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2395 bool hasQualifier() const { return getQualifier() != 0; }
2397 /// \brief If the member name was qualified, retrieves the
2398 /// nested-name-specifier that precedes the member name. Otherwise, returns
2400 NestedNameSpecifier *getQualifier() const {
2401 if (!HasQualifierOrFoundDecl)
2404 return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
2407 /// \brief If the member name was qualified, retrieves the
2408 /// nested-name-specifier that precedes the member name, with source-location
2410 NestedNameSpecifierLoc getQualifierLoc() const {
2411 if (!hasQualifier())
2412 return NestedNameSpecifierLoc();
2414 return getMemberQualifier()->QualifierLoc;
2417 /// \brief Return the optional template keyword and arguments info.
2418 ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
2419 if (!HasTemplateKWAndArgsInfo)
2422 if (!HasQualifierOrFoundDecl)
2423 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
2425 return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
2426 getMemberQualifier() + 1);
2429 /// \brief Return the optional template keyword and arguments info.
2430 const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
2431 return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
2434 /// \brief Retrieve the location of the template keyword preceding
2435 /// the member name, if any.
2436 SourceLocation getTemplateKeywordLoc() const {
2437 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2438 return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
2441 /// \brief Retrieve the location of the left angle bracket starting the
2442 /// explicit template argument list following the member name, if any.
2443 SourceLocation getLAngleLoc() const {
2444 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2445 return getTemplateKWAndArgsInfo()->LAngleLoc;
2448 /// \brief Retrieve the location of the right angle bracket ending the
2449 /// explicit template argument list following the member name, if any.
2450 SourceLocation getRAngleLoc() const {
2451 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2452 return getTemplateKWAndArgsInfo()->RAngleLoc;
2455 /// Determines whether the member name was preceded by the template keyword.
2456 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2458 /// \brief Determines whether the member name was followed by an
2459 /// explicit template argument list.
2460 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2462 /// \brief Copies the template arguments (if present) into the given
2464 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2465 if (hasExplicitTemplateArgs())
2466 getExplicitTemplateArgs().copyInto(List);
2469 /// \brief Retrieve the explicit template argument list that
2470 /// follow the member template name. This must only be called on an
2471 /// expression with explicit template arguments.
2472 ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
2473 assert(hasExplicitTemplateArgs());
2474 return *getTemplateKWAndArgsInfo();
2477 /// \brief Retrieve the explicit template argument list that
2478 /// followed the member template name. This must only be called on
2479 /// an expression with explicit template arguments.
2480 const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
2481 return const_cast<MemberExpr *>(this)->getExplicitTemplateArgs();
2484 /// \brief Retrieves the optional explicit template arguments.
2485 /// This points to the same data as getExplicitTemplateArgs(), but
2486 /// returns null if there are no explicit template arguments.
2487 const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
2488 if (!hasExplicitTemplateArgs()) return 0;
2489 return &getExplicitTemplateArgs();
2492 /// \brief Retrieve the template arguments provided as part of this
2494 const TemplateArgumentLoc *getTemplateArgs() const {
2495 if (!hasExplicitTemplateArgs())
2498 return getExplicitTemplateArgs().getTemplateArgs();
2501 /// \brief Retrieve the number of template arguments provided as part of this
2503 unsigned getNumTemplateArgs() const {
2504 if (!hasExplicitTemplateArgs())
2507 return getExplicitTemplateArgs().NumTemplateArgs;
2510 /// \brief Retrieve the member declaration name info.
2511 DeclarationNameInfo getMemberNameInfo() const {
2512 return DeclarationNameInfo(MemberDecl->getDeclName(),
2513 MemberLoc, MemberDNLoc);
2516 bool isArrow() const { return IsArrow; }
2517 void setArrow(bool A) { IsArrow = A; }
2519 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2520 /// location of 'F'.
2521 SourceLocation getMemberLoc() const { return MemberLoc; }
2522 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2524 SourceLocation getLocStart() const LLVM_READONLY;
2525 SourceLocation getLocEnd() const LLVM_READONLY;
2527 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2529 /// \brief Determine whether the base of this explicit is implicit.
2530 bool isImplicitAccess() const {
2531 return getBase() && getBase()->isImplicitCXXThis();
2534 /// \brief Returns true if this member expression refers to a method that
2535 /// was resolved from an overloaded set having size greater than 1.
2536 bool hadMultipleCandidates() const {
2537 return HadMultipleCandidates;
2539 /// \brief Sets the flag telling whether this expression refers to
2540 /// a method that was resolved from an overloaded set having size
2542 void setHadMultipleCandidates(bool V = true) {
2543 HadMultipleCandidates = V;
2546 static bool classof(const Stmt *T) {
2547 return T->getStmtClass() == MemberExprClass;
2551 child_range children() { return child_range(&Base, &Base+1); }
2553 friend class ASTReader;
2554 friend class ASTStmtWriter;
2557 /// CompoundLiteralExpr - [C99 6.5.2.5]
2559 class CompoundLiteralExpr : public Expr {
2560 /// LParenLoc - If non-null, this is the location of the left paren in a
2561 /// compound literal like "(int){4}". This can be null if this is a
2562 /// synthesized compound expression.
2563 SourceLocation LParenLoc;
2565 /// The type as written. This can be an incomplete array type, in
2566 /// which case the actual expression type will be different.
2567 /// The int part of the pair stores whether this expr is file scope.
2568 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2571 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2572 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2573 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2574 tinfo->getType()->isDependentType(),
2575 init->isValueDependent(),
2576 (init->isInstantiationDependent() ||
2577 tinfo->getType()->isInstantiationDependentType()),
2578 init->containsUnexpandedParameterPack()),
2579 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2581 /// \brief Construct an empty compound literal.
2582 explicit CompoundLiteralExpr(EmptyShell Empty)
2583 : Expr(CompoundLiteralExprClass, Empty) { }
2585 const Expr *getInitializer() const { return cast<Expr>(Init); }
2586 Expr *getInitializer() { return cast<Expr>(Init); }
2587 void setInitializer(Expr *E) { Init = E; }
2589 bool isFileScope() const { return TInfoAndScope.getInt(); }
2590 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2592 SourceLocation getLParenLoc() const { return LParenLoc; }
2593 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2595 TypeSourceInfo *getTypeSourceInfo() const {
2596 return TInfoAndScope.getPointer();
2598 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2599 TInfoAndScope.setPointer(tinfo);
2602 SourceLocation getLocStart() const LLVM_READONLY {
2603 // FIXME: Init should never be null.
2605 return SourceLocation();
2606 if (LParenLoc.isInvalid())
2607 return Init->getLocStart();
2610 SourceLocation getLocEnd() const LLVM_READONLY {
2611 // FIXME: Init should never be null.
2613 return SourceLocation();
2614 return Init->getLocEnd();
2617 static bool classof(const Stmt *T) {
2618 return T->getStmtClass() == CompoundLiteralExprClass;
2622 child_range children() { return child_range(&Init, &Init+1); }
2625 /// CastExpr - Base class for type casts, including both implicit
2626 /// casts (ImplicitCastExpr) and explicit casts that have some
2627 /// representation in the source code (ExplicitCastExpr's derived
2629 class CastExpr : public Expr {
2631 typedef clang::CastKind CastKind;
2636 void CheckCastConsistency() const;
2638 const CXXBaseSpecifier * const *path_buffer() const {
2639 return const_cast<CastExpr*>(this)->path_buffer();
2641 CXXBaseSpecifier **path_buffer();
2643 void setBasePathSize(unsigned basePathSize) {
2644 CastExprBits.BasePathSize = basePathSize;
2645 assert(CastExprBits.BasePathSize == basePathSize &&
2646 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2650 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
2651 const CastKind kind, Expr *op, unsigned BasePathSize) :
2652 Expr(SC, ty, VK, OK_Ordinary,
2653 // Cast expressions are type-dependent if the type is
2654 // dependent (C++ [temp.dep.expr]p3).
2655 ty->isDependentType(),
2656 // Cast expressions are value-dependent if the type is
2657 // dependent or if the subexpression is value-dependent.
2658 ty->isDependentType() || (op && op->isValueDependent()),
2659 (ty->isInstantiationDependentType() ||
2660 (op && op->isInstantiationDependent())),
2661 (ty->containsUnexpandedParameterPack() ||
2662 (op && op->containsUnexpandedParameterPack()))),
2664 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2665 CastExprBits.Kind = kind;
2666 setBasePathSize(BasePathSize);
2668 CheckCastConsistency();
2672 /// \brief Construct an empty cast.
2673 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2675 setBasePathSize(BasePathSize);
2679 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2680 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2681 const char *getCastKindName() const;
2683 Expr *getSubExpr() { return cast<Expr>(Op); }
2684 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2685 void setSubExpr(Expr *E) { Op = E; }
2687 /// \brief Retrieve the cast subexpression as it was written in the source
2688 /// code, looking through any implicit casts or other intermediate nodes
2689 /// introduced by semantic analysis.
2690 Expr *getSubExprAsWritten();
2691 const Expr *getSubExprAsWritten() const {
2692 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2695 typedef CXXBaseSpecifier **path_iterator;
2696 typedef const CXXBaseSpecifier * const *path_const_iterator;
2697 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2698 unsigned path_size() const { return CastExprBits.BasePathSize; }
2699 path_iterator path_begin() { return path_buffer(); }
2700 path_iterator path_end() { return path_buffer() + path_size(); }
2701 path_const_iterator path_begin() const { return path_buffer(); }
2702 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2704 void setCastPath(const CXXCastPath &Path);
2706 static bool classof(const Stmt *T) {
2707 return T->getStmtClass() >= firstCastExprConstant &&
2708 T->getStmtClass() <= lastCastExprConstant;
2712 child_range children() { return child_range(&Op, &Op+1); }
2715 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2716 /// conversions, which have no direct representation in the original
2717 /// source code. For example: converting T[]->T*, void f()->void
2718 /// (*f)(), float->double, short->int, etc.
2720 /// In C, implicit casts always produce rvalues. However, in C++, an
2721 /// implicit cast whose result is being bound to a reference will be
2722 /// an lvalue or xvalue. For example:
2726 /// class Derived : public Base { };
2727 /// Derived &&ref();
2728 /// void f(Derived d) {
2729 /// Base& b = d; // initializer is an ImplicitCastExpr
2730 /// // to an lvalue of type Base
2731 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2732 /// // to an xvalue of type Base
2735 class ImplicitCastExpr : public CastExpr {
2737 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2738 unsigned BasePathLength, ExprValueKind VK)
2739 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2742 /// \brief Construct an empty implicit cast.
2743 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2744 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2747 enum OnStack_t { OnStack };
2748 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2750 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2753 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2754 CastKind Kind, Expr *Operand,
2755 const CXXCastPath *BasePath,
2758 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2761 SourceLocation getLocStart() const LLVM_READONLY {
2762 return getSubExpr()->getLocStart();
2764 SourceLocation getLocEnd() const LLVM_READONLY {
2765 return getSubExpr()->getLocEnd();
2768 static bool classof(const Stmt *T) {
2769 return T->getStmtClass() == ImplicitCastExprClass;
2773 inline Expr *Expr::IgnoreImpCasts() {
2775 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2776 e = ice->getSubExpr();
2780 /// ExplicitCastExpr - An explicit cast written in the source
2783 /// This class is effectively an abstract class, because it provides
2784 /// the basic representation of an explicitly-written cast without
2785 /// specifying which kind of cast (C cast, functional cast, static
2786 /// cast, etc.) was written; specific derived classes represent the
2787 /// particular style of cast and its location information.
2789 /// Unlike implicit casts, explicit cast nodes have two different
2790 /// types: the type that was written into the source code, and the
2791 /// actual type of the expression as determined by semantic
2792 /// analysis. These types may differ slightly. For example, in C++ one
2793 /// can cast to a reference type, which indicates that the resulting
2794 /// expression will be an lvalue or xvalue. The reference type, however,
2795 /// will not be used as the type of the expression.
2796 class ExplicitCastExpr : public CastExpr {
2797 /// TInfo - Source type info for the (written) type
2798 /// this expression is casting to.
2799 TypeSourceInfo *TInfo;
2802 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2803 CastKind kind, Expr *op, unsigned PathSize,
2804 TypeSourceInfo *writtenTy)
2805 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2807 /// \brief Construct an empty explicit cast.
2808 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2809 : CastExpr(SC, Shell, PathSize) { }
2812 /// getTypeInfoAsWritten - Returns the type source info for the type
2813 /// that this expression is casting to.
2814 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2815 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2817 /// getTypeAsWritten - Returns the type that this expression is
2818 /// casting to, as written in the source code.
2819 QualType getTypeAsWritten() const { return TInfo->getType(); }
2821 static bool classof(const Stmt *T) {
2822 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2823 T->getStmtClass() <= lastExplicitCastExprConstant;
2827 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2828 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2829 /// (Type)expr. For example: @c (int)f.
2830 class CStyleCastExpr : public ExplicitCastExpr {
2831 SourceLocation LPLoc; // the location of the left paren
2832 SourceLocation RPLoc; // the location of the right paren
2834 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2835 unsigned PathSize, TypeSourceInfo *writtenTy,
2836 SourceLocation l, SourceLocation r)
2837 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2838 writtenTy), LPLoc(l), RPLoc(r) {}
2840 /// \brief Construct an empty C-style explicit cast.
2841 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2842 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2845 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2846 ExprValueKind VK, CastKind K,
2847 Expr *Op, const CXXCastPath *BasePath,
2848 TypeSourceInfo *WrittenTy, SourceLocation L,
2851 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2854 SourceLocation getLParenLoc() const { return LPLoc; }
2855 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2857 SourceLocation getRParenLoc() const { return RPLoc; }
2858 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2860 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2861 SourceLocation getLocEnd() const LLVM_READONLY {
2862 return getSubExpr()->getLocEnd();
2865 static bool classof(const Stmt *T) {
2866 return T->getStmtClass() == CStyleCastExprClass;
2870 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2872 /// This expression node kind describes a builtin binary operation,
2873 /// such as "x + y" for integer values "x" and "y". The operands will
2874 /// already have been converted to appropriate types (e.g., by
2875 /// performing promotions or conversions).
2877 /// In C++, where operators may be overloaded, a different kind of
2878 /// expression node (CXXOperatorCallExpr) is used to express the
2879 /// invocation of an overloaded operator with operator syntax. Within
2880 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2881 /// used to store an expression "x + y" depends on the subexpressions
2882 /// for x and y. If neither x or y is type-dependent, and the "+"
2883 /// operator resolves to a built-in operation, BinaryOperator will be
2884 /// used to express the computation (x and y may still be
2885 /// value-dependent). If either x or y is type-dependent, or if the
2886 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2887 /// be used to express the computation.
2888 class BinaryOperator : public Expr {
2890 typedef BinaryOperatorKind Opcode;
2895 // Records the FP_CONTRACT pragma status at the point that this binary
2896 // operator was parsed. This bit is only meaningful for operations on
2897 // floating point types. For all other types it should default to
2899 unsigned FPContractable : 1;
2900 SourceLocation OpLoc;
2902 enum { LHS, RHS, END_EXPR };
2903 Stmt* SubExprs[END_EXPR];
2906 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2907 ExprValueKind VK, ExprObjectKind OK,
2908 SourceLocation opLoc, bool fpContractable)
2909 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2910 lhs->isTypeDependent() || rhs->isTypeDependent(),
2911 lhs->isValueDependent() || rhs->isValueDependent(),
2912 (lhs->isInstantiationDependent() ||
2913 rhs->isInstantiationDependent()),
2914 (lhs->containsUnexpandedParameterPack() ||
2915 rhs->containsUnexpandedParameterPack())),
2916 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2917 SubExprs[LHS] = lhs;
2918 SubExprs[RHS] = rhs;
2919 assert(!isCompoundAssignmentOp() &&
2920 "Use CompoundAssignOperator for compound assignments");
2923 /// \brief Construct an empty binary operator.
2924 explicit BinaryOperator(EmptyShell Empty)
2925 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2927 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2928 SourceLocation getOperatorLoc() const { return OpLoc; }
2929 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2931 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2932 void setOpcode(Opcode O) { Opc = O; }
2934 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2935 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2936 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2937 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2939 SourceLocation getLocStart() const LLVM_READONLY {
2940 return getLHS()->getLocStart();
2942 SourceLocation getLocEnd() const LLVM_READONLY {
2943 return getRHS()->getLocEnd();
2946 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2947 /// corresponds to, e.g. "<<=".
2948 static StringRef getOpcodeStr(Opcode Op);
2950 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2952 /// \brief Retrieve the binary opcode that corresponds to the given
2953 /// overloaded operator.
2954 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2956 /// \brief Retrieve the overloaded operator kind that corresponds to
2957 /// the given binary opcode.
2958 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2960 /// predicates to categorize the respective opcodes.
2961 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2962 bool isMultiplicativeOp() const { return Opc >= BO_Mul && Opc <= BO_Rem; }
2963 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2964 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2965 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2966 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2968 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2969 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2971 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2972 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2974 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2975 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2977 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2978 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2980 static Opcode negateComparisonOp(Opcode Opc) {
2983 llvm_unreachable("Not a comparsion operator.");
2984 case BO_LT: return BO_GE;
2985 case BO_GT: return BO_LE;
2986 case BO_LE: return BO_GT;
2987 case BO_GE: return BO_LT;
2988 case BO_EQ: return BO_NE;
2989 case BO_NE: return BO_EQ;
2993 static Opcode reverseComparisonOp(Opcode Opc) {
2996 llvm_unreachable("Not a comparsion operator.");
2997 case BO_LT: return BO_GT;
2998 case BO_GT: return BO_LT;
2999 case BO_LE: return BO_GE;
3000 case BO_GE: return BO_LE;
3007 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3008 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3010 static bool isAssignmentOp(Opcode Opc) {
3011 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3013 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3015 static bool isCompoundAssignmentOp(Opcode Opc) {
3016 return Opc > BO_Assign && Opc <= BO_OrAssign;
3018 bool isCompoundAssignmentOp() const {
3019 return isCompoundAssignmentOp(getOpcode());
3021 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3022 assert(isCompoundAssignmentOp(Opc));
3023 if (Opc >= BO_AndAssign)
3024 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3026 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3029 static bool isShiftAssignOp(Opcode Opc) {
3030 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3032 bool isShiftAssignOp() const {
3033 return isShiftAssignOp(getOpcode());
3036 static bool classof(const Stmt *S) {
3037 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3038 S->getStmtClass() <= lastBinaryOperatorConstant;
3042 child_range children() {
3043 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3046 // Set the FP contractability status of this operator. Only meaningful for
3047 // operations on floating point types.
3048 void setFPContractable(bool FPC) { FPContractable = FPC; }
3050 // Get the FP contractability status of this operator. Only meaningful for
3051 // operations on floating point types.
3052 bool isFPContractable() const { return FPContractable; }
3055 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3056 ExprValueKind VK, ExprObjectKind OK,
3057 SourceLocation opLoc, bool fpContractable, bool dead2)
3058 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3059 lhs->isTypeDependent() || rhs->isTypeDependent(),
3060 lhs->isValueDependent() || rhs->isValueDependent(),
3061 (lhs->isInstantiationDependent() ||
3062 rhs->isInstantiationDependent()),
3063 (lhs->containsUnexpandedParameterPack() ||
3064 rhs->containsUnexpandedParameterPack())),
3065 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3066 SubExprs[LHS] = lhs;
3067 SubExprs[RHS] = rhs;
3070 BinaryOperator(StmtClass SC, EmptyShell Empty)
3071 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3074 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3075 /// track of the type the operation is performed in. Due to the semantics of
3076 /// these operators, the operands are promoted, the arithmetic performed, an
3077 /// implicit conversion back to the result type done, then the assignment takes
3078 /// place. This captures the intermediate type which the computation is done
3080 class CompoundAssignOperator : public BinaryOperator {
3081 QualType ComputationLHSType;
3082 QualType ComputationResultType;
3084 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3085 ExprValueKind VK, ExprObjectKind OK,
3086 QualType CompLHSType, QualType CompResultType,
3087 SourceLocation OpLoc, bool fpContractable)
3088 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3090 ComputationLHSType(CompLHSType),
3091 ComputationResultType(CompResultType) {
3092 assert(isCompoundAssignmentOp() &&
3093 "Only should be used for compound assignments");
3096 /// \brief Build an empty compound assignment operator expression.
3097 explicit CompoundAssignOperator(EmptyShell Empty)
3098 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3100 // The two computation types are the type the LHS is converted
3101 // to for the computation and the type of the result; the two are
3102 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3103 QualType getComputationLHSType() const { return ComputationLHSType; }
3104 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3106 QualType getComputationResultType() const { return ComputationResultType; }
3107 void setComputationResultType(QualType T) { ComputationResultType = T; }
3109 static bool classof(const Stmt *S) {
3110 return S->getStmtClass() == CompoundAssignOperatorClass;
3114 /// AbstractConditionalOperator - An abstract base class for
3115 /// ConditionalOperator and BinaryConditionalOperator.
3116 class AbstractConditionalOperator : public Expr {
3117 SourceLocation QuestionLoc, ColonLoc;
3118 friend class ASTStmtReader;
3121 AbstractConditionalOperator(StmtClass SC, QualType T,
3122 ExprValueKind VK, ExprObjectKind OK,
3123 bool TD, bool VD, bool ID,
3124 bool ContainsUnexpandedParameterPack,
3125 SourceLocation qloc,
3126 SourceLocation cloc)
3127 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3128 QuestionLoc(qloc), ColonLoc(cloc) {}
3130 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3131 : Expr(SC, Empty) { }
3134 // getCond - Return the expression representing the condition for
3136 Expr *getCond() const;
3138 // getTrueExpr - Return the subexpression representing the value of
3139 // the expression if the condition evaluates to true.
3140 Expr *getTrueExpr() const;
3142 // getFalseExpr - Return the subexpression representing the value of
3143 // the expression if the condition evaluates to false. This is
3144 // the same as getRHS.
3145 Expr *getFalseExpr() const;
3147 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3148 SourceLocation getColonLoc() const { return ColonLoc; }
3150 static bool classof(const Stmt *T) {
3151 return T->getStmtClass() == ConditionalOperatorClass ||
3152 T->getStmtClass() == BinaryConditionalOperatorClass;
3156 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3157 /// middle" extension is a BinaryConditionalOperator.
3158 class ConditionalOperator : public AbstractConditionalOperator {
3159 enum { COND, LHS, RHS, END_EXPR };
3160 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3162 friend class ASTStmtReader;
3164 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3165 SourceLocation CLoc, Expr *rhs,
3166 QualType t, ExprValueKind VK, ExprObjectKind OK)
3167 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3168 // FIXME: the type of the conditional operator doesn't
3169 // depend on the type of the conditional, but the standard
3170 // seems to imply that it could. File a bug!
3171 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3172 (cond->isValueDependent() || lhs->isValueDependent() ||
3173 rhs->isValueDependent()),
3174 (cond->isInstantiationDependent() ||
3175 lhs->isInstantiationDependent() ||
3176 rhs->isInstantiationDependent()),
3177 (cond->containsUnexpandedParameterPack() ||
3178 lhs->containsUnexpandedParameterPack() ||
3179 rhs->containsUnexpandedParameterPack()),
3181 SubExprs[COND] = cond;
3182 SubExprs[LHS] = lhs;
3183 SubExprs[RHS] = rhs;
3186 /// \brief Build an empty conditional operator.
3187 explicit ConditionalOperator(EmptyShell Empty)
3188 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3190 // getCond - Return the expression representing the condition for
3192 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3194 // getTrueExpr - Return the subexpression representing the value of
3195 // the expression if the condition evaluates to true.
3196 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3198 // getFalseExpr - Return the subexpression representing the value of
3199 // the expression if the condition evaluates to false. This is
3200 // the same as getRHS.
3201 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3203 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3204 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3206 SourceLocation getLocStart() const LLVM_READONLY {
3207 return getCond()->getLocStart();
3209 SourceLocation getLocEnd() const LLVM_READONLY {
3210 return getRHS()->getLocEnd();
3213 static bool classof(const Stmt *T) {
3214 return T->getStmtClass() == ConditionalOperatorClass;
3218 child_range children() {
3219 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3223 /// BinaryConditionalOperator - The GNU extension to the conditional
3224 /// operator which allows the middle operand to be omitted.
3226 /// This is a different expression kind on the assumption that almost
3227 /// every client ends up needing to know that these are different.
3228 class BinaryConditionalOperator : public AbstractConditionalOperator {
3229 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3231 /// - the common condition/left-hand-side expression, which will be
3232 /// evaluated as the opaque value
3233 /// - the condition, expressed in terms of the opaque value
3234 /// - the left-hand-side, expressed in terms of the opaque value
3235 /// - the right-hand-side
3236 Stmt *SubExprs[NUM_SUBEXPRS];
3237 OpaqueValueExpr *OpaqueValue;
3239 friend class ASTStmtReader;
3241 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3242 Expr *cond, Expr *lhs, Expr *rhs,
3243 SourceLocation qloc, SourceLocation cloc,
3244 QualType t, ExprValueKind VK, ExprObjectKind OK)
3245 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3246 (common->isTypeDependent() || rhs->isTypeDependent()),
3247 (common->isValueDependent() || rhs->isValueDependent()),
3248 (common->isInstantiationDependent() ||
3249 rhs->isInstantiationDependent()),
3250 (common->containsUnexpandedParameterPack() ||
3251 rhs->containsUnexpandedParameterPack()),
3253 OpaqueValue(opaqueValue) {
3254 SubExprs[COMMON] = common;
3255 SubExprs[COND] = cond;
3256 SubExprs[LHS] = lhs;
3257 SubExprs[RHS] = rhs;
3258 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3261 /// \brief Build an empty conditional operator.
3262 explicit BinaryConditionalOperator(EmptyShell Empty)
3263 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3265 /// \brief getCommon - Return the common expression, written to the
3266 /// left of the condition. The opaque value will be bound to the
3267 /// result of this expression.
3268 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3270 /// \brief getOpaqueValue - Return the opaque value placeholder.
3271 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3273 /// \brief getCond - Return the condition expression; this is defined
3274 /// in terms of the opaque value.
3275 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3277 /// \brief getTrueExpr - Return the subexpression which will be
3278 /// evaluated if the condition evaluates to true; this is defined
3279 /// in terms of the opaque value.
3280 Expr *getTrueExpr() const {
3281 return cast<Expr>(SubExprs[LHS]);
3284 /// \brief getFalseExpr - Return the subexpression which will be
3285 /// evaluated if the condnition evaluates to false; this is
3286 /// defined in terms of the opaque value.
3287 Expr *getFalseExpr() const {
3288 return cast<Expr>(SubExprs[RHS]);
3291 SourceLocation getLocStart() const LLVM_READONLY {
3292 return getCommon()->getLocStart();
3294 SourceLocation getLocEnd() const LLVM_READONLY {
3295 return getFalseExpr()->getLocEnd();
3298 static bool classof(const Stmt *T) {
3299 return T->getStmtClass() == BinaryConditionalOperatorClass;
3303 child_range children() {
3304 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3308 inline Expr *AbstractConditionalOperator::getCond() const {
3309 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3310 return co->getCond();
3311 return cast<BinaryConditionalOperator>(this)->getCond();
3314 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3315 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3316 return co->getTrueExpr();
3317 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3320 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3321 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3322 return co->getFalseExpr();
3323 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3326 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3327 class AddrLabelExpr : public Expr {
3328 SourceLocation AmpAmpLoc, LabelLoc;
3331 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3333 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3335 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3337 /// \brief Build an empty address of a label expression.
3338 explicit AddrLabelExpr(EmptyShell Empty)
3339 : Expr(AddrLabelExprClass, Empty) { }
3341 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3342 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3343 SourceLocation getLabelLoc() const { return LabelLoc; }
3344 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3346 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3347 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3349 LabelDecl *getLabel() const { return Label; }
3350 void setLabel(LabelDecl *L) { Label = L; }
3352 static bool classof(const Stmt *T) {
3353 return T->getStmtClass() == AddrLabelExprClass;
3357 child_range children() { return child_range(); }
3360 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3361 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3362 /// takes the value of the last subexpression.
3364 /// A StmtExpr is always an r-value; values "returned" out of a
3365 /// StmtExpr will be copied.
3366 class StmtExpr : public Expr {
3368 SourceLocation LParenLoc, RParenLoc;
3370 // FIXME: Does type-dependence need to be computed differently?
3371 // FIXME: Do we need to compute instantiation instantiation-dependence for
3372 // statements? (ugh!)
3373 StmtExpr(CompoundStmt *substmt, QualType T,
3374 SourceLocation lp, SourceLocation rp) :
3375 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3376 T->isDependentType(), false, false, false),
3377 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3379 /// \brief Build an empty statement expression.
3380 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3382 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3383 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3384 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3386 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3387 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3389 SourceLocation getLParenLoc() const { return LParenLoc; }
3390 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3391 SourceLocation getRParenLoc() const { return RParenLoc; }
3392 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3394 static bool classof(const Stmt *T) {
3395 return T->getStmtClass() == StmtExprClass;
3399 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3403 /// ShuffleVectorExpr - clang-specific builtin-in function
3404 /// __builtin_shufflevector.
3405 /// This AST node represents a operator that does a constant
3406 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3407 /// two vectors and a variable number of constant indices,
3408 /// and returns the appropriately shuffled vector.
3409 class ShuffleVectorExpr : public Expr {
3410 SourceLocation BuiltinLoc, RParenLoc;
3412 // SubExprs - the list of values passed to the __builtin_shufflevector
3413 // function. The first two are vectors, and the rest are constant
3414 // indices. The number of values in this list is always
3415 // 2+the number of indices in the vector type.
3420 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3421 SourceLocation BLoc, SourceLocation RP);
3423 /// \brief Build an empty vector-shuffle expression.
3424 explicit ShuffleVectorExpr(EmptyShell Empty)
3425 : Expr(ShuffleVectorExprClass, Empty), SubExprs(0) { }
3427 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3428 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3430 SourceLocation getRParenLoc() const { return RParenLoc; }
3431 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3433 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3434 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3436 static bool classof(const Stmt *T) {
3437 return T->getStmtClass() == ShuffleVectorExprClass;
3440 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3441 /// constant expression, the actual arguments passed in, and the function
3443 unsigned getNumSubExprs() const { return NumExprs; }
3445 /// \brief Retrieve the array of expressions.
3446 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3448 /// getExpr - Return the Expr at the specified index.
3449 Expr *getExpr(unsigned Index) {
3450 assert((Index < NumExprs) && "Arg access out of range!");
3451 return cast<Expr>(SubExprs[Index]);
3453 const Expr *getExpr(unsigned Index) const {
3454 assert((Index < NumExprs) && "Arg access out of range!");
3455 return cast<Expr>(SubExprs[Index]);
3458 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3460 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3461 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3462 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3466 child_range children() {
3467 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3471 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3472 /// This AST node provides support for converting a vector type to another
3473 /// vector type of the same arity.
3474 class ConvertVectorExpr : public Expr {
3477 TypeSourceInfo *TInfo;
3478 SourceLocation BuiltinLoc, RParenLoc;
3480 friend class ASTReader;
3481 friend class ASTStmtReader;
3482 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3485 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3486 ExprValueKind VK, ExprObjectKind OK,
3487 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3488 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3489 DstType->isDependentType(),
3490 DstType->isDependentType() || SrcExpr->isValueDependent(),
3491 (DstType->isInstantiationDependentType() ||
3492 SrcExpr->isInstantiationDependent()),
3493 (DstType->containsUnexpandedParameterPack() ||
3494 SrcExpr->containsUnexpandedParameterPack())),
3495 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3497 /// getSrcExpr - Return the Expr to be converted.
3498 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3500 /// getTypeSourceInfo - Return the destination type.
3501 TypeSourceInfo *getTypeSourceInfo() const {
3504 void setTypeSourceInfo(TypeSourceInfo *ti) {
3508 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3509 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3511 /// getRParenLoc - Return the location of final right parenthesis.
3512 SourceLocation getRParenLoc() const { return RParenLoc; }
3514 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3515 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3517 static bool classof(const Stmt *T) {
3518 return T->getStmtClass() == ConvertVectorExprClass;
3522 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3525 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3526 /// This AST node is similar to the conditional operator (?:) in C, with
3527 /// the following exceptions:
3528 /// - the test expression must be a integer constant expression.
3529 /// - the expression returned acts like the chosen subexpression in every
3530 /// visible way: the type is the same as that of the chosen subexpression,
3531 /// and all predicates (whether it's an l-value, whether it's an integer
3532 /// constant expression, etc.) return the same result as for the chosen
3534 class ChooseExpr : public Expr {
3535 enum { COND, LHS, RHS, END_EXPR };
3536 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3537 SourceLocation BuiltinLoc, RParenLoc;
3540 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3541 QualType t, ExprValueKind VK, ExprObjectKind OK,
3542 SourceLocation RP, bool condIsTrue,
3543 bool TypeDependent, bool ValueDependent)
3544 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3545 (cond->isInstantiationDependent() ||
3546 lhs->isInstantiationDependent() ||
3547 rhs->isInstantiationDependent()),
3548 (cond->containsUnexpandedParameterPack() ||
3549 lhs->containsUnexpandedParameterPack() ||
3550 rhs->containsUnexpandedParameterPack())),
3551 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3552 SubExprs[COND] = cond;
3553 SubExprs[LHS] = lhs;
3554 SubExprs[RHS] = rhs;
3557 /// \brief Build an empty __builtin_choose_expr.
3558 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3560 /// isConditionTrue - Return whether the condition is true (i.e. not
3562 bool isConditionTrue() const {
3563 assert(!isConditionDependent() &&
3564 "Dependent condition isn't true or false");
3567 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3569 bool isConditionDependent() const {
3570 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3573 /// getChosenSubExpr - Return the subexpression chosen according to the
3575 Expr *getChosenSubExpr() const {
3576 return isConditionTrue() ? getLHS() : getRHS();
3579 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3580 void setCond(Expr *E) { SubExprs[COND] = E; }
3581 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3582 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3583 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3584 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3586 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3587 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3589 SourceLocation getRParenLoc() const { return RParenLoc; }
3590 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3592 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3593 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3595 static bool classof(const Stmt *T) {
3596 return T->getStmtClass() == ChooseExprClass;
3600 child_range children() {
3601 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3605 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3606 /// for a null pointer constant that has integral type (e.g., int or
3607 /// long) and is the same size and alignment as a pointer. The __null
3608 /// extension is typically only used by system headers, which define
3609 /// NULL as __null in C++ rather than using 0 (which is an integer
3610 /// that may not match the size of a pointer).
3611 class GNUNullExpr : public Expr {
3612 /// TokenLoc - The location of the __null keyword.
3613 SourceLocation TokenLoc;
3616 GNUNullExpr(QualType Ty, SourceLocation Loc)
3617 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3621 /// \brief Build an empty GNU __null expression.
3622 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3624 /// getTokenLocation - The location of the __null token.
3625 SourceLocation getTokenLocation() const { return TokenLoc; }
3626 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3628 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3629 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3631 static bool classof(const Stmt *T) {
3632 return T->getStmtClass() == GNUNullExprClass;
3636 child_range children() { return child_range(); }
3639 /// VAArgExpr, used for the builtin function __builtin_va_arg.
3640 class VAArgExpr : public Expr {
3642 TypeSourceInfo *TInfo;
3643 SourceLocation BuiltinLoc, RParenLoc;
3645 VAArgExpr(SourceLocation BLoc, Expr* e, TypeSourceInfo *TInfo,
3646 SourceLocation RPLoc, QualType t)
3647 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary,
3648 t->isDependentType(), false,
3649 (TInfo->getType()->isInstantiationDependentType() ||
3650 e->isInstantiationDependent()),
3651 (TInfo->getType()->containsUnexpandedParameterPack() ||
3652 e->containsUnexpandedParameterPack())),
3653 Val(e), TInfo(TInfo),
3655 RParenLoc(RPLoc) { }
3657 /// \brief Create an empty __builtin_va_arg expression.
3658 explicit VAArgExpr(EmptyShell Empty) : Expr(VAArgExprClass, Empty) { }
3660 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3661 Expr *getSubExpr() { return cast<Expr>(Val); }
3662 void setSubExpr(Expr *E) { Val = E; }
3664 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo; }
3665 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo = TI; }
3667 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3668 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3670 SourceLocation getRParenLoc() const { return RParenLoc; }
3671 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3673 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3674 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3676 static bool classof(const Stmt *T) {
3677 return T->getStmtClass() == VAArgExprClass;
3681 child_range children() { return child_range(&Val, &Val+1); }
3684 /// @brief Describes an C or C++ initializer list.
3686 /// InitListExpr describes an initializer list, which can be used to
3687 /// initialize objects of different types, including
3688 /// struct/class/union types, arrays, and vectors. For example:
3691 /// struct foo x = { 1, { 2, 3 } };
3694 /// Prior to semantic analysis, an initializer list will represent the
3695 /// initializer list as written by the user, but will have the
3696 /// placeholder type "void". This initializer list is called the
3697 /// syntactic form of the initializer, and may contain C99 designated
3698 /// initializers (represented as DesignatedInitExprs), initializations
3699 /// of subobject members without explicit braces, and so on. Clients
3700 /// interested in the original syntax of the initializer list should
3701 /// use the syntactic form of the initializer list.
3703 /// After semantic analysis, the initializer list will represent the
3704 /// semantic form of the initializer, where the initializations of all
3705 /// subobjects are made explicit with nested InitListExpr nodes and
3706 /// C99 designators have been eliminated by placing the designated
3707 /// initializations into the subobject they initialize. Additionally,
3708 /// any "holes" in the initialization, where no initializer has been
3709 /// specified for a particular subobject, will be replaced with
3710 /// implicitly-generated ImplicitValueInitExpr expressions that
3711 /// value-initialize the subobjects. Note, however, that the
3712 /// initializer lists may still have fewer initializers than there are
3713 /// elements to initialize within the object.
3715 /// After semantic analysis has completed, given an initializer list,
3716 /// method isSemanticForm() returns true if and only if this is the
3717 /// semantic form of the initializer list (note: the same AST node
3718 /// may at the same time be the syntactic form).
3719 /// Given the semantic form of the initializer list, one can retrieve
3720 /// the syntactic form of that initializer list (when different)
3721 /// using method getSyntacticForm(); the method returns null if applied
3722 /// to a initializer list which is already in syntactic form.
3723 /// Similarly, given the syntactic form (i.e., an initializer list such
3724 /// that isSemanticForm() returns false), one can retrieve the semantic
3725 /// form using method getSemanticForm().
3726 /// Since many initializer lists have the same syntactic and semantic forms,
3727 /// getSyntacticForm() may return NULL, indicating that the current
3728 /// semantic initializer list also serves as its syntactic form.
3729 class InitListExpr : public Expr {
3730 // FIXME: Eliminate this vector in favor of ASTContext allocation
3731 typedef ASTVector<Stmt *> InitExprsTy;
3732 InitExprsTy InitExprs;
3733 SourceLocation LBraceLoc, RBraceLoc;
3735 /// The alternative form of the initializer list (if it exists).
3736 /// The int part of the pair stores whether this initializer list is
3737 /// in semantic form. If not null, the pointer points to:
3738 /// - the syntactic form, if this is in semantic form;
3739 /// - the semantic form, if this is in syntactic form.
3740 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3743 /// If this initializer list initializes an array with more elements than
3744 /// there are initializers in the list, specifies an expression to be used
3745 /// for value initialization of the rest of the elements.
3747 /// If this initializer list initializes a union, specifies which
3748 /// field within the union will be initialized.
3749 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3752 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3753 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3755 /// \brief Build an empty initializer list.
3756 explicit InitListExpr(EmptyShell Empty)
3757 : Expr(InitListExprClass, Empty) { }
3759 unsigned getNumInits() const { return InitExprs.size(); }
3761 /// \brief Retrieve the set of initializers.
3762 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3764 const Expr *getInit(unsigned Init) const {
3765 assert(Init < getNumInits() && "Initializer access out of range!");
3766 return cast_or_null<Expr>(InitExprs[Init]);
3769 Expr *getInit(unsigned Init) {
3770 assert(Init < getNumInits() && "Initializer access out of range!");
3771 return cast_or_null<Expr>(InitExprs[Init]);
3774 void setInit(unsigned Init, Expr *expr) {
3775 assert(Init < getNumInits() && "Initializer access out of range!");
3776 InitExprs[Init] = expr;
3779 /// \brief Reserve space for some number of initializers.
3780 void reserveInits(const ASTContext &C, unsigned NumInits);
3782 /// @brief Specify the number of initializers
3784 /// If there are more than @p NumInits initializers, the remaining
3785 /// initializers will be destroyed. If there are fewer than @p
3786 /// NumInits initializers, NULL expressions will be added for the
3787 /// unknown initializers.
3788 void resizeInits(const ASTContext &Context, unsigned NumInits);
3790 /// @brief Updates the initializer at index @p Init with the new
3791 /// expression @p expr, and returns the old expression at that
3794 /// When @p Init is out of range for this initializer list, the
3795 /// initializer list will be extended with NULL expressions to
3796 /// accommodate the new entry.
3797 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3799 /// \brief If this initializer list initializes an array with more elements
3800 /// than there are initializers in the list, specifies an expression to be
3801 /// used for value initialization of the rest of the elements.
3802 Expr *getArrayFiller() {
3803 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3805 const Expr *getArrayFiller() const {
3806 return const_cast<InitListExpr *>(this)->getArrayFiller();
3808 void setArrayFiller(Expr *filler);
3810 /// \brief Return true if this is an array initializer and its array "filler"
3812 bool hasArrayFiller() const { return getArrayFiller(); }
3814 /// \brief If this initializes a union, specifies which field in the
3815 /// union to initialize.
3817 /// Typically, this field is the first named field within the
3818 /// union. However, a designated initializer can specify the
3819 /// initialization of a different field within the union.
3820 FieldDecl *getInitializedFieldInUnion() {
3821 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3823 const FieldDecl *getInitializedFieldInUnion() const {
3824 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3826 void setInitializedFieldInUnion(FieldDecl *FD) {
3828 || getInitializedFieldInUnion() == 0
3829 || getInitializedFieldInUnion() == FD)
3830 && "Only one field of a union may be initialized at a time!");
3831 ArrayFillerOrUnionFieldInit = FD;
3834 // Explicit InitListExpr's originate from source code (and have valid source
3835 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3837 return LBraceLoc.isValid() && RBraceLoc.isValid();
3840 // Is this an initializer for an array of characters, initialized by a string
3841 // literal or an @encode?
3842 bool isStringLiteralInit() const;
3844 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3845 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3846 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3847 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3849 bool isSemanticForm() const { return AltForm.getInt(); }
3850 InitListExpr *getSemanticForm() const {
3851 return isSemanticForm() ? 0 : AltForm.getPointer();
3853 InitListExpr *getSyntacticForm() const {
3854 return isSemanticForm() ? AltForm.getPointer() : 0;
3857 void setSyntacticForm(InitListExpr *Init) {
3858 AltForm.setPointer(Init);
3859 AltForm.setInt(true);
3860 Init->AltForm.setPointer(this);
3861 Init->AltForm.setInt(false);
3864 bool hadArrayRangeDesignator() const {
3865 return InitListExprBits.HadArrayRangeDesignator != 0;
3867 void sawArrayRangeDesignator(bool ARD = true) {
3868 InitListExprBits.HadArrayRangeDesignator = ARD;
3871 SourceLocation getLocStart() const LLVM_READONLY;
3872 SourceLocation getLocEnd() const LLVM_READONLY;
3874 static bool classof(const Stmt *T) {
3875 return T->getStmtClass() == InitListExprClass;
3879 child_range children() {
3880 if (InitExprs.empty()) return child_range();
3881 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3884 typedef InitExprsTy::iterator iterator;
3885 typedef InitExprsTy::const_iterator const_iterator;
3886 typedef InitExprsTy::reverse_iterator reverse_iterator;
3887 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3889 iterator begin() { return InitExprs.begin(); }
3890 const_iterator begin() const { return InitExprs.begin(); }
3891 iterator end() { return InitExprs.end(); }
3892 const_iterator end() const { return InitExprs.end(); }
3893 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3894 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3895 reverse_iterator rend() { return InitExprs.rend(); }
3896 const_reverse_iterator rend() const { return InitExprs.rend(); }
3898 friend class ASTStmtReader;
3899 friend class ASTStmtWriter;
3902 /// @brief Represents a C99 designated initializer expression.
3904 /// A designated initializer expression (C99 6.7.8) contains one or
3905 /// more designators (which can be field designators, array
3906 /// designators, or GNU array-range designators) followed by an
3907 /// expression that initializes the field or element(s) that the
3908 /// designators refer to. For example, given:
3915 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3918 /// The InitListExpr contains three DesignatedInitExprs, the first of
3919 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3920 /// designators, one array designator for @c [2] followed by one field
3921 /// designator for @c .y. The initialization expression will be 1.0.
3922 class DesignatedInitExpr : public Expr {
3924 /// \brief Forward declaration of the Designator class.
3928 /// The location of the '=' or ':' prior to the actual initializer
3930 SourceLocation EqualOrColonLoc;
3932 /// Whether this designated initializer used the GNU deprecated
3933 /// syntax rather than the C99 '=' syntax.
3936 /// The number of designators in this initializer expression.
3937 unsigned NumDesignators : 15;
3939 /// The number of subexpressions of this initializer expression,
3940 /// which contains both the initializer and any additional
3941 /// expressions used by array and array-range designators.
3942 unsigned NumSubExprs : 16;
3944 /// \brief The designators in this designated initialization
3946 Designator *Designators;
3949 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3950 const Designator *Designators,
3951 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3952 ArrayRef<Expr*> IndexExprs, Expr *Init);
3954 explicit DesignatedInitExpr(unsigned NumSubExprs)
3955 : Expr(DesignatedInitExprClass, EmptyShell()),
3956 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(0) { }
3959 /// A field designator, e.g., ".x".
3960 struct FieldDesignator {
3961 /// Refers to the field that is being initialized. The low bit
3962 /// of this field determines whether this is actually a pointer
3963 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3964 /// initially constructed, a field designator will store an
3965 /// IdentifierInfo*. After semantic analysis has resolved that
3966 /// name, the field designator will instead store a FieldDecl*.
3967 uintptr_t NameOrField;
3969 /// The location of the '.' in the designated initializer.
3972 /// The location of the field name in the designated initializer.
3976 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3977 struct ArrayOrRangeDesignator {
3978 /// Location of the first index expression within the designated
3979 /// initializer expression's list of subexpressions.
3981 /// The location of the '[' starting the array range designator.
3982 unsigned LBracketLoc;
3983 /// The location of the ellipsis separating the start and end
3984 /// indices. Only valid for GNU array-range designators.
3985 unsigned EllipsisLoc;
3986 /// The location of the ']' terminating the array range designator.
3987 unsigned RBracketLoc;
3990 /// @brief Represents a single C99 designator.
3992 /// @todo This class is infuriatingly similar to clang::Designator,
3993 /// but minor differences (storing indices vs. storing pointers)
3994 /// keep us from reusing it. Try harder, later, to rectify these
3997 /// @brief The kind of designator this describes.
4001 ArrayRangeDesignator
4005 /// A field designator, e.g., ".x".
4006 struct FieldDesignator Field;
4007 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4008 struct ArrayOrRangeDesignator ArrayOrRange;
4010 friend class DesignatedInitExpr;
4015 /// @brief Initializes a field designator.
4016 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4017 SourceLocation FieldLoc)
4018 : Kind(FieldDesignator) {
4019 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4020 Field.DotLoc = DotLoc.getRawEncoding();
4021 Field.FieldLoc = FieldLoc.getRawEncoding();
4024 /// @brief Initializes an array designator.
4025 Designator(unsigned Index, SourceLocation LBracketLoc,
4026 SourceLocation RBracketLoc)
4027 : Kind(ArrayDesignator) {
4028 ArrayOrRange.Index = Index;
4029 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4030 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4031 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4034 /// @brief Initializes a GNU array-range designator.
4035 Designator(unsigned Index, SourceLocation LBracketLoc,
4036 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4037 : Kind(ArrayRangeDesignator) {
4038 ArrayOrRange.Index = Index;
4039 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4040 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4041 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4044 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4045 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4046 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4048 IdentifierInfo *getFieldName() const;
4050 FieldDecl *getField() const {
4051 assert(Kind == FieldDesignator && "Only valid on a field designator");
4052 if (Field.NameOrField & 0x01)
4055 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4058 void setField(FieldDecl *FD) {
4059 assert(Kind == FieldDesignator && "Only valid on a field designator");
4060 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4063 SourceLocation getDotLoc() const {
4064 assert(Kind == FieldDesignator && "Only valid on a field designator");
4065 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4068 SourceLocation getFieldLoc() const {
4069 assert(Kind == FieldDesignator && "Only valid on a field designator");
4070 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4073 SourceLocation getLBracketLoc() const {
4074 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4075 "Only valid on an array or array-range designator");
4076 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4079 SourceLocation getRBracketLoc() const {
4080 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4081 "Only valid on an array or array-range designator");
4082 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4085 SourceLocation getEllipsisLoc() const {
4086 assert(Kind == ArrayRangeDesignator &&
4087 "Only valid on an array-range designator");
4088 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4091 unsigned getFirstExprIndex() const {
4092 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4093 "Only valid on an array or array-range designator");
4094 return ArrayOrRange.Index;
4097 SourceLocation getLocStart() const LLVM_READONLY {
4098 if (Kind == FieldDesignator)
4099 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4101 return getLBracketLoc();
4103 SourceLocation getLocEnd() const LLVM_READONLY {
4104 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4106 SourceRange getSourceRange() const LLVM_READONLY {
4107 return SourceRange(getLocStart(), getLocEnd());
4111 static DesignatedInitExpr *Create(const ASTContext &C,
4112 Designator *Designators,
4113 unsigned NumDesignators,
4114 ArrayRef<Expr*> IndexExprs,
4115 SourceLocation EqualOrColonLoc,
4116 bool GNUSyntax, Expr *Init);
4118 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4119 unsigned NumIndexExprs);
4121 /// @brief Returns the number of designators in this initializer.
4122 unsigned size() const { return NumDesignators; }
4124 // Iterator access to the designators.
4125 typedef Designator *designators_iterator;
4126 designators_iterator designators_begin() { return Designators; }
4127 designators_iterator designators_end() {
4128 return Designators + NumDesignators;
4131 typedef const Designator *const_designators_iterator;
4132 const_designators_iterator designators_begin() const { return Designators; }
4133 const_designators_iterator designators_end() const {
4134 return Designators + NumDesignators;
4137 typedef std::reverse_iterator<designators_iterator>
4138 reverse_designators_iterator;
4139 reverse_designators_iterator designators_rbegin() {
4140 return reverse_designators_iterator(designators_end());
4142 reverse_designators_iterator designators_rend() {
4143 return reverse_designators_iterator(designators_begin());
4146 typedef std::reverse_iterator<const_designators_iterator>
4147 const_reverse_designators_iterator;
4148 const_reverse_designators_iterator designators_rbegin() const {
4149 return const_reverse_designators_iterator(designators_end());
4151 const_reverse_designators_iterator designators_rend() const {
4152 return const_reverse_designators_iterator(designators_begin());
4155 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4157 void setDesignators(const ASTContext &C, const Designator *Desigs,
4158 unsigned NumDesigs);
4160 Expr *getArrayIndex(const Designator &D) const;
4161 Expr *getArrayRangeStart(const Designator &D) const;
4162 Expr *getArrayRangeEnd(const Designator &D) const;
4164 /// @brief Retrieve the location of the '=' that precedes the
4165 /// initializer value itself, if present.
4166 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4167 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4169 /// @brief Determines whether this designated initializer used the
4170 /// deprecated GNU syntax for designated initializers.
4171 bool usesGNUSyntax() const { return GNUSyntax; }
4172 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4174 /// @brief Retrieve the initializer value.
4175 Expr *getInit() const {
4176 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4179 void setInit(Expr *init) {
4180 *child_begin() = init;
4183 /// \brief Retrieve the total number of subexpressions in this
4184 /// designated initializer expression, including the actual
4185 /// initialized value and any expressions that occur within array
4186 /// and array-range designators.
4187 unsigned getNumSubExprs() const { return NumSubExprs; }
4189 Expr *getSubExpr(unsigned Idx) {
4190 assert(Idx < NumSubExprs && "Subscript out of range");
4191 char* Ptr = static_cast<char*>(static_cast<void *>(this));
4192 Ptr += sizeof(DesignatedInitExpr);
4193 return reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx];
4196 void setSubExpr(unsigned Idx, Expr *E) {
4197 assert(Idx < NumSubExprs && "Subscript out of range");
4198 char* Ptr = static_cast<char*>(static_cast<void *>(this));
4199 Ptr += sizeof(DesignatedInitExpr);
4200 reinterpret_cast<Expr**>(reinterpret_cast<void**>(Ptr))[Idx] = E;
4203 /// \brief Replaces the designator at index @p Idx with the series
4204 /// of designators in [First, Last).
4205 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4206 const Designator *First, const Designator *Last);
4208 SourceRange getDesignatorsSourceRange() const;
4210 SourceLocation getLocStart() const LLVM_READONLY;
4211 SourceLocation getLocEnd() const LLVM_READONLY;
4213 static bool classof(const Stmt *T) {
4214 return T->getStmtClass() == DesignatedInitExprClass;
4218 child_range children() {
4219 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4220 return child_range(begin, begin + NumSubExprs);
4224 /// \brief Represents an implicitly-generated value initialization of
4225 /// an object of a given type.
4227 /// Implicit value initializations occur within semantic initializer
4228 /// list expressions (InitListExpr) as placeholders for subobject
4229 /// initializations not explicitly specified by the user.
4231 /// \see InitListExpr
4232 class ImplicitValueInitExpr : public Expr {
4234 explicit ImplicitValueInitExpr(QualType ty)
4235 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4236 false, false, ty->isInstantiationDependentType(), false) { }
4238 /// \brief Construct an empty implicit value initialization.
4239 explicit ImplicitValueInitExpr(EmptyShell Empty)
4240 : Expr(ImplicitValueInitExprClass, Empty) { }
4242 static bool classof(const Stmt *T) {
4243 return T->getStmtClass() == ImplicitValueInitExprClass;
4246 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4247 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4250 child_range children() { return child_range(); }
4254 class ParenListExpr : public Expr {
4257 SourceLocation LParenLoc, RParenLoc;
4260 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4261 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4263 /// \brief Build an empty paren list.
4264 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4266 unsigned getNumExprs() const { return NumExprs; }
4268 const Expr* getExpr(unsigned Init) const {
4269 assert(Init < getNumExprs() && "Initializer access out of range!");
4270 return cast_or_null<Expr>(Exprs[Init]);
4273 Expr* getExpr(unsigned Init) {
4274 assert(Init < getNumExprs() && "Initializer access out of range!");
4275 return cast_or_null<Expr>(Exprs[Init]);
4278 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4280 SourceLocation getLParenLoc() const { return LParenLoc; }
4281 SourceLocation getRParenLoc() const { return RParenLoc; }
4283 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4284 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4286 static bool classof(const Stmt *T) {
4287 return T->getStmtClass() == ParenListExprClass;
4291 child_range children() {
4292 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4295 friend class ASTStmtReader;
4296 friend class ASTStmtWriter;
4300 /// \brief Represents a C11 generic selection.
4302 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4303 /// expression, followed by one or more generic associations. Each generic
4304 /// association specifies a type name and an expression, or "default" and an
4305 /// expression (in which case it is known as a default generic association).
4306 /// The type and value of the generic selection are identical to those of its
4307 /// result expression, which is defined as the expression in the generic
4308 /// association with a type name that is compatible with the type of the
4309 /// controlling expression, or the expression in the default generic association
4310 /// if no types are compatible. For example:
4313 /// _Generic(X, double: 1, float: 2, default: 3)
4316 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4317 /// or 3 if "hello".
4319 /// As an extension, generic selections are allowed in C++, where the following
4320 /// additional semantics apply:
4322 /// Any generic selection whose controlling expression is type-dependent or
4323 /// which names a dependent type in its association list is result-dependent,
4324 /// which means that the choice of result expression is dependent.
4325 /// Result-dependent generic associations are both type- and value-dependent.
4326 class GenericSelectionExpr : public Expr {
4327 enum { CONTROLLING, END_EXPR };
4328 TypeSourceInfo **AssocTypes;
4330 unsigned NumAssocs, ResultIndex;
4331 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4334 GenericSelectionExpr(const ASTContext &Context,
4335 SourceLocation GenericLoc, Expr *ControllingExpr,
4336 ArrayRef<TypeSourceInfo*> AssocTypes,
4337 ArrayRef<Expr*> AssocExprs,
4338 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4339 bool ContainsUnexpandedParameterPack,
4340 unsigned ResultIndex);
4342 /// This constructor is used in the result-dependent case.
4343 GenericSelectionExpr(const ASTContext &Context,
4344 SourceLocation GenericLoc, Expr *ControllingExpr,
4345 ArrayRef<TypeSourceInfo*> AssocTypes,
4346 ArrayRef<Expr*> AssocExprs,
4347 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4348 bool ContainsUnexpandedParameterPack);
4350 explicit GenericSelectionExpr(EmptyShell Empty)
4351 : Expr(GenericSelectionExprClass, Empty) { }
4353 unsigned getNumAssocs() const { return NumAssocs; }
4355 SourceLocation getGenericLoc() const { return GenericLoc; }
4356 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4357 SourceLocation getRParenLoc() const { return RParenLoc; }
4359 const Expr *getAssocExpr(unsigned i) const {
4360 return cast<Expr>(SubExprs[END_EXPR+i]);
4362 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4364 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4365 return AssocTypes[i];
4367 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4369 QualType getAssocType(unsigned i) const {
4370 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4371 return TS->getType();
4376 const Expr *getControllingExpr() const {
4377 return cast<Expr>(SubExprs[CONTROLLING]);
4379 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4381 /// Whether this generic selection is result-dependent.
4382 bool isResultDependent() const { return ResultIndex == -1U; }
4384 /// The zero-based index of the result expression's generic association in
4385 /// the generic selection's association list. Defined only if the
4386 /// generic selection is not result-dependent.
4387 unsigned getResultIndex() const {
4388 assert(!isResultDependent() && "Generic selection is result-dependent");
4392 /// The generic selection's result expression. Defined only if the
4393 /// generic selection is not result-dependent.
4394 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4395 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4397 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4398 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4400 static bool classof(const Stmt *T) {
4401 return T->getStmtClass() == GenericSelectionExprClass;
4404 child_range children() {
4405 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4408 friend class ASTStmtReader;
4411 //===----------------------------------------------------------------------===//
4413 //===----------------------------------------------------------------------===//
4416 /// ExtVectorElementExpr - This represents access to specific elements of a
4417 /// vector, and may occur on the left hand side or right hand side. For example
4418 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4420 /// Note that the base may have either vector or pointer to vector type, just
4421 /// like a struct field reference.
4423 class ExtVectorElementExpr : public Expr {
4425 IdentifierInfo *Accessor;
4426 SourceLocation AccessorLoc;
4428 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4429 IdentifierInfo &accessor, SourceLocation loc)
4430 : Expr(ExtVectorElementExprClass, ty, VK,
4431 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4432 base->isTypeDependent(), base->isValueDependent(),
4433 base->isInstantiationDependent(),
4434 base->containsUnexpandedParameterPack()),
4435 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4437 /// \brief Build an empty vector element expression.
4438 explicit ExtVectorElementExpr(EmptyShell Empty)
4439 : Expr(ExtVectorElementExprClass, Empty) { }
4441 const Expr *getBase() const { return cast<Expr>(Base); }
4442 Expr *getBase() { return cast<Expr>(Base); }
4443 void setBase(Expr *E) { Base = E; }
4445 IdentifierInfo &getAccessor() const { return *Accessor; }
4446 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4448 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4449 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4451 /// getNumElements - Get the number of components being selected.
4452 unsigned getNumElements() const;
4454 /// containsDuplicateElements - Return true if any element access is
4456 bool containsDuplicateElements() const;
4458 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4459 /// aggregate Constant of ConstantInt(s).
4460 void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
4462 SourceLocation getLocStart() const LLVM_READONLY {
4463 return getBase()->getLocStart();
4465 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4467 /// isArrow - Return true if the base expression is a pointer to vector,
4468 /// return false if the base expression is a vector.
4469 bool isArrow() const;
4471 static bool classof(const Stmt *T) {
4472 return T->getStmtClass() == ExtVectorElementExprClass;
4476 child_range children() { return child_range(&Base, &Base+1); }
4480 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4481 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4482 class BlockExpr : public Expr {
4484 BlockDecl *TheBlock;
4486 BlockExpr(BlockDecl *BD, QualType ty)
4487 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4488 ty->isDependentType(), ty->isDependentType(),
4489 ty->isInstantiationDependentType() || BD->isDependentContext(),
4493 /// \brief Build an empty block expression.
4494 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4496 const BlockDecl *getBlockDecl() const { return TheBlock; }
4497 BlockDecl *getBlockDecl() { return TheBlock; }
4498 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4500 // Convenience functions for probing the underlying BlockDecl.
4501 SourceLocation getCaretLocation() const;
4502 const Stmt *getBody() const;
4505 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4506 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4508 /// getFunctionType - Return the underlying function type for this block.
4509 const FunctionProtoType *getFunctionType() const;
4511 static bool classof(const Stmt *T) {
4512 return T->getStmtClass() == BlockExprClass;
4516 child_range children() { return child_range(); }
4519 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4520 /// This AST node provides support for reinterpreting a type to another
4521 /// type of the same size.
4522 class AsTypeExpr : public Expr {
4525 SourceLocation BuiltinLoc, RParenLoc;
4527 friend class ASTReader;
4528 friend class ASTStmtReader;
4529 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4532 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4533 ExprValueKind VK, ExprObjectKind OK,
4534 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4535 : Expr(AsTypeExprClass, DstType, VK, OK,
4536 DstType->isDependentType(),
4537 DstType->isDependentType() || SrcExpr->isValueDependent(),
4538 (DstType->isInstantiationDependentType() ||
4539 SrcExpr->isInstantiationDependent()),
4540 (DstType->containsUnexpandedParameterPack() ||
4541 SrcExpr->containsUnexpandedParameterPack())),
4542 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4544 /// getSrcExpr - Return the Expr to be converted.
4545 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4547 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4548 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4550 /// getRParenLoc - Return the location of final right parenthesis.
4551 SourceLocation getRParenLoc() const { return RParenLoc; }
4553 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4554 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4556 static bool classof(const Stmt *T) {
4557 return T->getStmtClass() == AsTypeExprClass;
4561 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4564 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4565 /// l-value. A pseudo-object is an abstract object, accesses to which
4566 /// are translated to calls. The pseudo-object expression has a
4567 /// syntactic form, which shows how the expression was actually
4568 /// written in the source code, and a semantic form, which is a series
4569 /// of expressions to be executed in order which detail how the
4570 /// operation is actually evaluated. Optionally, one of the semantic
4571 /// forms may also provide a result value for the expression.
4573 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4574 /// that OVE is required to have a source expression, and it is bound
4575 /// to the result of that source expression. Such OVEs may appear
4576 /// only in subsequent semantic-form expressions and as
4577 /// sub-expressions of the syntactic form.
4579 /// PseudoObjectExpr should be used only when an operation can be
4580 /// usefully described in terms of fairly simple rewrite rules on
4581 /// objects and functions that are meant to be used by end-developers.
4582 /// For example, under the Itanium ABI, dynamic casts are implemented
4583 /// as a call to a runtime function called __dynamic_cast; using this
4584 /// class to describe that would be inappropriate because that call is
4585 /// not really part of the user-visible semantics, and instead the
4586 /// cast is properly reflected in the AST and IR-generation has been
4587 /// taught to generate the call as necessary. In contrast, an
4588 /// Objective-C property access is semantically defined to be
4589 /// equivalent to a particular message send, and this is very much
4590 /// part of the user model. The name of this class encourages this
4591 /// modelling design.
4592 class PseudoObjectExpr : public Expr {
4593 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4594 // Always at least two, because the first sub-expression is the
4597 // PseudoObjectExprBits.ResultIndex - The index of the
4598 // sub-expression holding the result. 0 means the result is void,
4599 // which is unambiguous because it's the index of the syntactic
4600 // form. Note that this is therefore 1 higher than the value passed
4601 // in to Create, which is an index within the semantic forms.
4602 // Note also that ASTStmtWriter assumes this encoding.
4604 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
4605 const Expr * const *getSubExprsBuffer() const {
4606 return reinterpret_cast<const Expr * const *>(this + 1);
4609 friend class ASTStmtReader;
4611 PseudoObjectExpr(QualType type, ExprValueKind VK,
4612 Expr *syntactic, ArrayRef<Expr*> semantic,
4613 unsigned resultIndex);
4615 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4617 unsigned getNumSubExprs() const {
4618 return PseudoObjectExprBits.NumSubExprs;
4622 /// NoResult - A value for the result index indicating that there is
4623 /// no semantic result.
4624 enum LLVM_ENUM_INT_TYPE(unsigned) { NoResult = ~0U };
4626 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4627 ArrayRef<Expr*> semantic,
4628 unsigned resultIndex);
4630 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4631 unsigned numSemanticExprs);
4633 /// Return the syntactic form of this expression, i.e. the
4634 /// expression it actually looks like. Likely to be expressed in
4635 /// terms of OpaqueValueExprs bound in the semantic form.
4636 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4637 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4639 /// Return the index of the result-bearing expression into the semantics
4640 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4641 unsigned getResultExprIndex() const {
4642 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4643 return PseudoObjectExprBits.ResultIndex - 1;
4646 /// Return the result-bearing expression, or null if there is none.
4647 Expr *getResultExpr() {
4648 if (PseudoObjectExprBits.ResultIndex == 0)
4650 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4652 const Expr *getResultExpr() const {
4653 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4656 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4658 typedef Expr * const *semantics_iterator;
4659 typedef const Expr * const *const_semantics_iterator;
4660 semantics_iterator semantics_begin() {
4661 return getSubExprsBuffer() + 1;
4663 const_semantics_iterator semantics_begin() const {
4664 return getSubExprsBuffer() + 1;
4666 semantics_iterator semantics_end() {
4667 return getSubExprsBuffer() + getNumSubExprs();
4669 const_semantics_iterator semantics_end() const {
4670 return getSubExprsBuffer() + getNumSubExprs();
4672 Expr *getSemanticExpr(unsigned index) {
4673 assert(index + 1 < getNumSubExprs());
4674 return getSubExprsBuffer()[index + 1];
4676 const Expr *getSemanticExpr(unsigned index) const {
4677 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4680 SourceLocation getExprLoc() const LLVM_READONLY {
4681 return getSyntacticForm()->getExprLoc();
4684 SourceLocation getLocStart() const LLVM_READONLY {
4685 return getSyntacticForm()->getLocStart();
4687 SourceLocation getLocEnd() const LLVM_READONLY {
4688 return getSyntacticForm()->getLocEnd();
4691 child_range children() {
4692 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4693 return child_range(cs, cs + getNumSubExprs());
4696 static bool classof(const Stmt *T) {
4697 return T->getStmtClass() == PseudoObjectExprClass;
4701 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4702 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4703 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4704 /// All of these instructions take one primary pointer and at least one memory
4706 class AtomicExpr : public Expr {
4709 #define BUILTIN(ID, TYPE, ATTRS)
4710 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4711 #include "clang/Basic/Builtins.def"
4712 // Avoid trailing comma
4717 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4718 Stmt* SubExprs[END_EXPR];
4719 unsigned NumSubExprs;
4720 SourceLocation BuiltinLoc, RParenLoc;
4723 friend class ASTStmtReader;
4726 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4727 AtomicOp op, SourceLocation RP);
4729 /// \brief Determine the number of arguments the specified atomic builtin
4731 static unsigned getNumSubExprs(AtomicOp Op);
4733 /// \brief Build an empty AtomicExpr.
4734 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4736 Expr *getPtr() const {
4737 return cast<Expr>(SubExprs[PTR]);
4739 Expr *getOrder() const {
4740 return cast<Expr>(SubExprs[ORDER]);
4742 Expr *getVal1() const {
4743 if (Op == AO__c11_atomic_init)
4744 return cast<Expr>(SubExprs[ORDER]);
4745 assert(NumSubExprs > VAL1);
4746 return cast<Expr>(SubExprs[VAL1]);
4748 Expr *getOrderFail() const {
4749 assert(NumSubExprs > ORDER_FAIL);
4750 return cast<Expr>(SubExprs[ORDER_FAIL]);
4752 Expr *getVal2() const {
4753 if (Op == AO__atomic_exchange)
4754 return cast<Expr>(SubExprs[ORDER_FAIL]);
4755 assert(NumSubExprs > VAL2);
4756 return cast<Expr>(SubExprs[VAL2]);
4758 Expr *getWeak() const {
4759 assert(NumSubExprs > WEAK);
4760 return cast<Expr>(SubExprs[WEAK]);
4763 AtomicOp getOp() const { return Op; }
4764 unsigned getNumSubExprs() { return NumSubExprs; }
4766 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4768 bool isVolatile() const {
4769 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4772 bool isCmpXChg() const {
4773 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4774 getOp() == AO__c11_atomic_compare_exchange_weak ||
4775 getOp() == AO__atomic_compare_exchange ||
4776 getOp() == AO__atomic_compare_exchange_n;
4779 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4780 SourceLocation getRParenLoc() const { return RParenLoc; }
4782 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4783 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4785 static bool classof(const Stmt *T) {
4786 return T->getStmtClass() == AtomicExprClass;
4790 child_range children() {
4791 return child_range(SubExprs, SubExprs+NumSubExprs);
4794 } // end namespace clang