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/TypeTraits.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APSInt.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Support/AtomicOrdering.h"
33 #include "llvm/Support/Compiler.h"
39 class CXXBaseSpecifier;
40 class CXXMemberCallExpr;
41 class CXXOperatorCallExpr;
45 class MaterializeTemporaryExpr;
47 class ObjCPropertyRefExpr;
48 class OpaqueValueExpr;
54 /// \brief A simple array of base specifiers.
55 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
57 /// \brief An adjustment to be made to the temporary created when emitting a
58 /// reference binding, which accesses a particular subobject of that temporary.
59 struct SubobjectAdjustment {
61 DerivedToBaseAdjustment,
63 MemberPointerAdjustment
67 const CastExpr *BasePath;
68 const CXXRecordDecl *DerivedClass;
72 const MemberPointerType *MPT;
77 struct DTB DerivedToBase;
82 SubobjectAdjustment(const CastExpr *BasePath,
83 const CXXRecordDecl *DerivedClass)
84 : Kind(DerivedToBaseAdjustment) {
85 DerivedToBase.BasePath = BasePath;
86 DerivedToBase.DerivedClass = DerivedClass;
89 SubobjectAdjustment(FieldDecl *Field)
90 : Kind(FieldAdjustment) {
94 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
95 : Kind(MemberPointerAdjustment) {
101 /// Expr - This represents one expression. Note that Expr's are subclasses of
102 /// Stmt. This allows an expression to be transparently used any place a Stmt
105 class Expr : public Stmt {
109 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
110 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
113 ExprBits.TypeDependent = TD;
114 ExprBits.ValueDependent = VD;
115 ExprBits.InstantiationDependent = ID;
116 ExprBits.ValueKind = VK;
117 ExprBits.ObjectKind = OK;
118 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
122 /// \brief Construct an empty expression.
123 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
126 QualType getType() const { return TR; }
127 void setType(QualType t) {
128 // In C++, the type of an expression is always adjusted so that it
129 // will not have reference type (C++ [expr]p6). Use
130 // QualType::getNonReferenceType() to retrieve the non-reference
131 // type. Additionally, inspect Expr::isLvalue to determine whether
132 // an expression that is adjusted in this manner should be
133 // considered an lvalue.
134 assert((t.isNull() || !t->isReferenceType()) &&
135 "Expressions can't have reference type");
140 /// isValueDependent - Determines whether this expression is
141 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
142 /// array bound of "Chars" in the following example is
145 /// template<int Size, char (&Chars)[Size]> struct meta_string;
147 bool isValueDependent() const { return ExprBits.ValueDependent; }
149 /// \brief Set whether this expression is value-dependent or not.
150 void setValueDependent(bool VD) {
151 ExprBits.ValueDependent = VD;
154 /// isTypeDependent - Determines whether this expression is
155 /// type-dependent (C++ [temp.dep.expr]), which means that its type
156 /// could change from one template instantiation to the next. For
157 /// example, the expressions "x" and "x + y" are type-dependent in
158 /// the following code, but "y" is not type-dependent:
160 /// template<typename T>
161 /// void add(T x, int y) {
165 bool isTypeDependent() const { return ExprBits.TypeDependent; }
167 /// \brief Set whether this expression is type-dependent or not.
168 void setTypeDependent(bool TD) {
169 ExprBits.TypeDependent = TD;
172 /// \brief Whether this expression is instantiation-dependent, meaning that
173 /// it depends in some way on a template parameter, even if neither its type
174 /// nor (constant) value can change due to the template instantiation.
176 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
177 /// instantiation-dependent (since it involves a template parameter \c T), but
178 /// is neither type- nor value-dependent, since the type of the inner
179 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
180 /// \c sizeof is known.
183 /// template<typename T>
184 /// void f(T x, T y) {
185 /// sizeof(sizeof(T() + T());
189 bool isInstantiationDependent() const {
190 return ExprBits.InstantiationDependent;
193 /// \brief Set whether this expression is instantiation-dependent or not.
194 void setInstantiationDependent(bool ID) {
195 ExprBits.InstantiationDependent = ID;
198 /// \brief Whether this expression contains an unexpanded parameter
199 /// pack (for C++11 variadic templates).
201 /// Given the following function template:
204 /// template<typename F, typename ...Types>
205 /// void forward(const F &f, Types &&...args) {
206 /// f(static_cast<Types&&>(args)...);
210 /// The expressions \c args and \c static_cast<Types&&>(args) both
211 /// contain parameter packs.
212 bool containsUnexpandedParameterPack() const {
213 return ExprBits.ContainsUnexpandedParameterPack;
216 /// \brief Set the bit that describes whether this expression
217 /// contains an unexpanded parameter pack.
218 void setContainsUnexpandedParameterPack(bool PP = true) {
219 ExprBits.ContainsUnexpandedParameterPack = PP;
222 /// getExprLoc - Return the preferred location for the arrow when diagnosing
223 /// a problem with a generic expression.
224 SourceLocation getExprLoc() const LLVM_READONLY;
226 /// isUnusedResultAWarning - Return true if this immediate expression should
227 /// be warned about if the result is unused. If so, fill in expr, location,
228 /// and ranges with expr to warn on and source locations/ranges appropriate
230 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
231 SourceRange &R1, SourceRange &R2,
232 ASTContext &Ctx) const;
234 /// isLValue - True if this expression is an "l-value" according to
235 /// the rules of the current language. C and C++ give somewhat
236 /// different rules for this concept, but in general, the result of
237 /// an l-value expression identifies a specific object whereas the
238 /// result of an r-value expression is a value detached from any
239 /// specific storage.
241 /// C++11 divides the concept of "r-value" into pure r-values
242 /// ("pr-values") and so-called expiring values ("x-values"), which
243 /// identify specific objects that can be safely cannibalized for
244 /// their resources. This is an unfortunate abuse of terminology on
245 /// the part of the C++ committee. In Clang, when we say "r-value",
246 /// we generally mean a pr-value.
247 bool isLValue() const { return getValueKind() == VK_LValue; }
248 bool isRValue() const { return getValueKind() == VK_RValue; }
249 bool isXValue() const { return getValueKind() == VK_XValue; }
250 bool isGLValue() const { return getValueKind() != VK_RValue; }
252 enum LValueClassification {
255 LV_IncompleteVoidType,
256 LV_DuplicateVectorComponents,
257 LV_InvalidExpression,
258 LV_InvalidMessageExpression,
260 LV_SubObjCPropertySetting,
264 /// Reasons why an expression might not be an l-value.
265 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
267 enum isModifiableLvalueResult {
270 MLV_IncompleteVoidType,
271 MLV_DuplicateVectorComponents,
272 MLV_InvalidExpression,
273 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
278 MLV_NoSetterProperty,
280 MLV_SubObjCPropertySetting,
281 MLV_InvalidMessageExpression,
285 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
286 /// does not have an incomplete type, does not have a const-qualified type,
287 /// and if it is a structure or union, does not have any member (including,
288 /// recursively, any member or element of all contained aggregates or unions)
289 /// with a const-qualified type.
291 /// \param Loc [in,out] - A source location which *may* be filled
292 /// in with the location of the expression making this a
293 /// non-modifiable lvalue, if specified.
294 isModifiableLvalueResult
295 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
297 /// \brief The return type of classify(). Represents the C++11 expression
299 class Classification {
301 /// \brief The various classification results. Most of these mean prvalue.
305 CL_Function, // Functions cannot be lvalues in C.
306 CL_Void, // Void cannot be an lvalue in C.
307 CL_AddressableVoid, // Void expression whose address can be taken in C.
308 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
309 CL_MemberFunction, // An expression referring to a member function
310 CL_SubObjCPropertySetting,
311 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
312 CL_ArrayTemporary, // A temporary of array type.
313 CL_ObjCMessageRValue, // ObjC message is an rvalue
314 CL_PRValue // A prvalue for any other reason, of any other type
316 /// \brief The results of modification testing.
317 enum ModifiableType {
318 CM_Untested, // testModifiable was false.
320 CM_RValue, // Not modifiable because it's an rvalue
321 CM_Function, // Not modifiable because it's a function; C++ only
322 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
323 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
334 unsigned short Modifiable;
336 explicit Classification(Kinds k, ModifiableType m)
337 : Kind(k), Modifiable(m)
343 Kinds getKind() const { return static_cast<Kinds>(Kind); }
344 ModifiableType getModifiable() const {
345 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
346 return static_cast<ModifiableType>(Modifiable);
348 bool isLValue() const { return Kind == CL_LValue; }
349 bool isXValue() const { return Kind == CL_XValue; }
350 bool isGLValue() const { return Kind <= CL_XValue; }
351 bool isPRValue() const { return Kind >= CL_Function; }
352 bool isRValue() const { return Kind >= CL_XValue; }
353 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
355 /// \brief Create a simple, modifiably lvalue
356 static Classification makeSimpleLValue() {
357 return Classification(CL_LValue, CM_Modifiable);
361 /// \brief Classify - Classify this expression according to the C++11
362 /// expression taxonomy.
364 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
365 /// old lvalue vs rvalue. This function determines the type of expression this
366 /// is. There are three expression types:
367 /// - lvalues are classical lvalues as in C++03.
368 /// - prvalues are equivalent to rvalues in C++03.
369 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
370 /// function returning an rvalue reference.
371 /// lvalues and xvalues are collectively referred to as glvalues, while
372 /// prvalues and xvalues together form rvalues.
373 Classification Classify(ASTContext &Ctx) const {
374 return ClassifyImpl(Ctx, nullptr);
377 /// \brief ClassifyModifiable - Classify this expression according to the
378 /// C++11 expression taxonomy, and see if it is valid on the left side
379 /// of an assignment.
381 /// This function extends classify in that it also tests whether the
382 /// expression is modifiable (C99 6.3.2.1p1).
383 /// \param Loc A source location that might be filled with a relevant location
384 /// if the expression is not modifiable.
385 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
386 return ClassifyImpl(Ctx, &Loc);
389 /// getValueKindForType - Given a formal return or parameter type,
390 /// give its value kind.
391 static ExprValueKind getValueKindForType(QualType T) {
392 if (const ReferenceType *RT = T->getAs<ReferenceType>())
393 return (isa<LValueReferenceType>(RT)
395 : (RT->getPointeeType()->isFunctionType()
396 ? VK_LValue : VK_XValue));
400 /// getValueKind - The value kind that this expression produces.
401 ExprValueKind getValueKind() const {
402 return static_cast<ExprValueKind>(ExprBits.ValueKind);
405 /// getObjectKind - The object kind that this expression produces.
406 /// Object kinds are meaningful only for expressions that yield an
407 /// l-value or x-value.
408 ExprObjectKind getObjectKind() const {
409 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
412 bool isOrdinaryOrBitFieldObject() const {
413 ExprObjectKind OK = getObjectKind();
414 return (OK == OK_Ordinary || OK == OK_BitField);
417 /// setValueKind - Set the value kind produced by this expression.
418 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
420 /// setObjectKind - Set the object kind produced by this expression.
421 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
424 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
428 /// \brief Returns true if this expression is a gl-value that
429 /// potentially refers to a bit-field.
431 /// In C++, whether a gl-value refers to a bitfield is essentially
432 /// an aspect of the value-kind type system.
433 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
435 /// \brief If this expression refers to a bit-field, retrieve the
436 /// declaration of that bit-field.
438 /// Note that this returns a non-null pointer in subtly different
439 /// places than refersToBitField returns true. In particular, this can
440 /// return a non-null pointer even for r-values loaded from
441 /// bit-fields, but it will return null for a conditional bit-field.
442 FieldDecl *getSourceBitField();
444 const FieldDecl *getSourceBitField() const {
445 return const_cast<Expr*>(this)->getSourceBitField();
448 Decl *getReferencedDeclOfCallee();
449 const Decl *getReferencedDeclOfCallee() const {
450 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
453 /// \brief If this expression is an l-value for an Objective C
454 /// property, find the underlying property reference expression.
455 const ObjCPropertyRefExpr *getObjCProperty() const;
457 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
458 bool isObjCSelfExpr() const;
460 /// \brief Returns whether this expression refers to a vector element.
461 bool refersToVectorElement() const;
463 /// \brief Returns whether this expression refers to a global register
465 bool refersToGlobalRegisterVar() const;
467 /// \brief Returns whether this expression has a placeholder type.
468 bool hasPlaceholderType() const {
469 return getType()->isPlaceholderType();
472 /// \brief Returns whether this expression has a specific placeholder type.
473 bool hasPlaceholderType(BuiltinType::Kind K) const {
474 assert(BuiltinType::isPlaceholderTypeKind(K));
475 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
476 return BT->getKind() == K;
480 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
481 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
482 /// but also int expressions which are produced by things like comparisons in
484 bool isKnownToHaveBooleanValue() const;
486 /// isIntegerConstantExpr - Return true if this expression is a valid integer
487 /// constant expression, and, if so, return its value in Result. If not a
488 /// valid i-c-e, return false and fill in Loc (if specified) with the location
489 /// of the invalid expression.
491 /// Note: This does not perform the implicit conversions required by C++11
493 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
494 SourceLocation *Loc = nullptr,
495 bool isEvaluated = true) const;
496 bool isIntegerConstantExpr(const ASTContext &Ctx,
497 SourceLocation *Loc = nullptr) const;
499 /// isCXX98IntegralConstantExpr - Return true if this expression is an
500 /// integral constant expression in C++98. Can only be used in C++.
501 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
503 /// isCXX11ConstantExpr - Return true if this expression is a constant
504 /// expression in C++11. Can only be used in C++.
506 /// Note: This does not perform the implicit conversions required by C++11
508 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
509 SourceLocation *Loc = nullptr) const;
511 /// isPotentialConstantExpr - Return true if this function's definition
512 /// might be usable in a constant expression in C++11, if it were marked
513 /// constexpr. Return false if the function can never produce a constant
514 /// expression, along with diagnostics describing why not.
515 static bool isPotentialConstantExpr(const FunctionDecl *FD,
517 PartialDiagnosticAt> &Diags);
519 /// isPotentialConstantExprUnevaluted - Return true if this expression might
520 /// be usable in a constant expression in C++11 in an unevaluated context, if
521 /// it were in function FD marked constexpr. Return false if the function can
522 /// never produce a constant expression, along with diagnostics describing
524 static bool isPotentialConstantExprUnevaluated(Expr *E,
525 const FunctionDecl *FD,
527 PartialDiagnosticAt> &Diags);
529 /// isConstantInitializer - Returns true if this expression can be emitted to
530 /// IR as a constant, and thus can be used as a constant initializer in C.
531 /// If this expression is not constant and Culprit is non-null,
532 /// it is used to store the address of first non constant expr.
533 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
534 const Expr **Culprit = nullptr) const;
536 /// EvalStatus is a struct with detailed info about an evaluation in progress.
538 /// \brief Whether the evaluated expression has side effects.
539 /// For example, (f() && 0) can be folded, but it still has side effects.
542 /// \brief Whether the evaluation hit undefined behavior.
543 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
544 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
545 bool HasUndefinedBehavior;
547 /// Diag - If this is non-null, it will be filled in with a stack of notes
548 /// indicating why evaluation failed (or why it failed to produce a constant
550 /// If the expression is unfoldable, the notes will indicate why it's not
551 /// foldable. If the expression is foldable, but not a constant expression,
552 /// the notes will describes why it isn't a constant expression. If the
553 /// expression *is* a constant expression, no notes will be produced.
554 SmallVectorImpl<PartialDiagnosticAt> *Diag;
557 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
559 // hasSideEffects - Return true if the evaluated expression has
561 bool hasSideEffects() const {
562 return HasSideEffects;
566 /// EvalResult is a struct with detailed info about an evaluated expression.
567 struct EvalResult : EvalStatus {
568 /// Val - This is the value the expression can be folded to.
571 // isGlobalLValue - Return true if the evaluated lvalue expression
573 bool isGlobalLValue() const;
576 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
577 /// an rvalue using any crazy technique (that has nothing to do with language
578 /// standards) that we want to, even if the expression has side-effects. If
579 /// this function returns true, it returns the folded constant in Result. If
580 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
582 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
584 /// EvaluateAsBooleanCondition - Return true if this is a constant
585 /// which we we can fold and convert to a boolean condition using
586 /// any crazy technique that we want to, even if the expression has
588 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
590 enum SideEffectsKind {
591 SE_NoSideEffects, ///< Strictly evaluate the expression.
592 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
593 ///< arbitrary unmodeled side effects.
594 SE_AllowSideEffects ///< Allow any unmodeled side effect.
597 /// EvaluateAsInt - Return true if this is a constant which we can fold and
598 /// convert to an integer, using any crazy technique that we want to.
599 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
600 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
602 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
603 /// convert to a floating point value, using any crazy technique that we
606 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
607 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
609 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
610 /// constant folded without side-effects, but discard the result.
611 bool isEvaluatable(const ASTContext &Ctx,
612 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
614 /// HasSideEffects - This routine returns true for all those expressions
615 /// which have any effect other than producing a value. Example is a function
616 /// call, volatile variable read, or throwing an exception. If
617 /// IncludePossibleEffects is false, this call treats certain expressions with
618 /// potential side effects (such as function call-like expressions,
619 /// instantiation-dependent expressions, or invocations from a macro) as not
620 /// having side effects.
621 bool HasSideEffects(const ASTContext &Ctx,
622 bool IncludePossibleEffects = true) const;
624 /// \brief Determine whether this expression involves a call to any function
625 /// that is not trivial.
626 bool hasNonTrivialCall(const ASTContext &Ctx) const;
628 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
629 /// integer. This must be called on an expression that constant folds to an
631 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
632 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
634 void EvaluateForOverflow(const ASTContext &Ctx) const;
636 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
637 /// lvalue with link time known address, with no side-effects.
638 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
640 /// EvaluateAsInitializer - Evaluate an expression as if it were the
641 /// initializer of the given declaration. Returns true if the initializer
642 /// can be folded to a constant, and produces any relevant notes. In C++11,
643 /// notes will be produced if the expression is not a constant expression.
644 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
646 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
648 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
649 /// of a call to the given function with the given arguments, inside an
650 /// unevaluated context. Returns true if the expression could be folded to a
652 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
653 const FunctionDecl *Callee,
654 ArrayRef<const Expr*> Args,
655 const Expr *This = nullptr) const;
657 /// \brief If the current Expr is a pointer, this will try to statically
658 /// determine the number of bytes available where the pointer is pointing.
659 /// Returns true if all of the above holds and we were able to figure out the
660 /// size, false otherwise.
662 /// \param Type - How to evaluate the size of the Expr, as defined by the
663 /// "type" parameter of __builtin_object_size
664 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
665 unsigned Type) const;
667 /// \brief Enumeration used to describe the kind of Null pointer constant
668 /// returned from \c isNullPointerConstant().
669 enum NullPointerConstantKind {
670 /// \brief Expression is not a Null pointer constant.
673 /// \brief Expression is a Null pointer constant built from a zero integer
674 /// expression that is not a simple, possibly parenthesized, zero literal.
675 /// C++ Core Issue 903 will classify these expressions as "not pointers"
676 /// once it is adopted.
677 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
680 /// \brief Expression is a Null pointer constant built from a literal zero.
683 /// \brief Expression is a C++11 nullptr.
686 /// \brief Expression is a GNU-style __null constant.
690 /// \brief Enumeration used to describe how \c isNullPointerConstant()
691 /// should cope with value-dependent expressions.
692 enum NullPointerConstantValueDependence {
693 /// \brief Specifies that the expression should never be value-dependent.
694 NPC_NeverValueDependent = 0,
696 /// \brief Specifies that a value-dependent expression of integral or
697 /// dependent type should be considered a null pointer constant.
698 NPC_ValueDependentIsNull,
700 /// \brief Specifies that a value-dependent expression should be considered
701 /// to never be a null pointer constant.
702 NPC_ValueDependentIsNotNull
705 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
706 /// a Null pointer constant. The return value can further distinguish the
707 /// kind of NULL pointer constant that was detected.
708 NullPointerConstantKind isNullPointerConstant(
710 NullPointerConstantValueDependence NPC) const;
712 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
714 bool isOBJCGCCandidate(ASTContext &Ctx) const;
716 /// \brief Returns true if this expression is a bound member function.
717 bool isBoundMemberFunction(ASTContext &Ctx) const;
719 /// \brief Given an expression of bound-member type, find the type
720 /// of the member. Returns null if this is an *overloaded* bound
721 /// member expression.
722 static QualType findBoundMemberType(const Expr *expr);
724 /// IgnoreImpCasts - Skip past any implicit casts which might
725 /// surround this expression. Only skips ImplicitCastExprs.
726 Expr *IgnoreImpCasts() LLVM_READONLY;
728 /// IgnoreImplicit - Skip past any implicit AST nodes which might
729 /// surround this expression.
730 Expr *IgnoreImplicit() LLVM_READONLY {
731 return cast<Expr>(Stmt::IgnoreImplicit());
734 const Expr *IgnoreImplicit() const LLVM_READONLY {
735 return const_cast<Expr*>(this)->IgnoreImplicit();
738 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
739 /// its subexpression. If that subexpression is also a ParenExpr,
740 /// then this method recursively returns its subexpression, and so forth.
741 /// Otherwise, the method returns the current Expr.
742 Expr *IgnoreParens() LLVM_READONLY;
744 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
745 /// or CastExprs, returning their operand.
746 Expr *IgnoreParenCasts() LLVM_READONLY;
748 /// Ignore casts. Strip off any CastExprs, returning their operand.
749 Expr *IgnoreCasts() LLVM_READONLY;
751 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
752 /// any ParenExpr or ImplicitCastExprs, returning their operand.
753 Expr *IgnoreParenImpCasts() LLVM_READONLY;
755 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
756 /// call to a conversion operator, return the argument.
757 Expr *IgnoreConversionOperator() LLVM_READONLY;
759 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
760 return const_cast<Expr*>(this)->IgnoreConversionOperator();
763 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
764 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
767 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
768 /// CastExprs that represent lvalue casts, returning their operand.
769 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
771 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
772 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
775 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
776 /// value (including ptr->int casts of the same size). Strip off any
777 /// ParenExpr or CastExprs, returning their operand.
778 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
780 /// Ignore parentheses and derived-to-base casts.
781 Expr *ignoreParenBaseCasts() LLVM_READONLY;
783 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
784 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
787 /// \brief Determine whether this expression is a default function argument.
789 /// Default arguments are implicitly generated in the abstract syntax tree
790 /// by semantic analysis for function calls, object constructions, etc. in
791 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
792 /// this routine also looks through any implicit casts to determine whether
793 /// the expression is a default argument.
794 bool isDefaultArgument() const;
796 /// \brief Determine whether the result of this expression is a
797 /// temporary object of the given class type.
798 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
800 /// \brief Whether this expression is an implicit reference to 'this' in C++.
801 bool isImplicitCXXThis() const;
803 const Expr *IgnoreImpCasts() const LLVM_READONLY {
804 return const_cast<Expr*>(this)->IgnoreImpCasts();
806 const Expr *IgnoreParens() const LLVM_READONLY {
807 return const_cast<Expr*>(this)->IgnoreParens();
809 const Expr *IgnoreParenCasts() const LLVM_READONLY {
810 return const_cast<Expr*>(this)->IgnoreParenCasts();
812 /// Strip off casts, but keep parentheses.
813 const Expr *IgnoreCasts() const LLVM_READONLY {
814 return const_cast<Expr*>(this)->IgnoreCasts();
817 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
818 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
821 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
823 /// \brief For an expression of class type or pointer to class type,
824 /// return the most derived class decl the expression is known to refer to.
826 /// If this expression is a cast, this method looks through it to find the
827 /// most derived decl that can be inferred from the expression.
828 /// This is valid because derived-to-base conversions have undefined
829 /// behavior if the object isn't dynamically of the derived type.
830 const CXXRecordDecl *getBestDynamicClassType() const;
832 /// \brief Get the inner expression that determines the best dynamic class.
833 /// If this is a prvalue, we guarantee that it is of the most-derived type
834 /// for the object itself.
835 const Expr *getBestDynamicClassTypeExpr() const;
837 /// Walk outwards from an expression we want to bind a reference to and
838 /// find the expression whose lifetime needs to be extended. Record
839 /// the LHSs of comma expressions and adjustments needed along the path.
840 const Expr *skipRValueSubobjectAdjustments(
841 SmallVectorImpl<const Expr *> &CommaLHS,
842 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
843 const Expr *skipRValueSubobjectAdjustments() const {
844 SmallVector<const Expr *, 8> CommaLHSs;
845 SmallVector<SubobjectAdjustment, 8> Adjustments;
846 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
849 static bool classof(const Stmt *T) {
850 return T->getStmtClass() >= firstExprConstant &&
851 T->getStmtClass() <= lastExprConstant;
855 //===----------------------------------------------------------------------===//
856 // Primary Expressions.
857 //===----------------------------------------------------------------------===//
859 /// OpaqueValueExpr - An expression referring to an opaque object of a
860 /// fixed type and value class. These don't correspond to concrete
861 /// syntax; instead they're used to express operations (usually copy
862 /// operations) on values whose source is generally obvious from
864 class OpaqueValueExpr : public Expr {
865 friend class ASTStmtReader;
870 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
871 ExprObjectKind OK = OK_Ordinary,
872 Expr *SourceExpr = nullptr)
873 : Expr(OpaqueValueExprClass, T, VK, OK,
874 T->isDependentType() ||
875 (SourceExpr && SourceExpr->isTypeDependent()),
876 T->isDependentType() ||
877 (SourceExpr && SourceExpr->isValueDependent()),
878 T->isInstantiationDependentType() ||
879 (SourceExpr && SourceExpr->isInstantiationDependent()),
881 SourceExpr(SourceExpr), Loc(Loc) {
884 /// Given an expression which invokes a copy constructor --- i.e. a
885 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
886 /// find the OpaqueValueExpr that's the source of the construction.
887 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
889 explicit OpaqueValueExpr(EmptyShell Empty)
890 : Expr(OpaqueValueExprClass, Empty) { }
892 /// \brief Retrieve the location of this expression.
893 SourceLocation getLocation() const { return Loc; }
895 SourceLocation getLocStart() const LLVM_READONLY {
896 return SourceExpr ? SourceExpr->getLocStart() : Loc;
898 SourceLocation getLocEnd() const LLVM_READONLY {
899 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
901 SourceLocation getExprLoc() const LLVM_READONLY {
902 if (SourceExpr) return SourceExpr->getExprLoc();
906 child_range children() {
907 return child_range(child_iterator(), child_iterator());
910 /// The source expression of an opaque value expression is the
911 /// expression which originally generated the value. This is
912 /// provided as a convenience for analyses that don't wish to
913 /// precisely model the execution behavior of the program.
915 /// The source expression is typically set when building the
916 /// expression which binds the opaque value expression in the first
918 Expr *getSourceExpr() const { return SourceExpr; }
920 static bool classof(const Stmt *T) {
921 return T->getStmtClass() == OpaqueValueExprClass;
925 /// \brief A reference to a declared variable, function, enum, etc.
928 /// This encodes all the information about how a declaration is referenced
929 /// within an expression.
931 /// There are several optional constructs attached to DeclRefExprs only when
932 /// they apply in order to conserve memory. These are laid out past the end of
933 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
935 /// DeclRefExprBits.HasQualifier:
936 /// Specifies when this declaration reference expression has a C++
937 /// nested-name-specifier.
938 /// DeclRefExprBits.HasFoundDecl:
939 /// Specifies when this declaration reference expression has a record of
940 /// a NamedDecl (different from the referenced ValueDecl) which was found
941 /// during name lookup and/or overload resolution.
942 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
943 /// Specifies when this declaration reference expression has an explicit
944 /// C++ template keyword and/or template argument list.
945 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
946 /// Specifies when this declaration reference expression (validly)
947 /// refers to an enclosed local or a captured variable.
948 class DeclRefExpr final
950 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
951 NamedDecl *, ASTTemplateKWAndArgsInfo,
952 TemplateArgumentLoc> {
953 /// \brief The declaration that we are referencing.
956 /// \brief The location of the declaration name itself.
959 /// \brief Provides source/type location info for the declaration name
961 DeclarationNameLoc DNLoc;
963 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
964 return hasQualifier() ? 1 : 0;
967 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
968 return hasFoundDecl() ? 1 : 0;
971 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
972 return hasTemplateKWAndArgsInfo() ? 1 : 0;
975 /// \brief Test whether there is a distinct FoundDecl attached to the end of
977 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
979 DeclRefExpr(const ASTContext &Ctx,
980 NestedNameSpecifierLoc QualifierLoc,
981 SourceLocation TemplateKWLoc,
982 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
983 const DeclarationNameInfo &NameInfo,
985 const TemplateArgumentListInfo *TemplateArgs,
986 QualType T, ExprValueKind VK);
988 /// \brief Construct an empty declaration reference expression.
989 explicit DeclRefExpr(EmptyShell Empty)
990 : Expr(DeclRefExprClass, Empty) { }
992 /// \brief Computes the type- and value-dependence flags for this
993 /// declaration reference expression.
994 void computeDependence(const ASTContext &C);
997 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
998 ExprValueKind VK, SourceLocation L,
999 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1000 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1001 D(D), Loc(L), DNLoc(LocInfo) {
1002 DeclRefExprBits.HasQualifier = 0;
1003 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1004 DeclRefExprBits.HasFoundDecl = 0;
1005 DeclRefExprBits.HadMultipleCandidates = 0;
1006 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1007 RefersToEnclosingVariableOrCapture;
1008 computeDependence(D->getASTContext());
1011 static DeclRefExpr *
1012 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1013 SourceLocation TemplateKWLoc, ValueDecl *D,
1014 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1015 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1016 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1018 static DeclRefExpr *
1019 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1020 SourceLocation TemplateKWLoc, ValueDecl *D,
1021 bool RefersToEnclosingVariableOrCapture,
1022 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1023 NamedDecl *FoundD = nullptr,
1024 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1026 /// \brief Construct an empty declaration reference expression.
1027 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1030 bool HasTemplateKWAndArgsInfo,
1031 unsigned NumTemplateArgs);
1033 ValueDecl *getDecl() { return D; }
1034 const ValueDecl *getDecl() const { return D; }
1035 void setDecl(ValueDecl *NewD) { D = NewD; }
1037 DeclarationNameInfo getNameInfo() const {
1038 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1041 SourceLocation getLocation() const { return Loc; }
1042 void setLocation(SourceLocation L) { Loc = L; }
1043 SourceLocation getLocStart() const LLVM_READONLY;
1044 SourceLocation getLocEnd() const LLVM_READONLY;
1046 /// \brief Determine whether this declaration reference was preceded by a
1047 /// C++ nested-name-specifier, e.g., \c N::foo.
1048 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1050 /// \brief If the name was qualified, retrieves the nested-name-specifier
1051 /// that precedes the name, with source-location information.
1052 NestedNameSpecifierLoc getQualifierLoc() const {
1053 if (!hasQualifier())
1054 return NestedNameSpecifierLoc();
1055 return *getTrailingObjects<NestedNameSpecifierLoc>();
1058 /// \brief If the name was qualified, retrieves the nested-name-specifier
1059 /// that precedes the name. Otherwise, returns NULL.
1060 NestedNameSpecifier *getQualifier() const {
1061 return getQualifierLoc().getNestedNameSpecifier();
1064 /// \brief Get the NamedDecl through which this reference occurred.
1066 /// This Decl may be different from the ValueDecl actually referred to in the
1067 /// presence of using declarations, etc. It always returns non-NULL, and may
1068 /// simple return the ValueDecl when appropriate.
1070 NamedDecl *getFoundDecl() {
1071 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1074 /// \brief Get the NamedDecl through which this reference occurred.
1075 /// See non-const variant.
1076 const NamedDecl *getFoundDecl() const {
1077 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1080 bool hasTemplateKWAndArgsInfo() const {
1081 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1084 /// \brief Retrieve the location of the template keyword preceding
1085 /// this name, if any.
1086 SourceLocation getTemplateKeywordLoc() const {
1087 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1088 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1091 /// \brief Retrieve the location of the left angle bracket starting the
1092 /// explicit template argument list following the name, if any.
1093 SourceLocation getLAngleLoc() const {
1094 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1095 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1098 /// \brief Retrieve the location of the right angle bracket ending the
1099 /// explicit template argument list following the name, if any.
1100 SourceLocation getRAngleLoc() const {
1101 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1102 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1105 /// \brief Determines whether the name in this declaration reference
1106 /// was preceded by the template keyword.
1107 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1109 /// \brief Determines whether this declaration reference was followed by an
1110 /// explicit template argument list.
1111 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1113 /// \brief Copies the template arguments (if present) into the given
1115 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1116 if (hasExplicitTemplateArgs())
1117 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1118 getTrailingObjects<TemplateArgumentLoc>(), List);
1121 /// \brief Retrieve the template arguments provided as part of this
1123 const TemplateArgumentLoc *getTemplateArgs() const {
1124 if (!hasExplicitTemplateArgs())
1127 return getTrailingObjects<TemplateArgumentLoc>();
1130 /// \brief Retrieve the number of template arguments provided as part of this
1132 unsigned getNumTemplateArgs() const {
1133 if (!hasExplicitTemplateArgs())
1136 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1139 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1140 return {getTemplateArgs(), getNumTemplateArgs()};
1143 /// \brief Returns true if this expression refers to a function that
1144 /// was resolved from an overloaded set having size greater than 1.
1145 bool hadMultipleCandidates() const {
1146 return DeclRefExprBits.HadMultipleCandidates;
1148 /// \brief Sets the flag telling whether this expression refers to
1149 /// a function that was resolved from an overloaded set having size
1151 void setHadMultipleCandidates(bool V = true) {
1152 DeclRefExprBits.HadMultipleCandidates = V;
1155 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1157 bool refersToEnclosingVariableOrCapture() const {
1158 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1161 static bool classof(const Stmt *T) {
1162 return T->getStmtClass() == DeclRefExprClass;
1166 child_range children() {
1167 return child_range(child_iterator(), child_iterator());
1170 friend TrailingObjects;
1171 friend class ASTStmtReader;
1172 friend class ASTStmtWriter;
1175 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1176 class PredefinedExpr : public Expr {
1181 LFunction, // Same as Function, but as wide string.
1185 /// \brief The same as PrettyFunction, except that the
1186 /// 'virtual' keyword is omitted for virtual member functions.
1187 PrettyFunctionNoVirtual
1196 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1199 /// \brief Construct an empty predefined expression.
1200 explicit PredefinedExpr(EmptyShell Empty)
1201 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1203 IdentType getIdentType() const { return Type; }
1205 SourceLocation getLocation() const { return Loc; }
1206 void setLocation(SourceLocation L) { Loc = L; }
1208 StringLiteral *getFunctionName();
1209 const StringLiteral *getFunctionName() const {
1210 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1213 static StringRef getIdentTypeName(IdentType IT);
1214 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1216 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1217 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1219 static bool classof(const Stmt *T) {
1220 return T->getStmtClass() == PredefinedExprClass;
1224 child_range children() { return child_range(&FnName, &FnName + 1); }
1226 friend class ASTStmtReader;
1229 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1232 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1233 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1234 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1235 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1236 /// ASTContext's allocator for memory allocation.
1237 class APNumericStorage {
1239 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1240 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1244 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1246 APNumericStorage(const APNumericStorage &) = delete;
1247 void operator=(const APNumericStorage &) = delete;
1250 APNumericStorage() : VAL(0), BitWidth(0) { }
1252 llvm::APInt getIntValue() const {
1253 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1255 return llvm::APInt(BitWidth, NumWords, pVal);
1257 return llvm::APInt(BitWidth, VAL);
1259 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1262 class APIntStorage : private APNumericStorage {
1264 llvm::APInt getValue() const { return getIntValue(); }
1265 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1266 setIntValue(C, Val);
1270 class APFloatStorage : private APNumericStorage {
1272 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1273 return llvm::APFloat(Semantics, getIntValue());
1275 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1276 setIntValue(C, Val.bitcastToAPInt());
1280 class IntegerLiteral : public Expr, public APIntStorage {
1283 /// \brief Construct an empty integer literal.
1284 explicit IntegerLiteral(EmptyShell Empty)
1285 : Expr(IntegerLiteralClass, Empty) { }
1288 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1289 // or UnsignedLongLongTy
1290 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1293 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1294 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1295 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1296 /// \param V - the value that the returned integer literal contains.
1297 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1298 QualType type, SourceLocation l);
1299 /// \brief Returns a new empty integer literal.
1300 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1302 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1303 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1305 /// \brief Retrieve the location of the literal.
1306 SourceLocation getLocation() const { return Loc; }
1308 void setLocation(SourceLocation Location) { Loc = Location; }
1310 static bool classof(const Stmt *T) {
1311 return T->getStmtClass() == IntegerLiteralClass;
1315 child_range children() {
1316 return child_range(child_iterator(), child_iterator());
1320 class CharacterLiteral : public Expr {
1322 enum CharacterKind {
1334 // type should be IntTy
1335 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1337 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1339 Value(value), Loc(l) {
1340 CharacterLiteralBits.Kind = kind;
1343 /// \brief Construct an empty character literal.
1344 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1346 SourceLocation getLocation() const { return Loc; }
1347 CharacterKind getKind() const {
1348 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1351 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1352 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1354 unsigned getValue() const { return Value; }
1356 void setLocation(SourceLocation Location) { Loc = Location; }
1357 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1358 void setValue(unsigned Val) { Value = Val; }
1360 static bool classof(const Stmt *T) {
1361 return T->getStmtClass() == CharacterLiteralClass;
1365 child_range children() {
1366 return child_range(child_iterator(), child_iterator());
1370 class FloatingLiteral : public Expr, private APFloatStorage {
1373 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1374 QualType Type, SourceLocation L);
1376 /// \brief Construct an empty floating-point literal.
1377 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1380 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1381 bool isexact, QualType Type, SourceLocation L);
1382 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1384 llvm::APFloat getValue() const {
1385 return APFloatStorage::getValue(getSemantics());
1387 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1388 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1389 APFloatStorage::setValue(C, Val);
1392 /// Get a raw enumeration value representing the floating-point semantics of
1393 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1394 APFloatSemantics getRawSemantics() const {
1395 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1398 /// Set the raw enumeration value representing the floating-point semantics of
1399 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1400 void setRawSemantics(APFloatSemantics Sem) {
1401 FloatingLiteralBits.Semantics = Sem;
1404 /// Return the APFloat semantics this literal uses.
1405 const llvm::fltSemantics &getSemantics() const;
1407 /// Set the APFloat semantics this literal uses.
1408 void setSemantics(const llvm::fltSemantics &Sem);
1410 bool isExact() const { return FloatingLiteralBits.IsExact; }
1411 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1413 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1414 /// double. Note that this may cause loss of precision, but is useful for
1415 /// debugging dumps, etc.
1416 double getValueAsApproximateDouble() const;
1418 SourceLocation getLocation() const { return Loc; }
1419 void setLocation(SourceLocation L) { Loc = L; }
1421 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1422 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1424 static bool classof(const Stmt *T) {
1425 return T->getStmtClass() == FloatingLiteralClass;
1429 child_range children() {
1430 return child_range(child_iterator(), child_iterator());
1434 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1435 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1436 /// IntegerLiteral classes. Instances of this class always have a Complex type
1437 /// whose element type matches the subexpression.
1439 class ImaginaryLiteral : public Expr {
1442 ImaginaryLiteral(Expr *val, QualType Ty)
1443 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1447 /// \brief Build an empty imaginary literal.
1448 explicit ImaginaryLiteral(EmptyShell Empty)
1449 : Expr(ImaginaryLiteralClass, Empty) { }
1451 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1452 Expr *getSubExpr() { return cast<Expr>(Val); }
1453 void setSubExpr(Expr *E) { Val = E; }
1455 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1456 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1458 static bool classof(const Stmt *T) {
1459 return T->getStmtClass() == ImaginaryLiteralClass;
1463 child_range children() { return child_range(&Val, &Val+1); }
1466 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1467 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1468 /// is NOT null-terminated, and the length of the string is determined by
1469 /// calling getByteLength(). The C type for a string is always a
1470 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1473 /// Note that strings in C can be formed by concatenation of multiple string
1474 /// literal pptokens in translation phase #6. This keeps track of the locations
1475 /// of each of these pieces.
1477 /// Strings in C can also be truncated and extended by assigning into arrays,
1478 /// e.g. with constructs like:
1479 /// char X[2] = "foobar";
1480 /// In this case, getByteLength() will return 6, but the string literal will
1481 /// have type "char[2]".
1482 class StringLiteral : public Expr {
1493 friend class ASTStmtReader;
1497 const uint16_t *asUInt16;
1498 const uint32_t *asUInt32;
1501 unsigned CharByteWidth : 4;
1503 unsigned IsPascal : 1;
1504 unsigned NumConcatenated;
1505 SourceLocation TokLocs[1];
1507 StringLiteral(QualType Ty) :
1508 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1511 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1514 /// This is the "fully general" constructor that allows representation of
1515 /// strings formed from multiple concatenated tokens.
1516 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1517 StringKind Kind, bool Pascal, QualType Ty,
1518 const SourceLocation *Loc, unsigned NumStrs);
1520 /// Simple constructor for string literals made from one token.
1521 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1522 StringKind Kind, bool Pascal, QualType Ty,
1523 SourceLocation Loc) {
1524 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1527 /// \brief Construct an empty string literal.
1528 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1530 StringRef getString() const {
1531 assert(CharByteWidth==1
1532 && "This function is used in places that assume strings use char");
1533 return StringRef(StrData.asChar, getByteLength());
1536 /// Allow access to clients that need the byte representation, such as
1537 /// ASTWriterStmt::VisitStringLiteral().
1538 StringRef getBytes() const {
1539 // FIXME: StringRef may not be the right type to use as a result for this.
1540 if (CharByteWidth == 1)
1541 return StringRef(StrData.asChar, getByteLength());
1542 if (CharByteWidth == 4)
1543 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1545 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1546 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1550 void outputString(raw_ostream &OS) const;
1552 uint32_t getCodeUnit(size_t i) const {
1553 assert(i < Length && "out of bounds access");
1554 if (CharByteWidth == 1)
1555 return static_cast<unsigned char>(StrData.asChar[i]);
1556 if (CharByteWidth == 4)
1557 return StrData.asUInt32[i];
1558 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1559 return StrData.asUInt16[i];
1562 unsigned getByteLength() const { return CharByteWidth*Length; }
1563 unsigned getLength() const { return Length; }
1564 unsigned getCharByteWidth() const { return CharByteWidth; }
1566 /// \brief Sets the string data to the given string data.
1567 void setString(const ASTContext &C, StringRef Str,
1568 StringKind Kind, bool IsPascal);
1570 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1573 bool isAscii() const { return Kind == Ascii; }
1574 bool isWide() const { return Kind == Wide; }
1575 bool isUTF8() const { return Kind == UTF8; }
1576 bool isUTF16() const { return Kind == UTF16; }
1577 bool isUTF32() const { return Kind == UTF32; }
1578 bool isPascal() const { return IsPascal; }
1580 bool containsNonAsciiOrNull() const {
1581 StringRef Str = getString();
1582 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1583 if (!isASCII(Str[i]) || !Str[i])
1588 /// getNumConcatenated - Get the number of string literal tokens that were
1589 /// concatenated in translation phase #6 to form this string literal.
1590 unsigned getNumConcatenated() const { return NumConcatenated; }
1592 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1593 assert(TokNum < NumConcatenated && "Invalid tok number");
1594 return TokLocs[TokNum];
1596 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1597 assert(TokNum < NumConcatenated && "Invalid tok number");
1598 TokLocs[TokNum] = L;
1601 /// getLocationOfByte - Return a source location that points to the specified
1602 /// byte of this string literal.
1604 /// Strings are amazingly complex. They can be formed from multiple tokens
1605 /// and can have escape sequences in them in addition to the usual trigraph
1606 /// and escaped newline business. This routine handles this complexity.
1609 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1610 const LangOptions &Features, const TargetInfo &Target,
1611 unsigned *StartToken = nullptr,
1612 unsigned *StartTokenByteOffset = nullptr) const;
1614 typedef const SourceLocation *tokloc_iterator;
1615 tokloc_iterator tokloc_begin() const { return TokLocs; }
1616 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1618 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1619 SourceLocation getLocEnd() const LLVM_READONLY {
1620 return TokLocs[NumConcatenated - 1];
1623 static bool classof(const Stmt *T) {
1624 return T->getStmtClass() == StringLiteralClass;
1628 child_range children() {
1629 return child_range(child_iterator(), child_iterator());
1633 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1634 /// AST node is only formed if full location information is requested.
1635 class ParenExpr : public Expr {
1636 SourceLocation L, R;
1639 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1640 : Expr(ParenExprClass, val->getType(),
1641 val->getValueKind(), val->getObjectKind(),
1642 val->isTypeDependent(), val->isValueDependent(),
1643 val->isInstantiationDependent(),
1644 val->containsUnexpandedParameterPack()),
1645 L(l), R(r), Val(val) {}
1647 /// \brief Construct an empty parenthesized expression.
1648 explicit ParenExpr(EmptyShell Empty)
1649 : Expr(ParenExprClass, Empty) { }
1651 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1652 Expr *getSubExpr() { return cast<Expr>(Val); }
1653 void setSubExpr(Expr *E) { Val = E; }
1655 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1656 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1658 /// \brief Get the location of the left parentheses '('.
1659 SourceLocation getLParen() const { return L; }
1660 void setLParen(SourceLocation Loc) { L = Loc; }
1662 /// \brief Get the location of the right parentheses ')'.
1663 SourceLocation getRParen() const { return R; }
1664 void setRParen(SourceLocation Loc) { R = Loc; }
1666 static bool classof(const Stmt *T) {
1667 return T->getStmtClass() == ParenExprClass;
1671 child_range children() { return child_range(&Val, &Val+1); }
1674 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1675 /// alignof), the postinc/postdec operators from postfix-expression, and various
1678 /// Notes on various nodes:
1680 /// Real/Imag - These return the real/imag part of a complex operand. If
1681 /// applied to a non-complex value, the former returns its operand and the
1682 /// later returns zero in the type of the operand.
1684 class UnaryOperator : public Expr {
1686 typedef UnaryOperatorKind Opcode;
1694 UnaryOperator(Expr *input, Opcode opc, QualType type,
1695 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1696 : Expr(UnaryOperatorClass, type, VK, OK,
1697 input->isTypeDependent() || type->isDependentType(),
1698 input->isValueDependent(),
1699 (input->isInstantiationDependent() ||
1700 type->isInstantiationDependentType()),
1701 input->containsUnexpandedParameterPack()),
1702 Opc(opc), Loc(l), Val(input) {}
1704 /// \brief Build an empty unary operator.
1705 explicit UnaryOperator(EmptyShell Empty)
1706 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1708 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1709 void setOpcode(Opcode O) { Opc = O; }
1711 Expr *getSubExpr() const { return cast<Expr>(Val); }
1712 void setSubExpr(Expr *E) { Val = E; }
1714 /// getOperatorLoc - Return the location of the operator.
1715 SourceLocation getOperatorLoc() const { return Loc; }
1716 void setOperatorLoc(SourceLocation L) { Loc = L; }
1718 /// isPostfix - Return true if this is a postfix operation, like x++.
1719 static bool isPostfix(Opcode Op) {
1720 return Op == UO_PostInc || Op == UO_PostDec;
1723 /// isPrefix - Return true if this is a prefix operation, like --x.
1724 static bool isPrefix(Opcode Op) {
1725 return Op == UO_PreInc || Op == UO_PreDec;
1728 bool isPrefix() const { return isPrefix(getOpcode()); }
1729 bool isPostfix() const { return isPostfix(getOpcode()); }
1731 static bool isIncrementOp(Opcode Op) {
1732 return Op == UO_PreInc || Op == UO_PostInc;
1734 bool isIncrementOp() const {
1735 return isIncrementOp(getOpcode());
1738 static bool isDecrementOp(Opcode Op) {
1739 return Op == UO_PreDec || Op == UO_PostDec;
1741 bool isDecrementOp() const {
1742 return isDecrementOp(getOpcode());
1745 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1746 bool isIncrementDecrementOp() const {
1747 return isIncrementDecrementOp(getOpcode());
1750 static bool isArithmeticOp(Opcode Op) {
1751 return Op >= UO_Plus && Op <= UO_LNot;
1753 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1755 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1756 /// corresponds to, e.g. "sizeof" or "[pre]++"
1757 static StringRef getOpcodeStr(Opcode Op);
1759 /// \brief Retrieve the unary opcode that corresponds to the given
1760 /// overloaded operator.
1761 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1763 /// \brief Retrieve the overloaded operator kind that corresponds to
1764 /// the given unary opcode.
1765 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1767 SourceLocation getLocStart() const LLVM_READONLY {
1768 return isPostfix() ? Val->getLocStart() : Loc;
1770 SourceLocation getLocEnd() const LLVM_READONLY {
1771 return isPostfix() ? Loc : Val->getLocEnd();
1773 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1775 static bool classof(const Stmt *T) {
1776 return T->getStmtClass() == UnaryOperatorClass;
1780 child_range children() { return child_range(&Val, &Val+1); }
1783 /// Helper class for OffsetOfExpr.
1785 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1786 class OffsetOfNode {
1788 /// \brief The kind of offsetof node we have.
1790 /// \brief An index into an array.
1794 /// \brief A field in a dependent type, known only by its name.
1796 /// \brief An implicit indirection through a C++ base class, when the
1797 /// field found is in a base class.
1802 enum { MaskBits = 2, Mask = 0x03 };
1804 /// \brief The source range that covers this part of the designator.
1807 /// \brief The data describing the designator, which comes in three
1808 /// different forms, depending on the lower two bits.
1809 /// - An unsigned index into the array of Expr*'s stored after this node
1810 /// in memory, for [constant-expression] designators.
1811 /// - A FieldDecl*, for references to a known field.
1812 /// - An IdentifierInfo*, for references to a field with a given name
1813 /// when the class type is dependent.
1814 /// - A CXXBaseSpecifier*, for references that look at a field in a
1819 /// \brief Create an offsetof node that refers to an array element.
1820 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1821 SourceLocation RBracketLoc)
1822 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1824 /// \brief Create an offsetof node that refers to a field.
1825 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1826 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1827 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1829 /// \brief Create an offsetof node that refers to an identifier.
1830 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1831 SourceLocation NameLoc)
1832 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1833 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1835 /// \brief Create an offsetof node that refers into a C++ base class.
1836 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1837 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1839 /// \brief Determine what kind of offsetof node this is.
1840 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1842 /// \brief For an array element node, returns the index into the array
1844 unsigned getArrayExprIndex() const {
1845 assert(getKind() == Array);
1849 /// \brief For a field offsetof node, returns the field.
1850 FieldDecl *getField() const {
1851 assert(getKind() == Field);
1852 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1855 /// \brief For a field or identifier offsetof node, returns the name of
1857 IdentifierInfo *getFieldName() const;
1859 /// \brief For a base class node, returns the base specifier.
1860 CXXBaseSpecifier *getBase() const {
1861 assert(getKind() == Base);
1862 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1865 /// \brief Retrieve the source range that covers this offsetof node.
1867 /// For an array element node, the source range contains the locations of
1868 /// the square brackets. For a field or identifier node, the source range
1869 /// contains the location of the period (if there is one) and the
1871 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1872 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1873 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1876 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1877 /// offsetof(record-type, member-designator). For example, given:
1888 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1890 class OffsetOfExpr final
1892 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1893 SourceLocation OperatorLoc, RParenLoc;
1895 TypeSourceInfo *TSInfo;
1896 // Number of sub-components (i.e. instances of OffsetOfNode).
1898 // Number of sub-expressions (i.e. array subscript expressions).
1901 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1905 OffsetOfExpr(const ASTContext &C, QualType type,
1906 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1907 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1908 SourceLocation RParenLoc);
1910 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1911 : Expr(OffsetOfExprClass, EmptyShell()),
1912 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1916 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1917 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1918 ArrayRef<OffsetOfNode> comps,
1919 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1921 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1922 unsigned NumComps, unsigned NumExprs);
1924 /// getOperatorLoc - Return the location of the operator.
1925 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1926 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1928 /// \brief Return the location of the right parentheses.
1929 SourceLocation getRParenLoc() const { return RParenLoc; }
1930 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1932 TypeSourceInfo *getTypeSourceInfo() const {
1935 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1939 const OffsetOfNode &getComponent(unsigned Idx) const {
1940 assert(Idx < NumComps && "Subscript out of range");
1941 return getTrailingObjects<OffsetOfNode>()[Idx];
1944 void setComponent(unsigned Idx, OffsetOfNode ON) {
1945 assert(Idx < NumComps && "Subscript out of range");
1946 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
1949 unsigned getNumComponents() const {
1953 Expr* getIndexExpr(unsigned Idx) {
1954 assert(Idx < NumExprs && "Subscript out of range");
1955 return getTrailingObjects<Expr *>()[Idx];
1958 const Expr *getIndexExpr(unsigned Idx) const {
1959 assert(Idx < NumExprs && "Subscript out of range");
1960 return getTrailingObjects<Expr *>()[Idx];
1963 void setIndexExpr(unsigned Idx, Expr* E) {
1964 assert(Idx < NumComps && "Subscript out of range");
1965 getTrailingObjects<Expr *>()[Idx] = E;
1968 unsigned getNumExpressions() const {
1972 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1973 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1975 static bool classof(const Stmt *T) {
1976 return T->getStmtClass() == OffsetOfExprClass;
1980 child_range children() {
1981 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
1982 return child_range(begin, begin + NumExprs);
1984 friend TrailingObjects;
1987 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1988 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1989 /// vec_step (OpenCL 1.1 6.11.12).
1990 class UnaryExprOrTypeTraitExpr : public Expr {
1995 SourceLocation OpLoc, RParenLoc;
1998 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1999 QualType resultType, SourceLocation op,
2000 SourceLocation rp) :
2001 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2002 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2003 // Value-dependent if the argument is type-dependent.
2004 TInfo->getType()->isDependentType(),
2005 TInfo->getType()->isInstantiationDependentType(),
2006 TInfo->getType()->containsUnexpandedParameterPack()),
2007 OpLoc(op), RParenLoc(rp) {
2008 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2009 UnaryExprOrTypeTraitExprBits.IsType = true;
2010 Argument.Ty = TInfo;
2013 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2014 QualType resultType, SourceLocation op,
2017 /// \brief Construct an empty sizeof/alignof expression.
2018 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2019 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2021 UnaryExprOrTypeTrait getKind() const {
2022 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2024 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2026 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2027 QualType getArgumentType() const {
2028 return getArgumentTypeInfo()->getType();
2030 TypeSourceInfo *getArgumentTypeInfo() const {
2031 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2034 Expr *getArgumentExpr() {
2035 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2036 return static_cast<Expr*>(Argument.Ex);
2038 const Expr *getArgumentExpr() const {
2039 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2042 void setArgument(Expr *E) {
2044 UnaryExprOrTypeTraitExprBits.IsType = false;
2046 void setArgument(TypeSourceInfo *TInfo) {
2047 Argument.Ty = TInfo;
2048 UnaryExprOrTypeTraitExprBits.IsType = true;
2051 /// Gets the argument type, or the type of the argument expression, whichever
2053 QualType getTypeOfArgument() const {
2054 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2057 SourceLocation getOperatorLoc() const { return OpLoc; }
2058 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2060 SourceLocation getRParenLoc() const { return RParenLoc; }
2061 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2063 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2064 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2066 static bool classof(const Stmt *T) {
2067 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2071 child_range children();
2074 //===----------------------------------------------------------------------===//
2075 // Postfix Operators.
2076 //===----------------------------------------------------------------------===//
2078 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2079 class ArraySubscriptExpr : public Expr {
2080 enum { LHS, RHS, END_EXPR=2 };
2081 Stmt* SubExprs[END_EXPR];
2082 SourceLocation RBracketLoc;
2084 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2085 ExprValueKind VK, ExprObjectKind OK,
2086 SourceLocation rbracketloc)
2087 : Expr(ArraySubscriptExprClass, t, VK, OK,
2088 lhs->isTypeDependent() || rhs->isTypeDependent(),
2089 lhs->isValueDependent() || rhs->isValueDependent(),
2090 (lhs->isInstantiationDependent() ||
2091 rhs->isInstantiationDependent()),
2092 (lhs->containsUnexpandedParameterPack() ||
2093 rhs->containsUnexpandedParameterPack())),
2094 RBracketLoc(rbracketloc) {
2095 SubExprs[LHS] = lhs;
2096 SubExprs[RHS] = rhs;
2099 /// \brief Create an empty array subscript expression.
2100 explicit ArraySubscriptExpr(EmptyShell Shell)
2101 : Expr(ArraySubscriptExprClass, Shell) { }
2103 /// An array access can be written A[4] or 4[A] (both are equivalent).
2104 /// - getBase() and getIdx() always present the normalized view: A[4].
2105 /// In this case getBase() returns "A" and getIdx() returns "4".
2106 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2107 /// 4[A] getLHS() returns "4".
2108 /// Note: Because vector element access is also written A[4] we must
2109 /// predicate the format conversion in getBase and getIdx only on the
2110 /// the type of the RHS, as it is possible for the LHS to be a vector of
2112 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2113 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2114 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2116 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2117 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2118 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2121 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2124 const Expr *getBase() const {
2125 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2129 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2132 const Expr *getIdx() const {
2133 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2136 SourceLocation getLocStart() const LLVM_READONLY {
2137 return getLHS()->getLocStart();
2139 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2141 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2142 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2144 SourceLocation getExprLoc() const LLVM_READONLY {
2145 return getBase()->getExprLoc();
2148 static bool classof(const Stmt *T) {
2149 return T->getStmtClass() == ArraySubscriptExprClass;
2153 child_range children() {
2154 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2158 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2159 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2160 /// while its subclasses may represent alternative syntax that (semantically)
2161 /// results in a function call. For example, CXXOperatorCallExpr is
2162 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2163 /// "str1 + str2" to resolve to a function call.
2164 class CallExpr : public Expr {
2165 enum { FN=0, PREARGS_START=1 };
2168 SourceLocation RParenLoc;
2170 void updateDependenciesFromArg(Expr *Arg);
2173 // These versions of the constructor are for derived classes.
2174 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2175 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2176 ExprValueKind VK, SourceLocation rparenloc);
2177 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2178 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2179 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2182 Stmt *getPreArg(unsigned i) {
2183 assert(i < getNumPreArgs() && "Prearg access out of range!");
2184 return SubExprs[PREARGS_START+i];
2186 const Stmt *getPreArg(unsigned i) const {
2187 assert(i < getNumPreArgs() && "Prearg access out of range!");
2188 return SubExprs[PREARGS_START+i];
2190 void setPreArg(unsigned i, Stmt *PreArg) {
2191 assert(i < getNumPreArgs() && "Prearg access out of range!");
2192 SubExprs[PREARGS_START+i] = PreArg;
2195 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2198 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2199 ExprValueKind VK, SourceLocation rparenloc);
2201 /// \brief Build an empty call expression.
2202 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2204 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2205 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2206 void setCallee(Expr *F) { SubExprs[FN] = F; }
2208 Decl *getCalleeDecl();
2209 const Decl *getCalleeDecl() const {
2210 return const_cast<CallExpr*>(this)->getCalleeDecl();
2213 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2214 FunctionDecl *getDirectCallee();
2215 const FunctionDecl *getDirectCallee() const {
2216 return const_cast<CallExpr*>(this)->getDirectCallee();
2219 /// getNumArgs - Return the number of actual arguments to this call.
2221 unsigned getNumArgs() const { return NumArgs; }
2223 /// \brief Retrieve the call arguments.
2225 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2227 const Expr *const *getArgs() const {
2228 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2232 /// getArg - Return the specified argument.
2233 Expr *getArg(unsigned Arg) {
2234 assert(Arg < NumArgs && "Arg access out of range!");
2235 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2237 const Expr *getArg(unsigned Arg) const {
2238 assert(Arg < NumArgs && "Arg access out of range!");
2239 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2242 /// setArg - Set the specified argument.
2243 void setArg(unsigned Arg, Expr *ArgExpr) {
2244 assert(Arg < NumArgs && "Arg access out of range!");
2245 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2248 /// setNumArgs - This changes the number of arguments present in this call.
2249 /// Any orphaned expressions are deleted by this, and any new operands are set
2251 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2253 typedef ExprIterator arg_iterator;
2254 typedef ConstExprIterator const_arg_iterator;
2255 typedef llvm::iterator_range<arg_iterator> arg_range;
2256 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2258 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2259 arg_const_range arguments() const {
2260 return arg_const_range(arg_begin(), arg_end());
2263 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2264 arg_iterator arg_end() {
2265 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2267 const_arg_iterator arg_begin() const {
2268 return SubExprs+PREARGS_START+getNumPreArgs();
2270 const_arg_iterator arg_end() const {
2271 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2274 /// This method provides fast access to all the subexpressions of
2275 /// a CallExpr without going through the slower virtual child_iterator
2276 /// interface. This provides efficient reverse iteration of the
2277 /// subexpressions. This is currently used for CFG construction.
2278 ArrayRef<Stmt*> getRawSubExprs() {
2279 return llvm::makeArrayRef(SubExprs,
2280 getNumPreArgs() + PREARGS_START + getNumArgs());
2283 /// getNumCommas - Return the number of commas that must have been present in
2284 /// this function call.
2285 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2287 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2288 /// of the callee. If not, return 0.
2289 unsigned getBuiltinCallee() const;
2291 /// \brief Returns \c true if this is a call to a builtin which does not
2292 /// evaluate side-effects within its arguments.
2293 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2295 /// getCallReturnType - Get the return type of the call expr. This is not
2296 /// always the type of the expr itself, if the return type is a reference
2298 QualType getCallReturnType(const ASTContext &Ctx) const;
2300 SourceLocation getRParenLoc() const { return RParenLoc; }
2301 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2303 SourceLocation getLocStart() const LLVM_READONLY;
2304 SourceLocation getLocEnd() const LLVM_READONLY;
2306 static bool classof(const Stmt *T) {
2307 return T->getStmtClass() >= firstCallExprConstant &&
2308 T->getStmtClass() <= lastCallExprConstant;
2312 child_range children() {
2313 return child_range(&SubExprs[0],
2314 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2318 /// Extra data stored in some MemberExpr objects.
2319 struct MemberExprNameQualifier {
2320 /// \brief The nested-name-specifier that qualifies the name, including
2321 /// source-location information.
2322 NestedNameSpecifierLoc QualifierLoc;
2324 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2325 /// name qualifiers.
2326 DeclAccessPair FoundDecl;
2329 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2331 class MemberExpr final
2333 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2334 ASTTemplateKWAndArgsInfo,
2335 TemplateArgumentLoc> {
2336 /// Base - the expression for the base pointer or structure references. In
2337 /// X.F, this is "X".
2340 /// MemberDecl - This is the decl being referenced by the field/member name.
2341 /// In X.F, this is the decl referenced by F.
2342 ValueDecl *MemberDecl;
2344 /// MemberDNLoc - Provides source/type location info for the
2345 /// declaration name embedded in MemberDecl.
2346 DeclarationNameLoc MemberDNLoc;
2348 /// MemberLoc - This is the location of the member name.
2349 SourceLocation MemberLoc;
2351 /// This is the location of the -> or . in the expression.
2352 SourceLocation OperatorLoc;
2354 /// IsArrow - True if this is "X->F", false if this is "X.F".
2357 /// \brief True if this member expression used a nested-name-specifier to
2358 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2359 /// declaration. When true, a MemberExprNameQualifier
2360 /// structure is allocated immediately after the MemberExpr.
2361 bool HasQualifierOrFoundDecl : 1;
2363 /// \brief True if this member expression specified a template keyword
2364 /// and/or a template argument list explicitly, e.g., x->f<int>,
2365 /// x->template f, x->template f<int>.
2366 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2367 /// TemplateArguments (if any) are present.
2368 bool HasTemplateKWAndArgsInfo : 1;
2370 /// \brief True if this member expression refers to a method that
2371 /// was resolved from an overloaded set having size greater than 1.
2372 bool HadMultipleCandidates : 1;
2374 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2375 return HasQualifierOrFoundDecl ? 1 : 0;
2378 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2379 return HasTemplateKWAndArgsInfo ? 1 : 0;
2383 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2384 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2385 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2386 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2387 base->isValueDependent(), base->isInstantiationDependent(),
2388 base->containsUnexpandedParameterPack()),
2389 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2390 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2391 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2392 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2393 assert(memberdecl->getDeclName() == NameInfo.getName());
2396 // NOTE: this constructor should be used only when it is known that
2397 // the member name can not provide additional syntactic info
2398 // (i.e., source locations for C++ operator names or type source info
2399 // for constructors, destructors and conversion operators).
2400 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2401 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2402 ExprValueKind VK, ExprObjectKind OK)
2403 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2404 base->isValueDependent(), base->isInstantiationDependent(),
2405 base->containsUnexpandedParameterPack()),
2406 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2407 OperatorLoc(operatorloc), IsArrow(isarrow),
2408 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2409 HadMultipleCandidates(false) {}
2411 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2412 SourceLocation OperatorLoc,
2413 NestedNameSpecifierLoc QualifierLoc,
2414 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2415 DeclAccessPair founddecl,
2416 DeclarationNameInfo MemberNameInfo,
2417 const TemplateArgumentListInfo *targs, QualType ty,
2418 ExprValueKind VK, ExprObjectKind OK);
2420 void setBase(Expr *E) { Base = E; }
2421 Expr *getBase() const { return cast<Expr>(Base); }
2423 /// \brief Retrieve the member declaration to which this expression refers.
2425 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2426 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2427 ValueDecl *getMemberDecl() const { return MemberDecl; }
2428 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2430 /// \brief Retrieves the declaration found by lookup.
2431 DeclAccessPair getFoundDecl() const {
2432 if (!HasQualifierOrFoundDecl)
2433 return DeclAccessPair::make(getMemberDecl(),
2434 getMemberDecl()->getAccess());
2435 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2438 /// \brief Determines whether this member expression actually had
2439 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2441 bool hasQualifier() const { return getQualifier() != nullptr; }
2443 /// \brief If the member name was qualified, retrieves the
2444 /// nested-name-specifier that precedes the member name, with source-location
2446 NestedNameSpecifierLoc getQualifierLoc() const {
2447 if (!HasQualifierOrFoundDecl)
2448 return NestedNameSpecifierLoc();
2450 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2453 /// \brief If the member name was qualified, retrieves the
2454 /// nested-name-specifier that precedes the member name. Otherwise, returns
2456 NestedNameSpecifier *getQualifier() const {
2457 return getQualifierLoc().getNestedNameSpecifier();
2460 /// \brief Retrieve the location of the template keyword preceding
2461 /// the member name, if any.
2462 SourceLocation getTemplateKeywordLoc() const {
2463 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2464 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2467 /// \brief Retrieve the location of the left angle bracket starting the
2468 /// explicit template argument list following the member name, if any.
2469 SourceLocation getLAngleLoc() const {
2470 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2471 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2474 /// \brief Retrieve the location of the right angle bracket ending the
2475 /// explicit template argument list following the member name, if any.
2476 SourceLocation getRAngleLoc() const {
2477 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2478 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2481 /// Determines whether the member name was preceded by the template keyword.
2482 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2484 /// \brief Determines whether the member name was followed by an
2485 /// explicit template argument list.
2486 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2488 /// \brief Copies the template arguments (if present) into the given
2490 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2491 if (hasExplicitTemplateArgs())
2492 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2493 getTrailingObjects<TemplateArgumentLoc>(), List);
2496 /// \brief Retrieve the template arguments provided as part of this
2498 const TemplateArgumentLoc *getTemplateArgs() const {
2499 if (!hasExplicitTemplateArgs())
2502 return getTrailingObjects<TemplateArgumentLoc>();
2505 /// \brief Retrieve the number of template arguments provided as part of this
2507 unsigned getNumTemplateArgs() const {
2508 if (!hasExplicitTemplateArgs())
2511 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2514 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2515 return {getTemplateArgs(), getNumTemplateArgs()};
2518 /// \brief Retrieve the member declaration name info.
2519 DeclarationNameInfo getMemberNameInfo() const {
2520 return DeclarationNameInfo(MemberDecl->getDeclName(),
2521 MemberLoc, MemberDNLoc);
2524 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2526 bool isArrow() const { return IsArrow; }
2527 void setArrow(bool A) { IsArrow = A; }
2529 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2530 /// location of 'F'.
2531 SourceLocation getMemberLoc() const { return MemberLoc; }
2532 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2534 SourceLocation getLocStart() const LLVM_READONLY;
2535 SourceLocation getLocEnd() const LLVM_READONLY;
2537 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2539 /// \brief Determine whether the base of this explicit is implicit.
2540 bool isImplicitAccess() const {
2541 return getBase() && getBase()->isImplicitCXXThis();
2544 /// \brief Returns true if this member expression refers to a method that
2545 /// was resolved from an overloaded set having size greater than 1.
2546 bool hadMultipleCandidates() const {
2547 return HadMultipleCandidates;
2549 /// \brief Sets the flag telling whether this expression refers to
2550 /// a method that was resolved from an overloaded set having size
2552 void setHadMultipleCandidates(bool V = true) {
2553 HadMultipleCandidates = V;
2556 /// \brief Returns true if virtual dispatch is performed.
2557 /// If the member access is fully qualified, (i.e. X::f()), virtual
2558 /// dispatching is not performed. In -fapple-kext mode qualified
2559 /// calls to virtual method will still go through the vtable.
2560 bool performsVirtualDispatch(const LangOptions &LO) const {
2561 return LO.AppleKext || !hasQualifier();
2564 static bool classof(const Stmt *T) {
2565 return T->getStmtClass() == MemberExprClass;
2569 child_range children() { return child_range(&Base, &Base+1); }
2571 friend TrailingObjects;
2572 friend class ASTReader;
2573 friend class ASTStmtWriter;
2576 /// CompoundLiteralExpr - [C99 6.5.2.5]
2578 class CompoundLiteralExpr : public Expr {
2579 /// LParenLoc - If non-null, this is the location of the left paren in a
2580 /// compound literal like "(int){4}". This can be null if this is a
2581 /// synthesized compound expression.
2582 SourceLocation LParenLoc;
2584 /// The type as written. This can be an incomplete array type, in
2585 /// which case the actual expression type will be different.
2586 /// The int part of the pair stores whether this expr is file scope.
2587 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2590 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2591 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2592 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2593 tinfo->getType()->isDependentType(),
2594 init->isValueDependent(),
2595 (init->isInstantiationDependent() ||
2596 tinfo->getType()->isInstantiationDependentType()),
2597 init->containsUnexpandedParameterPack()),
2598 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2600 /// \brief Construct an empty compound literal.
2601 explicit CompoundLiteralExpr(EmptyShell Empty)
2602 : Expr(CompoundLiteralExprClass, Empty) { }
2604 const Expr *getInitializer() const { return cast<Expr>(Init); }
2605 Expr *getInitializer() { return cast<Expr>(Init); }
2606 void setInitializer(Expr *E) { Init = E; }
2608 bool isFileScope() const { return TInfoAndScope.getInt(); }
2609 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2611 SourceLocation getLParenLoc() const { return LParenLoc; }
2612 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2614 TypeSourceInfo *getTypeSourceInfo() const {
2615 return TInfoAndScope.getPointer();
2617 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2618 TInfoAndScope.setPointer(tinfo);
2621 SourceLocation getLocStart() const LLVM_READONLY {
2622 // FIXME: Init should never be null.
2624 return SourceLocation();
2625 if (LParenLoc.isInvalid())
2626 return Init->getLocStart();
2629 SourceLocation getLocEnd() const LLVM_READONLY {
2630 // FIXME: Init should never be null.
2632 return SourceLocation();
2633 return Init->getLocEnd();
2636 static bool classof(const Stmt *T) {
2637 return T->getStmtClass() == CompoundLiteralExprClass;
2641 child_range children() { return child_range(&Init, &Init+1); }
2644 /// CastExpr - Base class for type casts, including both implicit
2645 /// casts (ImplicitCastExpr) and explicit casts that have some
2646 /// representation in the source code (ExplicitCastExpr's derived
2648 class CastExpr : public Expr {
2652 bool CastConsistency() const;
2654 const CXXBaseSpecifier * const *path_buffer() const {
2655 return const_cast<CastExpr*>(this)->path_buffer();
2657 CXXBaseSpecifier **path_buffer();
2659 void setBasePathSize(unsigned basePathSize) {
2660 CastExprBits.BasePathSize = basePathSize;
2661 assert(CastExprBits.BasePathSize == basePathSize &&
2662 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2666 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2667 Expr *op, unsigned BasePathSize)
2668 : Expr(SC, ty, VK, OK_Ordinary,
2669 // Cast expressions are type-dependent if the type is
2670 // dependent (C++ [temp.dep.expr]p3).
2671 ty->isDependentType(),
2672 // Cast expressions are value-dependent if the type is
2673 // dependent or if the subexpression is value-dependent.
2674 ty->isDependentType() || (op && op->isValueDependent()),
2675 (ty->isInstantiationDependentType() ||
2676 (op && op->isInstantiationDependent())),
2677 // An implicit cast expression doesn't (lexically) contain an
2678 // unexpanded pack, even if its target type does.
2679 ((SC != ImplicitCastExprClass &&
2680 ty->containsUnexpandedParameterPack()) ||
2681 (op && op->containsUnexpandedParameterPack()))),
2683 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2684 CastExprBits.Kind = kind;
2685 setBasePathSize(BasePathSize);
2686 assert(CastConsistency());
2689 /// \brief Construct an empty cast.
2690 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2692 setBasePathSize(BasePathSize);
2696 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2697 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2698 const char *getCastKindName() const;
2700 Expr *getSubExpr() { return cast<Expr>(Op); }
2701 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2702 void setSubExpr(Expr *E) { Op = E; }
2704 /// \brief Retrieve the cast subexpression as it was written in the source
2705 /// code, looking through any implicit casts or other intermediate nodes
2706 /// introduced by semantic analysis.
2707 Expr *getSubExprAsWritten();
2708 const Expr *getSubExprAsWritten() const {
2709 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2712 typedef CXXBaseSpecifier **path_iterator;
2713 typedef const CXXBaseSpecifier * const *path_const_iterator;
2714 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2715 unsigned path_size() const { return CastExprBits.BasePathSize; }
2716 path_iterator path_begin() { return path_buffer(); }
2717 path_iterator path_end() { return path_buffer() + path_size(); }
2718 path_const_iterator path_begin() const { return path_buffer(); }
2719 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2721 static bool classof(const Stmt *T) {
2722 return T->getStmtClass() >= firstCastExprConstant &&
2723 T->getStmtClass() <= lastCastExprConstant;
2727 child_range children() { return child_range(&Op, &Op+1); }
2730 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2731 /// conversions, which have no direct representation in the original
2732 /// source code. For example: converting T[]->T*, void f()->void
2733 /// (*f)(), float->double, short->int, etc.
2735 /// In C, implicit casts always produce rvalues. However, in C++, an
2736 /// implicit cast whose result is being bound to a reference will be
2737 /// an lvalue or xvalue. For example:
2741 /// class Derived : public Base { };
2742 /// Derived &&ref();
2743 /// void f(Derived d) {
2744 /// Base& b = d; // initializer is an ImplicitCastExpr
2745 /// // to an lvalue of type Base
2746 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2747 /// // to an xvalue of type Base
2750 class ImplicitCastExpr final
2752 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2754 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2755 unsigned BasePathLength, ExprValueKind VK)
2756 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2759 /// \brief Construct an empty implicit cast.
2760 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2761 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2764 enum OnStack_t { OnStack };
2765 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2767 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2770 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2771 CastKind Kind, Expr *Operand,
2772 const CXXCastPath *BasePath,
2775 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2778 SourceLocation getLocStart() const LLVM_READONLY {
2779 return getSubExpr()->getLocStart();
2781 SourceLocation getLocEnd() const LLVM_READONLY {
2782 return getSubExpr()->getLocEnd();
2785 static bool classof(const Stmt *T) {
2786 return T->getStmtClass() == ImplicitCastExprClass;
2789 friend TrailingObjects;
2790 friend class CastExpr;
2793 inline Expr *Expr::IgnoreImpCasts() {
2795 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2796 e = ice->getSubExpr();
2800 /// ExplicitCastExpr - An explicit cast written in the source
2803 /// This class is effectively an abstract class, because it provides
2804 /// the basic representation of an explicitly-written cast without
2805 /// specifying which kind of cast (C cast, functional cast, static
2806 /// cast, etc.) was written; specific derived classes represent the
2807 /// particular style of cast and its location information.
2809 /// Unlike implicit casts, explicit cast nodes have two different
2810 /// types: the type that was written into the source code, and the
2811 /// actual type of the expression as determined by semantic
2812 /// analysis. These types may differ slightly. For example, in C++ one
2813 /// can cast to a reference type, which indicates that the resulting
2814 /// expression will be an lvalue or xvalue. The reference type, however,
2815 /// will not be used as the type of the expression.
2816 class ExplicitCastExpr : public CastExpr {
2817 /// TInfo - Source type info for the (written) type
2818 /// this expression is casting to.
2819 TypeSourceInfo *TInfo;
2822 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2823 CastKind kind, Expr *op, unsigned PathSize,
2824 TypeSourceInfo *writtenTy)
2825 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2827 /// \brief Construct an empty explicit cast.
2828 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2829 : CastExpr(SC, Shell, PathSize) { }
2832 /// getTypeInfoAsWritten - Returns the type source info for the type
2833 /// that this expression is casting to.
2834 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2835 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2837 /// getTypeAsWritten - Returns the type that this expression is
2838 /// casting to, as written in the source code.
2839 QualType getTypeAsWritten() const { return TInfo->getType(); }
2841 static bool classof(const Stmt *T) {
2842 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2843 T->getStmtClass() <= lastExplicitCastExprConstant;
2847 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2848 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2849 /// (Type)expr. For example: @c (int)f.
2850 class CStyleCastExpr final
2851 : public ExplicitCastExpr,
2852 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2853 SourceLocation LPLoc; // the location of the left paren
2854 SourceLocation RPLoc; // the location of the right paren
2856 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2857 unsigned PathSize, TypeSourceInfo *writtenTy,
2858 SourceLocation l, SourceLocation r)
2859 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2860 writtenTy), LPLoc(l), RPLoc(r) {}
2862 /// \brief Construct an empty C-style explicit cast.
2863 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2864 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2867 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2868 ExprValueKind VK, CastKind K,
2869 Expr *Op, const CXXCastPath *BasePath,
2870 TypeSourceInfo *WrittenTy, SourceLocation L,
2873 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2876 SourceLocation getLParenLoc() const { return LPLoc; }
2877 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2879 SourceLocation getRParenLoc() const { return RPLoc; }
2880 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2882 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2883 SourceLocation getLocEnd() const LLVM_READONLY {
2884 return getSubExpr()->getLocEnd();
2887 static bool classof(const Stmt *T) {
2888 return T->getStmtClass() == CStyleCastExprClass;
2891 friend TrailingObjects;
2892 friend class CastExpr;
2895 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2897 /// This expression node kind describes a builtin binary operation,
2898 /// such as "x + y" for integer values "x" and "y". The operands will
2899 /// already have been converted to appropriate types (e.g., by
2900 /// performing promotions or conversions).
2902 /// In C++, where operators may be overloaded, a different kind of
2903 /// expression node (CXXOperatorCallExpr) is used to express the
2904 /// invocation of an overloaded operator with operator syntax. Within
2905 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2906 /// used to store an expression "x + y" depends on the subexpressions
2907 /// for x and y. If neither x or y is type-dependent, and the "+"
2908 /// operator resolves to a built-in operation, BinaryOperator will be
2909 /// used to express the computation (x and y may still be
2910 /// value-dependent). If either x or y is type-dependent, or if the
2911 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2912 /// be used to express the computation.
2913 class BinaryOperator : public Expr {
2915 typedef BinaryOperatorKind Opcode;
2920 // Records the FP_CONTRACT pragma status at the point that this binary
2921 // operator was parsed. This bit is only meaningful for operations on
2922 // floating point types. For all other types it should default to
2924 unsigned FPContractable : 1;
2925 SourceLocation OpLoc;
2927 enum { LHS, RHS, END_EXPR };
2928 Stmt* SubExprs[END_EXPR];
2931 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2932 ExprValueKind VK, ExprObjectKind OK,
2933 SourceLocation opLoc, bool fpContractable)
2934 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2935 lhs->isTypeDependent() || rhs->isTypeDependent(),
2936 lhs->isValueDependent() || rhs->isValueDependent(),
2937 (lhs->isInstantiationDependent() ||
2938 rhs->isInstantiationDependent()),
2939 (lhs->containsUnexpandedParameterPack() ||
2940 rhs->containsUnexpandedParameterPack())),
2941 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2942 SubExprs[LHS] = lhs;
2943 SubExprs[RHS] = rhs;
2944 assert(!isCompoundAssignmentOp() &&
2945 "Use CompoundAssignOperator for compound assignments");
2948 /// \brief Construct an empty binary operator.
2949 explicit BinaryOperator(EmptyShell Empty)
2950 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2952 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2953 SourceLocation getOperatorLoc() const { return OpLoc; }
2954 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2956 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2957 void setOpcode(Opcode O) { Opc = O; }
2959 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2960 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2961 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2962 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2964 SourceLocation getLocStart() const LLVM_READONLY {
2965 return getLHS()->getLocStart();
2967 SourceLocation getLocEnd() const LLVM_READONLY {
2968 return getRHS()->getLocEnd();
2971 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2972 /// corresponds to, e.g. "<<=".
2973 static StringRef getOpcodeStr(Opcode Op);
2975 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2977 /// \brief Retrieve the binary opcode that corresponds to the given
2978 /// overloaded operator.
2979 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2981 /// \brief Retrieve the overloaded operator kind that corresponds to
2982 /// the given binary opcode.
2983 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2985 /// predicates to categorize the respective opcodes.
2986 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2987 static bool isMultiplicativeOp(Opcode Opc) {
2988 return Opc >= BO_Mul && Opc <= BO_Rem;
2990 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
2991 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2992 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2993 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2994 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2996 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2997 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2999 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3000 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3002 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3003 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3005 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
3006 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3008 static Opcode negateComparisonOp(Opcode Opc) {
3011 llvm_unreachable("Not a comparsion operator.");
3012 case BO_LT: return BO_GE;
3013 case BO_GT: return BO_LE;
3014 case BO_LE: return BO_GT;
3015 case BO_GE: return BO_LT;
3016 case BO_EQ: return BO_NE;
3017 case BO_NE: return BO_EQ;
3021 static Opcode reverseComparisonOp(Opcode Opc) {
3024 llvm_unreachable("Not a comparsion operator.");
3025 case BO_LT: return BO_GT;
3026 case BO_GT: return BO_LT;
3027 case BO_LE: return BO_GE;
3028 case BO_GE: return BO_LE;
3035 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3036 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3038 static bool isAssignmentOp(Opcode Opc) {
3039 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3041 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3043 static bool isCompoundAssignmentOp(Opcode Opc) {
3044 return Opc > BO_Assign && Opc <= BO_OrAssign;
3046 bool isCompoundAssignmentOp() const {
3047 return isCompoundAssignmentOp(getOpcode());
3049 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3050 assert(isCompoundAssignmentOp(Opc));
3051 if (Opc >= BO_AndAssign)
3052 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3054 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3057 static bool isShiftAssignOp(Opcode Opc) {
3058 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3060 bool isShiftAssignOp() const {
3061 return isShiftAssignOp(getOpcode());
3064 static bool classof(const Stmt *S) {
3065 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3066 S->getStmtClass() <= lastBinaryOperatorConstant;
3070 child_range children() {
3071 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3074 // Set the FP contractability status of this operator. Only meaningful for
3075 // operations on floating point types.
3076 void setFPContractable(bool FPC) { FPContractable = FPC; }
3078 // Get the FP contractability status of this operator. Only meaningful for
3079 // operations on floating point types.
3080 bool isFPContractable() const { return FPContractable; }
3083 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3084 ExprValueKind VK, ExprObjectKind OK,
3085 SourceLocation opLoc, bool fpContractable, bool dead2)
3086 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3087 lhs->isTypeDependent() || rhs->isTypeDependent(),
3088 lhs->isValueDependent() || rhs->isValueDependent(),
3089 (lhs->isInstantiationDependent() ||
3090 rhs->isInstantiationDependent()),
3091 (lhs->containsUnexpandedParameterPack() ||
3092 rhs->containsUnexpandedParameterPack())),
3093 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3094 SubExprs[LHS] = lhs;
3095 SubExprs[RHS] = rhs;
3098 BinaryOperator(StmtClass SC, EmptyShell Empty)
3099 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3102 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3103 /// track of the type the operation is performed in. Due to the semantics of
3104 /// these operators, the operands are promoted, the arithmetic performed, an
3105 /// implicit conversion back to the result type done, then the assignment takes
3106 /// place. This captures the intermediate type which the computation is done
3108 class CompoundAssignOperator : public BinaryOperator {
3109 QualType ComputationLHSType;
3110 QualType ComputationResultType;
3112 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3113 ExprValueKind VK, ExprObjectKind OK,
3114 QualType CompLHSType, QualType CompResultType,
3115 SourceLocation OpLoc, bool fpContractable)
3116 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3118 ComputationLHSType(CompLHSType),
3119 ComputationResultType(CompResultType) {
3120 assert(isCompoundAssignmentOp() &&
3121 "Only should be used for compound assignments");
3124 /// \brief Build an empty compound assignment operator expression.
3125 explicit CompoundAssignOperator(EmptyShell Empty)
3126 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3128 // The two computation types are the type the LHS is converted
3129 // to for the computation and the type of the result; the two are
3130 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3131 QualType getComputationLHSType() const { return ComputationLHSType; }
3132 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3134 QualType getComputationResultType() const { return ComputationResultType; }
3135 void setComputationResultType(QualType T) { ComputationResultType = T; }
3137 static bool classof(const Stmt *S) {
3138 return S->getStmtClass() == CompoundAssignOperatorClass;
3142 /// AbstractConditionalOperator - An abstract base class for
3143 /// ConditionalOperator and BinaryConditionalOperator.
3144 class AbstractConditionalOperator : public Expr {
3145 SourceLocation QuestionLoc, ColonLoc;
3146 friend class ASTStmtReader;
3149 AbstractConditionalOperator(StmtClass SC, QualType T,
3150 ExprValueKind VK, ExprObjectKind OK,
3151 bool TD, bool VD, bool ID,
3152 bool ContainsUnexpandedParameterPack,
3153 SourceLocation qloc,
3154 SourceLocation cloc)
3155 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3156 QuestionLoc(qloc), ColonLoc(cloc) {}
3158 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3159 : Expr(SC, Empty) { }
3162 // getCond - Return the expression representing the condition for
3164 Expr *getCond() const;
3166 // getTrueExpr - Return the subexpression representing the value of
3167 // the expression if the condition evaluates to true.
3168 Expr *getTrueExpr() const;
3170 // getFalseExpr - Return the subexpression representing the value of
3171 // the expression if the condition evaluates to false. This is
3172 // the same as getRHS.
3173 Expr *getFalseExpr() const;
3175 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3176 SourceLocation getColonLoc() const { return ColonLoc; }
3178 static bool classof(const Stmt *T) {
3179 return T->getStmtClass() == ConditionalOperatorClass ||
3180 T->getStmtClass() == BinaryConditionalOperatorClass;
3184 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3185 /// middle" extension is a BinaryConditionalOperator.
3186 class ConditionalOperator : public AbstractConditionalOperator {
3187 enum { COND, LHS, RHS, END_EXPR };
3188 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3190 friend class ASTStmtReader;
3192 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3193 SourceLocation CLoc, Expr *rhs,
3194 QualType t, ExprValueKind VK, ExprObjectKind OK)
3195 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3196 // FIXME: the type of the conditional operator doesn't
3197 // depend on the type of the conditional, but the standard
3198 // seems to imply that it could. File a bug!
3199 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3200 (cond->isValueDependent() || lhs->isValueDependent() ||
3201 rhs->isValueDependent()),
3202 (cond->isInstantiationDependent() ||
3203 lhs->isInstantiationDependent() ||
3204 rhs->isInstantiationDependent()),
3205 (cond->containsUnexpandedParameterPack() ||
3206 lhs->containsUnexpandedParameterPack() ||
3207 rhs->containsUnexpandedParameterPack()),
3209 SubExprs[COND] = cond;
3210 SubExprs[LHS] = lhs;
3211 SubExprs[RHS] = rhs;
3214 /// \brief Build an empty conditional operator.
3215 explicit ConditionalOperator(EmptyShell Empty)
3216 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3218 // getCond - Return the expression representing the condition for
3220 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3222 // getTrueExpr - Return the subexpression representing the value of
3223 // the expression if the condition evaluates to true.
3224 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3226 // getFalseExpr - Return the subexpression representing the value of
3227 // the expression if the condition evaluates to false. This is
3228 // the same as getRHS.
3229 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3231 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3232 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3234 SourceLocation getLocStart() const LLVM_READONLY {
3235 return getCond()->getLocStart();
3237 SourceLocation getLocEnd() const LLVM_READONLY {
3238 return getRHS()->getLocEnd();
3241 static bool classof(const Stmt *T) {
3242 return T->getStmtClass() == ConditionalOperatorClass;
3246 child_range children() {
3247 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3251 /// BinaryConditionalOperator - The GNU extension to the conditional
3252 /// operator which allows the middle operand to be omitted.
3254 /// This is a different expression kind on the assumption that almost
3255 /// every client ends up needing to know that these are different.
3256 class BinaryConditionalOperator : public AbstractConditionalOperator {
3257 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3259 /// - the common condition/left-hand-side expression, which will be
3260 /// evaluated as the opaque value
3261 /// - the condition, expressed in terms of the opaque value
3262 /// - the left-hand-side, expressed in terms of the opaque value
3263 /// - the right-hand-side
3264 Stmt *SubExprs[NUM_SUBEXPRS];
3265 OpaqueValueExpr *OpaqueValue;
3267 friend class ASTStmtReader;
3269 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3270 Expr *cond, Expr *lhs, Expr *rhs,
3271 SourceLocation qloc, SourceLocation cloc,
3272 QualType t, ExprValueKind VK, ExprObjectKind OK)
3273 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3274 (common->isTypeDependent() || rhs->isTypeDependent()),
3275 (common->isValueDependent() || rhs->isValueDependent()),
3276 (common->isInstantiationDependent() ||
3277 rhs->isInstantiationDependent()),
3278 (common->containsUnexpandedParameterPack() ||
3279 rhs->containsUnexpandedParameterPack()),
3281 OpaqueValue(opaqueValue) {
3282 SubExprs[COMMON] = common;
3283 SubExprs[COND] = cond;
3284 SubExprs[LHS] = lhs;
3285 SubExprs[RHS] = rhs;
3286 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3289 /// \brief Build an empty conditional operator.
3290 explicit BinaryConditionalOperator(EmptyShell Empty)
3291 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3293 /// \brief getCommon - Return the common expression, written to the
3294 /// left of the condition. The opaque value will be bound to the
3295 /// result of this expression.
3296 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3298 /// \brief getOpaqueValue - Return the opaque value placeholder.
3299 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3301 /// \brief getCond - Return the condition expression; this is defined
3302 /// in terms of the opaque value.
3303 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3305 /// \brief getTrueExpr - Return the subexpression which will be
3306 /// evaluated if the condition evaluates to true; this is defined
3307 /// in terms of the opaque value.
3308 Expr *getTrueExpr() const {
3309 return cast<Expr>(SubExprs[LHS]);
3312 /// \brief getFalseExpr - Return the subexpression which will be
3313 /// evaluated if the condnition evaluates to false; this is
3314 /// defined in terms of the opaque value.
3315 Expr *getFalseExpr() const {
3316 return cast<Expr>(SubExprs[RHS]);
3319 SourceLocation getLocStart() const LLVM_READONLY {
3320 return getCommon()->getLocStart();
3322 SourceLocation getLocEnd() const LLVM_READONLY {
3323 return getFalseExpr()->getLocEnd();
3326 static bool classof(const Stmt *T) {
3327 return T->getStmtClass() == BinaryConditionalOperatorClass;
3331 child_range children() {
3332 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3336 inline Expr *AbstractConditionalOperator::getCond() const {
3337 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3338 return co->getCond();
3339 return cast<BinaryConditionalOperator>(this)->getCond();
3342 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3343 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3344 return co->getTrueExpr();
3345 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3348 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3349 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3350 return co->getFalseExpr();
3351 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3354 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3355 class AddrLabelExpr : public Expr {
3356 SourceLocation AmpAmpLoc, LabelLoc;
3359 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3361 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3363 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3365 /// \brief Build an empty address of a label expression.
3366 explicit AddrLabelExpr(EmptyShell Empty)
3367 : Expr(AddrLabelExprClass, Empty) { }
3369 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3370 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3371 SourceLocation getLabelLoc() const { return LabelLoc; }
3372 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3374 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3375 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3377 LabelDecl *getLabel() const { return Label; }
3378 void setLabel(LabelDecl *L) { Label = L; }
3380 static bool classof(const Stmt *T) {
3381 return T->getStmtClass() == AddrLabelExprClass;
3385 child_range children() {
3386 return child_range(child_iterator(), child_iterator());
3390 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3391 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3392 /// takes the value of the last subexpression.
3394 /// A StmtExpr is always an r-value; values "returned" out of a
3395 /// StmtExpr will be copied.
3396 class StmtExpr : public Expr {
3398 SourceLocation LParenLoc, RParenLoc;
3400 // FIXME: Does type-dependence need to be computed differently?
3401 // FIXME: Do we need to compute instantiation instantiation-dependence for
3402 // statements? (ugh!)
3403 StmtExpr(CompoundStmt *substmt, QualType T,
3404 SourceLocation lp, SourceLocation rp) :
3405 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3406 T->isDependentType(), false, false, false),
3407 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3409 /// \brief Build an empty statement expression.
3410 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3412 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3413 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3414 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3416 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3417 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3419 SourceLocation getLParenLoc() const { return LParenLoc; }
3420 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3421 SourceLocation getRParenLoc() const { return RParenLoc; }
3422 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3424 static bool classof(const Stmt *T) {
3425 return T->getStmtClass() == StmtExprClass;
3429 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3432 /// ShuffleVectorExpr - clang-specific builtin-in function
3433 /// __builtin_shufflevector.
3434 /// This AST node represents a operator that does a constant
3435 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3436 /// two vectors and a variable number of constant indices,
3437 /// and returns the appropriately shuffled vector.
3438 class ShuffleVectorExpr : public Expr {
3439 SourceLocation BuiltinLoc, RParenLoc;
3441 // SubExprs - the list of values passed to the __builtin_shufflevector
3442 // function. The first two are vectors, and the rest are constant
3443 // indices. The number of values in this list is always
3444 // 2+the number of indices in the vector type.
3449 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3450 SourceLocation BLoc, SourceLocation RP);
3452 /// \brief Build an empty vector-shuffle expression.
3453 explicit ShuffleVectorExpr(EmptyShell Empty)
3454 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3456 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3457 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3459 SourceLocation getRParenLoc() const { return RParenLoc; }
3460 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3462 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3463 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3465 static bool classof(const Stmt *T) {
3466 return T->getStmtClass() == ShuffleVectorExprClass;
3469 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3470 /// constant expression, the actual arguments passed in, and the function
3472 unsigned getNumSubExprs() const { return NumExprs; }
3474 /// \brief Retrieve the array of expressions.
3475 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3477 /// getExpr - Return the Expr at the specified index.
3478 Expr *getExpr(unsigned Index) {
3479 assert((Index < NumExprs) && "Arg access out of range!");
3480 return cast<Expr>(SubExprs[Index]);
3482 const Expr *getExpr(unsigned Index) const {
3483 assert((Index < NumExprs) && "Arg access out of range!");
3484 return cast<Expr>(SubExprs[Index]);
3487 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3489 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3490 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3491 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3495 child_range children() {
3496 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3500 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3501 /// This AST node provides support for converting a vector type to another
3502 /// vector type of the same arity.
3503 class ConvertVectorExpr : public Expr {
3506 TypeSourceInfo *TInfo;
3507 SourceLocation BuiltinLoc, RParenLoc;
3509 friend class ASTReader;
3510 friend class ASTStmtReader;
3511 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3514 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3515 ExprValueKind VK, ExprObjectKind OK,
3516 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3517 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3518 DstType->isDependentType(),
3519 DstType->isDependentType() || SrcExpr->isValueDependent(),
3520 (DstType->isInstantiationDependentType() ||
3521 SrcExpr->isInstantiationDependent()),
3522 (DstType->containsUnexpandedParameterPack() ||
3523 SrcExpr->containsUnexpandedParameterPack())),
3524 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3526 /// getSrcExpr - Return the Expr to be converted.
3527 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3529 /// getTypeSourceInfo - Return the destination type.
3530 TypeSourceInfo *getTypeSourceInfo() const {
3533 void setTypeSourceInfo(TypeSourceInfo *ti) {
3537 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3538 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3540 /// getRParenLoc - Return the location of final right parenthesis.
3541 SourceLocation getRParenLoc() const { return RParenLoc; }
3543 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3544 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3546 static bool classof(const Stmt *T) {
3547 return T->getStmtClass() == ConvertVectorExprClass;
3551 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3554 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3555 /// This AST node is similar to the conditional operator (?:) in C, with
3556 /// the following exceptions:
3557 /// - the test expression must be a integer constant expression.
3558 /// - the expression returned acts like the chosen subexpression in every
3559 /// visible way: the type is the same as that of the chosen subexpression,
3560 /// and all predicates (whether it's an l-value, whether it's an integer
3561 /// constant expression, etc.) return the same result as for the chosen
3563 class ChooseExpr : public Expr {
3564 enum { COND, LHS, RHS, END_EXPR };
3565 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3566 SourceLocation BuiltinLoc, RParenLoc;
3569 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3570 QualType t, ExprValueKind VK, ExprObjectKind OK,
3571 SourceLocation RP, bool condIsTrue,
3572 bool TypeDependent, bool ValueDependent)
3573 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3574 (cond->isInstantiationDependent() ||
3575 lhs->isInstantiationDependent() ||
3576 rhs->isInstantiationDependent()),
3577 (cond->containsUnexpandedParameterPack() ||
3578 lhs->containsUnexpandedParameterPack() ||
3579 rhs->containsUnexpandedParameterPack())),
3580 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3581 SubExprs[COND] = cond;
3582 SubExprs[LHS] = lhs;
3583 SubExprs[RHS] = rhs;
3586 /// \brief Build an empty __builtin_choose_expr.
3587 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3589 /// isConditionTrue - Return whether the condition is true (i.e. not
3591 bool isConditionTrue() const {
3592 assert(!isConditionDependent() &&
3593 "Dependent condition isn't true or false");
3596 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3598 bool isConditionDependent() const {
3599 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3602 /// getChosenSubExpr - Return the subexpression chosen according to the
3604 Expr *getChosenSubExpr() const {
3605 return isConditionTrue() ? getLHS() : getRHS();
3608 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3609 void setCond(Expr *E) { SubExprs[COND] = E; }
3610 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3611 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3612 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3613 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3615 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3616 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3618 SourceLocation getRParenLoc() const { return RParenLoc; }
3619 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3621 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3622 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3624 static bool classof(const Stmt *T) {
3625 return T->getStmtClass() == ChooseExprClass;
3629 child_range children() {
3630 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3634 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3635 /// for a null pointer constant that has integral type (e.g., int or
3636 /// long) and is the same size and alignment as a pointer. The __null
3637 /// extension is typically only used by system headers, which define
3638 /// NULL as __null in C++ rather than using 0 (which is an integer
3639 /// that may not match the size of a pointer).
3640 class GNUNullExpr : public Expr {
3641 /// TokenLoc - The location of the __null keyword.
3642 SourceLocation TokenLoc;
3645 GNUNullExpr(QualType Ty, SourceLocation Loc)
3646 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3650 /// \brief Build an empty GNU __null expression.
3651 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3653 /// getTokenLocation - The location of the __null token.
3654 SourceLocation getTokenLocation() const { return TokenLoc; }
3655 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3657 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3658 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3660 static bool classof(const Stmt *T) {
3661 return T->getStmtClass() == GNUNullExprClass;
3665 child_range children() {
3666 return child_range(child_iterator(), child_iterator());
3670 /// Represents a call to the builtin function \c __builtin_va_arg.
3671 class VAArgExpr : public Expr {
3673 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3674 SourceLocation BuiltinLoc, RParenLoc;
3676 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3677 SourceLocation RPLoc, QualType t, bool IsMS)
3678 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3679 false, (TInfo->getType()->isInstantiationDependentType() ||
3680 e->isInstantiationDependent()),
3681 (TInfo->getType()->containsUnexpandedParameterPack() ||
3682 e->containsUnexpandedParameterPack())),
3683 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3685 /// Create an empty __builtin_va_arg expression.
3686 explicit VAArgExpr(EmptyShell Empty)
3687 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3689 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3690 Expr *getSubExpr() { return cast<Expr>(Val); }
3691 void setSubExpr(Expr *E) { Val = E; }
3693 /// Returns whether this is really a Win64 ABI va_arg expression.
3694 bool isMicrosoftABI() const { return TInfo.getInt(); }
3695 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3697 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3698 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3700 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3701 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3703 SourceLocation getRParenLoc() const { return RParenLoc; }
3704 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3706 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3707 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3709 static bool classof(const Stmt *T) {
3710 return T->getStmtClass() == VAArgExprClass;
3714 child_range children() { return child_range(&Val, &Val+1); }
3717 /// @brief Describes an C or C++ initializer list.
3719 /// InitListExpr describes an initializer list, which can be used to
3720 /// initialize objects of different types, including
3721 /// struct/class/union types, arrays, and vectors. For example:
3724 /// struct foo x = { 1, { 2, 3 } };
3727 /// Prior to semantic analysis, an initializer list will represent the
3728 /// initializer list as written by the user, but will have the
3729 /// placeholder type "void". This initializer list is called the
3730 /// syntactic form of the initializer, and may contain C99 designated
3731 /// initializers (represented as DesignatedInitExprs), initializations
3732 /// of subobject members without explicit braces, and so on. Clients
3733 /// interested in the original syntax of the initializer list should
3734 /// use the syntactic form of the initializer list.
3736 /// After semantic analysis, the initializer list will represent the
3737 /// semantic form of the initializer, where the initializations of all
3738 /// subobjects are made explicit with nested InitListExpr nodes and
3739 /// C99 designators have been eliminated by placing the designated
3740 /// initializations into the subobject they initialize. Additionally,
3741 /// any "holes" in the initialization, where no initializer has been
3742 /// specified for a particular subobject, will be replaced with
3743 /// implicitly-generated ImplicitValueInitExpr expressions that
3744 /// value-initialize the subobjects. Note, however, that the
3745 /// initializer lists may still have fewer initializers than there are
3746 /// elements to initialize within the object.
3748 /// After semantic analysis has completed, given an initializer list,
3749 /// method isSemanticForm() returns true if and only if this is the
3750 /// semantic form of the initializer list (note: the same AST node
3751 /// may at the same time be the syntactic form).
3752 /// Given the semantic form of the initializer list, one can retrieve
3753 /// the syntactic form of that initializer list (when different)
3754 /// using method getSyntacticForm(); the method returns null if applied
3755 /// to a initializer list which is already in syntactic form.
3756 /// Similarly, given the syntactic form (i.e., an initializer list such
3757 /// that isSemanticForm() returns false), one can retrieve the semantic
3758 /// form using method getSemanticForm().
3759 /// Since many initializer lists have the same syntactic and semantic forms,
3760 /// getSyntacticForm() may return NULL, indicating that the current
3761 /// semantic initializer list also serves as its syntactic form.
3762 class InitListExpr : public Expr {
3763 // FIXME: Eliminate this vector in favor of ASTContext allocation
3764 typedef ASTVector<Stmt *> InitExprsTy;
3765 InitExprsTy InitExprs;
3766 SourceLocation LBraceLoc, RBraceLoc;
3768 /// The alternative form of the initializer list (if it exists).
3769 /// The int part of the pair stores whether this initializer list is
3770 /// in semantic form. If not null, the pointer points to:
3771 /// - the syntactic form, if this is in semantic form;
3772 /// - the semantic form, if this is in syntactic form.
3773 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3776 /// If this initializer list initializes an array with more elements than
3777 /// there are initializers in the list, specifies an expression to be used
3778 /// for value initialization of the rest of the elements.
3780 /// If this initializer list initializes a union, specifies which
3781 /// field within the union will be initialized.
3782 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3785 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3786 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3788 /// \brief Build an empty initializer list.
3789 explicit InitListExpr(EmptyShell Empty)
3790 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
3792 unsigned getNumInits() const { return InitExprs.size(); }
3794 /// \brief Retrieve the set of initializers.
3795 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3797 /// \brief Retrieve the set of initializers.
3798 Expr * const *getInits() const {
3799 return reinterpret_cast<Expr * const *>(InitExprs.data());
3802 ArrayRef<Expr *> inits() {
3803 return llvm::makeArrayRef(getInits(), getNumInits());
3806 ArrayRef<Expr *> inits() const {
3807 return llvm::makeArrayRef(getInits(), getNumInits());
3810 const Expr *getInit(unsigned Init) const {
3811 assert(Init < getNumInits() && "Initializer access out of range!");
3812 return cast_or_null<Expr>(InitExprs[Init]);
3815 Expr *getInit(unsigned Init) {
3816 assert(Init < getNumInits() && "Initializer access out of range!");
3817 return cast_or_null<Expr>(InitExprs[Init]);
3820 void setInit(unsigned Init, Expr *expr) {
3821 assert(Init < getNumInits() && "Initializer access out of range!");
3822 InitExprs[Init] = expr;
3825 ExprBits.TypeDependent |= expr->isTypeDependent();
3826 ExprBits.ValueDependent |= expr->isValueDependent();
3827 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3828 ExprBits.ContainsUnexpandedParameterPack |=
3829 expr->containsUnexpandedParameterPack();
3833 /// \brief Reserve space for some number of initializers.
3834 void reserveInits(const ASTContext &C, unsigned NumInits);
3836 /// @brief Specify the number of initializers
3838 /// If there are more than @p NumInits initializers, the remaining
3839 /// initializers will be destroyed. If there are fewer than @p
3840 /// NumInits initializers, NULL expressions will be added for the
3841 /// unknown initializers.
3842 void resizeInits(const ASTContext &Context, unsigned NumInits);
3844 /// @brief Updates the initializer at index @p Init with the new
3845 /// expression @p expr, and returns the old expression at that
3848 /// When @p Init is out of range for this initializer list, the
3849 /// initializer list will be extended with NULL expressions to
3850 /// accommodate the new entry.
3851 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3853 /// \brief If this initializer list initializes an array with more elements
3854 /// than there are initializers in the list, specifies an expression to be
3855 /// used for value initialization of the rest of the elements.
3856 Expr *getArrayFiller() {
3857 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3859 const Expr *getArrayFiller() const {
3860 return const_cast<InitListExpr *>(this)->getArrayFiller();
3862 void setArrayFiller(Expr *filler);
3864 /// \brief Return true if this is an array initializer and its array "filler"
3866 bool hasArrayFiller() const { return getArrayFiller(); }
3868 /// \brief If this initializes a union, specifies which field in the
3869 /// union to initialize.
3871 /// Typically, this field is the first named field within the
3872 /// union. However, a designated initializer can specify the
3873 /// initialization of a different field within the union.
3874 FieldDecl *getInitializedFieldInUnion() {
3875 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3877 const FieldDecl *getInitializedFieldInUnion() const {
3878 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3880 void setInitializedFieldInUnion(FieldDecl *FD) {
3881 assert((FD == nullptr
3882 || getInitializedFieldInUnion() == nullptr
3883 || getInitializedFieldInUnion() == FD)
3884 && "Only one field of a union may be initialized at a time!");
3885 ArrayFillerOrUnionFieldInit = FD;
3888 // Explicit InitListExpr's originate from source code (and have valid source
3889 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3890 bool isExplicit() const {
3891 return LBraceLoc.isValid() && RBraceLoc.isValid();
3894 // Is this an initializer for an array of characters, initialized by a string
3895 // literal or an @encode?
3896 bool isStringLiteralInit() const;
3898 /// Is this a transparent initializer list (that is, an InitListExpr that is
3899 /// purely syntactic, and whose semantics are that of the sole contained
3901 bool isTransparent() const;
3903 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3904 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3905 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3906 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3908 bool isSemanticForm() const { return AltForm.getInt(); }
3909 InitListExpr *getSemanticForm() const {
3910 return isSemanticForm() ? nullptr : AltForm.getPointer();
3912 InitListExpr *getSyntacticForm() const {
3913 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3916 void setSyntacticForm(InitListExpr *Init) {
3917 AltForm.setPointer(Init);
3918 AltForm.setInt(true);
3919 Init->AltForm.setPointer(this);
3920 Init->AltForm.setInt(false);
3923 bool hadArrayRangeDesignator() const {
3924 return InitListExprBits.HadArrayRangeDesignator != 0;
3926 void sawArrayRangeDesignator(bool ARD = true) {
3927 InitListExprBits.HadArrayRangeDesignator = ARD;
3930 SourceLocation getLocStart() const LLVM_READONLY;
3931 SourceLocation getLocEnd() const LLVM_READONLY;
3933 static bool classof(const Stmt *T) {
3934 return T->getStmtClass() == InitListExprClass;
3938 child_range children() {
3939 // FIXME: This does not include the array filler expression.
3940 if (InitExprs.empty())
3941 return child_range(child_iterator(), child_iterator());
3942 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3945 typedef InitExprsTy::iterator iterator;
3946 typedef InitExprsTy::const_iterator const_iterator;
3947 typedef InitExprsTy::reverse_iterator reverse_iterator;
3948 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3950 iterator begin() { return InitExprs.begin(); }
3951 const_iterator begin() const { return InitExprs.begin(); }
3952 iterator end() { return InitExprs.end(); }
3953 const_iterator end() const { return InitExprs.end(); }
3954 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3955 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3956 reverse_iterator rend() { return InitExprs.rend(); }
3957 const_reverse_iterator rend() const { return InitExprs.rend(); }
3959 friend class ASTStmtReader;
3960 friend class ASTStmtWriter;
3963 /// @brief Represents a C99 designated initializer expression.
3965 /// A designated initializer expression (C99 6.7.8) contains one or
3966 /// more designators (which can be field designators, array
3967 /// designators, or GNU array-range designators) followed by an
3968 /// expression that initializes the field or element(s) that the
3969 /// designators refer to. For example, given:
3976 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3979 /// The InitListExpr contains three DesignatedInitExprs, the first of
3980 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3981 /// designators, one array designator for @c [2] followed by one field
3982 /// designator for @c .y. The initialization expression will be 1.0.
3983 class DesignatedInitExpr final
3985 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
3987 /// \brief Forward declaration of the Designator class.
3991 /// The location of the '=' or ':' prior to the actual initializer
3993 SourceLocation EqualOrColonLoc;
3995 /// Whether this designated initializer used the GNU deprecated
3996 /// syntax rather than the C99 '=' syntax.
3997 unsigned GNUSyntax : 1;
3999 /// The number of designators in this initializer expression.
4000 unsigned NumDesignators : 15;
4002 /// The number of subexpressions of this initializer expression,
4003 /// which contains both the initializer and any additional
4004 /// expressions used by array and array-range designators.
4005 unsigned NumSubExprs : 16;
4007 /// \brief The designators in this designated initialization
4009 Designator *Designators;
4011 DesignatedInitExpr(const ASTContext &C, QualType Ty,
4012 llvm::ArrayRef<Designator> Designators,
4013 SourceLocation EqualOrColonLoc, bool GNUSyntax,
4014 ArrayRef<Expr *> IndexExprs, Expr *Init);
4016 explicit DesignatedInitExpr(unsigned NumSubExprs)
4017 : Expr(DesignatedInitExprClass, EmptyShell()),
4018 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4021 /// A field designator, e.g., ".x".
4022 struct FieldDesignator {
4023 /// Refers to the field that is being initialized. The low bit
4024 /// of this field determines whether this is actually a pointer
4025 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4026 /// initially constructed, a field designator will store an
4027 /// IdentifierInfo*. After semantic analysis has resolved that
4028 /// name, the field designator will instead store a FieldDecl*.
4029 uintptr_t NameOrField;
4031 /// The location of the '.' in the designated initializer.
4034 /// The location of the field name in the designated initializer.
4038 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4039 struct ArrayOrRangeDesignator {
4040 /// Location of the first index expression within the designated
4041 /// initializer expression's list of subexpressions.
4043 /// The location of the '[' starting the array range designator.
4044 unsigned LBracketLoc;
4045 /// The location of the ellipsis separating the start and end
4046 /// indices. Only valid for GNU array-range designators.
4047 unsigned EllipsisLoc;
4048 /// The location of the ']' terminating the array range designator.
4049 unsigned RBracketLoc;
4052 /// @brief Represents a single C99 designator.
4054 /// @todo This class is infuriatingly similar to clang::Designator,
4055 /// but minor differences (storing indices vs. storing pointers)
4056 /// keep us from reusing it. Try harder, later, to rectify these
4059 /// @brief The kind of designator this describes.
4063 ArrayRangeDesignator
4067 /// A field designator, e.g., ".x".
4068 struct FieldDesignator Field;
4069 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4070 struct ArrayOrRangeDesignator ArrayOrRange;
4072 friend class DesignatedInitExpr;
4077 /// @brief Initializes a field designator.
4078 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4079 SourceLocation FieldLoc)
4080 : Kind(FieldDesignator) {
4081 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4082 Field.DotLoc = DotLoc.getRawEncoding();
4083 Field.FieldLoc = FieldLoc.getRawEncoding();
4086 /// @brief Initializes an array designator.
4087 Designator(unsigned Index, SourceLocation LBracketLoc,
4088 SourceLocation RBracketLoc)
4089 : Kind(ArrayDesignator) {
4090 ArrayOrRange.Index = Index;
4091 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4092 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4093 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4096 /// @brief Initializes a GNU array-range designator.
4097 Designator(unsigned Index, SourceLocation LBracketLoc,
4098 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4099 : Kind(ArrayRangeDesignator) {
4100 ArrayOrRange.Index = Index;
4101 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4102 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4103 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4106 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4107 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4108 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4110 IdentifierInfo *getFieldName() const;
4112 FieldDecl *getField() const {
4113 assert(Kind == FieldDesignator && "Only valid on a field designator");
4114 if (Field.NameOrField & 0x01)
4117 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4120 void setField(FieldDecl *FD) {
4121 assert(Kind == FieldDesignator && "Only valid on a field designator");
4122 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4125 SourceLocation getDotLoc() const {
4126 assert(Kind == FieldDesignator && "Only valid on a field designator");
4127 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4130 SourceLocation getFieldLoc() const {
4131 assert(Kind == FieldDesignator && "Only valid on a field designator");
4132 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4135 SourceLocation getLBracketLoc() const {
4136 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4137 "Only valid on an array or array-range designator");
4138 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4141 SourceLocation getRBracketLoc() const {
4142 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4143 "Only valid on an array or array-range designator");
4144 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4147 SourceLocation getEllipsisLoc() const {
4148 assert(Kind == ArrayRangeDesignator &&
4149 "Only valid on an array-range designator");
4150 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4153 unsigned getFirstExprIndex() const {
4154 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4155 "Only valid on an array or array-range designator");
4156 return ArrayOrRange.Index;
4159 SourceLocation getLocStart() const LLVM_READONLY {
4160 if (Kind == FieldDesignator)
4161 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4163 return getLBracketLoc();
4165 SourceLocation getLocEnd() const LLVM_READONLY {
4166 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4168 SourceRange getSourceRange() const LLVM_READONLY {
4169 return SourceRange(getLocStart(), getLocEnd());
4173 static DesignatedInitExpr *Create(const ASTContext &C,
4174 llvm::ArrayRef<Designator> Designators,
4175 ArrayRef<Expr*> IndexExprs,
4176 SourceLocation EqualOrColonLoc,
4177 bool GNUSyntax, Expr *Init);
4179 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4180 unsigned NumIndexExprs);
4182 /// @brief Returns the number of designators in this initializer.
4183 unsigned size() const { return NumDesignators; }
4185 // Iterator access to the designators.
4186 llvm::MutableArrayRef<Designator> designators() {
4187 return {Designators, NumDesignators};
4190 llvm::ArrayRef<Designator> designators() const {
4191 return {Designators, NumDesignators};
4194 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4196 void setDesignators(const ASTContext &C, const Designator *Desigs,
4197 unsigned NumDesigs);
4199 Expr *getArrayIndex(const Designator &D) const;
4200 Expr *getArrayRangeStart(const Designator &D) const;
4201 Expr *getArrayRangeEnd(const Designator &D) const;
4203 /// @brief Retrieve the location of the '=' that precedes the
4204 /// initializer value itself, if present.
4205 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4206 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4208 /// @brief Determines whether this designated initializer used the
4209 /// deprecated GNU syntax for designated initializers.
4210 bool usesGNUSyntax() const { return GNUSyntax; }
4211 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4213 /// @brief Retrieve the initializer value.
4214 Expr *getInit() const {
4215 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4218 void setInit(Expr *init) {
4219 *child_begin() = init;
4222 /// \brief Retrieve the total number of subexpressions in this
4223 /// designated initializer expression, including the actual
4224 /// initialized value and any expressions that occur within array
4225 /// and array-range designators.
4226 unsigned getNumSubExprs() const { return NumSubExprs; }
4228 Expr *getSubExpr(unsigned Idx) const {
4229 assert(Idx < NumSubExprs && "Subscript out of range");
4230 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4233 void setSubExpr(unsigned Idx, Expr *E) {
4234 assert(Idx < NumSubExprs && "Subscript out of range");
4235 getTrailingObjects<Stmt *>()[Idx] = E;
4238 /// \brief Replaces the designator at index @p Idx with the series
4239 /// of designators in [First, Last).
4240 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4241 const Designator *First, const Designator *Last);
4243 SourceRange getDesignatorsSourceRange() const;
4245 SourceLocation getLocStart() const LLVM_READONLY;
4246 SourceLocation getLocEnd() const LLVM_READONLY;
4248 static bool classof(const Stmt *T) {
4249 return T->getStmtClass() == DesignatedInitExprClass;
4253 child_range children() {
4254 Stmt **begin = getTrailingObjects<Stmt *>();
4255 return child_range(begin, begin + NumSubExprs);
4258 friend TrailingObjects;
4261 /// \brief Represents a place-holder for an object not to be initialized by
4264 /// This only makes sense when it appears as part of an updater of a
4265 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4266 /// initializes a big object, and the NoInitExpr's mark the spots within the
4267 /// big object not to be overwritten by the updater.
4269 /// \see DesignatedInitUpdateExpr
4270 class NoInitExpr : public Expr {
4272 explicit NoInitExpr(QualType ty)
4273 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4274 false, false, ty->isInstantiationDependentType(), false) { }
4276 explicit NoInitExpr(EmptyShell Empty)
4277 : Expr(NoInitExprClass, Empty) { }
4279 static bool classof(const Stmt *T) {
4280 return T->getStmtClass() == NoInitExprClass;
4283 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4284 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4287 child_range children() {
4288 return child_range(child_iterator(), child_iterator());
4293 // struct Q { int a, b, c; };
4296 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4299 // We will have an InitListExpr for a, with type A, and then a
4300 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4301 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4303 class DesignatedInitUpdateExpr : public Expr {
4304 // BaseAndUpdaterExprs[0] is the base expression;
4305 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4306 Stmt *BaseAndUpdaterExprs[2];
4309 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4310 Expr *baseExprs, SourceLocation rBraceLoc);
4312 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4313 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4315 SourceLocation getLocStart() const LLVM_READONLY;
4316 SourceLocation getLocEnd() const LLVM_READONLY;
4318 static bool classof(const Stmt *T) {
4319 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4322 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4323 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4325 InitListExpr *getUpdater() const {
4326 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4328 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4331 // children = the base and the updater
4332 child_range children() {
4333 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4337 /// \brief Represents a loop initializing the elements of an array.
4339 /// The need to initialize the elements of an array occurs in a number of
4342 /// * in the implicit copy/move constructor for a class with an array member
4343 /// * when a lambda-expression captures an array by value
4344 /// * when a decomposition declaration decomposes an array
4346 /// There are two subexpressions: a common expression (the source array)
4347 /// that is evaluated once up-front, and a per-element initializer that
4348 /// runs once for each array element.
4350 /// Within the per-element initializer, the common expression may be referenced
4351 /// via an OpaqueValueExpr, and the current index may be obtained via an
4352 /// ArrayInitIndexExpr.
4353 class ArrayInitLoopExpr : public Expr {
4356 explicit ArrayInitLoopExpr(EmptyShell Empty)
4357 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4360 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4361 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4362 CommonInit->isValueDependent() || ElementInit->isValueDependent(),
4363 T->isInstantiationDependentType(),
4364 CommonInit->containsUnexpandedParameterPack() ||
4365 ElementInit->containsUnexpandedParameterPack()),
4366 SubExprs{CommonInit, ElementInit} {}
4368 /// Get the common subexpression shared by all initializations (the source
4370 OpaqueValueExpr *getCommonExpr() const {
4371 return cast<OpaqueValueExpr>(SubExprs[0]);
4374 /// Get the initializer to use for each array element.
4375 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
4377 llvm::APInt getArraySize() const {
4378 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
4382 static bool classof(const Stmt *S) {
4383 return S->getStmtClass() == ArrayInitLoopExprClass;
4386 SourceLocation getLocStart() const LLVM_READONLY {
4387 return getCommonExpr()->getLocStart();
4389 SourceLocation getLocEnd() const LLVM_READONLY {
4390 return getCommonExpr()->getLocEnd();
4393 child_range children() {
4394 return child_range(SubExprs, SubExprs + 2);
4397 friend class ASTReader;
4398 friend class ASTStmtReader;
4399 friend class ASTStmtWriter;
4402 /// \brief Represents the index of the current element of an array being
4403 /// initialized by an ArrayInitLoopExpr. This can only appear within the
4404 /// subexpression of an ArrayInitLoopExpr.
4405 class ArrayInitIndexExpr : public Expr {
4406 explicit ArrayInitIndexExpr(EmptyShell Empty)
4407 : Expr(ArrayInitIndexExprClass, Empty) {}
4410 explicit ArrayInitIndexExpr(QualType T)
4411 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
4412 false, false, false, false) {}
4414 static bool classof(const Stmt *S) {
4415 return S->getStmtClass() == ArrayInitIndexExprClass;
4418 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4419 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4421 child_range children() {
4422 return child_range(child_iterator(), child_iterator());
4425 friend class ASTReader;
4426 friend class ASTStmtReader;
4429 /// \brief Represents an implicitly-generated value initialization of
4430 /// an object of a given type.
4432 /// Implicit value initializations occur within semantic initializer
4433 /// list expressions (InitListExpr) as placeholders for subobject
4434 /// initializations not explicitly specified by the user.
4436 /// \see InitListExpr
4437 class ImplicitValueInitExpr : public Expr {
4439 explicit ImplicitValueInitExpr(QualType ty)
4440 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4441 false, false, ty->isInstantiationDependentType(), false) { }
4443 /// \brief Construct an empty implicit value initialization.
4444 explicit ImplicitValueInitExpr(EmptyShell Empty)
4445 : Expr(ImplicitValueInitExprClass, Empty) { }
4447 static bool classof(const Stmt *T) {
4448 return T->getStmtClass() == ImplicitValueInitExprClass;
4451 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4452 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4455 child_range children() {
4456 return child_range(child_iterator(), child_iterator());
4460 class ParenListExpr : public Expr {
4463 SourceLocation LParenLoc, RParenLoc;
4466 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4467 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4469 /// \brief Build an empty paren list.
4470 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4472 unsigned getNumExprs() const { return NumExprs; }
4474 const Expr* getExpr(unsigned Init) const {
4475 assert(Init < getNumExprs() && "Initializer access out of range!");
4476 return cast_or_null<Expr>(Exprs[Init]);
4479 Expr* getExpr(unsigned Init) {
4480 assert(Init < getNumExprs() && "Initializer access out of range!");
4481 return cast_or_null<Expr>(Exprs[Init]);
4484 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4486 ArrayRef<Expr *> exprs() {
4487 return llvm::makeArrayRef(getExprs(), getNumExprs());
4490 SourceLocation getLParenLoc() const { return LParenLoc; }
4491 SourceLocation getRParenLoc() const { return RParenLoc; }
4493 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4494 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4496 static bool classof(const Stmt *T) {
4497 return T->getStmtClass() == ParenListExprClass;
4501 child_range children() {
4502 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4505 friend class ASTStmtReader;
4506 friend class ASTStmtWriter;
4509 /// \brief Represents a C11 generic selection.
4511 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4512 /// expression, followed by one or more generic associations. Each generic
4513 /// association specifies a type name and an expression, or "default" and an
4514 /// expression (in which case it is known as a default generic association).
4515 /// The type and value of the generic selection are identical to those of its
4516 /// result expression, which is defined as the expression in the generic
4517 /// association with a type name that is compatible with the type of the
4518 /// controlling expression, or the expression in the default generic association
4519 /// if no types are compatible. For example:
4522 /// _Generic(X, double: 1, float: 2, default: 3)
4525 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4526 /// or 3 if "hello".
4528 /// As an extension, generic selections are allowed in C++, where the following
4529 /// additional semantics apply:
4531 /// Any generic selection whose controlling expression is type-dependent or
4532 /// which names a dependent type in its association list is result-dependent,
4533 /// which means that the choice of result expression is dependent.
4534 /// Result-dependent generic associations are both type- and value-dependent.
4535 class GenericSelectionExpr : public Expr {
4536 enum { CONTROLLING, END_EXPR };
4537 TypeSourceInfo **AssocTypes;
4539 unsigned NumAssocs, ResultIndex;
4540 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4543 GenericSelectionExpr(const ASTContext &Context,
4544 SourceLocation GenericLoc, Expr *ControllingExpr,
4545 ArrayRef<TypeSourceInfo*> AssocTypes,
4546 ArrayRef<Expr*> AssocExprs,
4547 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4548 bool ContainsUnexpandedParameterPack,
4549 unsigned ResultIndex);
4551 /// This constructor is used in the result-dependent case.
4552 GenericSelectionExpr(const ASTContext &Context,
4553 SourceLocation GenericLoc, Expr *ControllingExpr,
4554 ArrayRef<TypeSourceInfo*> AssocTypes,
4555 ArrayRef<Expr*> AssocExprs,
4556 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4557 bool ContainsUnexpandedParameterPack);
4559 explicit GenericSelectionExpr(EmptyShell Empty)
4560 : Expr(GenericSelectionExprClass, Empty) { }
4562 unsigned getNumAssocs() const { return NumAssocs; }
4564 SourceLocation getGenericLoc() const { return GenericLoc; }
4565 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4566 SourceLocation getRParenLoc() const { return RParenLoc; }
4568 const Expr *getAssocExpr(unsigned i) const {
4569 return cast<Expr>(SubExprs[END_EXPR+i]);
4571 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4572 ArrayRef<Expr *> getAssocExprs() const {
4574 ? llvm::makeArrayRef(
4575 &reinterpret_cast<Expr **>(SubExprs)[END_EXPR], NumAssocs)
4578 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4579 return AssocTypes[i];
4581 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4582 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
4583 return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : None;
4586 QualType getAssocType(unsigned i) const {
4587 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4588 return TS->getType();
4593 const Expr *getControllingExpr() const {
4594 return cast<Expr>(SubExprs[CONTROLLING]);
4596 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4598 /// Whether this generic selection is result-dependent.
4599 bool isResultDependent() const { return ResultIndex == -1U; }
4601 /// The zero-based index of the result expression's generic association in
4602 /// the generic selection's association list. Defined only if the
4603 /// generic selection is not result-dependent.
4604 unsigned getResultIndex() const {
4605 assert(!isResultDependent() && "Generic selection is result-dependent");
4609 /// The generic selection's result expression. Defined only if the
4610 /// generic selection is not result-dependent.
4611 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4612 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4614 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4615 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4617 static bool classof(const Stmt *T) {
4618 return T->getStmtClass() == GenericSelectionExprClass;
4621 child_range children() {
4622 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4625 friend class ASTStmtReader;
4628 //===----------------------------------------------------------------------===//
4630 //===----------------------------------------------------------------------===//
4632 /// ExtVectorElementExpr - This represents access to specific elements of a
4633 /// vector, and may occur on the left hand side or right hand side. For example
4634 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4636 /// Note that the base may have either vector or pointer to vector type, just
4637 /// like a struct field reference.
4639 class ExtVectorElementExpr : public Expr {
4641 IdentifierInfo *Accessor;
4642 SourceLocation AccessorLoc;
4644 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4645 IdentifierInfo &accessor, SourceLocation loc)
4646 : Expr(ExtVectorElementExprClass, ty, VK,
4647 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4648 base->isTypeDependent(), base->isValueDependent(),
4649 base->isInstantiationDependent(),
4650 base->containsUnexpandedParameterPack()),
4651 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4653 /// \brief Build an empty vector element expression.
4654 explicit ExtVectorElementExpr(EmptyShell Empty)
4655 : Expr(ExtVectorElementExprClass, Empty) { }
4657 const Expr *getBase() const { return cast<Expr>(Base); }
4658 Expr *getBase() { return cast<Expr>(Base); }
4659 void setBase(Expr *E) { Base = E; }
4661 IdentifierInfo &getAccessor() const { return *Accessor; }
4662 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4664 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4665 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4667 /// getNumElements - Get the number of components being selected.
4668 unsigned getNumElements() const;
4670 /// containsDuplicateElements - Return true if any element access is
4672 bool containsDuplicateElements() const;
4674 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4675 /// aggregate Constant of ConstantInt(s).
4676 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4678 SourceLocation getLocStart() const LLVM_READONLY {
4679 return getBase()->getLocStart();
4681 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4683 /// isArrow - Return true if the base expression is a pointer to vector,
4684 /// return false if the base expression is a vector.
4685 bool isArrow() const;
4687 static bool classof(const Stmt *T) {
4688 return T->getStmtClass() == ExtVectorElementExprClass;
4692 child_range children() { return child_range(&Base, &Base+1); }
4695 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4696 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4697 class BlockExpr : public Expr {
4699 BlockDecl *TheBlock;
4701 BlockExpr(BlockDecl *BD, QualType ty)
4702 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4703 ty->isDependentType(), ty->isDependentType(),
4704 ty->isInstantiationDependentType() || BD->isDependentContext(),
4708 /// \brief Build an empty block expression.
4709 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4711 const BlockDecl *getBlockDecl() const { return TheBlock; }
4712 BlockDecl *getBlockDecl() { return TheBlock; }
4713 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4715 // Convenience functions for probing the underlying BlockDecl.
4716 SourceLocation getCaretLocation() const;
4717 const Stmt *getBody() const;
4720 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4721 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4723 /// getFunctionType - Return the underlying function type for this block.
4724 const FunctionProtoType *getFunctionType() const;
4726 static bool classof(const Stmt *T) {
4727 return T->getStmtClass() == BlockExprClass;
4731 child_range children() {
4732 return child_range(child_iterator(), child_iterator());
4736 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4737 /// This AST node provides support for reinterpreting a type to another
4738 /// type of the same size.
4739 class AsTypeExpr : public Expr {
4742 SourceLocation BuiltinLoc, RParenLoc;
4744 friend class ASTReader;
4745 friend class ASTStmtReader;
4746 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4749 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4750 ExprValueKind VK, ExprObjectKind OK,
4751 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4752 : Expr(AsTypeExprClass, DstType, VK, OK,
4753 DstType->isDependentType(),
4754 DstType->isDependentType() || SrcExpr->isValueDependent(),
4755 (DstType->isInstantiationDependentType() ||
4756 SrcExpr->isInstantiationDependent()),
4757 (DstType->containsUnexpandedParameterPack() ||
4758 SrcExpr->containsUnexpandedParameterPack())),
4759 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4761 /// getSrcExpr - Return the Expr to be converted.
4762 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4764 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4765 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4767 /// getRParenLoc - Return the location of final right parenthesis.
4768 SourceLocation getRParenLoc() const { return RParenLoc; }
4770 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4771 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4773 static bool classof(const Stmt *T) {
4774 return T->getStmtClass() == AsTypeExprClass;
4778 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4781 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4782 /// l-value. A pseudo-object is an abstract object, accesses to which
4783 /// are translated to calls. The pseudo-object expression has a
4784 /// syntactic form, which shows how the expression was actually
4785 /// written in the source code, and a semantic form, which is a series
4786 /// of expressions to be executed in order which detail how the
4787 /// operation is actually evaluated. Optionally, one of the semantic
4788 /// forms may also provide a result value for the expression.
4790 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4791 /// that OVE is required to have a source expression, and it is bound
4792 /// to the result of that source expression. Such OVEs may appear
4793 /// only in subsequent semantic-form expressions and as
4794 /// sub-expressions of the syntactic form.
4796 /// PseudoObjectExpr should be used only when an operation can be
4797 /// usefully described in terms of fairly simple rewrite rules on
4798 /// objects and functions that are meant to be used by end-developers.
4799 /// For example, under the Itanium ABI, dynamic casts are implemented
4800 /// as a call to a runtime function called __dynamic_cast; using this
4801 /// class to describe that would be inappropriate because that call is
4802 /// not really part of the user-visible semantics, and instead the
4803 /// cast is properly reflected in the AST and IR-generation has been
4804 /// taught to generate the call as necessary. In contrast, an
4805 /// Objective-C property access is semantically defined to be
4806 /// equivalent to a particular message send, and this is very much
4807 /// part of the user model. The name of this class encourages this
4808 /// modelling design.
4809 class PseudoObjectExpr final
4811 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
4812 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4813 // Always at least two, because the first sub-expression is the
4816 // PseudoObjectExprBits.ResultIndex - The index of the
4817 // sub-expression holding the result. 0 means the result is void,
4818 // which is unambiguous because it's the index of the syntactic
4819 // form. Note that this is therefore 1 higher than the value passed
4820 // in to Create, which is an index within the semantic forms.
4821 // Note also that ASTStmtWriter assumes this encoding.
4823 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
4824 const Expr * const *getSubExprsBuffer() const {
4825 return getTrailingObjects<Expr *>();
4828 PseudoObjectExpr(QualType type, ExprValueKind VK,
4829 Expr *syntactic, ArrayRef<Expr*> semantic,
4830 unsigned resultIndex);
4832 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4834 unsigned getNumSubExprs() const {
4835 return PseudoObjectExprBits.NumSubExprs;
4839 /// NoResult - A value for the result index indicating that there is
4840 /// no semantic result.
4841 enum : unsigned { NoResult = ~0U };
4843 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4844 ArrayRef<Expr*> semantic,
4845 unsigned resultIndex);
4847 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4848 unsigned numSemanticExprs);
4850 /// Return the syntactic form of this expression, i.e. the
4851 /// expression it actually looks like. Likely to be expressed in
4852 /// terms of OpaqueValueExprs bound in the semantic form.
4853 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4854 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4856 /// Return the index of the result-bearing expression into the semantics
4857 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4858 unsigned getResultExprIndex() const {
4859 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4860 return PseudoObjectExprBits.ResultIndex - 1;
4863 /// Return the result-bearing expression, or null if there is none.
4864 Expr *getResultExpr() {
4865 if (PseudoObjectExprBits.ResultIndex == 0)
4867 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4869 const Expr *getResultExpr() const {
4870 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4873 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4875 typedef Expr * const *semantics_iterator;
4876 typedef const Expr * const *const_semantics_iterator;
4877 semantics_iterator semantics_begin() {
4878 return getSubExprsBuffer() + 1;
4880 const_semantics_iterator semantics_begin() const {
4881 return getSubExprsBuffer() + 1;
4883 semantics_iterator semantics_end() {
4884 return getSubExprsBuffer() + getNumSubExprs();
4886 const_semantics_iterator semantics_end() const {
4887 return getSubExprsBuffer() + getNumSubExprs();
4890 llvm::iterator_range<semantics_iterator> semantics() {
4891 return llvm::make_range(semantics_begin(), semantics_end());
4893 llvm::iterator_range<const_semantics_iterator> semantics() const {
4894 return llvm::make_range(semantics_begin(), semantics_end());
4897 Expr *getSemanticExpr(unsigned index) {
4898 assert(index + 1 < getNumSubExprs());
4899 return getSubExprsBuffer()[index + 1];
4901 const Expr *getSemanticExpr(unsigned index) const {
4902 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4905 SourceLocation getExprLoc() const LLVM_READONLY {
4906 return getSyntacticForm()->getExprLoc();
4909 SourceLocation getLocStart() const LLVM_READONLY {
4910 return getSyntacticForm()->getLocStart();
4912 SourceLocation getLocEnd() const LLVM_READONLY {
4913 return getSyntacticForm()->getLocEnd();
4916 child_range children() {
4917 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4918 return child_range(cs, cs + getNumSubExprs());
4921 static bool classof(const Stmt *T) {
4922 return T->getStmtClass() == PseudoObjectExprClass;
4925 friend TrailingObjects;
4926 friend class ASTStmtReader;
4929 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4930 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4931 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4932 /// All of these instructions take one primary pointer and at least one memory
4934 class AtomicExpr : public Expr {
4937 #define BUILTIN(ID, TYPE, ATTRS)
4938 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4939 #include "clang/Basic/Builtins.def"
4940 // Avoid trailing comma
4945 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4946 Stmt* SubExprs[END_EXPR];
4947 unsigned NumSubExprs;
4948 SourceLocation BuiltinLoc, RParenLoc;
4951 friend class ASTStmtReader;
4954 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4955 AtomicOp op, SourceLocation RP);
4957 /// \brief Determine the number of arguments the specified atomic builtin
4959 static unsigned getNumSubExprs(AtomicOp Op);
4961 /// \brief Build an empty AtomicExpr.
4962 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4964 Expr *getPtr() const {
4965 return cast<Expr>(SubExprs[PTR]);
4967 Expr *getOrder() const {
4968 return cast<Expr>(SubExprs[ORDER]);
4970 Expr *getVal1() const {
4971 if (Op == AO__c11_atomic_init)
4972 return cast<Expr>(SubExprs[ORDER]);
4973 assert(NumSubExprs > VAL1);
4974 return cast<Expr>(SubExprs[VAL1]);
4976 Expr *getOrderFail() const {
4977 assert(NumSubExprs > ORDER_FAIL);
4978 return cast<Expr>(SubExprs[ORDER_FAIL]);
4980 Expr *getVal2() const {
4981 if (Op == AO__atomic_exchange)
4982 return cast<Expr>(SubExprs[ORDER_FAIL]);
4983 assert(NumSubExprs > VAL2);
4984 return cast<Expr>(SubExprs[VAL2]);
4986 Expr *getWeak() const {
4987 assert(NumSubExprs > WEAK);
4988 return cast<Expr>(SubExprs[WEAK]);
4991 AtomicOp getOp() const { return Op; }
4992 unsigned getNumSubExprs() const { return NumSubExprs; }
4994 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4995 const Expr * const *getSubExprs() const {
4996 return reinterpret_cast<Expr * const *>(SubExprs);
4999 bool isVolatile() const {
5000 return getPtr()->getType()->getPointeeType().isVolatileQualified();
5003 bool isCmpXChg() const {
5004 return getOp() == AO__c11_atomic_compare_exchange_strong ||
5005 getOp() == AO__c11_atomic_compare_exchange_weak ||
5006 getOp() == AO__atomic_compare_exchange ||
5007 getOp() == AO__atomic_compare_exchange_n;
5010 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5011 SourceLocation getRParenLoc() const { return RParenLoc; }
5013 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
5014 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
5016 static bool classof(const Stmt *T) {
5017 return T->getStmtClass() == AtomicExprClass;
5021 child_range children() {
5022 return child_range(SubExprs, SubExprs+NumSubExprs);
5026 /// TypoExpr - Internal placeholder for expressions where typo correction
5027 /// still needs to be performed and/or an error diagnostic emitted.
5028 class TypoExpr : public Expr {
5030 TypoExpr(QualType T)
5031 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5032 /*isTypeDependent*/ true,
5033 /*isValueDependent*/ true,
5034 /*isInstantiationDependent*/ true,
5035 /*containsUnexpandedParameterPack*/ false) {
5036 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
5039 child_range children() {
5040 return child_range(child_iterator(), child_iterator());
5042 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
5043 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
5045 static bool classof(const Stmt *T) {
5046 return T->getStmtClass() == TypoExprClass;
5050 } // end namespace clang
5052 #endif // LLVM_CLANG_AST_EXPR_H