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/LangOptions.h"
27 #include "clang/Basic/SyncScope.h"
28 #include "clang/Basic/TypeTraits.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/AtomicOrdering.h"
34 #include "llvm/Support/Compiler.h"
40 class CXXBaseSpecifier;
41 class CXXMemberCallExpr;
42 class CXXOperatorCallExpr;
46 class MaterializeTemporaryExpr;
48 class ObjCPropertyRefExpr;
49 class OpaqueValueExpr;
55 /// \brief A simple array of base specifiers.
56 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
58 /// \brief An adjustment to be made to the temporary created when emitting a
59 /// reference binding, which accesses a particular subobject of that temporary.
60 struct SubobjectAdjustment {
62 DerivedToBaseAdjustment,
64 MemberPointerAdjustment
68 const CastExpr *BasePath;
69 const CXXRecordDecl *DerivedClass;
73 const MemberPointerType *MPT;
78 struct DTB DerivedToBase;
83 SubobjectAdjustment(const CastExpr *BasePath,
84 const CXXRecordDecl *DerivedClass)
85 : Kind(DerivedToBaseAdjustment) {
86 DerivedToBase.BasePath = BasePath;
87 DerivedToBase.DerivedClass = DerivedClass;
90 SubobjectAdjustment(FieldDecl *Field)
91 : Kind(FieldAdjustment) {
95 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
96 : Kind(MemberPointerAdjustment) {
102 /// Expr - This represents one expression. Note that Expr's are subclasses of
103 /// Stmt. This allows an expression to be transparently used any place a Stmt
106 class Expr : public Stmt {
110 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
111 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
114 ExprBits.TypeDependent = TD;
115 ExprBits.ValueDependent = VD;
116 ExprBits.InstantiationDependent = ID;
117 ExprBits.ValueKind = VK;
118 ExprBits.ObjectKind = OK;
119 assert(ExprBits.ObjectKind == OK && "truncated kind");
120 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
124 /// \brief Construct an empty expression.
125 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
128 QualType getType() const { return TR; }
129 void setType(QualType t) {
130 // In C++, the type of an expression is always adjusted so that it
131 // will not have reference type (C++ [expr]p6). Use
132 // QualType::getNonReferenceType() to retrieve the non-reference
133 // type. Additionally, inspect Expr::isLvalue to determine whether
134 // an expression that is adjusted in this manner should be
135 // considered an lvalue.
136 assert((t.isNull() || !t->isReferenceType()) &&
137 "Expressions can't have reference type");
142 /// isValueDependent - Determines whether this expression is
143 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
144 /// array bound of "Chars" in the following example is
147 /// template<int Size, char (&Chars)[Size]> struct meta_string;
149 bool isValueDependent() const { return ExprBits.ValueDependent; }
151 /// \brief Set whether this expression is value-dependent or not.
152 void setValueDependent(bool VD) {
153 ExprBits.ValueDependent = VD;
156 /// isTypeDependent - Determines whether this expression is
157 /// type-dependent (C++ [temp.dep.expr]), which means that its type
158 /// could change from one template instantiation to the next. For
159 /// example, the expressions "x" and "x + y" are type-dependent in
160 /// the following code, but "y" is not type-dependent:
162 /// template<typename T>
163 /// void add(T x, int y) {
167 bool isTypeDependent() const { return ExprBits.TypeDependent; }
169 /// \brief Set whether this expression is type-dependent or not.
170 void setTypeDependent(bool TD) {
171 ExprBits.TypeDependent = TD;
174 /// \brief Whether this expression is instantiation-dependent, meaning that
175 /// it depends in some way on a template parameter, even if neither its type
176 /// nor (constant) value can change due to the template instantiation.
178 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
179 /// instantiation-dependent (since it involves a template parameter \c T), but
180 /// is neither type- nor value-dependent, since the type of the inner
181 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
182 /// \c sizeof is known.
185 /// template<typename T>
186 /// void f(T x, T y) {
187 /// sizeof(sizeof(T() + T());
191 bool isInstantiationDependent() const {
192 return ExprBits.InstantiationDependent;
195 /// \brief Set whether this expression is instantiation-dependent or not.
196 void setInstantiationDependent(bool ID) {
197 ExprBits.InstantiationDependent = ID;
200 /// \brief Whether this expression contains an unexpanded parameter
201 /// pack (for C++11 variadic templates).
203 /// Given the following function template:
206 /// template<typename F, typename ...Types>
207 /// void forward(const F &f, Types &&...args) {
208 /// f(static_cast<Types&&>(args)...);
212 /// The expressions \c args and \c static_cast<Types&&>(args) both
213 /// contain parameter packs.
214 bool containsUnexpandedParameterPack() const {
215 return ExprBits.ContainsUnexpandedParameterPack;
218 /// \brief Set the bit that describes whether this expression
219 /// contains an unexpanded parameter pack.
220 void setContainsUnexpandedParameterPack(bool PP = true) {
221 ExprBits.ContainsUnexpandedParameterPack = PP;
224 /// getExprLoc - Return the preferred location for the arrow when diagnosing
225 /// a problem with a generic expression.
226 SourceLocation getExprLoc() const LLVM_READONLY;
228 /// isUnusedResultAWarning - Return true if this immediate expression should
229 /// be warned about if the result is unused. If so, fill in expr, location,
230 /// and ranges with expr to warn on and source locations/ranges appropriate
232 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
233 SourceRange &R1, SourceRange &R2,
234 ASTContext &Ctx) const;
236 /// isLValue - True if this expression is an "l-value" according to
237 /// the rules of the current language. C and C++ give somewhat
238 /// different rules for this concept, but in general, the result of
239 /// an l-value expression identifies a specific object whereas the
240 /// result of an r-value expression is a value detached from any
241 /// specific storage.
243 /// C++11 divides the concept of "r-value" into pure r-values
244 /// ("pr-values") and so-called expiring values ("x-values"), which
245 /// identify specific objects that can be safely cannibalized for
246 /// their resources. This is an unfortunate abuse of terminology on
247 /// the part of the C++ committee. In Clang, when we say "r-value",
248 /// we generally mean a pr-value.
249 bool isLValue() const { return getValueKind() == VK_LValue; }
250 bool isRValue() const { return getValueKind() == VK_RValue; }
251 bool isXValue() const { return getValueKind() == VK_XValue; }
252 bool isGLValue() const { return getValueKind() != VK_RValue; }
254 enum LValueClassification {
257 LV_IncompleteVoidType,
258 LV_DuplicateVectorComponents,
259 LV_InvalidExpression,
260 LV_InvalidMessageExpression,
262 LV_SubObjCPropertySetting,
266 /// Reasons why an expression might not be an l-value.
267 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
269 enum isModifiableLvalueResult {
272 MLV_IncompleteVoidType,
273 MLV_DuplicateVectorComponents,
274 MLV_InvalidExpression,
275 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
278 MLV_ConstQualifiedField,
281 MLV_NoSetterProperty,
283 MLV_SubObjCPropertySetting,
284 MLV_InvalidMessageExpression,
288 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289 /// does not have an incomplete type, does not have a const-qualified type,
290 /// and if it is a structure or union, does not have any member (including,
291 /// recursively, any member or element of all contained aggregates or unions)
292 /// with a const-qualified type.
294 /// \param Loc [in,out] - A source location which *may* be filled
295 /// in with the location of the expression making this a
296 /// non-modifiable lvalue, if specified.
297 isModifiableLvalueResult
298 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
300 /// \brief The return type of classify(). Represents the C++11 expression
302 class Classification {
304 /// \brief The various classification results. Most of these mean prvalue.
308 CL_Function, // Functions cannot be lvalues in C.
309 CL_Void, // Void cannot be an lvalue in C.
310 CL_AddressableVoid, // Void expression whose address can be taken in C.
311 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312 CL_MemberFunction, // An expression referring to a member function
313 CL_SubObjCPropertySetting,
314 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315 CL_ArrayTemporary, // A temporary of array type.
316 CL_ObjCMessageRValue, // ObjC message is an rvalue
317 CL_PRValue // A prvalue for any other reason, of any other type
319 /// \brief The results of modification testing.
320 enum ModifiableType {
321 CM_Untested, // testModifiable was false.
323 CM_RValue, // Not modifiable because it's an rvalue
324 CM_Function, // Not modifiable because it's a function; C++ only
325 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
328 CM_ConstQualifiedField,
338 unsigned short Modifiable;
340 explicit Classification(Kinds k, ModifiableType m)
341 : Kind(k), Modifiable(m)
347 Kinds getKind() const { return static_cast<Kinds>(Kind); }
348 ModifiableType getModifiable() const {
349 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
350 return static_cast<ModifiableType>(Modifiable);
352 bool isLValue() const { return Kind == CL_LValue; }
353 bool isXValue() const { return Kind == CL_XValue; }
354 bool isGLValue() const { return Kind <= CL_XValue; }
355 bool isPRValue() const { return Kind >= CL_Function; }
356 bool isRValue() const { return Kind >= CL_XValue; }
357 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
359 /// \brief Create a simple, modifiably lvalue
360 static Classification makeSimpleLValue() {
361 return Classification(CL_LValue, CM_Modifiable);
365 /// \brief Classify - Classify this expression according to the C++11
366 /// expression taxonomy.
368 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
369 /// old lvalue vs rvalue. This function determines the type of expression this
370 /// is. There are three expression types:
371 /// - lvalues are classical lvalues as in C++03.
372 /// - prvalues are equivalent to rvalues in C++03.
373 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
374 /// function returning an rvalue reference.
375 /// lvalues and xvalues are collectively referred to as glvalues, while
376 /// prvalues and xvalues together form rvalues.
377 Classification Classify(ASTContext &Ctx) const {
378 return ClassifyImpl(Ctx, nullptr);
381 /// \brief ClassifyModifiable - Classify this expression according to the
382 /// C++11 expression taxonomy, and see if it is valid on the left side
383 /// of an assignment.
385 /// This function extends classify in that it also tests whether the
386 /// expression is modifiable (C99 6.3.2.1p1).
387 /// \param Loc A source location that might be filled with a relevant location
388 /// if the expression is not modifiable.
389 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
390 return ClassifyImpl(Ctx, &Loc);
393 /// getValueKindForType - Given a formal return or parameter type,
394 /// give its value kind.
395 static ExprValueKind getValueKindForType(QualType T) {
396 if (const ReferenceType *RT = T->getAs<ReferenceType>())
397 return (isa<LValueReferenceType>(RT)
399 : (RT->getPointeeType()->isFunctionType()
400 ? VK_LValue : VK_XValue));
404 /// getValueKind - The value kind that this expression produces.
405 ExprValueKind getValueKind() const {
406 return static_cast<ExprValueKind>(ExprBits.ValueKind);
409 /// getObjectKind - The object kind that this expression produces.
410 /// Object kinds are meaningful only for expressions that yield an
411 /// l-value or x-value.
412 ExprObjectKind getObjectKind() const {
413 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
416 bool isOrdinaryOrBitFieldObject() const {
417 ExprObjectKind OK = getObjectKind();
418 return (OK == OK_Ordinary || OK == OK_BitField);
421 /// setValueKind - Set the value kind produced by this expression.
422 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
424 /// setObjectKind - Set the object kind produced by this expression.
425 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
428 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
432 /// \brief Returns true if this expression is a gl-value that
433 /// potentially refers to a bit-field.
435 /// In C++, whether a gl-value refers to a bitfield is essentially
436 /// an aspect of the value-kind type system.
437 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
439 /// \brief If this expression refers to a bit-field, retrieve the
440 /// declaration of that bit-field.
442 /// Note that this returns a non-null pointer in subtly different
443 /// places than refersToBitField returns true. In particular, this can
444 /// return a non-null pointer even for r-values loaded from
445 /// bit-fields, but it will return null for a conditional bit-field.
446 FieldDecl *getSourceBitField();
448 const FieldDecl *getSourceBitField() const {
449 return const_cast<Expr*>(this)->getSourceBitField();
452 Decl *getReferencedDeclOfCallee();
453 const Decl *getReferencedDeclOfCallee() const {
454 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
457 /// \brief If this expression is an l-value for an Objective C
458 /// property, find the underlying property reference expression.
459 const ObjCPropertyRefExpr *getObjCProperty() const;
461 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
462 bool isObjCSelfExpr() const;
464 /// \brief Returns whether this expression refers to a vector element.
465 bool refersToVectorElement() const;
467 /// \brief Returns whether this expression refers to a global register
469 bool refersToGlobalRegisterVar() const;
471 /// \brief Returns whether this expression has a placeholder type.
472 bool hasPlaceholderType() const {
473 return getType()->isPlaceholderType();
476 /// \brief Returns whether this expression has a specific placeholder type.
477 bool hasPlaceholderType(BuiltinType::Kind K) const {
478 assert(BuiltinType::isPlaceholderTypeKind(K));
479 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
480 return BT->getKind() == K;
484 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
485 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
486 /// but also int expressions which are produced by things like comparisons in
488 bool isKnownToHaveBooleanValue() const;
490 /// isIntegerConstantExpr - Return true if this expression is a valid integer
491 /// constant expression, and, if so, return its value in Result. If not a
492 /// valid i-c-e, return false and fill in Loc (if specified) with the location
493 /// of the invalid expression.
495 /// Note: This does not perform the implicit conversions required by C++11
497 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
498 SourceLocation *Loc = nullptr,
499 bool isEvaluated = true) const;
500 bool isIntegerConstantExpr(const ASTContext &Ctx,
501 SourceLocation *Loc = nullptr) const;
503 /// isCXX98IntegralConstantExpr - Return true if this expression is an
504 /// integral constant expression in C++98. Can only be used in C++.
505 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
507 /// isCXX11ConstantExpr - Return true if this expression is a constant
508 /// expression in C++11. Can only be used in C++.
510 /// Note: This does not perform the implicit conversions required by C++11
512 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
513 SourceLocation *Loc = nullptr) const;
515 /// isPotentialConstantExpr - Return true if this function's definition
516 /// might be usable in a constant expression in C++11, if it were marked
517 /// constexpr. Return false if the function can never produce a constant
518 /// expression, along with diagnostics describing why not.
519 static bool isPotentialConstantExpr(const FunctionDecl *FD,
521 PartialDiagnosticAt> &Diags);
523 /// isPotentialConstantExprUnevaluted - Return true if this expression might
524 /// be usable in a constant expression in C++11 in an unevaluated context, if
525 /// it were in function FD marked constexpr. Return false if the function can
526 /// never produce a constant expression, along with diagnostics describing
528 static bool isPotentialConstantExprUnevaluated(Expr *E,
529 const FunctionDecl *FD,
531 PartialDiagnosticAt> &Diags);
533 /// isConstantInitializer - Returns true if this expression can be emitted to
534 /// IR as a constant, and thus can be used as a constant initializer in C.
535 /// If this expression is not constant and Culprit is non-null,
536 /// it is used to store the address of first non constant expr.
537 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
538 const Expr **Culprit = nullptr) const;
540 /// EvalStatus is a struct with detailed info about an evaluation in progress.
542 /// \brief Whether the evaluated expression has side effects.
543 /// For example, (f() && 0) can be folded, but it still has side effects.
546 /// \brief Whether the evaluation hit undefined behavior.
547 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
548 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
549 bool HasUndefinedBehavior;
551 /// Diag - If this is non-null, it will be filled in with a stack of notes
552 /// indicating why evaluation failed (or why it failed to produce a constant
554 /// If the expression is unfoldable, the notes will indicate why it's not
555 /// foldable. If the expression is foldable, but not a constant expression,
556 /// the notes will describes why it isn't a constant expression. If the
557 /// expression *is* a constant expression, no notes will be produced.
558 SmallVectorImpl<PartialDiagnosticAt> *Diag;
561 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
563 // hasSideEffects - Return true if the evaluated expression has
565 bool hasSideEffects() const {
566 return HasSideEffects;
570 /// EvalResult is a struct with detailed info about an evaluated expression.
571 struct EvalResult : EvalStatus {
572 /// Val - This is the value the expression can be folded to.
575 // isGlobalLValue - Return true if the evaluated lvalue expression
577 bool isGlobalLValue() const;
580 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
581 /// an rvalue using any crazy technique (that has nothing to do with language
582 /// standards) that we want to, even if the expression has side-effects. If
583 /// this function returns true, it returns the folded constant in Result. If
584 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
586 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
588 /// EvaluateAsBooleanCondition - Return true if this is a constant
589 /// which we we can fold and convert to a boolean condition using
590 /// any crazy technique that we want to, even if the expression has
592 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
594 enum SideEffectsKind {
595 SE_NoSideEffects, ///< Strictly evaluate the expression.
596 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
597 ///< arbitrary unmodeled side effects.
598 SE_AllowSideEffects ///< Allow any unmodeled side effect.
601 /// EvaluateAsInt - Return true if this is a constant which we can fold and
602 /// convert to an integer, using any crazy technique that we want to.
603 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
604 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
606 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
607 /// convert to a floating point value, using any crazy technique that we
610 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
611 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
613 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
614 /// constant folded without side-effects, but discard the result.
615 bool isEvaluatable(const ASTContext &Ctx,
616 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
618 /// HasSideEffects - This routine returns true for all those expressions
619 /// which have any effect other than producing a value. Example is a function
620 /// call, volatile variable read, or throwing an exception. If
621 /// IncludePossibleEffects is false, this call treats certain expressions with
622 /// potential side effects (such as function call-like expressions,
623 /// instantiation-dependent expressions, or invocations from a macro) as not
624 /// having side effects.
625 bool HasSideEffects(const ASTContext &Ctx,
626 bool IncludePossibleEffects = true) const;
628 /// \brief Determine whether this expression involves a call to any function
629 /// that is not trivial.
630 bool hasNonTrivialCall(const ASTContext &Ctx) const;
632 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
633 /// integer. This must be called on an expression that constant folds to an
635 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
636 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
638 void EvaluateForOverflow(const ASTContext &Ctx) const;
640 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
641 /// lvalue with link time known address, with no side-effects.
642 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
644 /// EvaluateAsInitializer - Evaluate an expression as if it were the
645 /// initializer of the given declaration. Returns true if the initializer
646 /// can be folded to a constant, and produces any relevant notes. In C++11,
647 /// notes will be produced if the expression is not a constant expression.
648 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
650 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
652 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
653 /// of a call to the given function with the given arguments, inside an
654 /// unevaluated context. Returns true if the expression could be folded to a
656 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
657 const FunctionDecl *Callee,
658 ArrayRef<const Expr*> Args,
659 const Expr *This = nullptr) const;
661 /// \brief If the current Expr is a pointer, this will try to statically
662 /// determine the number of bytes available where the pointer is pointing.
663 /// Returns true if all of the above holds and we were able to figure out the
664 /// size, false otherwise.
666 /// \param Type - How to evaluate the size of the Expr, as defined by the
667 /// "type" parameter of __builtin_object_size
668 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
669 unsigned Type) const;
671 /// \brief Enumeration used to describe the kind of Null pointer constant
672 /// returned from \c isNullPointerConstant().
673 enum NullPointerConstantKind {
674 /// \brief Expression is not a Null pointer constant.
677 /// \brief Expression is a Null pointer constant built from a zero integer
678 /// expression that is not a simple, possibly parenthesized, zero literal.
679 /// C++ Core Issue 903 will classify these expressions as "not pointers"
680 /// once it is adopted.
681 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
684 /// \brief Expression is a Null pointer constant built from a literal zero.
687 /// \brief Expression is a C++11 nullptr.
690 /// \brief Expression is a GNU-style __null constant.
694 /// \brief Enumeration used to describe how \c isNullPointerConstant()
695 /// should cope with value-dependent expressions.
696 enum NullPointerConstantValueDependence {
697 /// \brief Specifies that the expression should never be value-dependent.
698 NPC_NeverValueDependent = 0,
700 /// \brief Specifies that a value-dependent expression of integral or
701 /// dependent type should be considered a null pointer constant.
702 NPC_ValueDependentIsNull,
704 /// \brief Specifies that a value-dependent expression should be considered
705 /// to never be a null pointer constant.
706 NPC_ValueDependentIsNotNull
709 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
710 /// a Null pointer constant. The return value can further distinguish the
711 /// kind of NULL pointer constant that was detected.
712 NullPointerConstantKind isNullPointerConstant(
714 NullPointerConstantValueDependence NPC) const;
716 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
718 bool isOBJCGCCandidate(ASTContext &Ctx) const;
720 /// \brief Returns true if this expression is a bound member function.
721 bool isBoundMemberFunction(ASTContext &Ctx) const;
723 /// \brief Given an expression of bound-member type, find the type
724 /// of the member. Returns null if this is an *overloaded* bound
725 /// member expression.
726 static QualType findBoundMemberType(const Expr *expr);
728 /// IgnoreImpCasts - Skip past any implicit casts which might
729 /// surround this expression. Only skips ImplicitCastExprs.
730 Expr *IgnoreImpCasts() LLVM_READONLY;
732 /// IgnoreImplicit - Skip past any implicit AST nodes which might
733 /// surround this expression.
734 Expr *IgnoreImplicit() LLVM_READONLY {
735 return cast<Expr>(Stmt::IgnoreImplicit());
738 const Expr *IgnoreImplicit() const LLVM_READONLY {
739 return const_cast<Expr*>(this)->IgnoreImplicit();
742 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
743 /// its subexpression. If that subexpression is also a ParenExpr,
744 /// then this method recursively returns its subexpression, and so forth.
745 /// Otherwise, the method returns the current Expr.
746 Expr *IgnoreParens() LLVM_READONLY;
748 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
749 /// or CastExprs, returning their operand.
750 Expr *IgnoreParenCasts() LLVM_READONLY;
752 /// Ignore casts. Strip off any CastExprs, returning their operand.
753 Expr *IgnoreCasts() LLVM_READONLY;
755 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
756 /// any ParenExpr or ImplicitCastExprs, returning their operand.
757 Expr *IgnoreParenImpCasts() LLVM_READONLY;
759 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
760 /// call to a conversion operator, return the argument.
761 Expr *IgnoreConversionOperator() LLVM_READONLY;
763 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
764 return const_cast<Expr*>(this)->IgnoreConversionOperator();
767 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
768 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
771 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
772 /// CastExprs that represent lvalue casts, returning their operand.
773 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
775 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
776 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
779 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
780 /// value (including ptr->int casts of the same size). Strip off any
781 /// ParenExpr or CastExprs, returning their operand.
782 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
784 /// Ignore parentheses and derived-to-base casts.
785 Expr *ignoreParenBaseCasts() LLVM_READONLY;
787 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
788 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
791 /// \brief Determine whether this expression is a default function argument.
793 /// Default arguments are implicitly generated in the abstract syntax tree
794 /// by semantic analysis for function calls, object constructions, etc. in
795 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
796 /// this routine also looks through any implicit casts to determine whether
797 /// the expression is a default argument.
798 bool isDefaultArgument() const;
800 /// \brief Determine whether the result of this expression is a
801 /// temporary object of the given class type.
802 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
804 /// \brief Whether this expression is an implicit reference to 'this' in C++.
805 bool isImplicitCXXThis() const;
807 const Expr *IgnoreImpCasts() const LLVM_READONLY {
808 return const_cast<Expr*>(this)->IgnoreImpCasts();
810 const Expr *IgnoreParens() const LLVM_READONLY {
811 return const_cast<Expr*>(this)->IgnoreParens();
813 const Expr *IgnoreParenCasts() const LLVM_READONLY {
814 return const_cast<Expr*>(this)->IgnoreParenCasts();
816 /// Strip off casts, but keep parentheses.
817 const Expr *IgnoreCasts() const LLVM_READONLY {
818 return const_cast<Expr*>(this)->IgnoreCasts();
821 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
822 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
825 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
827 /// \brief For an expression of class type or pointer to class type,
828 /// return the most derived class decl the expression is known to refer to.
830 /// If this expression is a cast, this method looks through it to find the
831 /// most derived decl that can be inferred from the expression.
832 /// This is valid because derived-to-base conversions have undefined
833 /// behavior if the object isn't dynamically of the derived type.
834 const CXXRecordDecl *getBestDynamicClassType() const;
836 /// \brief Get the inner expression that determines the best dynamic class.
837 /// If this is a prvalue, we guarantee that it is of the most-derived type
838 /// for the object itself.
839 const Expr *getBestDynamicClassTypeExpr() const;
841 /// Walk outwards from an expression we want to bind a reference to and
842 /// find the expression whose lifetime needs to be extended. Record
843 /// the LHSs of comma expressions and adjustments needed along the path.
844 const Expr *skipRValueSubobjectAdjustments(
845 SmallVectorImpl<const Expr *> &CommaLHS,
846 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
847 const Expr *skipRValueSubobjectAdjustments() const {
848 SmallVector<const Expr *, 8> CommaLHSs;
849 SmallVector<SubobjectAdjustment, 8> Adjustments;
850 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
853 static bool classof(const Stmt *T) {
854 return T->getStmtClass() >= firstExprConstant &&
855 T->getStmtClass() <= lastExprConstant;
859 //===----------------------------------------------------------------------===//
860 // Primary Expressions.
861 //===----------------------------------------------------------------------===//
863 /// OpaqueValueExpr - An expression referring to an opaque object of a
864 /// fixed type and value class. These don't correspond to concrete
865 /// syntax; instead they're used to express operations (usually copy
866 /// operations) on values whose source is generally obvious from
868 class OpaqueValueExpr : public Expr {
869 friend class ASTStmtReader;
874 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
875 ExprObjectKind OK = OK_Ordinary,
876 Expr *SourceExpr = nullptr)
877 : Expr(OpaqueValueExprClass, T, VK, OK,
878 T->isDependentType() ||
879 (SourceExpr && SourceExpr->isTypeDependent()),
880 T->isDependentType() ||
881 (SourceExpr && SourceExpr->isValueDependent()),
882 T->isInstantiationDependentType() ||
883 (SourceExpr && SourceExpr->isInstantiationDependent()),
885 SourceExpr(SourceExpr), Loc(Loc) {
888 /// Given an expression which invokes a copy constructor --- i.e. a
889 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
890 /// find the OpaqueValueExpr that's the source of the construction.
891 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
893 explicit OpaqueValueExpr(EmptyShell Empty)
894 : Expr(OpaqueValueExprClass, Empty) { }
896 /// \brief Retrieve the location of this expression.
897 SourceLocation getLocation() const { return Loc; }
899 SourceLocation getLocStart() const LLVM_READONLY {
900 return SourceExpr ? SourceExpr->getLocStart() : Loc;
902 SourceLocation getLocEnd() const LLVM_READONLY {
903 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
905 SourceLocation getExprLoc() const LLVM_READONLY {
906 if (SourceExpr) return SourceExpr->getExprLoc();
910 child_range children() {
911 return child_range(child_iterator(), child_iterator());
914 const_child_range children() const {
915 return const_child_range(const_child_iterator(), const_child_iterator());
918 /// The source expression of an opaque value expression is the
919 /// expression which originally generated the value. This is
920 /// provided as a convenience for analyses that don't wish to
921 /// precisely model the execution behavior of the program.
923 /// The source expression is typically set when building the
924 /// expression which binds the opaque value expression in the first
926 Expr *getSourceExpr() const { return SourceExpr; }
928 static bool classof(const Stmt *T) {
929 return T->getStmtClass() == OpaqueValueExprClass;
933 /// \brief A reference to a declared variable, function, enum, etc.
936 /// This encodes all the information about how a declaration is referenced
937 /// within an expression.
939 /// There are several optional constructs attached to DeclRefExprs only when
940 /// they apply in order to conserve memory. These are laid out past the end of
941 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
943 /// DeclRefExprBits.HasQualifier:
944 /// Specifies when this declaration reference expression has a C++
945 /// nested-name-specifier.
946 /// DeclRefExprBits.HasFoundDecl:
947 /// Specifies when this declaration reference expression has a record of
948 /// a NamedDecl (different from the referenced ValueDecl) which was found
949 /// during name lookup and/or overload resolution.
950 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
951 /// Specifies when this declaration reference expression has an explicit
952 /// C++ template keyword and/or template argument list.
953 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
954 /// Specifies when this declaration reference expression (validly)
955 /// refers to an enclosed local or a captured variable.
956 class DeclRefExpr final
958 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
959 NamedDecl *, ASTTemplateKWAndArgsInfo,
960 TemplateArgumentLoc> {
961 /// \brief The declaration that we are referencing.
964 /// \brief The location of the declaration name itself.
967 /// \brief Provides source/type location info for the declaration name
969 DeclarationNameLoc DNLoc;
971 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
972 return hasQualifier() ? 1 : 0;
975 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
976 return hasFoundDecl() ? 1 : 0;
979 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
980 return hasTemplateKWAndArgsInfo() ? 1 : 0;
983 /// \brief Test whether there is a distinct FoundDecl attached to the end of
985 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
987 DeclRefExpr(const ASTContext &Ctx,
988 NestedNameSpecifierLoc QualifierLoc,
989 SourceLocation TemplateKWLoc,
990 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
991 const DeclarationNameInfo &NameInfo,
993 const TemplateArgumentListInfo *TemplateArgs,
994 QualType T, ExprValueKind VK);
996 /// \brief Construct an empty declaration reference expression.
997 explicit DeclRefExpr(EmptyShell Empty)
998 : Expr(DeclRefExprClass, Empty) { }
1000 /// \brief Computes the type- and value-dependence flags for this
1001 /// declaration reference expression.
1002 void computeDependence(const ASTContext &C);
1005 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1006 ExprValueKind VK, SourceLocation L,
1007 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1008 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1009 D(D), Loc(L), DNLoc(LocInfo) {
1010 DeclRefExprBits.HasQualifier = 0;
1011 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1012 DeclRefExprBits.HasFoundDecl = 0;
1013 DeclRefExprBits.HadMultipleCandidates = 0;
1014 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1015 RefersToEnclosingVariableOrCapture;
1016 computeDependence(D->getASTContext());
1019 static DeclRefExpr *
1020 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1021 SourceLocation TemplateKWLoc, ValueDecl *D,
1022 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1023 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1024 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1026 static DeclRefExpr *
1027 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1028 SourceLocation TemplateKWLoc, ValueDecl *D,
1029 bool RefersToEnclosingVariableOrCapture,
1030 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1031 NamedDecl *FoundD = nullptr,
1032 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1034 /// \brief Construct an empty declaration reference expression.
1035 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1038 bool HasTemplateKWAndArgsInfo,
1039 unsigned NumTemplateArgs);
1041 ValueDecl *getDecl() { return D; }
1042 const ValueDecl *getDecl() const { return D; }
1043 void setDecl(ValueDecl *NewD) { D = NewD; }
1045 DeclarationNameInfo getNameInfo() const {
1046 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1049 SourceLocation getLocation() const { return Loc; }
1050 void setLocation(SourceLocation L) { Loc = L; }
1051 SourceLocation getLocStart() const LLVM_READONLY;
1052 SourceLocation getLocEnd() const LLVM_READONLY;
1054 /// \brief Determine whether this declaration reference was preceded by a
1055 /// C++ nested-name-specifier, e.g., \c N::foo.
1056 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1058 /// \brief If the name was qualified, retrieves the nested-name-specifier
1059 /// that precedes the name, with source-location information.
1060 NestedNameSpecifierLoc getQualifierLoc() const {
1061 if (!hasQualifier())
1062 return NestedNameSpecifierLoc();
1063 return *getTrailingObjects<NestedNameSpecifierLoc>();
1066 /// \brief If the name was qualified, retrieves the nested-name-specifier
1067 /// that precedes the name. Otherwise, returns NULL.
1068 NestedNameSpecifier *getQualifier() const {
1069 return getQualifierLoc().getNestedNameSpecifier();
1072 /// \brief Get the NamedDecl through which this reference occurred.
1074 /// This Decl may be different from the ValueDecl actually referred to in the
1075 /// presence of using declarations, etc. It always returns non-NULL, and may
1076 /// simple return the ValueDecl when appropriate.
1078 NamedDecl *getFoundDecl() {
1079 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1082 /// \brief Get the NamedDecl through which this reference occurred.
1083 /// See non-const variant.
1084 const NamedDecl *getFoundDecl() const {
1085 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1088 bool hasTemplateKWAndArgsInfo() const {
1089 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1092 /// \brief Retrieve the location of the template keyword preceding
1093 /// this name, if any.
1094 SourceLocation getTemplateKeywordLoc() const {
1095 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1096 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1099 /// \brief Retrieve the location of the left angle bracket starting the
1100 /// explicit template argument list following the name, if any.
1101 SourceLocation getLAngleLoc() const {
1102 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1103 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1106 /// \brief Retrieve the location of the right angle bracket ending the
1107 /// explicit template argument list following the name, if any.
1108 SourceLocation getRAngleLoc() const {
1109 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1110 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1113 /// \brief Determines whether the name in this declaration reference
1114 /// was preceded by the template keyword.
1115 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1117 /// \brief Determines whether this declaration reference was followed by an
1118 /// explicit template argument list.
1119 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1121 /// \brief Copies the template arguments (if present) into the given
1123 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1124 if (hasExplicitTemplateArgs())
1125 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1126 getTrailingObjects<TemplateArgumentLoc>(), List);
1129 /// \brief Retrieve the template arguments provided as part of this
1131 const TemplateArgumentLoc *getTemplateArgs() const {
1132 if (!hasExplicitTemplateArgs())
1135 return getTrailingObjects<TemplateArgumentLoc>();
1138 /// \brief Retrieve the number of template arguments provided as part of this
1140 unsigned getNumTemplateArgs() const {
1141 if (!hasExplicitTemplateArgs())
1144 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1147 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1148 return {getTemplateArgs(), getNumTemplateArgs()};
1151 /// \brief Returns true if this expression refers to a function that
1152 /// was resolved from an overloaded set having size greater than 1.
1153 bool hadMultipleCandidates() const {
1154 return DeclRefExprBits.HadMultipleCandidates;
1156 /// \brief Sets the flag telling whether this expression refers to
1157 /// a function that was resolved from an overloaded set having size
1159 void setHadMultipleCandidates(bool V = true) {
1160 DeclRefExprBits.HadMultipleCandidates = V;
1163 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1165 bool refersToEnclosingVariableOrCapture() const {
1166 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1169 static bool classof(const Stmt *T) {
1170 return T->getStmtClass() == DeclRefExprClass;
1174 child_range children() {
1175 return child_range(child_iterator(), child_iterator());
1178 const_child_range children() const {
1179 return const_child_range(const_child_iterator(), const_child_iterator());
1182 friend TrailingObjects;
1183 friend class ASTStmtReader;
1184 friend class ASTStmtWriter;
1187 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1188 class PredefinedExpr : public Expr {
1193 LFunction, // Same as Function, but as wide string.
1197 /// \brief The same as PrettyFunction, except that the
1198 /// 'virtual' keyword is omitted for virtual member functions.
1199 PrettyFunctionNoVirtual
1208 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1211 /// \brief Construct an empty predefined expression.
1212 explicit PredefinedExpr(EmptyShell Empty)
1213 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1215 IdentType getIdentType() const { return Type; }
1217 SourceLocation getLocation() const { return Loc; }
1218 void setLocation(SourceLocation L) { Loc = L; }
1220 StringLiteral *getFunctionName();
1221 const StringLiteral *getFunctionName() const {
1222 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1225 static StringRef getIdentTypeName(IdentType IT);
1226 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1228 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1229 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1231 static bool classof(const Stmt *T) {
1232 return T->getStmtClass() == PredefinedExprClass;
1236 child_range children() { return child_range(&FnName, &FnName + 1); }
1237 const_child_range children() const {
1238 return const_child_range(&FnName, &FnName + 1);
1241 friend class ASTStmtReader;
1244 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1247 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1248 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1249 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1250 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1251 /// ASTContext's allocator for memory allocation.
1252 class APNumericStorage {
1254 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1255 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1259 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1261 APNumericStorage(const APNumericStorage &) = delete;
1262 void operator=(const APNumericStorage &) = delete;
1265 APNumericStorage() : VAL(0), BitWidth(0) { }
1267 llvm::APInt getIntValue() const {
1268 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1270 return llvm::APInt(BitWidth, NumWords, pVal);
1272 return llvm::APInt(BitWidth, VAL);
1274 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1277 class APIntStorage : private APNumericStorage {
1279 llvm::APInt getValue() const { return getIntValue(); }
1280 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1281 setIntValue(C, Val);
1285 class APFloatStorage : private APNumericStorage {
1287 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1288 return llvm::APFloat(Semantics, getIntValue());
1290 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1291 setIntValue(C, Val.bitcastToAPInt());
1295 class IntegerLiteral : public Expr, public APIntStorage {
1298 /// \brief Construct an empty integer literal.
1299 explicit IntegerLiteral(EmptyShell Empty)
1300 : Expr(IntegerLiteralClass, Empty) { }
1303 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1304 // or UnsignedLongLongTy
1305 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1308 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1309 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1310 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1311 /// \param V - the value that the returned integer literal contains.
1312 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1313 QualType type, SourceLocation l);
1314 /// \brief Returns a new empty integer literal.
1315 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1317 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1318 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1320 /// \brief Retrieve the location of the literal.
1321 SourceLocation getLocation() const { return Loc; }
1323 void setLocation(SourceLocation Location) { Loc = Location; }
1325 static bool classof(const Stmt *T) {
1326 return T->getStmtClass() == IntegerLiteralClass;
1330 child_range children() {
1331 return child_range(child_iterator(), child_iterator());
1333 const_child_range children() const {
1334 return const_child_range(const_child_iterator(), const_child_iterator());
1338 class CharacterLiteral : public Expr {
1340 enum CharacterKind {
1352 // type should be IntTy
1353 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1355 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1357 Value(value), Loc(l) {
1358 CharacterLiteralBits.Kind = kind;
1361 /// \brief Construct an empty character literal.
1362 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1364 SourceLocation getLocation() const { return Loc; }
1365 CharacterKind getKind() const {
1366 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1369 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1370 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1372 unsigned getValue() const { return Value; }
1374 void setLocation(SourceLocation Location) { Loc = Location; }
1375 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1376 void setValue(unsigned Val) { Value = Val; }
1378 static bool classof(const Stmt *T) {
1379 return T->getStmtClass() == CharacterLiteralClass;
1383 child_range children() {
1384 return child_range(child_iterator(), child_iterator());
1386 const_child_range children() const {
1387 return const_child_range(const_child_iterator(), const_child_iterator());
1391 class FloatingLiteral : public Expr, private APFloatStorage {
1394 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1395 QualType Type, SourceLocation L);
1397 /// \brief Construct an empty floating-point literal.
1398 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1401 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1402 bool isexact, QualType Type, SourceLocation L);
1403 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1405 llvm::APFloat getValue() const {
1406 return APFloatStorage::getValue(getSemantics());
1408 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1409 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1410 APFloatStorage::setValue(C, Val);
1413 /// Get a raw enumeration value representing the floating-point semantics of
1414 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1415 APFloatSemantics getRawSemantics() const {
1416 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1419 /// Set the raw enumeration value representing the floating-point semantics of
1420 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1421 void setRawSemantics(APFloatSemantics Sem) {
1422 FloatingLiteralBits.Semantics = Sem;
1425 /// Return the APFloat semantics this literal uses.
1426 const llvm::fltSemantics &getSemantics() const;
1428 /// Set the APFloat semantics this literal uses.
1429 void setSemantics(const llvm::fltSemantics &Sem);
1431 bool isExact() const { return FloatingLiteralBits.IsExact; }
1432 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1434 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1435 /// double. Note that this may cause loss of precision, but is useful for
1436 /// debugging dumps, etc.
1437 double getValueAsApproximateDouble() const;
1439 SourceLocation getLocation() const { return Loc; }
1440 void setLocation(SourceLocation L) { Loc = L; }
1442 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1443 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1445 static bool classof(const Stmt *T) {
1446 return T->getStmtClass() == FloatingLiteralClass;
1450 child_range children() {
1451 return child_range(child_iterator(), child_iterator());
1453 const_child_range children() const {
1454 return const_child_range(const_child_iterator(), const_child_iterator());
1458 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1459 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1460 /// IntegerLiteral classes. Instances of this class always have a Complex type
1461 /// whose element type matches the subexpression.
1463 class ImaginaryLiteral : public Expr {
1466 ImaginaryLiteral(Expr *val, QualType Ty)
1467 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1471 /// \brief Build an empty imaginary literal.
1472 explicit ImaginaryLiteral(EmptyShell Empty)
1473 : Expr(ImaginaryLiteralClass, Empty) { }
1475 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1476 Expr *getSubExpr() { return cast<Expr>(Val); }
1477 void setSubExpr(Expr *E) { Val = E; }
1479 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1480 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1482 static bool classof(const Stmt *T) {
1483 return T->getStmtClass() == ImaginaryLiteralClass;
1487 child_range children() { return child_range(&Val, &Val+1); }
1488 const_child_range children() const {
1489 return const_child_range(&Val, &Val + 1);
1493 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1494 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1495 /// is NOT null-terminated, and the length of the string is determined by
1496 /// calling getByteLength(). The C type for a string is always a
1497 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1500 /// Note that strings in C can be formed by concatenation of multiple string
1501 /// literal pptokens in translation phase #6. This keeps track of the locations
1502 /// of each of these pieces.
1504 /// Strings in C can also be truncated and extended by assigning into arrays,
1505 /// e.g. with constructs like:
1506 /// char X[2] = "foobar";
1507 /// In this case, getByteLength() will return 6, but the string literal will
1508 /// have type "char[2]".
1509 class StringLiteral : public Expr {
1520 friend class ASTStmtReader;
1524 const uint16_t *asUInt16;
1525 const uint32_t *asUInt32;
1528 unsigned CharByteWidth : 4;
1530 unsigned IsPascal : 1;
1531 unsigned NumConcatenated;
1532 SourceLocation TokLocs[1];
1534 StringLiteral(QualType Ty) :
1535 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1538 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1541 /// This is the "fully general" constructor that allows representation of
1542 /// strings formed from multiple concatenated tokens.
1543 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1544 StringKind Kind, bool Pascal, QualType Ty,
1545 const SourceLocation *Loc, unsigned NumStrs);
1547 /// Simple constructor for string literals made from one token.
1548 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1549 StringKind Kind, bool Pascal, QualType Ty,
1550 SourceLocation Loc) {
1551 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1554 /// \brief Construct an empty string literal.
1555 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1557 StringRef getString() const {
1558 assert(CharByteWidth==1
1559 && "This function is used in places that assume strings use char");
1560 return StringRef(StrData.asChar, getByteLength());
1563 /// Allow access to clients that need the byte representation, such as
1564 /// ASTWriterStmt::VisitStringLiteral().
1565 StringRef getBytes() const {
1566 // FIXME: StringRef may not be the right type to use as a result for this.
1567 if (CharByteWidth == 1)
1568 return StringRef(StrData.asChar, getByteLength());
1569 if (CharByteWidth == 4)
1570 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1572 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1573 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1577 void outputString(raw_ostream &OS) const;
1579 uint32_t getCodeUnit(size_t i) const {
1580 assert(i < Length && "out of bounds access");
1581 if (CharByteWidth == 1)
1582 return static_cast<unsigned char>(StrData.asChar[i]);
1583 if (CharByteWidth == 4)
1584 return StrData.asUInt32[i];
1585 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1586 return StrData.asUInt16[i];
1589 unsigned getByteLength() const { return CharByteWidth*Length; }
1590 unsigned getLength() const { return Length; }
1591 unsigned getCharByteWidth() const { return CharByteWidth; }
1593 /// \brief Sets the string data to the given string data.
1594 void setString(const ASTContext &C, StringRef Str,
1595 StringKind Kind, bool IsPascal);
1597 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1600 bool isAscii() const { return Kind == Ascii; }
1601 bool isWide() const { return Kind == Wide; }
1602 bool isUTF8() const { return Kind == UTF8; }
1603 bool isUTF16() const { return Kind == UTF16; }
1604 bool isUTF32() const { return Kind == UTF32; }
1605 bool isPascal() const { return IsPascal; }
1607 bool containsNonAsciiOrNull() const {
1608 StringRef Str = getString();
1609 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1610 if (!isASCII(Str[i]) || !Str[i])
1615 /// getNumConcatenated - Get the number of string literal tokens that were
1616 /// concatenated in translation phase #6 to form this string literal.
1617 unsigned getNumConcatenated() const { return NumConcatenated; }
1619 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1620 assert(TokNum < NumConcatenated && "Invalid tok number");
1621 return TokLocs[TokNum];
1623 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1624 assert(TokNum < NumConcatenated && "Invalid tok number");
1625 TokLocs[TokNum] = L;
1628 /// getLocationOfByte - Return a source location that points to the specified
1629 /// byte of this string literal.
1631 /// Strings are amazingly complex. They can be formed from multiple tokens
1632 /// and can have escape sequences in them in addition to the usual trigraph
1633 /// and escaped newline business. This routine handles this complexity.
1636 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1637 const LangOptions &Features, const TargetInfo &Target,
1638 unsigned *StartToken = nullptr,
1639 unsigned *StartTokenByteOffset = nullptr) const;
1641 typedef const SourceLocation *tokloc_iterator;
1642 tokloc_iterator tokloc_begin() const { return TokLocs; }
1643 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1645 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1646 SourceLocation getLocEnd() const LLVM_READONLY {
1647 return TokLocs[NumConcatenated - 1];
1650 static bool classof(const Stmt *T) {
1651 return T->getStmtClass() == StringLiteralClass;
1655 child_range children() {
1656 return child_range(child_iterator(), child_iterator());
1658 const_child_range children() const {
1659 return const_child_range(const_child_iterator(), const_child_iterator());
1663 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1664 /// AST node is only formed if full location information is requested.
1665 class ParenExpr : public Expr {
1666 SourceLocation L, R;
1669 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1670 : Expr(ParenExprClass, val->getType(),
1671 val->getValueKind(), val->getObjectKind(),
1672 val->isTypeDependent(), val->isValueDependent(),
1673 val->isInstantiationDependent(),
1674 val->containsUnexpandedParameterPack()),
1675 L(l), R(r), Val(val) {}
1677 /// \brief Construct an empty parenthesized expression.
1678 explicit ParenExpr(EmptyShell Empty)
1679 : Expr(ParenExprClass, Empty) { }
1681 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1682 Expr *getSubExpr() { return cast<Expr>(Val); }
1683 void setSubExpr(Expr *E) { Val = E; }
1685 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1686 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1688 /// \brief Get the location of the left parentheses '('.
1689 SourceLocation getLParen() const { return L; }
1690 void setLParen(SourceLocation Loc) { L = Loc; }
1692 /// \brief Get the location of the right parentheses ')'.
1693 SourceLocation getRParen() const { return R; }
1694 void setRParen(SourceLocation Loc) { R = Loc; }
1696 static bool classof(const Stmt *T) {
1697 return T->getStmtClass() == ParenExprClass;
1701 child_range children() { return child_range(&Val, &Val+1); }
1702 const_child_range children() const {
1703 return const_child_range(&Val, &Val + 1);
1707 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1708 /// alignof), the postinc/postdec operators from postfix-expression, and various
1711 /// Notes on various nodes:
1713 /// Real/Imag - These return the real/imag part of a complex operand. If
1714 /// applied to a non-complex value, the former returns its operand and the
1715 /// later returns zero in the type of the operand.
1717 class UnaryOperator : public Expr {
1719 typedef UnaryOperatorKind Opcode;
1727 UnaryOperator(Expr *input, Opcode opc, QualType type,
1728 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1729 : Expr(UnaryOperatorClass, type, VK, OK,
1730 input->isTypeDependent() || type->isDependentType(),
1731 input->isValueDependent(),
1732 (input->isInstantiationDependent() ||
1733 type->isInstantiationDependentType()),
1734 input->containsUnexpandedParameterPack()),
1735 Opc(opc), Loc(l), Val(input) {}
1737 /// \brief Build an empty unary operator.
1738 explicit UnaryOperator(EmptyShell Empty)
1739 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1741 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1742 void setOpcode(Opcode O) { Opc = O; }
1744 Expr *getSubExpr() const { return cast<Expr>(Val); }
1745 void setSubExpr(Expr *E) { Val = E; }
1747 /// getOperatorLoc - Return the location of the operator.
1748 SourceLocation getOperatorLoc() const { return Loc; }
1749 void setOperatorLoc(SourceLocation L) { Loc = L; }
1751 /// isPostfix - Return true if this is a postfix operation, like x++.
1752 static bool isPostfix(Opcode Op) {
1753 return Op == UO_PostInc || Op == UO_PostDec;
1756 /// isPrefix - Return true if this is a prefix operation, like --x.
1757 static bool isPrefix(Opcode Op) {
1758 return Op == UO_PreInc || Op == UO_PreDec;
1761 bool isPrefix() const { return isPrefix(getOpcode()); }
1762 bool isPostfix() const { return isPostfix(getOpcode()); }
1764 static bool isIncrementOp(Opcode Op) {
1765 return Op == UO_PreInc || Op == UO_PostInc;
1767 bool isIncrementOp() const {
1768 return isIncrementOp(getOpcode());
1771 static bool isDecrementOp(Opcode Op) {
1772 return Op == UO_PreDec || Op == UO_PostDec;
1774 bool isDecrementOp() const {
1775 return isDecrementOp(getOpcode());
1778 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1779 bool isIncrementDecrementOp() const {
1780 return isIncrementDecrementOp(getOpcode());
1783 static bool isArithmeticOp(Opcode Op) {
1784 return Op >= UO_Plus && Op <= UO_LNot;
1786 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1788 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1789 /// corresponds to, e.g. "sizeof" or "[pre]++"
1790 static StringRef getOpcodeStr(Opcode Op);
1792 /// \brief Retrieve the unary opcode that corresponds to the given
1793 /// overloaded operator.
1794 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1796 /// \brief Retrieve the overloaded operator kind that corresponds to
1797 /// the given unary opcode.
1798 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1800 SourceLocation getLocStart() const LLVM_READONLY {
1801 return isPostfix() ? Val->getLocStart() : Loc;
1803 SourceLocation getLocEnd() const LLVM_READONLY {
1804 return isPostfix() ? Loc : Val->getLocEnd();
1806 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1808 static bool classof(const Stmt *T) {
1809 return T->getStmtClass() == UnaryOperatorClass;
1813 child_range children() { return child_range(&Val, &Val+1); }
1814 const_child_range children() const {
1815 return const_child_range(&Val, &Val + 1);
1819 /// Helper class for OffsetOfExpr.
1821 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1822 class OffsetOfNode {
1824 /// \brief The kind of offsetof node we have.
1826 /// \brief An index into an array.
1830 /// \brief A field in a dependent type, known only by its name.
1832 /// \brief An implicit indirection through a C++ base class, when the
1833 /// field found is in a base class.
1838 enum { MaskBits = 2, Mask = 0x03 };
1840 /// \brief The source range that covers this part of the designator.
1843 /// \brief The data describing the designator, which comes in three
1844 /// different forms, depending on the lower two bits.
1845 /// - An unsigned index into the array of Expr*'s stored after this node
1846 /// in memory, for [constant-expression] designators.
1847 /// - A FieldDecl*, for references to a known field.
1848 /// - An IdentifierInfo*, for references to a field with a given name
1849 /// when the class type is dependent.
1850 /// - A CXXBaseSpecifier*, for references that look at a field in a
1855 /// \brief Create an offsetof node that refers to an array element.
1856 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1857 SourceLocation RBracketLoc)
1858 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1860 /// \brief Create an offsetof node that refers to a field.
1861 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1862 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1863 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1865 /// \brief Create an offsetof node that refers to an identifier.
1866 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1867 SourceLocation NameLoc)
1868 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1869 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1871 /// \brief Create an offsetof node that refers into a C++ base class.
1872 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1873 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1875 /// \brief Determine what kind of offsetof node this is.
1876 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1878 /// \brief For an array element node, returns the index into the array
1880 unsigned getArrayExprIndex() const {
1881 assert(getKind() == Array);
1885 /// \brief For a field offsetof node, returns the field.
1886 FieldDecl *getField() const {
1887 assert(getKind() == Field);
1888 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1891 /// \brief For a field or identifier offsetof node, returns the name of
1893 IdentifierInfo *getFieldName() const;
1895 /// \brief For a base class node, returns the base specifier.
1896 CXXBaseSpecifier *getBase() const {
1897 assert(getKind() == Base);
1898 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1901 /// \brief Retrieve the source range that covers this offsetof node.
1903 /// For an array element node, the source range contains the locations of
1904 /// the square brackets. For a field or identifier node, the source range
1905 /// contains the location of the period (if there is one) and the
1907 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1908 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1909 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1912 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1913 /// offsetof(record-type, member-designator). For example, given:
1924 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1926 class OffsetOfExpr final
1928 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1929 SourceLocation OperatorLoc, RParenLoc;
1931 TypeSourceInfo *TSInfo;
1932 // Number of sub-components (i.e. instances of OffsetOfNode).
1934 // Number of sub-expressions (i.e. array subscript expressions).
1937 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1941 OffsetOfExpr(const ASTContext &C, QualType type,
1942 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1943 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1944 SourceLocation RParenLoc);
1946 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1947 : Expr(OffsetOfExprClass, EmptyShell()),
1948 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1952 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1953 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1954 ArrayRef<OffsetOfNode> comps,
1955 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1957 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1958 unsigned NumComps, unsigned NumExprs);
1960 /// getOperatorLoc - Return the location of the operator.
1961 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1962 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1964 /// \brief Return the location of the right parentheses.
1965 SourceLocation getRParenLoc() const { return RParenLoc; }
1966 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1968 TypeSourceInfo *getTypeSourceInfo() const {
1971 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1975 const OffsetOfNode &getComponent(unsigned Idx) const {
1976 assert(Idx < NumComps && "Subscript out of range");
1977 return getTrailingObjects<OffsetOfNode>()[Idx];
1980 void setComponent(unsigned Idx, OffsetOfNode ON) {
1981 assert(Idx < NumComps && "Subscript out of range");
1982 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
1985 unsigned getNumComponents() const {
1989 Expr* getIndexExpr(unsigned Idx) {
1990 assert(Idx < NumExprs && "Subscript out of range");
1991 return getTrailingObjects<Expr *>()[Idx];
1994 const Expr *getIndexExpr(unsigned Idx) const {
1995 assert(Idx < NumExprs && "Subscript out of range");
1996 return getTrailingObjects<Expr *>()[Idx];
1999 void setIndexExpr(unsigned Idx, Expr* E) {
2000 assert(Idx < NumComps && "Subscript out of range");
2001 getTrailingObjects<Expr *>()[Idx] = E;
2004 unsigned getNumExpressions() const {
2008 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
2009 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2011 static bool classof(const Stmt *T) {
2012 return T->getStmtClass() == OffsetOfExprClass;
2016 child_range children() {
2017 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2018 return child_range(begin, begin + NumExprs);
2020 const_child_range children() const {
2021 Stmt *const *begin =
2022 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2023 return const_child_range(begin, begin + NumExprs);
2025 friend TrailingObjects;
2028 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2029 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2030 /// vec_step (OpenCL 1.1 6.11.12).
2031 class UnaryExprOrTypeTraitExpr : public Expr {
2036 SourceLocation OpLoc, RParenLoc;
2039 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2040 QualType resultType, SourceLocation op,
2041 SourceLocation rp) :
2042 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2043 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2044 // Value-dependent if the argument is type-dependent.
2045 TInfo->getType()->isDependentType(),
2046 TInfo->getType()->isInstantiationDependentType(),
2047 TInfo->getType()->containsUnexpandedParameterPack()),
2048 OpLoc(op), RParenLoc(rp) {
2049 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2050 UnaryExprOrTypeTraitExprBits.IsType = true;
2051 Argument.Ty = TInfo;
2054 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2055 QualType resultType, SourceLocation op,
2058 /// \brief Construct an empty sizeof/alignof expression.
2059 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2060 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2062 UnaryExprOrTypeTrait getKind() const {
2063 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2065 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2067 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2068 QualType getArgumentType() const {
2069 return getArgumentTypeInfo()->getType();
2071 TypeSourceInfo *getArgumentTypeInfo() const {
2072 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2075 Expr *getArgumentExpr() {
2076 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2077 return static_cast<Expr*>(Argument.Ex);
2079 const Expr *getArgumentExpr() const {
2080 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2083 void setArgument(Expr *E) {
2085 UnaryExprOrTypeTraitExprBits.IsType = false;
2087 void setArgument(TypeSourceInfo *TInfo) {
2088 Argument.Ty = TInfo;
2089 UnaryExprOrTypeTraitExprBits.IsType = true;
2092 /// Gets the argument type, or the type of the argument expression, whichever
2094 QualType getTypeOfArgument() const {
2095 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2098 SourceLocation getOperatorLoc() const { return OpLoc; }
2099 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2101 SourceLocation getRParenLoc() const { return RParenLoc; }
2102 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2104 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2105 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2107 static bool classof(const Stmt *T) {
2108 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2112 child_range children();
2113 const_child_range children() const;
2116 //===----------------------------------------------------------------------===//
2117 // Postfix Operators.
2118 //===----------------------------------------------------------------------===//
2120 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2121 class ArraySubscriptExpr : public Expr {
2122 enum { LHS, RHS, END_EXPR=2 };
2123 Stmt* SubExprs[END_EXPR];
2124 SourceLocation RBracketLoc;
2126 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2127 ExprValueKind VK, ExprObjectKind OK,
2128 SourceLocation rbracketloc)
2129 : Expr(ArraySubscriptExprClass, t, VK, OK,
2130 lhs->isTypeDependent() || rhs->isTypeDependent(),
2131 lhs->isValueDependent() || rhs->isValueDependent(),
2132 (lhs->isInstantiationDependent() ||
2133 rhs->isInstantiationDependent()),
2134 (lhs->containsUnexpandedParameterPack() ||
2135 rhs->containsUnexpandedParameterPack())),
2136 RBracketLoc(rbracketloc) {
2137 SubExprs[LHS] = lhs;
2138 SubExprs[RHS] = rhs;
2141 /// \brief Create an empty array subscript expression.
2142 explicit ArraySubscriptExpr(EmptyShell Shell)
2143 : Expr(ArraySubscriptExprClass, Shell) { }
2145 /// An array access can be written A[4] or 4[A] (both are equivalent).
2146 /// - getBase() and getIdx() always present the normalized view: A[4].
2147 /// In this case getBase() returns "A" and getIdx() returns "4".
2148 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2149 /// 4[A] getLHS() returns "4".
2150 /// Note: Because vector element access is also written A[4] we must
2151 /// predicate the format conversion in getBase and getIdx only on the
2152 /// the type of the RHS, as it is possible for the LHS to be a vector of
2154 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2155 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2156 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2158 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2159 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2160 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2163 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2166 const Expr *getBase() const {
2167 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2171 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2174 const Expr *getIdx() const {
2175 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2178 SourceLocation getLocStart() const LLVM_READONLY {
2179 return getLHS()->getLocStart();
2181 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2183 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2184 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2186 SourceLocation getExprLoc() const LLVM_READONLY {
2187 return getBase()->getExprLoc();
2190 static bool classof(const Stmt *T) {
2191 return T->getStmtClass() == ArraySubscriptExprClass;
2195 child_range children() {
2196 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2198 const_child_range children() const {
2199 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2203 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2204 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2205 /// while its subclasses may represent alternative syntax that (semantically)
2206 /// results in a function call. For example, CXXOperatorCallExpr is
2207 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2208 /// "str1 + str2" to resolve to a function call.
2209 class CallExpr : public Expr {
2210 enum { FN=0, PREARGS_START=1 };
2213 SourceLocation RParenLoc;
2215 void updateDependenciesFromArg(Expr *Arg);
2218 // These versions of the constructor are for derived classes.
2219 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2220 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2221 ExprValueKind VK, SourceLocation rparenloc);
2222 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2223 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2224 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2227 Stmt *getPreArg(unsigned i) {
2228 assert(i < getNumPreArgs() && "Prearg access out of range!");
2229 return SubExprs[PREARGS_START+i];
2231 const Stmt *getPreArg(unsigned i) const {
2232 assert(i < getNumPreArgs() && "Prearg access out of range!");
2233 return SubExprs[PREARGS_START+i];
2235 void setPreArg(unsigned i, Stmt *PreArg) {
2236 assert(i < getNumPreArgs() && "Prearg access out of range!");
2237 SubExprs[PREARGS_START+i] = PreArg;
2240 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2243 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2244 ExprValueKind VK, SourceLocation rparenloc);
2246 /// \brief Build an empty call expression.
2247 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2249 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2250 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2251 void setCallee(Expr *F) { SubExprs[FN] = F; }
2253 Decl *getCalleeDecl();
2254 const Decl *getCalleeDecl() const {
2255 return const_cast<CallExpr*>(this)->getCalleeDecl();
2258 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2259 FunctionDecl *getDirectCallee();
2260 const FunctionDecl *getDirectCallee() const {
2261 return const_cast<CallExpr*>(this)->getDirectCallee();
2264 /// getNumArgs - Return the number of actual arguments to this call.
2266 unsigned getNumArgs() const { return NumArgs; }
2268 /// \brief Retrieve the call arguments.
2270 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2272 const Expr *const *getArgs() const {
2273 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2277 /// getArg - Return the specified argument.
2278 Expr *getArg(unsigned Arg) {
2279 assert(Arg < NumArgs && "Arg access out of range!");
2280 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2282 const Expr *getArg(unsigned Arg) const {
2283 assert(Arg < NumArgs && "Arg access out of range!");
2284 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2287 /// setArg - Set the specified argument.
2288 void setArg(unsigned Arg, Expr *ArgExpr) {
2289 assert(Arg < NumArgs && "Arg access out of range!");
2290 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2293 /// setNumArgs - This changes the number of arguments present in this call.
2294 /// Any orphaned expressions are deleted by this, and any new operands are set
2296 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2298 typedef ExprIterator arg_iterator;
2299 typedef ConstExprIterator const_arg_iterator;
2300 typedef llvm::iterator_range<arg_iterator> arg_range;
2301 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2303 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2304 arg_const_range arguments() const {
2305 return arg_const_range(arg_begin(), arg_end());
2308 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2309 arg_iterator arg_end() {
2310 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2312 const_arg_iterator arg_begin() const {
2313 return SubExprs+PREARGS_START+getNumPreArgs();
2315 const_arg_iterator arg_end() const {
2316 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2319 /// This method provides fast access to all the subexpressions of
2320 /// a CallExpr without going through the slower virtual child_iterator
2321 /// interface. This provides efficient reverse iteration of the
2322 /// subexpressions. This is currently used for CFG construction.
2323 ArrayRef<Stmt*> getRawSubExprs() {
2324 return llvm::makeArrayRef(SubExprs,
2325 getNumPreArgs() + PREARGS_START + getNumArgs());
2328 /// getNumCommas - Return the number of commas that must have been present in
2329 /// this function call.
2330 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2332 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2333 /// of the callee. If not, return 0.
2334 unsigned getBuiltinCallee() const;
2336 /// \brief Returns \c true if this is a call to a builtin which does not
2337 /// evaluate side-effects within its arguments.
2338 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2340 /// getCallReturnType - Get the return type of the call expr. This is not
2341 /// always the type of the expr itself, if the return type is a reference
2343 QualType getCallReturnType(const ASTContext &Ctx) const;
2345 SourceLocation getRParenLoc() const { return RParenLoc; }
2346 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2348 SourceLocation getLocStart() const LLVM_READONLY;
2349 SourceLocation getLocEnd() const LLVM_READONLY;
2351 bool isCallToStdMove() const {
2352 const FunctionDecl* FD = getDirectCallee();
2353 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2354 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2357 static bool classof(const Stmt *T) {
2358 return T->getStmtClass() >= firstCallExprConstant &&
2359 T->getStmtClass() <= lastCallExprConstant;
2363 child_range children() {
2364 return child_range(&SubExprs[0],
2365 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2368 const_child_range children() const {
2369 return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2370 getNumPreArgs() + PREARGS_START);
2374 /// Extra data stored in some MemberExpr objects.
2375 struct MemberExprNameQualifier {
2376 /// \brief The nested-name-specifier that qualifies the name, including
2377 /// source-location information.
2378 NestedNameSpecifierLoc QualifierLoc;
2380 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2381 /// name qualifiers.
2382 DeclAccessPair FoundDecl;
2385 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2387 class MemberExpr final
2389 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2390 ASTTemplateKWAndArgsInfo,
2391 TemplateArgumentLoc> {
2392 /// Base - the expression for the base pointer or structure references. In
2393 /// X.F, this is "X".
2396 /// MemberDecl - This is the decl being referenced by the field/member name.
2397 /// In X.F, this is the decl referenced by F.
2398 ValueDecl *MemberDecl;
2400 /// MemberDNLoc - Provides source/type location info for the
2401 /// declaration name embedded in MemberDecl.
2402 DeclarationNameLoc MemberDNLoc;
2404 /// MemberLoc - This is the location of the member name.
2405 SourceLocation MemberLoc;
2407 /// This is the location of the -> or . in the expression.
2408 SourceLocation OperatorLoc;
2410 /// IsArrow - True if this is "X->F", false if this is "X.F".
2413 /// \brief True if this member expression used a nested-name-specifier to
2414 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2415 /// declaration. When true, a MemberExprNameQualifier
2416 /// structure is allocated immediately after the MemberExpr.
2417 bool HasQualifierOrFoundDecl : 1;
2419 /// \brief True if this member expression specified a template keyword
2420 /// and/or a template argument list explicitly, e.g., x->f<int>,
2421 /// x->template f, x->template f<int>.
2422 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2423 /// TemplateArguments (if any) are present.
2424 bool HasTemplateKWAndArgsInfo : 1;
2426 /// \brief True if this member expression refers to a method that
2427 /// was resolved from an overloaded set having size greater than 1.
2428 bool HadMultipleCandidates : 1;
2430 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2431 return HasQualifierOrFoundDecl ? 1 : 0;
2434 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2435 return HasTemplateKWAndArgsInfo ? 1 : 0;
2439 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2440 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2441 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2442 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2443 base->isValueDependent(), base->isInstantiationDependent(),
2444 base->containsUnexpandedParameterPack()),
2445 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2446 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2447 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2448 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2449 assert(memberdecl->getDeclName() == NameInfo.getName());
2452 // NOTE: this constructor should be used only when it is known that
2453 // the member name can not provide additional syntactic info
2454 // (i.e., source locations for C++ operator names or type source info
2455 // for constructors, destructors and conversion operators).
2456 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2457 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2458 ExprValueKind VK, ExprObjectKind OK)
2459 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2460 base->isValueDependent(), base->isInstantiationDependent(),
2461 base->containsUnexpandedParameterPack()),
2462 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2463 OperatorLoc(operatorloc), IsArrow(isarrow),
2464 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2465 HadMultipleCandidates(false) {}
2467 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2468 SourceLocation OperatorLoc,
2469 NestedNameSpecifierLoc QualifierLoc,
2470 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2471 DeclAccessPair founddecl,
2472 DeclarationNameInfo MemberNameInfo,
2473 const TemplateArgumentListInfo *targs, QualType ty,
2474 ExprValueKind VK, ExprObjectKind OK);
2476 void setBase(Expr *E) { Base = E; }
2477 Expr *getBase() const { return cast<Expr>(Base); }
2479 /// \brief Retrieve the member declaration to which this expression refers.
2481 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2482 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2483 ValueDecl *getMemberDecl() const { return MemberDecl; }
2484 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2486 /// \brief Retrieves the declaration found by lookup.
2487 DeclAccessPair getFoundDecl() const {
2488 if (!HasQualifierOrFoundDecl)
2489 return DeclAccessPair::make(getMemberDecl(),
2490 getMemberDecl()->getAccess());
2491 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2494 /// \brief Determines whether this member expression actually had
2495 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2497 bool hasQualifier() const { return getQualifier() != nullptr; }
2499 /// \brief If the member name was qualified, retrieves the
2500 /// nested-name-specifier that precedes the member name, with source-location
2502 NestedNameSpecifierLoc getQualifierLoc() const {
2503 if (!HasQualifierOrFoundDecl)
2504 return NestedNameSpecifierLoc();
2506 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2509 /// \brief If the member name was qualified, retrieves the
2510 /// nested-name-specifier that precedes the member name. Otherwise, returns
2512 NestedNameSpecifier *getQualifier() const {
2513 return getQualifierLoc().getNestedNameSpecifier();
2516 /// \brief Retrieve the location of the template keyword preceding
2517 /// the member name, if any.
2518 SourceLocation getTemplateKeywordLoc() const {
2519 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2520 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2523 /// \brief Retrieve the location of the left angle bracket starting the
2524 /// explicit template argument list following the member name, if any.
2525 SourceLocation getLAngleLoc() const {
2526 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2527 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2530 /// \brief Retrieve the location of the right angle bracket ending the
2531 /// explicit template argument list following the member name, if any.
2532 SourceLocation getRAngleLoc() const {
2533 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2534 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2537 /// Determines whether the member name was preceded by the template keyword.
2538 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2540 /// \brief Determines whether the member name was followed by an
2541 /// explicit template argument list.
2542 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2544 /// \brief Copies the template arguments (if present) into the given
2546 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2547 if (hasExplicitTemplateArgs())
2548 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2549 getTrailingObjects<TemplateArgumentLoc>(), List);
2552 /// \brief Retrieve the template arguments provided as part of this
2554 const TemplateArgumentLoc *getTemplateArgs() const {
2555 if (!hasExplicitTemplateArgs())
2558 return getTrailingObjects<TemplateArgumentLoc>();
2561 /// \brief Retrieve the number of template arguments provided as part of this
2563 unsigned getNumTemplateArgs() const {
2564 if (!hasExplicitTemplateArgs())
2567 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2570 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2571 return {getTemplateArgs(), getNumTemplateArgs()};
2574 /// \brief Retrieve the member declaration name info.
2575 DeclarationNameInfo getMemberNameInfo() const {
2576 return DeclarationNameInfo(MemberDecl->getDeclName(),
2577 MemberLoc, MemberDNLoc);
2580 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2582 bool isArrow() const { return IsArrow; }
2583 void setArrow(bool A) { IsArrow = A; }
2585 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2586 /// location of 'F'.
2587 SourceLocation getMemberLoc() const { return MemberLoc; }
2588 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2590 SourceLocation getLocStart() const LLVM_READONLY;
2591 SourceLocation getLocEnd() const LLVM_READONLY;
2593 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2595 /// \brief Determine whether the base of this explicit is implicit.
2596 bool isImplicitAccess() const {
2597 return getBase() && getBase()->isImplicitCXXThis();
2600 /// \brief Returns true if this member expression refers to a method that
2601 /// was resolved from an overloaded set having size greater than 1.
2602 bool hadMultipleCandidates() const {
2603 return HadMultipleCandidates;
2605 /// \brief Sets the flag telling whether this expression refers to
2606 /// a method that was resolved from an overloaded set having size
2608 void setHadMultipleCandidates(bool V = true) {
2609 HadMultipleCandidates = V;
2612 /// \brief Returns true if virtual dispatch is performed.
2613 /// If the member access is fully qualified, (i.e. X::f()), virtual
2614 /// dispatching is not performed. In -fapple-kext mode qualified
2615 /// calls to virtual method will still go through the vtable.
2616 bool performsVirtualDispatch(const LangOptions &LO) const {
2617 return LO.AppleKext || !hasQualifier();
2620 static bool classof(const Stmt *T) {
2621 return T->getStmtClass() == MemberExprClass;
2625 child_range children() { return child_range(&Base, &Base+1); }
2626 const_child_range children() const {
2627 return const_child_range(&Base, &Base + 1);
2630 friend TrailingObjects;
2631 friend class ASTReader;
2632 friend class ASTStmtWriter;
2635 /// CompoundLiteralExpr - [C99 6.5.2.5]
2637 class CompoundLiteralExpr : public Expr {
2638 /// LParenLoc - If non-null, this is the location of the left paren in a
2639 /// compound literal like "(int){4}". This can be null if this is a
2640 /// synthesized compound expression.
2641 SourceLocation LParenLoc;
2643 /// The type as written. This can be an incomplete array type, in
2644 /// which case the actual expression type will be different.
2645 /// The int part of the pair stores whether this expr is file scope.
2646 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2649 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2650 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2651 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2652 tinfo->getType()->isDependentType(),
2653 init->isValueDependent(),
2654 (init->isInstantiationDependent() ||
2655 tinfo->getType()->isInstantiationDependentType()),
2656 init->containsUnexpandedParameterPack()),
2657 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2659 /// \brief Construct an empty compound literal.
2660 explicit CompoundLiteralExpr(EmptyShell Empty)
2661 : Expr(CompoundLiteralExprClass, Empty) { }
2663 const Expr *getInitializer() const { return cast<Expr>(Init); }
2664 Expr *getInitializer() { return cast<Expr>(Init); }
2665 void setInitializer(Expr *E) { Init = E; }
2667 bool isFileScope() const { return TInfoAndScope.getInt(); }
2668 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2670 SourceLocation getLParenLoc() const { return LParenLoc; }
2671 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2673 TypeSourceInfo *getTypeSourceInfo() const {
2674 return TInfoAndScope.getPointer();
2676 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2677 TInfoAndScope.setPointer(tinfo);
2680 SourceLocation getLocStart() const LLVM_READONLY {
2681 // FIXME: Init should never be null.
2683 return SourceLocation();
2684 if (LParenLoc.isInvalid())
2685 return Init->getLocStart();
2688 SourceLocation getLocEnd() const LLVM_READONLY {
2689 // FIXME: Init should never be null.
2691 return SourceLocation();
2692 return Init->getLocEnd();
2695 static bool classof(const Stmt *T) {
2696 return T->getStmtClass() == CompoundLiteralExprClass;
2700 child_range children() { return child_range(&Init, &Init+1); }
2701 const_child_range children() const {
2702 return const_child_range(&Init, &Init + 1);
2706 /// CastExpr - Base class for type casts, including both implicit
2707 /// casts (ImplicitCastExpr) and explicit casts that have some
2708 /// representation in the source code (ExplicitCastExpr's derived
2710 class CastExpr : public Expr {
2714 bool CastConsistency() const;
2716 const CXXBaseSpecifier * const *path_buffer() const {
2717 return const_cast<CastExpr*>(this)->path_buffer();
2719 CXXBaseSpecifier **path_buffer();
2721 void setBasePathSize(unsigned basePathSize) {
2722 CastExprBits.BasePathSize = basePathSize;
2723 assert(CastExprBits.BasePathSize == basePathSize &&
2724 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2728 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2729 Expr *op, unsigned BasePathSize)
2730 : Expr(SC, ty, VK, OK_Ordinary,
2731 // Cast expressions are type-dependent if the type is
2732 // dependent (C++ [temp.dep.expr]p3).
2733 ty->isDependentType(),
2734 // Cast expressions are value-dependent if the type is
2735 // dependent or if the subexpression is value-dependent.
2736 ty->isDependentType() || (op && op->isValueDependent()),
2737 (ty->isInstantiationDependentType() ||
2738 (op && op->isInstantiationDependent())),
2739 // An implicit cast expression doesn't (lexically) contain an
2740 // unexpanded pack, even if its target type does.
2741 ((SC != ImplicitCastExprClass &&
2742 ty->containsUnexpandedParameterPack()) ||
2743 (op && op->containsUnexpandedParameterPack()))),
2745 CastExprBits.Kind = kind;
2746 setBasePathSize(BasePathSize);
2747 assert(CastConsistency());
2750 /// \brief Construct an empty cast.
2751 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2753 setBasePathSize(BasePathSize);
2757 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2758 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2759 const char *getCastKindName() const;
2761 Expr *getSubExpr() { return cast<Expr>(Op); }
2762 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2763 void setSubExpr(Expr *E) { Op = E; }
2765 /// \brief Retrieve the cast subexpression as it was written in the source
2766 /// code, looking through any implicit casts or other intermediate nodes
2767 /// introduced by semantic analysis.
2768 Expr *getSubExprAsWritten();
2769 const Expr *getSubExprAsWritten() const {
2770 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2773 typedef CXXBaseSpecifier **path_iterator;
2774 typedef const CXXBaseSpecifier * const *path_const_iterator;
2775 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2776 unsigned path_size() const { return CastExprBits.BasePathSize; }
2777 path_iterator path_begin() { return path_buffer(); }
2778 path_iterator path_end() { return path_buffer() + path_size(); }
2779 path_const_iterator path_begin() const { return path_buffer(); }
2780 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2782 const FieldDecl *getTargetUnionField() const {
2783 assert(getCastKind() == CK_ToUnion);
2784 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2787 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2789 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2792 static bool classof(const Stmt *T) {
2793 return T->getStmtClass() >= firstCastExprConstant &&
2794 T->getStmtClass() <= lastCastExprConstant;
2798 child_range children() { return child_range(&Op, &Op+1); }
2799 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2802 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2803 /// conversions, which have no direct representation in the original
2804 /// source code. For example: converting T[]->T*, void f()->void
2805 /// (*f)(), float->double, short->int, etc.
2807 /// In C, implicit casts always produce rvalues. However, in C++, an
2808 /// implicit cast whose result is being bound to a reference will be
2809 /// an lvalue or xvalue. For example:
2813 /// class Derived : public Base { };
2814 /// Derived &&ref();
2815 /// void f(Derived d) {
2816 /// Base& b = d; // initializer is an ImplicitCastExpr
2817 /// // to an lvalue of type Base
2818 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2819 /// // to an xvalue of type Base
2822 class ImplicitCastExpr final
2824 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2826 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2827 unsigned BasePathLength, ExprValueKind VK)
2828 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2831 /// \brief Construct an empty implicit cast.
2832 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2833 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2836 enum OnStack_t { OnStack };
2837 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2839 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2842 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2843 CastKind Kind, Expr *Operand,
2844 const CXXCastPath *BasePath,
2847 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2850 SourceLocation getLocStart() const LLVM_READONLY {
2851 return getSubExpr()->getLocStart();
2853 SourceLocation getLocEnd() const LLVM_READONLY {
2854 return getSubExpr()->getLocEnd();
2857 static bool classof(const Stmt *T) {
2858 return T->getStmtClass() == ImplicitCastExprClass;
2861 friend TrailingObjects;
2862 friend class CastExpr;
2865 inline Expr *Expr::IgnoreImpCasts() {
2867 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2868 e = ice->getSubExpr();
2872 /// ExplicitCastExpr - An explicit cast written in the source
2875 /// This class is effectively an abstract class, because it provides
2876 /// the basic representation of an explicitly-written cast without
2877 /// specifying which kind of cast (C cast, functional cast, static
2878 /// cast, etc.) was written; specific derived classes represent the
2879 /// particular style of cast and its location information.
2881 /// Unlike implicit casts, explicit cast nodes have two different
2882 /// types: the type that was written into the source code, and the
2883 /// actual type of the expression as determined by semantic
2884 /// analysis. These types may differ slightly. For example, in C++ one
2885 /// can cast to a reference type, which indicates that the resulting
2886 /// expression will be an lvalue or xvalue. The reference type, however,
2887 /// will not be used as the type of the expression.
2888 class ExplicitCastExpr : public CastExpr {
2889 /// TInfo - Source type info for the (written) type
2890 /// this expression is casting to.
2891 TypeSourceInfo *TInfo;
2894 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2895 CastKind kind, Expr *op, unsigned PathSize,
2896 TypeSourceInfo *writtenTy)
2897 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2899 /// \brief Construct an empty explicit cast.
2900 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2901 : CastExpr(SC, Shell, PathSize) { }
2904 /// getTypeInfoAsWritten - Returns the type source info for the type
2905 /// that this expression is casting to.
2906 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2907 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2909 /// getTypeAsWritten - Returns the type that this expression is
2910 /// casting to, as written in the source code.
2911 QualType getTypeAsWritten() const { return TInfo->getType(); }
2913 static bool classof(const Stmt *T) {
2914 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2915 T->getStmtClass() <= lastExplicitCastExprConstant;
2919 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2920 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2921 /// (Type)expr. For example: @c (int)f.
2922 class CStyleCastExpr final
2923 : public ExplicitCastExpr,
2924 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2925 SourceLocation LPLoc; // the location of the left paren
2926 SourceLocation RPLoc; // the location of the right paren
2928 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2929 unsigned PathSize, TypeSourceInfo *writtenTy,
2930 SourceLocation l, SourceLocation r)
2931 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2932 writtenTy), LPLoc(l), RPLoc(r) {}
2934 /// \brief Construct an empty C-style explicit cast.
2935 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2936 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2939 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2940 ExprValueKind VK, CastKind K,
2941 Expr *Op, const CXXCastPath *BasePath,
2942 TypeSourceInfo *WrittenTy, SourceLocation L,
2945 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2948 SourceLocation getLParenLoc() const { return LPLoc; }
2949 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2951 SourceLocation getRParenLoc() const { return RPLoc; }
2952 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2954 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2955 SourceLocation getLocEnd() const LLVM_READONLY {
2956 return getSubExpr()->getLocEnd();
2959 static bool classof(const Stmt *T) {
2960 return T->getStmtClass() == CStyleCastExprClass;
2963 friend TrailingObjects;
2964 friend class CastExpr;
2967 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2969 /// This expression node kind describes a builtin binary operation,
2970 /// such as "x + y" for integer values "x" and "y". The operands will
2971 /// already have been converted to appropriate types (e.g., by
2972 /// performing promotions or conversions).
2974 /// In C++, where operators may be overloaded, a different kind of
2975 /// expression node (CXXOperatorCallExpr) is used to express the
2976 /// invocation of an overloaded operator with operator syntax. Within
2977 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2978 /// used to store an expression "x + y" depends on the subexpressions
2979 /// for x and y. If neither x or y is type-dependent, and the "+"
2980 /// operator resolves to a built-in operation, BinaryOperator will be
2981 /// used to express the computation (x and y may still be
2982 /// value-dependent). If either x or y is type-dependent, or if the
2983 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2984 /// be used to express the computation.
2985 class BinaryOperator : public Expr {
2987 typedef BinaryOperatorKind Opcode;
2992 // This is only meaningful for operations on floating point types and 0
2994 unsigned FPFeatures : 2;
2995 SourceLocation OpLoc;
2997 enum { LHS, RHS, END_EXPR };
2998 Stmt* SubExprs[END_EXPR];
3001 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3002 ExprValueKind VK, ExprObjectKind OK,
3003 SourceLocation opLoc, FPOptions FPFeatures)
3004 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3005 lhs->isTypeDependent() || rhs->isTypeDependent(),
3006 lhs->isValueDependent() || rhs->isValueDependent(),
3007 (lhs->isInstantiationDependent() ||
3008 rhs->isInstantiationDependent()),
3009 (lhs->containsUnexpandedParameterPack() ||
3010 rhs->containsUnexpandedParameterPack())),
3011 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3012 SubExprs[LHS] = lhs;
3013 SubExprs[RHS] = rhs;
3014 assert(!isCompoundAssignmentOp() &&
3015 "Use CompoundAssignOperator for compound assignments");
3018 /// \brief Construct an empty binary operator.
3019 explicit BinaryOperator(EmptyShell Empty)
3020 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
3022 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
3023 SourceLocation getOperatorLoc() const { return OpLoc; }
3024 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3026 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3027 void setOpcode(Opcode O) { Opc = O; }
3029 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3030 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3031 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3032 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3034 SourceLocation getLocStart() const LLVM_READONLY {
3035 return getLHS()->getLocStart();
3037 SourceLocation getLocEnd() const LLVM_READONLY {
3038 return getRHS()->getLocEnd();
3041 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3042 /// corresponds to, e.g. "<<=".
3043 static StringRef getOpcodeStr(Opcode Op);
3045 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3047 /// \brief Retrieve the binary opcode that corresponds to the given
3048 /// overloaded operator.
3049 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3051 /// \brief Retrieve the overloaded operator kind that corresponds to
3052 /// the given binary opcode.
3053 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3055 /// predicates to categorize the respective opcodes.
3056 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
3057 static bool isMultiplicativeOp(Opcode Opc) {
3058 return Opc >= BO_Mul && Opc <= BO_Rem;
3060 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3061 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3062 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3063 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3064 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3066 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3067 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3069 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3070 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3072 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3073 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3075 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3076 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3078 static Opcode negateComparisonOp(Opcode Opc) {
3081 llvm_unreachable("Not a comparsion operator.");
3082 case BO_LT: return BO_GE;
3083 case BO_GT: return BO_LE;
3084 case BO_LE: return BO_GT;
3085 case BO_GE: return BO_LT;
3086 case BO_EQ: return BO_NE;
3087 case BO_NE: return BO_EQ;
3091 static Opcode reverseComparisonOp(Opcode Opc) {
3094 llvm_unreachable("Not a comparsion operator.");
3095 case BO_LT: return BO_GT;
3096 case BO_GT: return BO_LT;
3097 case BO_LE: return BO_GE;
3098 case BO_GE: return BO_LE;
3105 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3106 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3108 static bool isAssignmentOp(Opcode Opc) {
3109 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3111 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3113 static bool isCompoundAssignmentOp(Opcode Opc) {
3114 return Opc > BO_Assign && Opc <= BO_OrAssign;
3116 bool isCompoundAssignmentOp() const {
3117 return isCompoundAssignmentOp(getOpcode());
3119 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3120 assert(isCompoundAssignmentOp(Opc));
3121 if (Opc >= BO_AndAssign)
3122 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3124 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3127 static bool isShiftAssignOp(Opcode Opc) {
3128 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3130 bool isShiftAssignOp() const {
3131 return isShiftAssignOp(getOpcode());
3134 // Return true if a binary operator using the specified opcode and operands
3135 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3136 // integer to a pointer.
3137 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3138 Expr *LHS, Expr *RHS);
3140 static bool classof(const Stmt *S) {
3141 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3142 S->getStmtClass() <= lastBinaryOperatorConstant;
3146 child_range children() {
3147 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3149 const_child_range children() const {
3150 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3153 // Set the FP contractability status of this operator. Only meaningful for
3154 // operations on floating point types.
3155 void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3157 FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3159 // Get the FP contractability status of this operator. Only meaningful for
3160 // operations on floating point types.
3161 bool isFPContractableWithinStatement() const {
3162 return FPOptions(FPFeatures).allowFPContractWithinStatement();
3166 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3167 ExprValueKind VK, ExprObjectKind OK,
3168 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3169 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3170 lhs->isTypeDependent() || rhs->isTypeDependent(),
3171 lhs->isValueDependent() || rhs->isValueDependent(),
3172 (lhs->isInstantiationDependent() ||
3173 rhs->isInstantiationDependent()),
3174 (lhs->containsUnexpandedParameterPack() ||
3175 rhs->containsUnexpandedParameterPack())),
3176 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3177 SubExprs[LHS] = lhs;
3178 SubExprs[RHS] = rhs;
3181 BinaryOperator(StmtClass SC, EmptyShell Empty)
3182 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3185 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3186 /// track of the type the operation is performed in. Due to the semantics of
3187 /// these operators, the operands are promoted, the arithmetic performed, an
3188 /// implicit conversion back to the result type done, then the assignment takes
3189 /// place. This captures the intermediate type which the computation is done
3191 class CompoundAssignOperator : public BinaryOperator {
3192 QualType ComputationLHSType;
3193 QualType ComputationResultType;
3195 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3196 ExprValueKind VK, ExprObjectKind OK,
3197 QualType CompLHSType, QualType CompResultType,
3198 SourceLocation OpLoc, FPOptions FPFeatures)
3199 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3201 ComputationLHSType(CompLHSType),
3202 ComputationResultType(CompResultType) {
3203 assert(isCompoundAssignmentOp() &&
3204 "Only should be used for compound assignments");
3207 /// \brief Build an empty compound assignment operator expression.
3208 explicit CompoundAssignOperator(EmptyShell Empty)
3209 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3211 // The two computation types are the type the LHS is converted
3212 // to for the computation and the type of the result; the two are
3213 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3214 QualType getComputationLHSType() const { return ComputationLHSType; }
3215 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3217 QualType getComputationResultType() const { return ComputationResultType; }
3218 void setComputationResultType(QualType T) { ComputationResultType = T; }
3220 static bool classof(const Stmt *S) {
3221 return S->getStmtClass() == CompoundAssignOperatorClass;
3225 /// AbstractConditionalOperator - An abstract base class for
3226 /// ConditionalOperator and BinaryConditionalOperator.
3227 class AbstractConditionalOperator : public Expr {
3228 SourceLocation QuestionLoc, ColonLoc;
3229 friend class ASTStmtReader;
3232 AbstractConditionalOperator(StmtClass SC, QualType T,
3233 ExprValueKind VK, ExprObjectKind OK,
3234 bool TD, bool VD, bool ID,
3235 bool ContainsUnexpandedParameterPack,
3236 SourceLocation qloc,
3237 SourceLocation cloc)
3238 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3239 QuestionLoc(qloc), ColonLoc(cloc) {}
3241 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3242 : Expr(SC, Empty) { }
3245 // getCond - Return the expression representing the condition for
3247 Expr *getCond() const;
3249 // getTrueExpr - Return the subexpression representing the value of
3250 // the expression if the condition evaluates to true.
3251 Expr *getTrueExpr() const;
3253 // getFalseExpr - Return the subexpression representing the value of
3254 // the expression if the condition evaluates to false. This is
3255 // the same as getRHS.
3256 Expr *getFalseExpr() const;
3258 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3259 SourceLocation getColonLoc() const { return ColonLoc; }
3261 static bool classof(const Stmt *T) {
3262 return T->getStmtClass() == ConditionalOperatorClass ||
3263 T->getStmtClass() == BinaryConditionalOperatorClass;
3267 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3268 /// middle" extension is a BinaryConditionalOperator.
3269 class ConditionalOperator : public AbstractConditionalOperator {
3270 enum { COND, LHS, RHS, END_EXPR };
3271 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3273 friend class ASTStmtReader;
3275 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3276 SourceLocation CLoc, Expr *rhs,
3277 QualType t, ExprValueKind VK, ExprObjectKind OK)
3278 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3279 // FIXME: the type of the conditional operator doesn't
3280 // depend on the type of the conditional, but the standard
3281 // seems to imply that it could. File a bug!
3282 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3283 (cond->isValueDependent() || lhs->isValueDependent() ||
3284 rhs->isValueDependent()),
3285 (cond->isInstantiationDependent() ||
3286 lhs->isInstantiationDependent() ||
3287 rhs->isInstantiationDependent()),
3288 (cond->containsUnexpandedParameterPack() ||
3289 lhs->containsUnexpandedParameterPack() ||
3290 rhs->containsUnexpandedParameterPack()),
3292 SubExprs[COND] = cond;
3293 SubExprs[LHS] = lhs;
3294 SubExprs[RHS] = rhs;
3297 /// \brief Build an empty conditional operator.
3298 explicit ConditionalOperator(EmptyShell Empty)
3299 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3301 // getCond - Return the expression representing the condition for
3303 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3305 // getTrueExpr - Return the subexpression representing the value of
3306 // the expression if the condition evaluates to true.
3307 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3309 // getFalseExpr - Return the subexpression representing the value of
3310 // the expression if the condition evaluates to false. This is
3311 // the same as getRHS.
3312 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3314 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3315 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3317 SourceLocation getLocStart() const LLVM_READONLY {
3318 return getCond()->getLocStart();
3320 SourceLocation getLocEnd() const LLVM_READONLY {
3321 return getRHS()->getLocEnd();
3324 static bool classof(const Stmt *T) {
3325 return T->getStmtClass() == ConditionalOperatorClass;
3329 child_range children() {
3330 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3332 const_child_range children() const {
3333 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3337 /// BinaryConditionalOperator - The GNU extension to the conditional
3338 /// operator which allows the middle operand to be omitted.
3340 /// This is a different expression kind on the assumption that almost
3341 /// every client ends up needing to know that these are different.
3342 class BinaryConditionalOperator : public AbstractConditionalOperator {
3343 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3345 /// - the common condition/left-hand-side expression, which will be
3346 /// evaluated as the opaque value
3347 /// - the condition, expressed in terms of the opaque value
3348 /// - the left-hand-side, expressed in terms of the opaque value
3349 /// - the right-hand-side
3350 Stmt *SubExprs[NUM_SUBEXPRS];
3351 OpaqueValueExpr *OpaqueValue;
3353 friend class ASTStmtReader;
3355 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3356 Expr *cond, Expr *lhs, Expr *rhs,
3357 SourceLocation qloc, SourceLocation cloc,
3358 QualType t, ExprValueKind VK, ExprObjectKind OK)
3359 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3360 (common->isTypeDependent() || rhs->isTypeDependent()),
3361 (common->isValueDependent() || rhs->isValueDependent()),
3362 (common->isInstantiationDependent() ||
3363 rhs->isInstantiationDependent()),
3364 (common->containsUnexpandedParameterPack() ||
3365 rhs->containsUnexpandedParameterPack()),
3367 OpaqueValue(opaqueValue) {
3368 SubExprs[COMMON] = common;
3369 SubExprs[COND] = cond;
3370 SubExprs[LHS] = lhs;
3371 SubExprs[RHS] = rhs;
3372 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3375 /// \brief Build an empty conditional operator.
3376 explicit BinaryConditionalOperator(EmptyShell Empty)
3377 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3379 /// \brief getCommon - Return the common expression, written to the
3380 /// left of the condition. The opaque value will be bound to the
3381 /// result of this expression.
3382 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3384 /// \brief getOpaqueValue - Return the opaque value placeholder.
3385 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3387 /// \brief getCond - Return the condition expression; this is defined
3388 /// in terms of the opaque value.
3389 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3391 /// \brief getTrueExpr - Return the subexpression which will be
3392 /// evaluated if the condition evaluates to true; this is defined
3393 /// in terms of the opaque value.
3394 Expr *getTrueExpr() const {
3395 return cast<Expr>(SubExprs[LHS]);
3398 /// \brief getFalseExpr - Return the subexpression which will be
3399 /// evaluated if the condnition evaluates to false; this is
3400 /// defined in terms of the opaque value.
3401 Expr *getFalseExpr() const {
3402 return cast<Expr>(SubExprs[RHS]);
3405 SourceLocation getLocStart() const LLVM_READONLY {
3406 return getCommon()->getLocStart();
3408 SourceLocation getLocEnd() const LLVM_READONLY {
3409 return getFalseExpr()->getLocEnd();
3412 static bool classof(const Stmt *T) {
3413 return T->getStmtClass() == BinaryConditionalOperatorClass;
3417 child_range children() {
3418 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3420 const_child_range children() const {
3421 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3425 inline Expr *AbstractConditionalOperator::getCond() const {
3426 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3427 return co->getCond();
3428 return cast<BinaryConditionalOperator>(this)->getCond();
3431 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3432 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3433 return co->getTrueExpr();
3434 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3437 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3438 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3439 return co->getFalseExpr();
3440 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3443 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3444 class AddrLabelExpr : public Expr {
3445 SourceLocation AmpAmpLoc, LabelLoc;
3448 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3450 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3452 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3454 /// \brief Build an empty address of a label expression.
3455 explicit AddrLabelExpr(EmptyShell Empty)
3456 : Expr(AddrLabelExprClass, Empty) { }
3458 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3459 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3460 SourceLocation getLabelLoc() const { return LabelLoc; }
3461 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3463 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3464 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3466 LabelDecl *getLabel() const { return Label; }
3467 void setLabel(LabelDecl *L) { Label = L; }
3469 static bool classof(const Stmt *T) {
3470 return T->getStmtClass() == AddrLabelExprClass;
3474 child_range children() {
3475 return child_range(child_iterator(), child_iterator());
3477 const_child_range children() const {
3478 return const_child_range(const_child_iterator(), const_child_iterator());
3482 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3483 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3484 /// takes the value of the last subexpression.
3486 /// A StmtExpr is always an r-value; values "returned" out of a
3487 /// StmtExpr will be copied.
3488 class StmtExpr : public Expr {
3490 SourceLocation LParenLoc, RParenLoc;
3492 // FIXME: Does type-dependence need to be computed differently?
3493 // FIXME: Do we need to compute instantiation instantiation-dependence for
3494 // statements? (ugh!)
3495 StmtExpr(CompoundStmt *substmt, QualType T,
3496 SourceLocation lp, SourceLocation rp) :
3497 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3498 T->isDependentType(), false, false, false),
3499 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3501 /// \brief Build an empty statement expression.
3502 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3504 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3505 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3506 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3508 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3509 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3511 SourceLocation getLParenLoc() const { return LParenLoc; }
3512 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3513 SourceLocation getRParenLoc() const { return RParenLoc; }
3514 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3516 static bool classof(const Stmt *T) {
3517 return T->getStmtClass() == StmtExprClass;
3521 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3522 const_child_range children() const {
3523 return const_child_range(&SubStmt, &SubStmt + 1);
3527 /// ShuffleVectorExpr - clang-specific builtin-in function
3528 /// __builtin_shufflevector.
3529 /// This AST node represents a operator that does a constant
3530 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3531 /// two vectors and a variable number of constant indices,
3532 /// and returns the appropriately shuffled vector.
3533 class ShuffleVectorExpr : public Expr {
3534 SourceLocation BuiltinLoc, RParenLoc;
3536 // SubExprs - the list of values passed to the __builtin_shufflevector
3537 // function. The first two are vectors, and the rest are constant
3538 // indices. The number of values in this list is always
3539 // 2+the number of indices in the vector type.
3544 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3545 SourceLocation BLoc, SourceLocation RP);
3547 /// \brief Build an empty vector-shuffle expression.
3548 explicit ShuffleVectorExpr(EmptyShell Empty)
3549 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3551 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3552 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3554 SourceLocation getRParenLoc() const { return RParenLoc; }
3555 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3557 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3558 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3560 static bool classof(const Stmt *T) {
3561 return T->getStmtClass() == ShuffleVectorExprClass;
3564 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3565 /// constant expression, the actual arguments passed in, and the function
3567 unsigned getNumSubExprs() const { return NumExprs; }
3569 /// \brief Retrieve the array of expressions.
3570 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3572 /// getExpr - Return the Expr at the specified index.
3573 Expr *getExpr(unsigned Index) {
3574 assert((Index < NumExprs) && "Arg access out of range!");
3575 return cast<Expr>(SubExprs[Index]);
3577 const Expr *getExpr(unsigned Index) const {
3578 assert((Index < NumExprs) && "Arg access out of range!");
3579 return cast<Expr>(SubExprs[Index]);
3582 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3584 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3585 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3586 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3590 child_range children() {
3591 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3593 const_child_range children() const {
3594 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
3598 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3599 /// This AST node provides support for converting a vector type to another
3600 /// vector type of the same arity.
3601 class ConvertVectorExpr : public Expr {
3604 TypeSourceInfo *TInfo;
3605 SourceLocation BuiltinLoc, RParenLoc;
3607 friend class ASTReader;
3608 friend class ASTStmtReader;
3609 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3612 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3613 ExprValueKind VK, ExprObjectKind OK,
3614 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3615 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3616 DstType->isDependentType(),
3617 DstType->isDependentType() || SrcExpr->isValueDependent(),
3618 (DstType->isInstantiationDependentType() ||
3619 SrcExpr->isInstantiationDependent()),
3620 (DstType->containsUnexpandedParameterPack() ||
3621 SrcExpr->containsUnexpandedParameterPack())),
3622 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3624 /// getSrcExpr - Return the Expr to be converted.
3625 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3627 /// getTypeSourceInfo - Return the destination type.
3628 TypeSourceInfo *getTypeSourceInfo() const {
3631 void setTypeSourceInfo(TypeSourceInfo *ti) {
3635 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3636 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3638 /// getRParenLoc - Return the location of final right parenthesis.
3639 SourceLocation getRParenLoc() const { return RParenLoc; }
3641 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3642 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3644 static bool classof(const Stmt *T) {
3645 return T->getStmtClass() == ConvertVectorExprClass;
3649 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3650 const_child_range children() const {
3651 return const_child_range(&SrcExpr, &SrcExpr + 1);
3655 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3656 /// This AST node is similar to the conditional operator (?:) in C, with
3657 /// the following exceptions:
3658 /// - the test expression must be a integer constant expression.
3659 /// - the expression returned acts like the chosen subexpression in every
3660 /// visible way: the type is the same as that of the chosen subexpression,
3661 /// and all predicates (whether it's an l-value, whether it's an integer
3662 /// constant expression, etc.) return the same result as for the chosen
3664 class ChooseExpr : public Expr {
3665 enum { COND, LHS, RHS, END_EXPR };
3666 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3667 SourceLocation BuiltinLoc, RParenLoc;
3670 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3671 QualType t, ExprValueKind VK, ExprObjectKind OK,
3672 SourceLocation RP, bool condIsTrue,
3673 bool TypeDependent, bool ValueDependent)
3674 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3675 (cond->isInstantiationDependent() ||
3676 lhs->isInstantiationDependent() ||
3677 rhs->isInstantiationDependent()),
3678 (cond->containsUnexpandedParameterPack() ||
3679 lhs->containsUnexpandedParameterPack() ||
3680 rhs->containsUnexpandedParameterPack())),
3681 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3682 SubExprs[COND] = cond;
3683 SubExprs[LHS] = lhs;
3684 SubExprs[RHS] = rhs;
3687 /// \brief Build an empty __builtin_choose_expr.
3688 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3690 /// isConditionTrue - Return whether the condition is true (i.e. not
3692 bool isConditionTrue() const {
3693 assert(!isConditionDependent() &&
3694 "Dependent condition isn't true or false");
3697 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3699 bool isConditionDependent() const {
3700 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3703 /// getChosenSubExpr - Return the subexpression chosen according to the
3705 Expr *getChosenSubExpr() const {
3706 return isConditionTrue() ? getLHS() : getRHS();
3709 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3710 void setCond(Expr *E) { SubExprs[COND] = E; }
3711 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3712 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3713 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3714 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3716 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3717 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3719 SourceLocation getRParenLoc() const { return RParenLoc; }
3720 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3722 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3723 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3725 static bool classof(const Stmt *T) {
3726 return T->getStmtClass() == ChooseExprClass;
3730 child_range children() {
3731 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3733 const_child_range children() const {
3734 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3738 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3739 /// for a null pointer constant that has integral type (e.g., int or
3740 /// long) and is the same size and alignment as a pointer. The __null
3741 /// extension is typically only used by system headers, which define
3742 /// NULL as __null in C++ rather than using 0 (which is an integer
3743 /// that may not match the size of a pointer).
3744 class GNUNullExpr : public Expr {
3745 /// TokenLoc - The location of the __null keyword.
3746 SourceLocation TokenLoc;
3749 GNUNullExpr(QualType Ty, SourceLocation Loc)
3750 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3754 /// \brief Build an empty GNU __null expression.
3755 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3757 /// getTokenLocation - The location of the __null token.
3758 SourceLocation getTokenLocation() const { return TokenLoc; }
3759 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3761 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3762 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3764 static bool classof(const Stmt *T) {
3765 return T->getStmtClass() == GNUNullExprClass;
3769 child_range children() {
3770 return child_range(child_iterator(), child_iterator());
3772 const_child_range children() const {
3773 return const_child_range(const_child_iterator(), const_child_iterator());
3777 /// Represents a call to the builtin function \c __builtin_va_arg.
3778 class VAArgExpr : public Expr {
3780 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3781 SourceLocation BuiltinLoc, RParenLoc;
3783 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3784 SourceLocation RPLoc, QualType t, bool IsMS)
3785 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3786 false, (TInfo->getType()->isInstantiationDependentType() ||
3787 e->isInstantiationDependent()),
3788 (TInfo->getType()->containsUnexpandedParameterPack() ||
3789 e->containsUnexpandedParameterPack())),
3790 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3792 /// Create an empty __builtin_va_arg expression.
3793 explicit VAArgExpr(EmptyShell Empty)
3794 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3796 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3797 Expr *getSubExpr() { return cast<Expr>(Val); }
3798 void setSubExpr(Expr *E) { Val = E; }
3800 /// Returns whether this is really a Win64 ABI va_arg expression.
3801 bool isMicrosoftABI() const { return TInfo.getInt(); }
3802 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3804 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3805 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3807 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3808 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3810 SourceLocation getRParenLoc() const { return RParenLoc; }
3811 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3813 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3814 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3816 static bool classof(const Stmt *T) {
3817 return T->getStmtClass() == VAArgExprClass;
3821 child_range children() { return child_range(&Val, &Val+1); }
3822 const_child_range children() const {
3823 return const_child_range(&Val, &Val + 1);
3827 /// @brief Describes an C or C++ initializer list.
3829 /// InitListExpr describes an initializer list, which can be used to
3830 /// initialize objects of different types, including
3831 /// struct/class/union types, arrays, and vectors. For example:
3834 /// struct foo x = { 1, { 2, 3 } };
3837 /// Prior to semantic analysis, an initializer list will represent the
3838 /// initializer list as written by the user, but will have the
3839 /// placeholder type "void". This initializer list is called the
3840 /// syntactic form of the initializer, and may contain C99 designated
3841 /// initializers (represented as DesignatedInitExprs), initializations
3842 /// of subobject members without explicit braces, and so on. Clients
3843 /// interested in the original syntax of the initializer list should
3844 /// use the syntactic form of the initializer list.
3846 /// After semantic analysis, the initializer list will represent the
3847 /// semantic form of the initializer, where the initializations of all
3848 /// subobjects are made explicit with nested InitListExpr nodes and
3849 /// C99 designators have been eliminated by placing the designated
3850 /// initializations into the subobject they initialize. Additionally,
3851 /// any "holes" in the initialization, where no initializer has been
3852 /// specified for a particular subobject, will be replaced with
3853 /// implicitly-generated ImplicitValueInitExpr expressions that
3854 /// value-initialize the subobjects. Note, however, that the
3855 /// initializer lists may still have fewer initializers than there are
3856 /// elements to initialize within the object.
3858 /// After semantic analysis has completed, given an initializer list,
3859 /// method isSemanticForm() returns true if and only if this is the
3860 /// semantic form of the initializer list (note: the same AST node
3861 /// may at the same time be the syntactic form).
3862 /// Given the semantic form of the initializer list, one can retrieve
3863 /// the syntactic form of that initializer list (when different)
3864 /// using method getSyntacticForm(); the method returns null if applied
3865 /// to a initializer list which is already in syntactic form.
3866 /// Similarly, given the syntactic form (i.e., an initializer list such
3867 /// that isSemanticForm() returns false), one can retrieve the semantic
3868 /// form using method getSemanticForm().
3869 /// Since many initializer lists have the same syntactic and semantic forms,
3870 /// getSyntacticForm() may return NULL, indicating that the current
3871 /// semantic initializer list also serves as its syntactic form.
3872 class InitListExpr : public Expr {
3873 // FIXME: Eliminate this vector in favor of ASTContext allocation
3874 typedef ASTVector<Stmt *> InitExprsTy;
3875 InitExprsTy InitExprs;
3876 SourceLocation LBraceLoc, RBraceLoc;
3878 /// The alternative form of the initializer list (if it exists).
3879 /// The int part of the pair stores whether this initializer list is
3880 /// in semantic form. If not null, the pointer points to:
3881 /// - the syntactic form, if this is in semantic form;
3882 /// - the semantic form, if this is in syntactic form.
3883 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3886 /// If this initializer list initializes an array with more elements than
3887 /// there are initializers in the list, specifies an expression to be used
3888 /// for value initialization of the rest of the elements.
3890 /// If this initializer list initializes a union, specifies which
3891 /// field within the union will be initialized.
3892 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3895 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3896 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3898 /// \brief Build an empty initializer list.
3899 explicit InitListExpr(EmptyShell Empty)
3900 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
3902 unsigned getNumInits() const { return InitExprs.size(); }
3904 /// \brief Retrieve the set of initializers.
3905 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3907 /// \brief Retrieve the set of initializers.
3908 Expr * const *getInits() const {
3909 return reinterpret_cast<Expr * const *>(InitExprs.data());
3912 ArrayRef<Expr *> inits() {
3913 return llvm::makeArrayRef(getInits(), getNumInits());
3916 ArrayRef<Expr *> inits() const {
3917 return llvm::makeArrayRef(getInits(), getNumInits());
3920 const Expr *getInit(unsigned Init) const {
3921 assert(Init < getNumInits() && "Initializer access out of range!");
3922 return cast_or_null<Expr>(InitExprs[Init]);
3925 Expr *getInit(unsigned Init) {
3926 assert(Init < getNumInits() && "Initializer access out of range!");
3927 return cast_or_null<Expr>(InitExprs[Init]);
3930 void setInit(unsigned Init, Expr *expr) {
3931 assert(Init < getNumInits() && "Initializer access out of range!");
3932 InitExprs[Init] = expr;
3935 ExprBits.TypeDependent |= expr->isTypeDependent();
3936 ExprBits.ValueDependent |= expr->isValueDependent();
3937 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3938 ExprBits.ContainsUnexpandedParameterPack |=
3939 expr->containsUnexpandedParameterPack();
3943 /// \brief Reserve space for some number of initializers.
3944 void reserveInits(const ASTContext &C, unsigned NumInits);
3946 /// @brief Specify the number of initializers
3948 /// If there are more than @p NumInits initializers, the remaining
3949 /// initializers will be destroyed. If there are fewer than @p
3950 /// NumInits initializers, NULL expressions will be added for the
3951 /// unknown initializers.
3952 void resizeInits(const ASTContext &Context, unsigned NumInits);
3954 /// @brief Updates the initializer at index @p Init with the new
3955 /// expression @p expr, and returns the old expression at that
3958 /// When @p Init is out of range for this initializer list, the
3959 /// initializer list will be extended with NULL expressions to
3960 /// accommodate the new entry.
3961 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3963 /// \brief If this initializer list initializes an array with more elements
3964 /// than there are initializers in the list, specifies an expression to be
3965 /// used for value initialization of the rest of the elements.
3966 Expr *getArrayFiller() {
3967 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3969 const Expr *getArrayFiller() const {
3970 return const_cast<InitListExpr *>(this)->getArrayFiller();
3972 void setArrayFiller(Expr *filler);
3974 /// \brief Return true if this is an array initializer and its array "filler"
3976 bool hasArrayFiller() const { return getArrayFiller(); }
3978 /// \brief If this initializes a union, specifies which field in the
3979 /// union to initialize.
3981 /// Typically, this field is the first named field within the
3982 /// union. However, a designated initializer can specify the
3983 /// initialization of a different field within the union.
3984 FieldDecl *getInitializedFieldInUnion() {
3985 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3987 const FieldDecl *getInitializedFieldInUnion() const {
3988 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3990 void setInitializedFieldInUnion(FieldDecl *FD) {
3991 assert((FD == nullptr
3992 || getInitializedFieldInUnion() == nullptr
3993 || getInitializedFieldInUnion() == FD)
3994 && "Only one field of a union may be initialized at a time!");
3995 ArrayFillerOrUnionFieldInit = FD;
3998 // Explicit InitListExpr's originate from source code (and have valid source
3999 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4000 bool isExplicit() const {
4001 return LBraceLoc.isValid() && RBraceLoc.isValid();
4004 // Is this an initializer for an array of characters, initialized by a string
4005 // literal or an @encode?
4006 bool isStringLiteralInit() const;
4008 /// Is this a transparent initializer list (that is, an InitListExpr that is
4009 /// purely syntactic, and whose semantics are that of the sole contained
4011 bool isTransparent() const;
4013 /// Is this the zero initializer {0} in a language which considers it
4015 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4017 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4018 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4019 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4020 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4022 bool isSemanticForm() const { return AltForm.getInt(); }
4023 InitListExpr *getSemanticForm() const {
4024 return isSemanticForm() ? nullptr : AltForm.getPointer();
4026 bool isSyntacticForm() const {
4027 return !AltForm.getInt() || !AltForm.getPointer();
4029 InitListExpr *getSyntacticForm() const {
4030 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4033 void setSyntacticForm(InitListExpr *Init) {
4034 AltForm.setPointer(Init);
4035 AltForm.setInt(true);
4036 Init->AltForm.setPointer(this);
4037 Init->AltForm.setInt(false);
4040 bool hadArrayRangeDesignator() const {
4041 return InitListExprBits.HadArrayRangeDesignator != 0;
4043 void sawArrayRangeDesignator(bool ARD = true) {
4044 InitListExprBits.HadArrayRangeDesignator = ARD;
4047 SourceLocation getLocStart() const LLVM_READONLY;
4048 SourceLocation getLocEnd() const LLVM_READONLY;
4050 static bool classof(const Stmt *T) {
4051 return T->getStmtClass() == InitListExprClass;
4055 child_range children() {
4056 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4057 return child_range(cast_away_const(CCR.begin()),
4058 cast_away_const(CCR.end()));
4061 const_child_range children() const {
4062 // FIXME: This does not include the array filler expression.
4063 if (InitExprs.empty())
4064 return const_child_range(const_child_iterator(), const_child_iterator());
4065 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4068 typedef InitExprsTy::iterator iterator;
4069 typedef InitExprsTy::const_iterator const_iterator;
4070 typedef InitExprsTy::reverse_iterator reverse_iterator;
4071 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4073 iterator begin() { return InitExprs.begin(); }
4074 const_iterator begin() const { return InitExprs.begin(); }
4075 iterator end() { return InitExprs.end(); }
4076 const_iterator end() const { return InitExprs.end(); }
4077 reverse_iterator rbegin() { return InitExprs.rbegin(); }
4078 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4079 reverse_iterator rend() { return InitExprs.rend(); }
4080 const_reverse_iterator rend() const { return InitExprs.rend(); }
4082 friend class ASTStmtReader;
4083 friend class ASTStmtWriter;
4086 /// @brief Represents a C99 designated initializer expression.
4088 /// A designated initializer expression (C99 6.7.8) contains one or
4089 /// more designators (which can be field designators, array
4090 /// designators, or GNU array-range designators) followed by an
4091 /// expression that initializes the field or element(s) that the
4092 /// designators refer to. For example, given:
4099 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4102 /// The InitListExpr contains three DesignatedInitExprs, the first of
4103 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4104 /// designators, one array designator for @c [2] followed by one field
4105 /// designator for @c .y. The initialization expression will be 1.0.
4106 class DesignatedInitExpr final
4108 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4110 /// \brief Forward declaration of the Designator class.
4114 /// The location of the '=' or ':' prior to the actual initializer
4116 SourceLocation EqualOrColonLoc;
4118 /// Whether this designated initializer used the GNU deprecated
4119 /// syntax rather than the C99 '=' syntax.
4120 unsigned GNUSyntax : 1;
4122 /// The number of designators in this initializer expression.
4123 unsigned NumDesignators : 15;
4125 /// The number of subexpressions of this initializer expression,
4126 /// which contains both the initializer and any additional
4127 /// expressions used by array and array-range designators.
4128 unsigned NumSubExprs : 16;
4130 /// \brief The designators in this designated initialization
4132 Designator *Designators;
4134 DesignatedInitExpr(const ASTContext &C, QualType Ty,
4135 llvm::ArrayRef<Designator> Designators,
4136 SourceLocation EqualOrColonLoc, bool GNUSyntax,
4137 ArrayRef<Expr *> IndexExprs, Expr *Init);
4139 explicit DesignatedInitExpr(unsigned NumSubExprs)
4140 : Expr(DesignatedInitExprClass, EmptyShell()),
4141 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4144 /// A field designator, e.g., ".x".
4145 struct FieldDesignator {
4146 /// Refers to the field that is being initialized. The low bit
4147 /// of this field determines whether this is actually a pointer
4148 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4149 /// initially constructed, a field designator will store an
4150 /// IdentifierInfo*. After semantic analysis has resolved that
4151 /// name, the field designator will instead store a FieldDecl*.
4152 uintptr_t NameOrField;
4154 /// The location of the '.' in the designated initializer.
4157 /// The location of the field name in the designated initializer.
4161 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4162 struct ArrayOrRangeDesignator {
4163 /// Location of the first index expression within the designated
4164 /// initializer expression's list of subexpressions.
4166 /// The location of the '[' starting the array range designator.
4167 unsigned LBracketLoc;
4168 /// The location of the ellipsis separating the start and end
4169 /// indices. Only valid for GNU array-range designators.
4170 unsigned EllipsisLoc;
4171 /// The location of the ']' terminating the array range designator.
4172 unsigned RBracketLoc;
4175 /// @brief Represents a single C99 designator.
4177 /// @todo This class is infuriatingly similar to clang::Designator,
4178 /// but minor differences (storing indices vs. storing pointers)
4179 /// keep us from reusing it. Try harder, later, to rectify these
4182 /// @brief The kind of designator this describes.
4186 ArrayRangeDesignator
4190 /// A field designator, e.g., ".x".
4191 struct FieldDesignator Field;
4192 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4193 struct ArrayOrRangeDesignator ArrayOrRange;
4195 friend class DesignatedInitExpr;
4200 /// @brief Initializes a field designator.
4201 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4202 SourceLocation FieldLoc)
4203 : Kind(FieldDesignator) {
4204 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4205 Field.DotLoc = DotLoc.getRawEncoding();
4206 Field.FieldLoc = FieldLoc.getRawEncoding();
4209 /// @brief Initializes an array designator.
4210 Designator(unsigned Index, SourceLocation LBracketLoc,
4211 SourceLocation RBracketLoc)
4212 : Kind(ArrayDesignator) {
4213 ArrayOrRange.Index = Index;
4214 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4215 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4216 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4219 /// @brief Initializes a GNU array-range designator.
4220 Designator(unsigned Index, SourceLocation LBracketLoc,
4221 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4222 : Kind(ArrayRangeDesignator) {
4223 ArrayOrRange.Index = Index;
4224 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4225 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4226 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4229 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4230 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4231 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4233 IdentifierInfo *getFieldName() const;
4235 FieldDecl *getField() const {
4236 assert(Kind == FieldDesignator && "Only valid on a field designator");
4237 if (Field.NameOrField & 0x01)
4240 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4243 void setField(FieldDecl *FD) {
4244 assert(Kind == FieldDesignator && "Only valid on a field designator");
4245 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4248 SourceLocation getDotLoc() const {
4249 assert(Kind == FieldDesignator && "Only valid on a field designator");
4250 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4253 SourceLocation getFieldLoc() const {
4254 assert(Kind == FieldDesignator && "Only valid on a field designator");
4255 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4258 SourceLocation getLBracketLoc() const {
4259 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4260 "Only valid on an array or array-range designator");
4261 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4264 SourceLocation getRBracketLoc() const {
4265 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4266 "Only valid on an array or array-range designator");
4267 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4270 SourceLocation getEllipsisLoc() const {
4271 assert(Kind == ArrayRangeDesignator &&
4272 "Only valid on an array-range designator");
4273 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4276 unsigned getFirstExprIndex() const {
4277 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4278 "Only valid on an array or array-range designator");
4279 return ArrayOrRange.Index;
4282 SourceLocation getLocStart() const LLVM_READONLY {
4283 if (Kind == FieldDesignator)
4284 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4286 return getLBracketLoc();
4288 SourceLocation getLocEnd() const LLVM_READONLY {
4289 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4291 SourceRange getSourceRange() const LLVM_READONLY {
4292 return SourceRange(getLocStart(), getLocEnd());
4296 static DesignatedInitExpr *Create(const ASTContext &C,
4297 llvm::ArrayRef<Designator> Designators,
4298 ArrayRef<Expr*> IndexExprs,
4299 SourceLocation EqualOrColonLoc,
4300 bool GNUSyntax, Expr *Init);
4302 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4303 unsigned NumIndexExprs);
4305 /// @brief Returns the number of designators in this initializer.
4306 unsigned size() const { return NumDesignators; }
4308 // Iterator access to the designators.
4309 llvm::MutableArrayRef<Designator> designators() {
4310 return {Designators, NumDesignators};
4313 llvm::ArrayRef<Designator> designators() const {
4314 return {Designators, NumDesignators};
4317 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4318 const Designator *getDesignator(unsigned Idx) const {
4319 return &designators()[Idx];
4322 void setDesignators(const ASTContext &C, const Designator *Desigs,
4323 unsigned NumDesigs);
4325 Expr *getArrayIndex(const Designator &D) const;
4326 Expr *getArrayRangeStart(const Designator &D) const;
4327 Expr *getArrayRangeEnd(const Designator &D) const;
4329 /// @brief Retrieve the location of the '=' that precedes the
4330 /// initializer value itself, if present.
4331 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4332 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4334 /// @brief Determines whether this designated initializer used the
4335 /// deprecated GNU syntax for designated initializers.
4336 bool usesGNUSyntax() const { return GNUSyntax; }
4337 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4339 /// @brief Retrieve the initializer value.
4340 Expr *getInit() const {
4341 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4344 void setInit(Expr *init) {
4345 *child_begin() = init;
4348 /// \brief Retrieve the total number of subexpressions in this
4349 /// designated initializer expression, including the actual
4350 /// initialized value and any expressions that occur within array
4351 /// and array-range designators.
4352 unsigned getNumSubExprs() const { return NumSubExprs; }
4354 Expr *getSubExpr(unsigned Idx) const {
4355 assert(Idx < NumSubExprs && "Subscript out of range");
4356 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4359 void setSubExpr(unsigned Idx, Expr *E) {
4360 assert(Idx < NumSubExprs && "Subscript out of range");
4361 getTrailingObjects<Stmt *>()[Idx] = E;
4364 /// \brief Replaces the designator at index @p Idx with the series
4365 /// of designators in [First, Last).
4366 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4367 const Designator *First, const Designator *Last);
4369 SourceRange getDesignatorsSourceRange() const;
4371 SourceLocation getLocStart() const LLVM_READONLY;
4372 SourceLocation getLocEnd() const LLVM_READONLY;
4374 static bool classof(const Stmt *T) {
4375 return T->getStmtClass() == DesignatedInitExprClass;
4379 child_range children() {
4380 Stmt **begin = getTrailingObjects<Stmt *>();
4381 return child_range(begin, begin + NumSubExprs);
4383 const_child_range children() const {
4384 Stmt * const *begin = getTrailingObjects<Stmt *>();
4385 return const_child_range(begin, begin + NumSubExprs);
4388 friend TrailingObjects;
4391 /// \brief Represents a place-holder for an object not to be initialized by
4394 /// This only makes sense when it appears as part of an updater of a
4395 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4396 /// initializes a big object, and the NoInitExpr's mark the spots within the
4397 /// big object not to be overwritten by the updater.
4399 /// \see DesignatedInitUpdateExpr
4400 class NoInitExpr : public Expr {
4402 explicit NoInitExpr(QualType ty)
4403 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4404 false, false, ty->isInstantiationDependentType(), false) { }
4406 explicit NoInitExpr(EmptyShell Empty)
4407 : Expr(NoInitExprClass, Empty) { }
4409 static bool classof(const Stmt *T) {
4410 return T->getStmtClass() == NoInitExprClass;
4413 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4414 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4417 child_range children() {
4418 return child_range(child_iterator(), child_iterator());
4420 const_child_range children() const {
4421 return const_child_range(const_child_iterator(), const_child_iterator());
4426 // struct Q { int a, b, c; };
4429 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4432 // We will have an InitListExpr for a, with type A, and then a
4433 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4434 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4436 class DesignatedInitUpdateExpr : public Expr {
4437 // BaseAndUpdaterExprs[0] is the base expression;
4438 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4439 Stmt *BaseAndUpdaterExprs[2];
4442 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4443 Expr *baseExprs, SourceLocation rBraceLoc);
4445 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4446 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4448 SourceLocation getLocStart() const LLVM_READONLY;
4449 SourceLocation getLocEnd() const LLVM_READONLY;
4451 static bool classof(const Stmt *T) {
4452 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4455 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4456 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4458 InitListExpr *getUpdater() const {
4459 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4461 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4464 // children = the base and the updater
4465 child_range children() {
4466 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4468 const_child_range children() const {
4469 return const_child_range(&BaseAndUpdaterExprs[0],
4470 &BaseAndUpdaterExprs[0] + 2);
4474 /// \brief Represents a loop initializing the elements of an array.
4476 /// The need to initialize the elements of an array occurs in a number of
4479 /// * in the implicit copy/move constructor for a class with an array member
4480 /// * when a lambda-expression captures an array by value
4481 /// * when a decomposition declaration decomposes an array
4483 /// There are two subexpressions: a common expression (the source array)
4484 /// that is evaluated once up-front, and a per-element initializer that
4485 /// runs once for each array element.
4487 /// Within the per-element initializer, the common expression may be referenced
4488 /// via an OpaqueValueExpr, and the current index may be obtained via an
4489 /// ArrayInitIndexExpr.
4490 class ArrayInitLoopExpr : public Expr {
4493 explicit ArrayInitLoopExpr(EmptyShell Empty)
4494 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4497 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4498 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4499 CommonInit->isValueDependent() || ElementInit->isValueDependent(),
4500 T->isInstantiationDependentType(),
4501 CommonInit->containsUnexpandedParameterPack() ||
4502 ElementInit->containsUnexpandedParameterPack()),
4503 SubExprs{CommonInit, ElementInit} {}
4505 /// Get the common subexpression shared by all initializations (the source
4507 OpaqueValueExpr *getCommonExpr() const {
4508 return cast<OpaqueValueExpr>(SubExprs[0]);
4511 /// Get the initializer to use for each array element.
4512 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
4514 llvm::APInt getArraySize() const {
4515 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
4519 static bool classof(const Stmt *S) {
4520 return S->getStmtClass() == ArrayInitLoopExprClass;
4523 SourceLocation getLocStart() const LLVM_READONLY {
4524 return getCommonExpr()->getLocStart();
4526 SourceLocation getLocEnd() const LLVM_READONLY {
4527 return getCommonExpr()->getLocEnd();
4530 child_range children() {
4531 return child_range(SubExprs, SubExprs + 2);
4533 const_child_range children() const {
4534 return const_child_range(SubExprs, SubExprs + 2);
4537 friend class ASTReader;
4538 friend class ASTStmtReader;
4539 friend class ASTStmtWriter;
4542 /// \brief Represents the index of the current element of an array being
4543 /// initialized by an ArrayInitLoopExpr. This can only appear within the
4544 /// subexpression of an ArrayInitLoopExpr.
4545 class ArrayInitIndexExpr : public Expr {
4546 explicit ArrayInitIndexExpr(EmptyShell Empty)
4547 : Expr(ArrayInitIndexExprClass, Empty) {}
4550 explicit ArrayInitIndexExpr(QualType T)
4551 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
4552 false, false, false, false) {}
4554 static bool classof(const Stmt *S) {
4555 return S->getStmtClass() == ArrayInitIndexExprClass;
4558 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4559 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4561 child_range children() {
4562 return child_range(child_iterator(), child_iterator());
4564 const_child_range children() const {
4565 return const_child_range(const_child_iterator(), const_child_iterator());
4568 friend class ASTReader;
4569 friend class ASTStmtReader;
4572 /// \brief Represents an implicitly-generated value initialization of
4573 /// an object of a given type.
4575 /// Implicit value initializations occur within semantic initializer
4576 /// list expressions (InitListExpr) as placeholders for subobject
4577 /// initializations not explicitly specified by the user.
4579 /// \see InitListExpr
4580 class ImplicitValueInitExpr : public Expr {
4582 explicit ImplicitValueInitExpr(QualType ty)
4583 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4584 false, false, ty->isInstantiationDependentType(), false) { }
4586 /// \brief Construct an empty implicit value initialization.
4587 explicit ImplicitValueInitExpr(EmptyShell Empty)
4588 : Expr(ImplicitValueInitExprClass, Empty) { }
4590 static bool classof(const Stmt *T) {
4591 return T->getStmtClass() == ImplicitValueInitExprClass;
4594 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4595 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4598 child_range children() {
4599 return child_range(child_iterator(), child_iterator());
4601 const_child_range children() const {
4602 return const_child_range(const_child_iterator(), const_child_iterator());
4606 class ParenListExpr : public Expr {
4609 SourceLocation LParenLoc, RParenLoc;
4612 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4613 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4615 /// \brief Build an empty paren list.
4616 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4618 unsigned getNumExprs() const { return NumExprs; }
4620 const Expr* getExpr(unsigned Init) const {
4621 assert(Init < getNumExprs() && "Initializer access out of range!");
4622 return cast_or_null<Expr>(Exprs[Init]);
4625 Expr* getExpr(unsigned Init) {
4626 assert(Init < getNumExprs() && "Initializer access out of range!");
4627 return cast_or_null<Expr>(Exprs[Init]);
4630 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4632 ArrayRef<Expr *> exprs() {
4633 return llvm::makeArrayRef(getExprs(), getNumExprs());
4636 SourceLocation getLParenLoc() const { return LParenLoc; }
4637 SourceLocation getRParenLoc() const { return RParenLoc; }
4639 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4640 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4642 static bool classof(const Stmt *T) {
4643 return T->getStmtClass() == ParenListExprClass;
4647 child_range children() {
4648 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4650 const_child_range children() const {
4651 return const_child_range(&Exprs[0], &Exprs[0] + NumExprs);
4654 friend class ASTStmtReader;
4655 friend class ASTStmtWriter;
4658 /// \brief Represents a C11 generic selection.
4660 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4661 /// expression, followed by one or more generic associations. Each generic
4662 /// association specifies a type name and an expression, or "default" and an
4663 /// expression (in which case it is known as a default generic association).
4664 /// The type and value of the generic selection are identical to those of its
4665 /// result expression, which is defined as the expression in the generic
4666 /// association with a type name that is compatible with the type of the
4667 /// controlling expression, or the expression in the default generic association
4668 /// if no types are compatible. For example:
4671 /// _Generic(X, double: 1, float: 2, default: 3)
4674 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4675 /// or 3 if "hello".
4677 /// As an extension, generic selections are allowed in C++, where the following
4678 /// additional semantics apply:
4680 /// Any generic selection whose controlling expression is type-dependent or
4681 /// which names a dependent type in its association list is result-dependent,
4682 /// which means that the choice of result expression is dependent.
4683 /// Result-dependent generic associations are both type- and value-dependent.
4684 class GenericSelectionExpr : public Expr {
4685 enum { CONTROLLING, END_EXPR };
4686 TypeSourceInfo **AssocTypes;
4688 unsigned NumAssocs, ResultIndex;
4689 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4692 GenericSelectionExpr(const ASTContext &Context,
4693 SourceLocation GenericLoc, Expr *ControllingExpr,
4694 ArrayRef<TypeSourceInfo*> AssocTypes,
4695 ArrayRef<Expr*> AssocExprs,
4696 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4697 bool ContainsUnexpandedParameterPack,
4698 unsigned ResultIndex);
4700 /// This constructor is used in the result-dependent case.
4701 GenericSelectionExpr(const ASTContext &Context,
4702 SourceLocation GenericLoc, Expr *ControllingExpr,
4703 ArrayRef<TypeSourceInfo*> AssocTypes,
4704 ArrayRef<Expr*> AssocExprs,
4705 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4706 bool ContainsUnexpandedParameterPack);
4708 explicit GenericSelectionExpr(EmptyShell Empty)
4709 : Expr(GenericSelectionExprClass, Empty) { }
4711 unsigned getNumAssocs() const { return NumAssocs; }
4713 SourceLocation getGenericLoc() const { return GenericLoc; }
4714 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4715 SourceLocation getRParenLoc() const { return RParenLoc; }
4717 const Expr *getAssocExpr(unsigned i) const {
4718 return cast<Expr>(SubExprs[END_EXPR+i]);
4720 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4721 ArrayRef<Expr *> getAssocExprs() const {
4723 ? llvm::makeArrayRef(
4724 &reinterpret_cast<Expr **>(SubExprs)[END_EXPR], NumAssocs)
4727 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4728 return AssocTypes[i];
4730 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4731 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
4732 return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : None;
4735 QualType getAssocType(unsigned i) const {
4736 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4737 return TS->getType();
4742 const Expr *getControllingExpr() const {
4743 return cast<Expr>(SubExprs[CONTROLLING]);
4745 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4747 /// Whether this generic selection is result-dependent.
4748 bool isResultDependent() const { return ResultIndex == -1U; }
4750 /// The zero-based index of the result expression's generic association in
4751 /// the generic selection's association list. Defined only if the
4752 /// generic selection is not result-dependent.
4753 unsigned getResultIndex() const {
4754 assert(!isResultDependent() && "Generic selection is result-dependent");
4758 /// The generic selection's result expression. Defined only if the
4759 /// generic selection is not result-dependent.
4760 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4761 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4763 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4764 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4766 static bool classof(const Stmt *T) {
4767 return T->getStmtClass() == GenericSelectionExprClass;
4770 child_range children() {
4771 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4773 const_child_range children() const {
4774 return const_child_range(SubExprs, SubExprs + END_EXPR + NumAssocs);
4776 friend class ASTStmtReader;
4779 //===----------------------------------------------------------------------===//
4781 //===----------------------------------------------------------------------===//
4783 /// ExtVectorElementExpr - This represents access to specific elements of a
4784 /// vector, and may occur on the left hand side or right hand side. For example
4785 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4787 /// Note that the base may have either vector or pointer to vector type, just
4788 /// like a struct field reference.
4790 class ExtVectorElementExpr : public Expr {
4792 IdentifierInfo *Accessor;
4793 SourceLocation AccessorLoc;
4795 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4796 IdentifierInfo &accessor, SourceLocation loc)
4797 : Expr(ExtVectorElementExprClass, ty, VK,
4798 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4799 base->isTypeDependent(), base->isValueDependent(),
4800 base->isInstantiationDependent(),
4801 base->containsUnexpandedParameterPack()),
4802 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4804 /// \brief Build an empty vector element expression.
4805 explicit ExtVectorElementExpr(EmptyShell Empty)
4806 : Expr(ExtVectorElementExprClass, Empty) { }
4808 const Expr *getBase() const { return cast<Expr>(Base); }
4809 Expr *getBase() { return cast<Expr>(Base); }
4810 void setBase(Expr *E) { Base = E; }
4812 IdentifierInfo &getAccessor() const { return *Accessor; }
4813 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4815 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4816 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4818 /// getNumElements - Get the number of components being selected.
4819 unsigned getNumElements() const;
4821 /// containsDuplicateElements - Return true if any element access is
4823 bool containsDuplicateElements() const;
4825 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4826 /// aggregate Constant of ConstantInt(s).
4827 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4829 SourceLocation getLocStart() const LLVM_READONLY {
4830 return getBase()->getLocStart();
4832 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4834 /// isArrow - Return true if the base expression is a pointer to vector,
4835 /// return false if the base expression is a vector.
4836 bool isArrow() const;
4838 static bool classof(const Stmt *T) {
4839 return T->getStmtClass() == ExtVectorElementExprClass;
4843 child_range children() { return child_range(&Base, &Base+1); }
4844 const_child_range children() const {
4845 return const_child_range(&Base, &Base + 1);
4849 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4850 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4851 class BlockExpr : public Expr {
4853 BlockDecl *TheBlock;
4855 BlockExpr(BlockDecl *BD, QualType ty)
4856 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4857 ty->isDependentType(), ty->isDependentType(),
4858 ty->isInstantiationDependentType() || BD->isDependentContext(),
4862 /// \brief Build an empty block expression.
4863 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4865 const BlockDecl *getBlockDecl() const { return TheBlock; }
4866 BlockDecl *getBlockDecl() { return TheBlock; }
4867 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4869 // Convenience functions for probing the underlying BlockDecl.
4870 SourceLocation getCaretLocation() const;
4871 const Stmt *getBody() const;
4874 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4875 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4877 /// getFunctionType - Return the underlying function type for this block.
4878 const FunctionProtoType *getFunctionType() const;
4880 static bool classof(const Stmt *T) {
4881 return T->getStmtClass() == BlockExprClass;
4885 child_range children() {
4886 return child_range(child_iterator(), child_iterator());
4888 const_child_range children() const {
4889 return const_child_range(const_child_iterator(), const_child_iterator());
4893 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4894 /// This AST node provides support for reinterpreting a type to another
4895 /// type of the same size.
4896 class AsTypeExpr : public Expr {
4899 SourceLocation BuiltinLoc, RParenLoc;
4901 friend class ASTReader;
4902 friend class ASTStmtReader;
4903 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4906 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4907 ExprValueKind VK, ExprObjectKind OK,
4908 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4909 : Expr(AsTypeExprClass, DstType, VK, OK,
4910 DstType->isDependentType(),
4911 DstType->isDependentType() || SrcExpr->isValueDependent(),
4912 (DstType->isInstantiationDependentType() ||
4913 SrcExpr->isInstantiationDependent()),
4914 (DstType->containsUnexpandedParameterPack() ||
4915 SrcExpr->containsUnexpandedParameterPack())),
4916 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4918 /// getSrcExpr - Return the Expr to be converted.
4919 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4921 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4922 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4924 /// getRParenLoc - Return the location of final right parenthesis.
4925 SourceLocation getRParenLoc() const { return RParenLoc; }
4927 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4928 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4930 static bool classof(const Stmt *T) {
4931 return T->getStmtClass() == AsTypeExprClass;
4935 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4936 const_child_range children() const {
4937 return const_child_range(&SrcExpr, &SrcExpr + 1);
4941 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4942 /// l-value. A pseudo-object is an abstract object, accesses to which
4943 /// are translated to calls. The pseudo-object expression has a
4944 /// syntactic form, which shows how the expression was actually
4945 /// written in the source code, and a semantic form, which is a series
4946 /// of expressions to be executed in order which detail how the
4947 /// operation is actually evaluated. Optionally, one of the semantic
4948 /// forms may also provide a result value for the expression.
4950 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4951 /// that OVE is required to have a source expression, and it is bound
4952 /// to the result of that source expression. Such OVEs may appear
4953 /// only in subsequent semantic-form expressions and as
4954 /// sub-expressions of the syntactic form.
4956 /// PseudoObjectExpr should be used only when an operation can be
4957 /// usefully described in terms of fairly simple rewrite rules on
4958 /// objects and functions that are meant to be used by end-developers.
4959 /// For example, under the Itanium ABI, dynamic casts are implemented
4960 /// as a call to a runtime function called __dynamic_cast; using this
4961 /// class to describe that would be inappropriate because that call is
4962 /// not really part of the user-visible semantics, and instead the
4963 /// cast is properly reflected in the AST and IR-generation has been
4964 /// taught to generate the call as necessary. In contrast, an
4965 /// Objective-C property access is semantically defined to be
4966 /// equivalent to a particular message send, and this is very much
4967 /// part of the user model. The name of this class encourages this
4968 /// modelling design.
4969 class PseudoObjectExpr final
4971 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
4972 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4973 // Always at least two, because the first sub-expression is the
4976 // PseudoObjectExprBits.ResultIndex - The index of the
4977 // sub-expression holding the result. 0 means the result is void,
4978 // which is unambiguous because it's the index of the syntactic
4979 // form. Note that this is therefore 1 higher than the value passed
4980 // in to Create, which is an index within the semantic forms.
4981 // Note also that ASTStmtWriter assumes this encoding.
4983 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
4984 const Expr * const *getSubExprsBuffer() const {
4985 return getTrailingObjects<Expr *>();
4988 PseudoObjectExpr(QualType type, ExprValueKind VK,
4989 Expr *syntactic, ArrayRef<Expr*> semantic,
4990 unsigned resultIndex);
4992 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4994 unsigned getNumSubExprs() const {
4995 return PseudoObjectExprBits.NumSubExprs;
4999 /// NoResult - A value for the result index indicating that there is
5000 /// no semantic result.
5001 enum : unsigned { NoResult = ~0U };
5003 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
5004 ArrayRef<Expr*> semantic,
5005 unsigned resultIndex);
5007 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
5008 unsigned numSemanticExprs);
5010 /// Return the syntactic form of this expression, i.e. the
5011 /// expression it actually looks like. Likely to be expressed in
5012 /// terms of OpaqueValueExprs bound in the semantic form.
5013 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
5014 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
5016 /// Return the index of the result-bearing expression into the semantics
5017 /// expressions, or PseudoObjectExpr::NoResult if there is none.
5018 unsigned getResultExprIndex() const {
5019 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
5020 return PseudoObjectExprBits.ResultIndex - 1;
5023 /// Return the result-bearing expression, or null if there is none.
5024 Expr *getResultExpr() {
5025 if (PseudoObjectExprBits.ResultIndex == 0)
5027 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
5029 const Expr *getResultExpr() const {
5030 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
5033 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
5035 typedef Expr * const *semantics_iterator;
5036 typedef const Expr * const *const_semantics_iterator;
5037 semantics_iterator semantics_begin() {
5038 return getSubExprsBuffer() + 1;
5040 const_semantics_iterator semantics_begin() const {
5041 return getSubExprsBuffer() + 1;
5043 semantics_iterator semantics_end() {
5044 return getSubExprsBuffer() + getNumSubExprs();
5046 const_semantics_iterator semantics_end() const {
5047 return getSubExprsBuffer() + getNumSubExprs();
5050 llvm::iterator_range<semantics_iterator> semantics() {
5051 return llvm::make_range(semantics_begin(), semantics_end());
5053 llvm::iterator_range<const_semantics_iterator> semantics() const {
5054 return llvm::make_range(semantics_begin(), semantics_end());
5057 Expr *getSemanticExpr(unsigned index) {
5058 assert(index + 1 < getNumSubExprs());
5059 return getSubExprsBuffer()[index + 1];
5061 const Expr *getSemanticExpr(unsigned index) const {
5062 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
5065 SourceLocation getExprLoc() const LLVM_READONLY {
5066 return getSyntacticForm()->getExprLoc();
5069 SourceLocation getLocStart() const LLVM_READONLY {
5070 return getSyntacticForm()->getLocStart();
5072 SourceLocation getLocEnd() const LLVM_READONLY {
5073 return getSyntacticForm()->getLocEnd();
5076 child_range children() {
5077 const_child_range CCR =
5078 const_cast<const PseudoObjectExpr *>(this)->children();
5079 return child_range(cast_away_const(CCR.begin()),
5080 cast_away_const(CCR.end()));
5082 const_child_range children() const {
5083 Stmt *const *cs = const_cast<Stmt *const *>(
5084 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
5085 return const_child_range(cs, cs + getNumSubExprs());
5088 static bool classof(const Stmt *T) {
5089 return T->getStmtClass() == PseudoObjectExprClass;
5092 friend TrailingObjects;
5093 friend class ASTStmtReader;
5096 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
5097 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
5098 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
5099 /// and corresponding __opencl_atomic_* for OpenCL 2.0.
5100 /// All of these instructions take one primary pointer, at least one memory
5101 /// order. The instructions for which getScopeModel returns non-null value
5102 /// take one synch scope.
5103 class AtomicExpr : public Expr {
5106 #define BUILTIN(ID, TYPE, ATTRS)
5107 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
5108 #include "clang/Basic/Builtins.def"
5109 // Avoid trailing comma
5114 /// \brief Location of sub-expressions.
5115 /// The location of Scope sub-expression is NumSubExprs - 1, which is
5116 /// not fixed, therefore is not defined in enum.
5117 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
5118 Stmt *SubExprs[END_EXPR + 1];
5119 unsigned NumSubExprs;
5120 SourceLocation BuiltinLoc, RParenLoc;
5123 friend class ASTStmtReader;
5125 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
5126 AtomicOp op, SourceLocation RP);
5128 /// \brief Determine the number of arguments the specified atomic builtin
5130 static unsigned getNumSubExprs(AtomicOp Op);
5132 /// \brief Build an empty AtomicExpr.
5133 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
5135 Expr *getPtr() const {
5136 return cast<Expr>(SubExprs[PTR]);
5138 Expr *getOrder() const {
5139 return cast<Expr>(SubExprs[ORDER]);
5141 Expr *getScope() const {
5142 assert(getScopeModel() && "No scope");
5143 return cast<Expr>(SubExprs[NumSubExprs - 1]);
5145 Expr *getVal1() const {
5146 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
5147 return cast<Expr>(SubExprs[ORDER]);
5148 assert(NumSubExprs > VAL1);
5149 return cast<Expr>(SubExprs[VAL1]);
5151 Expr *getOrderFail() const {
5152 assert(NumSubExprs > ORDER_FAIL);
5153 return cast<Expr>(SubExprs[ORDER_FAIL]);
5155 Expr *getVal2() const {
5156 if (Op == AO__atomic_exchange)
5157 return cast<Expr>(SubExprs[ORDER_FAIL]);
5158 assert(NumSubExprs > VAL2);
5159 return cast<Expr>(SubExprs[VAL2]);
5161 Expr *getWeak() const {
5162 assert(NumSubExprs > WEAK);
5163 return cast<Expr>(SubExprs[WEAK]);
5165 QualType getValueType() const;
5167 AtomicOp getOp() const { return Op; }
5168 unsigned getNumSubExprs() const { return NumSubExprs; }
5170 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
5171 const Expr * const *getSubExprs() const {
5172 return reinterpret_cast<Expr * const *>(SubExprs);
5175 bool isVolatile() const {
5176 return getPtr()->getType()->getPointeeType().isVolatileQualified();
5179 bool isCmpXChg() const {
5180 return getOp() == AO__c11_atomic_compare_exchange_strong ||
5181 getOp() == AO__c11_atomic_compare_exchange_weak ||
5182 getOp() == AO__opencl_atomic_compare_exchange_strong ||
5183 getOp() == AO__opencl_atomic_compare_exchange_weak ||
5184 getOp() == AO__atomic_compare_exchange ||
5185 getOp() == AO__atomic_compare_exchange_n;
5188 bool isOpenCL() const {
5189 return getOp() >= AO__opencl_atomic_init &&
5190 getOp() <= AO__opencl_atomic_fetch_max;
5193 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5194 SourceLocation getRParenLoc() const { return RParenLoc; }
5196 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
5197 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
5199 static bool classof(const Stmt *T) {
5200 return T->getStmtClass() == AtomicExprClass;
5204 child_range children() {
5205 return child_range(SubExprs, SubExprs+NumSubExprs);
5207 const_child_range children() const {
5208 return const_child_range(SubExprs, SubExprs + NumSubExprs);
5211 /// \brief Get atomic scope model for the atomic op code.
5212 /// \return empty atomic scope model if the atomic op code does not have
5214 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
5216 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
5217 ? AtomicScopeModelKind::OpenCL
5218 : AtomicScopeModelKind::None;
5219 return AtomicScopeModel::create(Kind);
5222 /// \brief Get atomic scope model.
5223 /// \return empty atomic scope model if this atomic expression does not have
5225 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
5226 return getScopeModel(getOp());
5230 /// TypoExpr - Internal placeholder for expressions where typo correction
5231 /// still needs to be performed and/or an error diagnostic emitted.
5232 class TypoExpr : public Expr {
5234 TypoExpr(QualType T)
5235 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5236 /*isTypeDependent*/ true,
5237 /*isValueDependent*/ true,
5238 /*isInstantiationDependent*/ true,
5239 /*containsUnexpandedParameterPack*/ false) {
5240 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
5243 child_range children() {
5244 return child_range(child_iterator(), child_iterator());
5246 const_child_range children() const {
5247 return const_child_range(const_child_iterator(), const_child_iterator());
5250 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
5251 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
5253 static bool classof(const Stmt *T) {
5254 return T->getStmtClass() == TypoExprClass;
5258 } // end namespace clang
5260 #endif // LLVM_CLANG_AST_EXPR_H