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 /// \brief If this expression is an l-value for an Objective C
449 /// property, find the underlying property reference expression.
450 const ObjCPropertyRefExpr *getObjCProperty() const;
452 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
453 bool isObjCSelfExpr() const;
455 /// \brief Returns whether this expression refers to a vector element.
456 bool refersToVectorElement() const;
458 /// \brief Returns whether this expression refers to a global register
460 bool refersToGlobalRegisterVar() const;
462 /// \brief Returns whether this expression has a placeholder type.
463 bool hasPlaceholderType() const {
464 return getType()->isPlaceholderType();
467 /// \brief Returns whether this expression has a specific placeholder type.
468 bool hasPlaceholderType(BuiltinType::Kind K) const {
469 assert(BuiltinType::isPlaceholderTypeKind(K));
470 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
471 return BT->getKind() == K;
475 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
476 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
477 /// but also int expressions which are produced by things like comparisons in
479 bool isKnownToHaveBooleanValue() const;
481 /// isIntegerConstantExpr - Return true if this expression is a valid integer
482 /// constant expression, and, if so, return its value in Result. If not a
483 /// valid i-c-e, return false and fill in Loc (if specified) with the location
484 /// of the invalid expression.
486 /// Note: This does not perform the implicit conversions required by C++11
488 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
489 SourceLocation *Loc = nullptr,
490 bool isEvaluated = true) const;
491 bool isIntegerConstantExpr(const ASTContext &Ctx,
492 SourceLocation *Loc = nullptr) const;
494 /// isCXX98IntegralConstantExpr - Return true if this expression is an
495 /// integral constant expression in C++98. Can only be used in C++.
496 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
498 /// isCXX11ConstantExpr - Return true if this expression is a constant
499 /// expression in C++11. Can only be used in C++.
501 /// Note: This does not perform the implicit conversions required by C++11
503 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
504 SourceLocation *Loc = nullptr) const;
506 /// isPotentialConstantExpr - Return true if this function's definition
507 /// might be usable in a constant expression in C++11, if it were marked
508 /// constexpr. Return false if the function can never produce a constant
509 /// expression, along with diagnostics describing why not.
510 static bool isPotentialConstantExpr(const FunctionDecl *FD,
512 PartialDiagnosticAt> &Diags);
514 /// isPotentialConstantExprUnevaluted - Return true if this expression might
515 /// be usable in a constant expression in C++11 in an unevaluated context, if
516 /// it were in function FD marked constexpr. Return false if the function can
517 /// never produce a constant expression, along with diagnostics describing
519 static bool isPotentialConstantExprUnevaluated(Expr *E,
520 const FunctionDecl *FD,
522 PartialDiagnosticAt> &Diags);
524 /// isConstantInitializer - Returns true if this expression can be emitted to
525 /// IR as a constant, and thus can be used as a constant initializer in C.
526 /// If this expression is not constant and Culprit is non-null,
527 /// it is used to store the address of first non constant expr.
528 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
529 const Expr **Culprit = nullptr) const;
531 /// EvalStatus is a struct with detailed info about an evaluation in progress.
533 /// \brief Whether the evaluated expression has side effects.
534 /// For example, (f() && 0) can be folded, but it still has side effects.
537 /// \brief Whether the evaluation hit undefined behavior.
538 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
539 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
540 bool HasUndefinedBehavior;
542 /// Diag - If this is non-null, it will be filled in with a stack of notes
543 /// indicating why evaluation failed (or why it failed to produce a constant
545 /// If the expression is unfoldable, the notes will indicate why it's not
546 /// foldable. If the expression is foldable, but not a constant expression,
547 /// the notes will describes why it isn't a constant expression. If the
548 /// expression *is* a constant expression, no notes will be produced.
549 SmallVectorImpl<PartialDiagnosticAt> *Diag;
552 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
554 // hasSideEffects - Return true if the evaluated expression has
556 bool hasSideEffects() const {
557 return HasSideEffects;
561 /// EvalResult is a struct with detailed info about an evaluated expression.
562 struct EvalResult : EvalStatus {
563 /// Val - This is the value the expression can be folded to.
566 // isGlobalLValue - Return true if the evaluated lvalue expression
568 bool isGlobalLValue() const;
571 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
572 /// an rvalue using any crazy technique (that has nothing to do with language
573 /// standards) that we want to, even if the expression has side-effects. If
574 /// this function returns true, it returns the folded constant in Result. If
575 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
577 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
579 /// EvaluateAsBooleanCondition - Return true if this is a constant
580 /// which we we can fold and convert to a boolean condition using
581 /// any crazy technique that we want to, even if the expression has
583 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
585 enum SideEffectsKind {
586 SE_NoSideEffects, ///< Strictly evaluate the expression.
587 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
588 ///< arbitrary unmodeled side effects.
589 SE_AllowSideEffects ///< Allow any unmodeled side effect.
592 /// EvaluateAsInt - Return true if this is a constant which we can fold and
593 /// convert to an integer, using any crazy technique that we want to.
594 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
595 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
597 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
598 /// convert to a floating point value, using any crazy technique that we
601 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
602 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
604 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
605 /// constant folded without side-effects, but discard the result.
606 bool isEvaluatable(const ASTContext &Ctx,
607 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
609 /// HasSideEffects - This routine returns true for all those expressions
610 /// which have any effect other than producing a value. Example is a function
611 /// call, volatile variable read, or throwing an exception. If
612 /// IncludePossibleEffects is false, this call treats certain expressions with
613 /// potential side effects (such as function call-like expressions,
614 /// instantiation-dependent expressions, or invocations from a macro) as not
615 /// having side effects.
616 bool HasSideEffects(const ASTContext &Ctx,
617 bool IncludePossibleEffects = true) const;
619 /// \brief Determine whether this expression involves a call to any function
620 /// that is not trivial.
621 bool hasNonTrivialCall(const ASTContext &Ctx) const;
623 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
624 /// integer. This must be called on an expression that constant folds to an
626 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
627 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
629 void EvaluateForOverflow(const ASTContext &Ctx) const;
631 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
632 /// lvalue with link time known address, with no side-effects.
633 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
635 /// EvaluateAsInitializer - Evaluate an expression as if it were the
636 /// initializer of the given declaration. Returns true if the initializer
637 /// can be folded to a constant, and produces any relevant notes. In C++11,
638 /// notes will be produced if the expression is not a constant expression.
639 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
641 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
643 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
644 /// of a call to the given function with the given arguments, inside an
645 /// unevaluated context. Returns true if the expression could be folded to a
647 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
648 const FunctionDecl *Callee,
649 ArrayRef<const Expr*> Args) const;
651 /// \brief If the current Expr is a pointer, this will try to statically
652 /// determine the number of bytes available where the pointer is pointing.
653 /// Returns true if all of the above holds and we were able to figure out the
654 /// size, false otherwise.
656 /// \param Type - How to evaluate the size of the Expr, as defined by the
657 /// "type" parameter of __builtin_object_size
658 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
659 unsigned Type) const;
661 /// \brief Enumeration used to describe the kind of Null pointer constant
662 /// returned from \c isNullPointerConstant().
663 enum NullPointerConstantKind {
664 /// \brief Expression is not a Null pointer constant.
667 /// \brief Expression is a Null pointer constant built from a zero integer
668 /// expression that is not a simple, possibly parenthesized, zero literal.
669 /// C++ Core Issue 903 will classify these expressions as "not pointers"
670 /// once it is adopted.
671 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
674 /// \brief Expression is a Null pointer constant built from a literal zero.
677 /// \brief Expression is a C++11 nullptr.
680 /// \brief Expression is a GNU-style __null constant.
684 /// \brief Enumeration used to describe how \c isNullPointerConstant()
685 /// should cope with value-dependent expressions.
686 enum NullPointerConstantValueDependence {
687 /// \brief Specifies that the expression should never be value-dependent.
688 NPC_NeverValueDependent = 0,
690 /// \brief Specifies that a value-dependent expression of integral or
691 /// dependent type should be considered a null pointer constant.
692 NPC_ValueDependentIsNull,
694 /// \brief Specifies that a value-dependent expression should be considered
695 /// to never be a null pointer constant.
696 NPC_ValueDependentIsNotNull
699 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
700 /// a Null pointer constant. The return value can further distinguish the
701 /// kind of NULL pointer constant that was detected.
702 NullPointerConstantKind isNullPointerConstant(
704 NullPointerConstantValueDependence NPC) const;
706 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
708 bool isOBJCGCCandidate(ASTContext &Ctx) const;
710 /// \brief Returns true if this expression is a bound member function.
711 bool isBoundMemberFunction(ASTContext &Ctx) const;
713 /// \brief Given an expression of bound-member type, find the type
714 /// of the member. Returns null if this is an *overloaded* bound
715 /// member expression.
716 static QualType findBoundMemberType(const Expr *expr);
718 /// IgnoreImpCasts - Skip past any implicit casts which might
719 /// surround this expression. Only skips ImplicitCastExprs.
720 Expr *IgnoreImpCasts() LLVM_READONLY;
722 /// IgnoreImplicit - Skip past any implicit AST nodes which might
723 /// surround this expression.
724 Expr *IgnoreImplicit() LLVM_READONLY {
725 return cast<Expr>(Stmt::IgnoreImplicit());
728 const Expr *IgnoreImplicit() const LLVM_READONLY {
729 return const_cast<Expr*>(this)->IgnoreImplicit();
732 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
733 /// its subexpression. If that subexpression is also a ParenExpr,
734 /// then this method recursively returns its subexpression, and so forth.
735 /// Otherwise, the method returns the current Expr.
736 Expr *IgnoreParens() LLVM_READONLY;
738 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
739 /// or CastExprs, returning their operand.
740 Expr *IgnoreParenCasts() LLVM_READONLY;
742 /// Ignore casts. Strip off any CastExprs, returning their operand.
743 Expr *IgnoreCasts() LLVM_READONLY;
745 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
746 /// any ParenExpr or ImplicitCastExprs, returning their operand.
747 Expr *IgnoreParenImpCasts() LLVM_READONLY;
749 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
750 /// call to a conversion operator, return the argument.
751 Expr *IgnoreConversionOperator() LLVM_READONLY;
753 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
754 return const_cast<Expr*>(this)->IgnoreConversionOperator();
757 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
758 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
761 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
762 /// CastExprs that represent lvalue casts, returning their operand.
763 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
765 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
766 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
769 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
770 /// value (including ptr->int casts of the same size). Strip off any
771 /// ParenExpr or CastExprs, returning their operand.
772 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
774 /// Ignore parentheses and derived-to-base casts.
775 Expr *ignoreParenBaseCasts() LLVM_READONLY;
777 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
778 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
781 /// \brief Determine whether this expression is a default function argument.
783 /// Default arguments are implicitly generated in the abstract syntax tree
784 /// by semantic analysis for function calls, object constructions, etc. in
785 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
786 /// this routine also looks through any implicit casts to determine whether
787 /// the expression is a default argument.
788 bool isDefaultArgument() const;
790 /// \brief Determine whether the result of this expression is a
791 /// temporary object of the given class type.
792 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
794 /// \brief Whether this expression is an implicit reference to 'this' in C++.
795 bool isImplicitCXXThis() const;
797 const Expr *IgnoreImpCasts() const LLVM_READONLY {
798 return const_cast<Expr*>(this)->IgnoreImpCasts();
800 const Expr *IgnoreParens() const LLVM_READONLY {
801 return const_cast<Expr*>(this)->IgnoreParens();
803 const Expr *IgnoreParenCasts() const LLVM_READONLY {
804 return const_cast<Expr*>(this)->IgnoreParenCasts();
806 /// Strip off casts, but keep parentheses.
807 const Expr *IgnoreCasts() const LLVM_READONLY {
808 return const_cast<Expr*>(this)->IgnoreCasts();
811 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
812 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
815 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
817 /// \brief For an expression of class type or pointer to class type,
818 /// return the most derived class decl the expression is known to refer to.
820 /// If this expression is a cast, this method looks through it to find the
821 /// most derived decl that can be inferred from the expression.
822 /// This is valid because derived-to-base conversions have undefined
823 /// behavior if the object isn't dynamically of the derived type.
824 const CXXRecordDecl *getBestDynamicClassType() const;
826 /// Walk outwards from an expression we want to bind a reference to and
827 /// find the expression whose lifetime needs to be extended. Record
828 /// the LHSs of comma expressions and adjustments needed along the path.
829 const Expr *skipRValueSubobjectAdjustments(
830 SmallVectorImpl<const Expr *> &CommaLHS,
831 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
833 static bool classof(const Stmt *T) {
834 return T->getStmtClass() >= firstExprConstant &&
835 T->getStmtClass() <= lastExprConstant;
839 //===----------------------------------------------------------------------===//
840 // Primary Expressions.
841 //===----------------------------------------------------------------------===//
843 /// OpaqueValueExpr - An expression referring to an opaque object of a
844 /// fixed type and value class. These don't correspond to concrete
845 /// syntax; instead they're used to express operations (usually copy
846 /// operations) on values whose source is generally obvious from
848 class OpaqueValueExpr : public Expr {
849 friend class ASTStmtReader;
854 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
855 ExprObjectKind OK = OK_Ordinary,
856 Expr *SourceExpr = nullptr)
857 : Expr(OpaqueValueExprClass, T, VK, OK,
858 T->isDependentType() ||
859 (SourceExpr && SourceExpr->isTypeDependent()),
860 T->isDependentType() ||
861 (SourceExpr && SourceExpr->isValueDependent()),
862 T->isInstantiationDependentType() ||
863 (SourceExpr && SourceExpr->isInstantiationDependent()),
865 SourceExpr(SourceExpr), Loc(Loc) {
868 /// Given an expression which invokes a copy constructor --- i.e. a
869 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
870 /// find the OpaqueValueExpr that's the source of the construction.
871 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
873 explicit OpaqueValueExpr(EmptyShell Empty)
874 : Expr(OpaqueValueExprClass, Empty) { }
876 /// \brief Retrieve the location of this expression.
877 SourceLocation getLocation() const { return Loc; }
879 SourceLocation getLocStart() const LLVM_READONLY {
880 return SourceExpr ? SourceExpr->getLocStart() : Loc;
882 SourceLocation getLocEnd() const LLVM_READONLY {
883 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
885 SourceLocation getExprLoc() const LLVM_READONLY {
886 if (SourceExpr) return SourceExpr->getExprLoc();
890 child_range children() {
891 return child_range(child_iterator(), child_iterator());
894 /// The source expression of an opaque value expression is the
895 /// expression which originally generated the value. This is
896 /// provided as a convenience for analyses that don't wish to
897 /// precisely model the execution behavior of the program.
899 /// The source expression is typically set when building the
900 /// expression which binds the opaque value expression in the first
902 Expr *getSourceExpr() const { return SourceExpr; }
904 static bool classof(const Stmt *T) {
905 return T->getStmtClass() == OpaqueValueExprClass;
909 /// \brief A reference to a declared variable, function, enum, etc.
912 /// This encodes all the information about how a declaration is referenced
913 /// within an expression.
915 /// There are several optional constructs attached to DeclRefExprs only when
916 /// they apply in order to conserve memory. These are laid out past the end of
917 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
919 /// DeclRefExprBits.HasQualifier:
920 /// Specifies when this declaration reference expression has a C++
921 /// nested-name-specifier.
922 /// DeclRefExprBits.HasFoundDecl:
923 /// Specifies when this declaration reference expression has a record of
924 /// a NamedDecl (different from the referenced ValueDecl) which was found
925 /// during name lookup and/or overload resolution.
926 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
927 /// Specifies when this declaration reference expression has an explicit
928 /// C++ template keyword and/or template argument list.
929 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
930 /// Specifies when this declaration reference expression (validly)
931 /// refers to an enclosed local or a captured variable.
932 class DeclRefExpr final
934 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
935 NamedDecl *, ASTTemplateKWAndArgsInfo,
936 TemplateArgumentLoc> {
937 /// \brief The declaration that we are referencing.
940 /// \brief The location of the declaration name itself.
943 /// \brief Provides source/type location info for the declaration name
945 DeclarationNameLoc DNLoc;
947 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
948 return hasQualifier() ? 1 : 0;
951 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
952 return hasFoundDecl() ? 1 : 0;
955 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
956 return hasTemplateKWAndArgsInfo() ? 1 : 0;
959 /// \brief Test whether there is a distinct FoundDecl attached to the end of
961 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
963 DeclRefExpr(const ASTContext &Ctx,
964 NestedNameSpecifierLoc QualifierLoc,
965 SourceLocation TemplateKWLoc,
966 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
967 const DeclarationNameInfo &NameInfo,
969 const TemplateArgumentListInfo *TemplateArgs,
970 QualType T, ExprValueKind VK);
972 /// \brief Construct an empty declaration reference expression.
973 explicit DeclRefExpr(EmptyShell Empty)
974 : Expr(DeclRefExprClass, Empty) { }
976 /// \brief Computes the type- and value-dependence flags for this
977 /// declaration reference expression.
978 void computeDependence(const ASTContext &C);
981 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
982 ExprValueKind VK, SourceLocation L,
983 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
984 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
985 D(D), Loc(L), DNLoc(LocInfo) {
986 DeclRefExprBits.HasQualifier = 0;
987 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
988 DeclRefExprBits.HasFoundDecl = 0;
989 DeclRefExprBits.HadMultipleCandidates = 0;
990 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
991 RefersToEnclosingVariableOrCapture;
992 computeDependence(D->getASTContext());
996 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
997 SourceLocation TemplateKWLoc, ValueDecl *D,
998 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
999 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1000 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1002 static DeclRefExpr *
1003 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1004 SourceLocation TemplateKWLoc, ValueDecl *D,
1005 bool RefersToEnclosingVariableOrCapture,
1006 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1007 NamedDecl *FoundD = nullptr,
1008 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1010 /// \brief Construct an empty declaration reference expression.
1011 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1014 bool HasTemplateKWAndArgsInfo,
1015 unsigned NumTemplateArgs);
1017 ValueDecl *getDecl() { return D; }
1018 const ValueDecl *getDecl() const { return D; }
1019 void setDecl(ValueDecl *NewD) { D = NewD; }
1021 DeclarationNameInfo getNameInfo() const {
1022 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1025 SourceLocation getLocation() const { return Loc; }
1026 void setLocation(SourceLocation L) { Loc = L; }
1027 SourceLocation getLocStart() const LLVM_READONLY;
1028 SourceLocation getLocEnd() const LLVM_READONLY;
1030 /// \brief Determine whether this declaration reference was preceded by a
1031 /// C++ nested-name-specifier, e.g., \c N::foo.
1032 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1034 /// \brief If the name was qualified, retrieves the nested-name-specifier
1035 /// that precedes the name, with source-location information.
1036 NestedNameSpecifierLoc getQualifierLoc() const {
1037 if (!hasQualifier())
1038 return NestedNameSpecifierLoc();
1039 return *getTrailingObjects<NestedNameSpecifierLoc>();
1042 /// \brief If the name was qualified, retrieves the nested-name-specifier
1043 /// that precedes the name. Otherwise, returns NULL.
1044 NestedNameSpecifier *getQualifier() const {
1045 return getQualifierLoc().getNestedNameSpecifier();
1048 /// \brief Get the NamedDecl through which this reference occurred.
1050 /// This Decl may be different from the ValueDecl actually referred to in the
1051 /// presence of using declarations, etc. It always returns non-NULL, and may
1052 /// simple return the ValueDecl when appropriate.
1054 NamedDecl *getFoundDecl() {
1055 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1058 /// \brief Get the NamedDecl through which this reference occurred.
1059 /// See non-const variant.
1060 const NamedDecl *getFoundDecl() const {
1061 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1064 bool hasTemplateKWAndArgsInfo() const {
1065 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1068 /// \brief Retrieve the location of the template keyword preceding
1069 /// this name, if any.
1070 SourceLocation getTemplateKeywordLoc() const {
1071 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1072 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1075 /// \brief Retrieve the location of the left angle bracket starting the
1076 /// explicit template argument list following the name, if any.
1077 SourceLocation getLAngleLoc() const {
1078 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1079 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1082 /// \brief Retrieve the location of the right angle bracket ending the
1083 /// explicit template argument list following the name, if any.
1084 SourceLocation getRAngleLoc() const {
1085 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1086 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1089 /// \brief Determines whether the name in this declaration reference
1090 /// was preceded by the template keyword.
1091 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1093 /// \brief Determines whether this declaration reference was followed by an
1094 /// explicit template argument list.
1095 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1097 /// \brief Copies the template arguments (if present) into the given
1099 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1100 if (hasExplicitTemplateArgs())
1101 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1102 getTrailingObjects<TemplateArgumentLoc>(), List);
1105 /// \brief Retrieve the template arguments provided as part of this
1107 const TemplateArgumentLoc *getTemplateArgs() const {
1108 if (!hasExplicitTemplateArgs())
1111 return getTrailingObjects<TemplateArgumentLoc>();
1114 /// \brief Retrieve the number of template arguments provided as part of this
1116 unsigned getNumTemplateArgs() const {
1117 if (!hasExplicitTemplateArgs())
1120 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1123 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1124 return {getTemplateArgs(), getNumTemplateArgs()};
1127 /// \brief Returns true if this expression refers to a function that
1128 /// was resolved from an overloaded set having size greater than 1.
1129 bool hadMultipleCandidates() const {
1130 return DeclRefExprBits.HadMultipleCandidates;
1132 /// \brief Sets the flag telling whether this expression refers to
1133 /// a function that was resolved from an overloaded set having size
1135 void setHadMultipleCandidates(bool V = true) {
1136 DeclRefExprBits.HadMultipleCandidates = V;
1139 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1141 bool refersToEnclosingVariableOrCapture() const {
1142 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1145 static bool classof(const Stmt *T) {
1146 return T->getStmtClass() == DeclRefExprClass;
1150 child_range children() {
1151 return child_range(child_iterator(), child_iterator());
1154 friend TrailingObjects;
1155 friend class ASTStmtReader;
1156 friend class ASTStmtWriter;
1159 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1160 class PredefinedExpr : public Expr {
1165 LFunction, // Same as Function, but as wide string.
1169 /// \brief The same as PrettyFunction, except that the
1170 /// 'virtual' keyword is omitted for virtual member functions.
1171 PrettyFunctionNoVirtual
1180 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1183 /// \brief Construct an empty predefined expression.
1184 explicit PredefinedExpr(EmptyShell Empty)
1185 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1187 IdentType getIdentType() const { return Type; }
1189 SourceLocation getLocation() const { return Loc; }
1190 void setLocation(SourceLocation L) { Loc = L; }
1192 StringLiteral *getFunctionName();
1193 const StringLiteral *getFunctionName() const {
1194 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1197 static StringRef getIdentTypeName(IdentType IT);
1198 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1200 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1201 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1203 static bool classof(const Stmt *T) {
1204 return T->getStmtClass() == PredefinedExprClass;
1208 child_range children() { return child_range(&FnName, &FnName + 1); }
1210 friend class ASTStmtReader;
1213 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1216 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1217 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1218 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1219 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1220 /// ASTContext's allocator for memory allocation.
1221 class APNumericStorage {
1223 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1224 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1228 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1230 APNumericStorage(const APNumericStorage &) = delete;
1231 void operator=(const APNumericStorage &) = delete;
1234 APNumericStorage() : VAL(0), BitWidth(0) { }
1236 llvm::APInt getIntValue() const {
1237 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1239 return llvm::APInt(BitWidth, NumWords, pVal);
1241 return llvm::APInt(BitWidth, VAL);
1243 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1246 class APIntStorage : private APNumericStorage {
1248 llvm::APInt getValue() const { return getIntValue(); }
1249 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1250 setIntValue(C, Val);
1254 class APFloatStorage : private APNumericStorage {
1256 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1257 return llvm::APFloat(Semantics, getIntValue());
1259 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1260 setIntValue(C, Val.bitcastToAPInt());
1264 class IntegerLiteral : public Expr, public APIntStorage {
1267 /// \brief Construct an empty integer literal.
1268 explicit IntegerLiteral(EmptyShell Empty)
1269 : Expr(IntegerLiteralClass, Empty) { }
1272 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1273 // or UnsignedLongLongTy
1274 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1277 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1278 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1279 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1280 /// \param V - the value that the returned integer literal contains.
1281 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1282 QualType type, SourceLocation l);
1283 /// \brief Returns a new empty integer literal.
1284 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1286 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1287 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1289 /// \brief Retrieve the location of the literal.
1290 SourceLocation getLocation() const { return Loc; }
1292 void setLocation(SourceLocation Location) { Loc = Location; }
1294 static bool classof(const Stmt *T) {
1295 return T->getStmtClass() == IntegerLiteralClass;
1299 child_range children() {
1300 return child_range(child_iterator(), child_iterator());
1304 class CharacterLiteral : public Expr {
1306 enum CharacterKind {
1318 // type should be IntTy
1319 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1321 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1323 Value(value), Loc(l) {
1324 CharacterLiteralBits.Kind = kind;
1327 /// \brief Construct an empty character literal.
1328 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1330 SourceLocation getLocation() const { return Loc; }
1331 CharacterKind getKind() const {
1332 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1335 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1336 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1338 unsigned getValue() const { return Value; }
1340 void setLocation(SourceLocation Location) { Loc = Location; }
1341 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1342 void setValue(unsigned Val) { Value = Val; }
1344 static bool classof(const Stmt *T) {
1345 return T->getStmtClass() == CharacterLiteralClass;
1349 child_range children() {
1350 return child_range(child_iterator(), child_iterator());
1354 class FloatingLiteral : public Expr, private APFloatStorage {
1357 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1358 QualType Type, SourceLocation L);
1360 /// \brief Construct an empty floating-point literal.
1361 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1364 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1365 bool isexact, QualType Type, SourceLocation L);
1366 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1368 llvm::APFloat getValue() const {
1369 return APFloatStorage::getValue(getSemantics());
1371 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1372 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1373 APFloatStorage::setValue(C, Val);
1376 /// Get a raw enumeration value representing the floating-point semantics of
1377 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1378 APFloatSemantics getRawSemantics() const {
1379 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1382 /// Set the raw enumeration value representing the floating-point semantics of
1383 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1384 void setRawSemantics(APFloatSemantics Sem) {
1385 FloatingLiteralBits.Semantics = Sem;
1388 /// Return the APFloat semantics this literal uses.
1389 const llvm::fltSemantics &getSemantics() const;
1391 /// Set the APFloat semantics this literal uses.
1392 void setSemantics(const llvm::fltSemantics &Sem);
1394 bool isExact() const { return FloatingLiteralBits.IsExact; }
1395 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1397 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1398 /// double. Note that this may cause loss of precision, but is useful for
1399 /// debugging dumps, etc.
1400 double getValueAsApproximateDouble() const;
1402 SourceLocation getLocation() const { return Loc; }
1403 void setLocation(SourceLocation L) { Loc = L; }
1405 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1406 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1408 static bool classof(const Stmt *T) {
1409 return T->getStmtClass() == FloatingLiteralClass;
1413 child_range children() {
1414 return child_range(child_iterator(), child_iterator());
1418 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1419 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1420 /// IntegerLiteral classes. Instances of this class always have a Complex type
1421 /// whose element type matches the subexpression.
1423 class ImaginaryLiteral : public Expr {
1426 ImaginaryLiteral(Expr *val, QualType Ty)
1427 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1431 /// \brief Build an empty imaginary literal.
1432 explicit ImaginaryLiteral(EmptyShell Empty)
1433 : Expr(ImaginaryLiteralClass, Empty) { }
1435 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1436 Expr *getSubExpr() { return cast<Expr>(Val); }
1437 void setSubExpr(Expr *E) { Val = E; }
1439 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1440 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1442 static bool classof(const Stmt *T) {
1443 return T->getStmtClass() == ImaginaryLiteralClass;
1447 child_range children() { return child_range(&Val, &Val+1); }
1450 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1451 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1452 /// is NOT null-terminated, and the length of the string is determined by
1453 /// calling getByteLength(). The C type for a string is always a
1454 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1457 /// Note that strings in C can be formed by concatenation of multiple string
1458 /// literal pptokens in translation phase #6. This keeps track of the locations
1459 /// of each of these pieces.
1461 /// Strings in C can also be truncated and extended by assigning into arrays,
1462 /// e.g. with constructs like:
1463 /// char X[2] = "foobar";
1464 /// In this case, getByteLength() will return 6, but the string literal will
1465 /// have type "char[2]".
1466 class StringLiteral : public Expr {
1477 friend class ASTStmtReader;
1481 const uint16_t *asUInt16;
1482 const uint32_t *asUInt32;
1485 unsigned CharByteWidth : 4;
1487 unsigned IsPascal : 1;
1488 unsigned NumConcatenated;
1489 SourceLocation TokLocs[1];
1491 StringLiteral(QualType Ty) :
1492 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1495 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1498 /// This is the "fully general" constructor that allows representation of
1499 /// strings formed from multiple concatenated tokens.
1500 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1501 StringKind Kind, bool Pascal, QualType Ty,
1502 const SourceLocation *Loc, unsigned NumStrs);
1504 /// Simple constructor for string literals made from one token.
1505 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1506 StringKind Kind, bool Pascal, QualType Ty,
1507 SourceLocation Loc) {
1508 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1511 /// \brief Construct an empty string literal.
1512 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1514 StringRef getString() const {
1515 assert(CharByteWidth==1
1516 && "This function is used in places that assume strings use char");
1517 return StringRef(StrData.asChar, getByteLength());
1520 /// Allow access to clients that need the byte representation, such as
1521 /// ASTWriterStmt::VisitStringLiteral().
1522 StringRef getBytes() const {
1523 // FIXME: StringRef may not be the right type to use as a result for this.
1524 if (CharByteWidth == 1)
1525 return StringRef(StrData.asChar, getByteLength());
1526 if (CharByteWidth == 4)
1527 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1529 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1530 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1534 void outputString(raw_ostream &OS) const;
1536 uint32_t getCodeUnit(size_t i) const {
1537 assert(i < Length && "out of bounds access");
1538 if (CharByteWidth == 1)
1539 return static_cast<unsigned char>(StrData.asChar[i]);
1540 if (CharByteWidth == 4)
1541 return StrData.asUInt32[i];
1542 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1543 return StrData.asUInt16[i];
1546 unsigned getByteLength() const { return CharByteWidth*Length; }
1547 unsigned getLength() const { return Length; }
1548 unsigned getCharByteWidth() const { return CharByteWidth; }
1550 /// \brief Sets the string data to the given string data.
1551 void setString(const ASTContext &C, StringRef Str,
1552 StringKind Kind, bool IsPascal);
1554 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1557 bool isAscii() const { return Kind == Ascii; }
1558 bool isWide() const { return Kind == Wide; }
1559 bool isUTF8() const { return Kind == UTF8; }
1560 bool isUTF16() const { return Kind == UTF16; }
1561 bool isUTF32() const { return Kind == UTF32; }
1562 bool isPascal() const { return IsPascal; }
1564 bool containsNonAsciiOrNull() const {
1565 StringRef Str = getString();
1566 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1567 if (!isASCII(Str[i]) || !Str[i])
1572 /// getNumConcatenated - Get the number of string literal tokens that were
1573 /// concatenated in translation phase #6 to form this string literal.
1574 unsigned getNumConcatenated() const { return NumConcatenated; }
1576 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1577 assert(TokNum < NumConcatenated && "Invalid tok number");
1578 return TokLocs[TokNum];
1580 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1581 assert(TokNum < NumConcatenated && "Invalid tok number");
1582 TokLocs[TokNum] = L;
1585 /// getLocationOfByte - Return a source location that points to the specified
1586 /// byte of this string literal.
1588 /// Strings are amazingly complex. They can be formed from multiple tokens
1589 /// and can have escape sequences in them in addition to the usual trigraph
1590 /// and escaped newline business. This routine handles this complexity.
1593 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1594 const LangOptions &Features, const TargetInfo &Target,
1595 unsigned *StartToken = nullptr,
1596 unsigned *StartTokenByteOffset = nullptr) const;
1598 typedef const SourceLocation *tokloc_iterator;
1599 tokloc_iterator tokloc_begin() const { return TokLocs; }
1600 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1602 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1603 SourceLocation getLocEnd() const LLVM_READONLY {
1604 return TokLocs[NumConcatenated - 1];
1607 static bool classof(const Stmt *T) {
1608 return T->getStmtClass() == StringLiteralClass;
1612 child_range children() {
1613 return child_range(child_iterator(), child_iterator());
1617 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1618 /// AST node is only formed if full location information is requested.
1619 class ParenExpr : public Expr {
1620 SourceLocation L, R;
1623 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1624 : Expr(ParenExprClass, val->getType(),
1625 val->getValueKind(), val->getObjectKind(),
1626 val->isTypeDependent(), val->isValueDependent(),
1627 val->isInstantiationDependent(),
1628 val->containsUnexpandedParameterPack()),
1629 L(l), R(r), Val(val) {}
1631 /// \brief Construct an empty parenthesized expression.
1632 explicit ParenExpr(EmptyShell Empty)
1633 : Expr(ParenExprClass, Empty) { }
1635 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1636 Expr *getSubExpr() { return cast<Expr>(Val); }
1637 void setSubExpr(Expr *E) { Val = E; }
1639 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1640 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1642 /// \brief Get the location of the left parentheses '('.
1643 SourceLocation getLParen() const { return L; }
1644 void setLParen(SourceLocation Loc) { L = Loc; }
1646 /// \brief Get the location of the right parentheses ')'.
1647 SourceLocation getRParen() const { return R; }
1648 void setRParen(SourceLocation Loc) { R = Loc; }
1650 static bool classof(const Stmt *T) {
1651 return T->getStmtClass() == ParenExprClass;
1655 child_range children() { return child_range(&Val, &Val+1); }
1658 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1659 /// alignof), the postinc/postdec operators from postfix-expression, and various
1662 /// Notes on various nodes:
1664 /// Real/Imag - These return the real/imag part of a complex operand. If
1665 /// applied to a non-complex value, the former returns its operand and the
1666 /// later returns zero in the type of the operand.
1668 class UnaryOperator : public Expr {
1670 typedef UnaryOperatorKind Opcode;
1678 UnaryOperator(Expr *input, Opcode opc, QualType type,
1679 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1680 : Expr(UnaryOperatorClass, type, VK, OK,
1681 input->isTypeDependent() || type->isDependentType(),
1682 input->isValueDependent(),
1683 (input->isInstantiationDependent() ||
1684 type->isInstantiationDependentType()),
1685 input->containsUnexpandedParameterPack()),
1686 Opc(opc), Loc(l), Val(input) {}
1688 /// \brief Build an empty unary operator.
1689 explicit UnaryOperator(EmptyShell Empty)
1690 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1692 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1693 void setOpcode(Opcode O) { Opc = O; }
1695 Expr *getSubExpr() const { return cast<Expr>(Val); }
1696 void setSubExpr(Expr *E) { Val = E; }
1698 /// getOperatorLoc - Return the location of the operator.
1699 SourceLocation getOperatorLoc() const { return Loc; }
1700 void setOperatorLoc(SourceLocation L) { Loc = L; }
1702 /// isPostfix - Return true if this is a postfix operation, like x++.
1703 static bool isPostfix(Opcode Op) {
1704 return Op == UO_PostInc || Op == UO_PostDec;
1707 /// isPrefix - Return true if this is a prefix operation, like --x.
1708 static bool isPrefix(Opcode Op) {
1709 return Op == UO_PreInc || Op == UO_PreDec;
1712 bool isPrefix() const { return isPrefix(getOpcode()); }
1713 bool isPostfix() const { return isPostfix(getOpcode()); }
1715 static bool isIncrementOp(Opcode Op) {
1716 return Op == UO_PreInc || Op == UO_PostInc;
1718 bool isIncrementOp() const {
1719 return isIncrementOp(getOpcode());
1722 static bool isDecrementOp(Opcode Op) {
1723 return Op == UO_PreDec || Op == UO_PostDec;
1725 bool isDecrementOp() const {
1726 return isDecrementOp(getOpcode());
1729 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1730 bool isIncrementDecrementOp() const {
1731 return isIncrementDecrementOp(getOpcode());
1734 static bool isArithmeticOp(Opcode Op) {
1735 return Op >= UO_Plus && Op <= UO_LNot;
1737 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1739 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1740 /// corresponds to, e.g. "sizeof" or "[pre]++"
1741 static StringRef getOpcodeStr(Opcode Op);
1743 /// \brief Retrieve the unary opcode that corresponds to the given
1744 /// overloaded operator.
1745 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1747 /// \brief Retrieve the overloaded operator kind that corresponds to
1748 /// the given unary opcode.
1749 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1751 SourceLocation getLocStart() const LLVM_READONLY {
1752 return isPostfix() ? Val->getLocStart() : Loc;
1754 SourceLocation getLocEnd() const LLVM_READONLY {
1755 return isPostfix() ? Loc : Val->getLocEnd();
1757 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1759 static bool classof(const Stmt *T) {
1760 return T->getStmtClass() == UnaryOperatorClass;
1764 child_range children() { return child_range(&Val, &Val+1); }
1767 /// Helper class for OffsetOfExpr.
1769 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1770 class OffsetOfNode {
1772 /// \brief The kind of offsetof node we have.
1774 /// \brief An index into an array.
1778 /// \brief A field in a dependent type, known only by its name.
1780 /// \brief An implicit indirection through a C++ base class, when the
1781 /// field found is in a base class.
1786 enum { MaskBits = 2, Mask = 0x03 };
1788 /// \brief The source range that covers this part of the designator.
1791 /// \brief The data describing the designator, which comes in three
1792 /// different forms, depending on the lower two bits.
1793 /// - An unsigned index into the array of Expr*'s stored after this node
1794 /// in memory, for [constant-expression] designators.
1795 /// - A FieldDecl*, for references to a known field.
1796 /// - An IdentifierInfo*, for references to a field with a given name
1797 /// when the class type is dependent.
1798 /// - A CXXBaseSpecifier*, for references that look at a field in a
1803 /// \brief Create an offsetof node that refers to an array element.
1804 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1805 SourceLocation RBracketLoc)
1806 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1808 /// \brief Create an offsetof node that refers to a field.
1809 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1810 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1811 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1813 /// \brief Create an offsetof node that refers to an identifier.
1814 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1815 SourceLocation NameLoc)
1816 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1817 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1819 /// \brief Create an offsetof node that refers into a C++ base class.
1820 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1821 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1823 /// \brief Determine what kind of offsetof node this is.
1824 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1826 /// \brief For an array element node, returns the index into the array
1828 unsigned getArrayExprIndex() const {
1829 assert(getKind() == Array);
1833 /// \brief For a field offsetof node, returns the field.
1834 FieldDecl *getField() const {
1835 assert(getKind() == Field);
1836 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1839 /// \brief For a field or identifier offsetof node, returns the name of
1841 IdentifierInfo *getFieldName() const;
1843 /// \brief For a base class node, returns the base specifier.
1844 CXXBaseSpecifier *getBase() const {
1845 assert(getKind() == Base);
1846 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1849 /// \brief Retrieve the source range that covers this offsetof node.
1851 /// For an array element node, the source range contains the locations of
1852 /// the square brackets. For a field or identifier node, the source range
1853 /// contains the location of the period (if there is one) and the
1855 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1856 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1857 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1860 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1861 /// offsetof(record-type, member-designator). For example, given:
1872 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1874 class OffsetOfExpr final
1876 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1877 SourceLocation OperatorLoc, RParenLoc;
1879 TypeSourceInfo *TSInfo;
1880 // Number of sub-components (i.e. instances of OffsetOfNode).
1882 // Number of sub-expressions (i.e. array subscript expressions).
1885 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1889 OffsetOfExpr(const ASTContext &C, QualType type,
1890 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1891 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1892 SourceLocation RParenLoc);
1894 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1895 : Expr(OffsetOfExprClass, EmptyShell()),
1896 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1900 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1901 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1902 ArrayRef<OffsetOfNode> comps,
1903 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1905 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1906 unsigned NumComps, unsigned NumExprs);
1908 /// getOperatorLoc - Return the location of the operator.
1909 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1910 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1912 /// \brief Return the location of the right parentheses.
1913 SourceLocation getRParenLoc() const { return RParenLoc; }
1914 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1916 TypeSourceInfo *getTypeSourceInfo() const {
1919 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1923 const OffsetOfNode &getComponent(unsigned Idx) const {
1924 assert(Idx < NumComps && "Subscript out of range");
1925 return getTrailingObjects<OffsetOfNode>()[Idx];
1928 void setComponent(unsigned Idx, OffsetOfNode ON) {
1929 assert(Idx < NumComps && "Subscript out of range");
1930 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
1933 unsigned getNumComponents() const {
1937 Expr* getIndexExpr(unsigned Idx) {
1938 assert(Idx < NumExprs && "Subscript out of range");
1939 return getTrailingObjects<Expr *>()[Idx];
1942 const Expr *getIndexExpr(unsigned Idx) const {
1943 assert(Idx < NumExprs && "Subscript out of range");
1944 return getTrailingObjects<Expr *>()[Idx];
1947 void setIndexExpr(unsigned Idx, Expr* E) {
1948 assert(Idx < NumComps && "Subscript out of range");
1949 getTrailingObjects<Expr *>()[Idx] = E;
1952 unsigned getNumExpressions() const {
1956 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1957 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1959 static bool classof(const Stmt *T) {
1960 return T->getStmtClass() == OffsetOfExprClass;
1964 child_range children() {
1965 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
1966 return child_range(begin, begin + NumExprs);
1968 friend TrailingObjects;
1971 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1972 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1973 /// vec_step (OpenCL 1.1 6.11.12).
1974 class UnaryExprOrTypeTraitExpr : public Expr {
1979 SourceLocation OpLoc, RParenLoc;
1982 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1983 QualType resultType, SourceLocation op,
1984 SourceLocation rp) :
1985 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1986 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1987 // Value-dependent if the argument is type-dependent.
1988 TInfo->getType()->isDependentType(),
1989 TInfo->getType()->isInstantiationDependentType(),
1990 TInfo->getType()->containsUnexpandedParameterPack()),
1991 OpLoc(op), RParenLoc(rp) {
1992 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1993 UnaryExprOrTypeTraitExprBits.IsType = true;
1994 Argument.Ty = TInfo;
1997 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1998 QualType resultType, SourceLocation op,
2001 /// \brief Construct an empty sizeof/alignof expression.
2002 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2003 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2005 UnaryExprOrTypeTrait getKind() const {
2006 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2008 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2010 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2011 QualType getArgumentType() const {
2012 return getArgumentTypeInfo()->getType();
2014 TypeSourceInfo *getArgumentTypeInfo() const {
2015 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2018 Expr *getArgumentExpr() {
2019 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2020 return static_cast<Expr*>(Argument.Ex);
2022 const Expr *getArgumentExpr() const {
2023 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2026 void setArgument(Expr *E) {
2028 UnaryExprOrTypeTraitExprBits.IsType = false;
2030 void setArgument(TypeSourceInfo *TInfo) {
2031 Argument.Ty = TInfo;
2032 UnaryExprOrTypeTraitExprBits.IsType = true;
2035 /// Gets the argument type, or the type of the argument expression, whichever
2037 QualType getTypeOfArgument() const {
2038 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2041 SourceLocation getOperatorLoc() const { return OpLoc; }
2042 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2044 SourceLocation getRParenLoc() const { return RParenLoc; }
2045 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2047 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2048 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2050 static bool classof(const Stmt *T) {
2051 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2055 child_range children();
2058 //===----------------------------------------------------------------------===//
2059 // Postfix Operators.
2060 //===----------------------------------------------------------------------===//
2062 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2063 class ArraySubscriptExpr : public Expr {
2064 enum { LHS, RHS, END_EXPR=2 };
2065 Stmt* SubExprs[END_EXPR];
2066 SourceLocation RBracketLoc;
2068 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2069 ExprValueKind VK, ExprObjectKind OK,
2070 SourceLocation rbracketloc)
2071 : Expr(ArraySubscriptExprClass, t, VK, OK,
2072 lhs->isTypeDependent() || rhs->isTypeDependent(),
2073 lhs->isValueDependent() || rhs->isValueDependent(),
2074 (lhs->isInstantiationDependent() ||
2075 rhs->isInstantiationDependent()),
2076 (lhs->containsUnexpandedParameterPack() ||
2077 rhs->containsUnexpandedParameterPack())),
2078 RBracketLoc(rbracketloc) {
2079 SubExprs[LHS] = lhs;
2080 SubExprs[RHS] = rhs;
2083 /// \brief Create an empty array subscript expression.
2084 explicit ArraySubscriptExpr(EmptyShell Shell)
2085 : Expr(ArraySubscriptExprClass, Shell) { }
2087 /// An array access can be written A[4] or 4[A] (both are equivalent).
2088 /// - getBase() and getIdx() always present the normalized view: A[4].
2089 /// In this case getBase() returns "A" and getIdx() returns "4".
2090 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2091 /// 4[A] getLHS() returns "4".
2092 /// Note: Because vector element access is also written A[4] we must
2093 /// predicate the format conversion in getBase and getIdx only on the
2094 /// the type of the RHS, as it is possible for the LHS to be a vector of
2096 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2097 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2098 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2100 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2101 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2102 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2105 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2108 const Expr *getBase() const {
2109 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2113 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2116 const Expr *getIdx() const {
2117 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2120 SourceLocation getLocStart() const LLVM_READONLY {
2121 return getLHS()->getLocStart();
2123 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2125 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2126 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2128 SourceLocation getExprLoc() const LLVM_READONLY {
2129 return getBase()->getExprLoc();
2132 static bool classof(const Stmt *T) {
2133 return T->getStmtClass() == ArraySubscriptExprClass;
2137 child_range children() {
2138 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2142 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2143 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2144 /// while its subclasses may represent alternative syntax that (semantically)
2145 /// results in a function call. For example, CXXOperatorCallExpr is
2146 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2147 /// "str1 + str2" to resolve to a function call.
2148 class CallExpr : public Expr {
2149 enum { FN=0, PREARGS_START=1 };
2152 SourceLocation RParenLoc;
2154 void updateDependenciesFromArg(Expr *Arg);
2157 // These versions of the constructor are for derived classes.
2158 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2159 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2160 ExprValueKind VK, SourceLocation rparenloc);
2161 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2162 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2163 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2166 Stmt *getPreArg(unsigned i) {
2167 assert(i < getNumPreArgs() && "Prearg access out of range!");
2168 return SubExprs[PREARGS_START+i];
2170 const Stmt *getPreArg(unsigned i) const {
2171 assert(i < getNumPreArgs() && "Prearg access out of range!");
2172 return SubExprs[PREARGS_START+i];
2174 void setPreArg(unsigned i, Stmt *PreArg) {
2175 assert(i < getNumPreArgs() && "Prearg access out of range!");
2176 SubExprs[PREARGS_START+i] = PreArg;
2179 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2182 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2183 ExprValueKind VK, SourceLocation rparenloc);
2185 /// \brief Build an empty call expression.
2186 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2188 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2189 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2190 void setCallee(Expr *F) { SubExprs[FN] = F; }
2192 Decl *getCalleeDecl();
2193 const Decl *getCalleeDecl() const {
2194 return const_cast<CallExpr*>(this)->getCalleeDecl();
2197 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2198 FunctionDecl *getDirectCallee();
2199 const FunctionDecl *getDirectCallee() const {
2200 return const_cast<CallExpr*>(this)->getDirectCallee();
2203 /// getNumArgs - Return the number of actual arguments to this call.
2205 unsigned getNumArgs() const { return NumArgs; }
2207 /// \brief Retrieve the call arguments.
2209 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2211 const Expr *const *getArgs() const {
2212 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2216 /// getArg - Return the specified argument.
2217 Expr *getArg(unsigned Arg) {
2218 assert(Arg < NumArgs && "Arg access out of range!");
2219 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2221 const Expr *getArg(unsigned Arg) const {
2222 assert(Arg < NumArgs && "Arg access out of range!");
2223 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2226 /// setArg - Set the specified argument.
2227 void setArg(unsigned Arg, Expr *ArgExpr) {
2228 assert(Arg < NumArgs && "Arg access out of range!");
2229 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2232 /// setNumArgs - This changes the number of arguments present in this call.
2233 /// Any orphaned expressions are deleted by this, and any new operands are set
2235 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2237 typedef ExprIterator arg_iterator;
2238 typedef ConstExprIterator const_arg_iterator;
2239 typedef llvm::iterator_range<arg_iterator> arg_range;
2240 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2242 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2243 arg_const_range arguments() const {
2244 return arg_const_range(arg_begin(), arg_end());
2247 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2248 arg_iterator arg_end() {
2249 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2251 const_arg_iterator arg_begin() const {
2252 return SubExprs+PREARGS_START+getNumPreArgs();
2254 const_arg_iterator arg_end() const {
2255 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2258 /// This method provides fast access to all the subexpressions of
2259 /// a CallExpr without going through the slower virtual child_iterator
2260 /// interface. This provides efficient reverse iteration of the
2261 /// subexpressions. This is currently used for CFG construction.
2262 ArrayRef<Stmt*> getRawSubExprs() {
2263 return llvm::makeArrayRef(SubExprs,
2264 getNumPreArgs() + PREARGS_START + getNumArgs());
2267 /// getNumCommas - Return the number of commas that must have been present in
2268 /// this function call.
2269 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2271 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2272 /// of the callee. If not, return 0.
2273 unsigned getBuiltinCallee() const;
2275 /// \brief Returns \c true if this is a call to a builtin which does not
2276 /// evaluate side-effects within its arguments.
2277 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2279 /// getCallReturnType - Get the return type of the call expr. This is not
2280 /// always the type of the expr itself, if the return type is a reference
2282 QualType getCallReturnType(const ASTContext &Ctx) const;
2284 SourceLocation getRParenLoc() const { return RParenLoc; }
2285 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2287 SourceLocation getLocStart() const LLVM_READONLY;
2288 SourceLocation getLocEnd() const LLVM_READONLY;
2290 static bool classof(const Stmt *T) {
2291 return T->getStmtClass() >= firstCallExprConstant &&
2292 T->getStmtClass() <= lastCallExprConstant;
2296 child_range children() {
2297 return child_range(&SubExprs[0],
2298 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2302 /// Extra data stored in some MemberExpr objects.
2303 struct MemberExprNameQualifier {
2304 /// \brief The nested-name-specifier that qualifies the name, including
2305 /// source-location information.
2306 NestedNameSpecifierLoc QualifierLoc;
2308 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2309 /// name qualifiers.
2310 DeclAccessPair FoundDecl;
2313 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2315 class MemberExpr final
2317 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2318 ASTTemplateKWAndArgsInfo,
2319 TemplateArgumentLoc> {
2320 /// Base - the expression for the base pointer or structure references. In
2321 /// X.F, this is "X".
2324 /// MemberDecl - This is the decl being referenced by the field/member name.
2325 /// In X.F, this is the decl referenced by F.
2326 ValueDecl *MemberDecl;
2328 /// MemberDNLoc - Provides source/type location info for the
2329 /// declaration name embedded in MemberDecl.
2330 DeclarationNameLoc MemberDNLoc;
2332 /// MemberLoc - This is the location of the member name.
2333 SourceLocation MemberLoc;
2335 /// This is the location of the -> or . in the expression.
2336 SourceLocation OperatorLoc;
2338 /// IsArrow - True if this is "X->F", false if this is "X.F".
2341 /// \brief True if this member expression used a nested-name-specifier to
2342 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2343 /// declaration. When true, a MemberExprNameQualifier
2344 /// structure is allocated immediately after the MemberExpr.
2345 bool HasQualifierOrFoundDecl : 1;
2347 /// \brief True if this member expression specified a template keyword
2348 /// and/or a template argument list explicitly, e.g., x->f<int>,
2349 /// x->template f, x->template f<int>.
2350 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2351 /// TemplateArguments (if any) are present.
2352 bool HasTemplateKWAndArgsInfo : 1;
2354 /// \brief True if this member expression refers to a method that
2355 /// was resolved from an overloaded set having size greater than 1.
2356 bool HadMultipleCandidates : 1;
2358 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2359 return HasQualifierOrFoundDecl ? 1 : 0;
2362 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2363 return HasTemplateKWAndArgsInfo ? 1 : 0;
2367 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2368 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2369 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2370 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2371 base->isValueDependent(), base->isInstantiationDependent(),
2372 base->containsUnexpandedParameterPack()),
2373 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2374 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2375 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2376 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2377 assert(memberdecl->getDeclName() == NameInfo.getName());
2380 // NOTE: this constructor should be used only when it is known that
2381 // the member name can not provide additional syntactic info
2382 // (i.e., source locations for C++ operator names or type source info
2383 // for constructors, destructors and conversion operators).
2384 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2385 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2386 ExprValueKind VK, ExprObjectKind OK)
2387 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2388 base->isValueDependent(), base->isInstantiationDependent(),
2389 base->containsUnexpandedParameterPack()),
2390 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2391 OperatorLoc(operatorloc), IsArrow(isarrow),
2392 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2393 HadMultipleCandidates(false) {}
2395 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2396 SourceLocation OperatorLoc,
2397 NestedNameSpecifierLoc QualifierLoc,
2398 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2399 DeclAccessPair founddecl,
2400 DeclarationNameInfo MemberNameInfo,
2401 const TemplateArgumentListInfo *targs, QualType ty,
2402 ExprValueKind VK, ExprObjectKind OK);
2404 void setBase(Expr *E) { Base = E; }
2405 Expr *getBase() const { return cast<Expr>(Base); }
2407 /// \brief Retrieve the member declaration to which this expression refers.
2409 /// The returned declaration will either be a FieldDecl or (in C++)
2410 /// a CXXMethodDecl.
2411 ValueDecl *getMemberDecl() const { return MemberDecl; }
2412 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2414 /// \brief Retrieves the declaration found by lookup.
2415 DeclAccessPair getFoundDecl() const {
2416 if (!HasQualifierOrFoundDecl)
2417 return DeclAccessPair::make(getMemberDecl(),
2418 getMemberDecl()->getAccess());
2419 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2422 /// \brief Determines whether this member expression actually had
2423 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2425 bool hasQualifier() const { return getQualifier() != nullptr; }
2427 /// \brief If the member name was qualified, retrieves the
2428 /// nested-name-specifier that precedes the member name, with source-location
2430 NestedNameSpecifierLoc getQualifierLoc() const {
2431 if (!HasQualifierOrFoundDecl)
2432 return NestedNameSpecifierLoc();
2434 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2437 /// \brief If the member name was qualified, retrieves the
2438 /// nested-name-specifier that precedes the member name. Otherwise, returns
2440 NestedNameSpecifier *getQualifier() const {
2441 return getQualifierLoc().getNestedNameSpecifier();
2444 /// \brief Retrieve the location of the template keyword preceding
2445 /// the member name, if any.
2446 SourceLocation getTemplateKeywordLoc() const {
2447 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2448 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2451 /// \brief Retrieve the location of the left angle bracket starting the
2452 /// explicit template argument list following the member name, if any.
2453 SourceLocation getLAngleLoc() const {
2454 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2455 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2458 /// \brief Retrieve the location of the right angle bracket ending the
2459 /// explicit template argument list following the member name, if any.
2460 SourceLocation getRAngleLoc() const {
2461 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2462 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2465 /// Determines whether the member name was preceded by the template keyword.
2466 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2468 /// \brief Determines whether the member name was followed by an
2469 /// explicit template argument list.
2470 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2472 /// \brief Copies the template arguments (if present) into the given
2474 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2475 if (hasExplicitTemplateArgs())
2476 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2477 getTrailingObjects<TemplateArgumentLoc>(), List);
2480 /// \brief Retrieve the template arguments provided as part of this
2482 const TemplateArgumentLoc *getTemplateArgs() const {
2483 if (!hasExplicitTemplateArgs())
2486 return getTrailingObjects<TemplateArgumentLoc>();
2489 /// \brief Retrieve the number of template arguments provided as part of this
2491 unsigned getNumTemplateArgs() const {
2492 if (!hasExplicitTemplateArgs())
2495 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2498 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2499 return {getTemplateArgs(), getNumTemplateArgs()};
2502 /// \brief Retrieve the member declaration name info.
2503 DeclarationNameInfo getMemberNameInfo() const {
2504 return DeclarationNameInfo(MemberDecl->getDeclName(),
2505 MemberLoc, MemberDNLoc);
2508 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2510 bool isArrow() const { return IsArrow; }
2511 void setArrow(bool A) { IsArrow = A; }
2513 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2514 /// location of 'F'.
2515 SourceLocation getMemberLoc() const { return MemberLoc; }
2516 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2518 SourceLocation getLocStart() const LLVM_READONLY;
2519 SourceLocation getLocEnd() const LLVM_READONLY;
2521 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2523 /// \brief Determine whether the base of this explicit is implicit.
2524 bool isImplicitAccess() const {
2525 return getBase() && getBase()->isImplicitCXXThis();
2528 /// \brief Returns true if this member expression refers to a method that
2529 /// was resolved from an overloaded set having size greater than 1.
2530 bool hadMultipleCandidates() const {
2531 return HadMultipleCandidates;
2533 /// \brief Sets the flag telling whether this expression refers to
2534 /// a method that was resolved from an overloaded set having size
2536 void setHadMultipleCandidates(bool V = true) {
2537 HadMultipleCandidates = V;
2540 /// \brief Returns true if virtual dispatch is performed.
2541 /// If the member access is fully qualified, (i.e. X::f()), virtual
2542 /// dispatching is not performed. In -fapple-kext mode qualified
2543 /// calls to virtual method will still go through the vtable.
2544 bool performsVirtualDispatch(const LangOptions &LO) const {
2545 return LO.AppleKext || !hasQualifier();
2548 static bool classof(const Stmt *T) {
2549 return T->getStmtClass() == MemberExprClass;
2553 child_range children() { return child_range(&Base, &Base+1); }
2555 friend TrailingObjects;
2556 friend class ASTReader;
2557 friend class ASTStmtWriter;
2560 /// CompoundLiteralExpr - [C99 6.5.2.5]
2562 class CompoundLiteralExpr : public Expr {
2563 /// LParenLoc - If non-null, this is the location of the left paren in a
2564 /// compound literal like "(int){4}". This can be null if this is a
2565 /// synthesized compound expression.
2566 SourceLocation LParenLoc;
2568 /// The type as written. This can be an incomplete array type, in
2569 /// which case the actual expression type will be different.
2570 /// The int part of the pair stores whether this expr is file scope.
2571 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2574 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2575 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2576 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2577 tinfo->getType()->isDependentType(),
2578 init->isValueDependent(),
2579 (init->isInstantiationDependent() ||
2580 tinfo->getType()->isInstantiationDependentType()),
2581 init->containsUnexpandedParameterPack()),
2582 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2584 /// \brief Construct an empty compound literal.
2585 explicit CompoundLiteralExpr(EmptyShell Empty)
2586 : Expr(CompoundLiteralExprClass, Empty) { }
2588 const Expr *getInitializer() const { return cast<Expr>(Init); }
2589 Expr *getInitializer() { return cast<Expr>(Init); }
2590 void setInitializer(Expr *E) { Init = E; }
2592 bool isFileScope() const { return TInfoAndScope.getInt(); }
2593 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2595 SourceLocation getLParenLoc() const { return LParenLoc; }
2596 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2598 TypeSourceInfo *getTypeSourceInfo() const {
2599 return TInfoAndScope.getPointer();
2601 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2602 TInfoAndScope.setPointer(tinfo);
2605 SourceLocation getLocStart() const LLVM_READONLY {
2606 // FIXME: Init should never be null.
2608 return SourceLocation();
2609 if (LParenLoc.isInvalid())
2610 return Init->getLocStart();
2613 SourceLocation getLocEnd() const LLVM_READONLY {
2614 // FIXME: Init should never be null.
2616 return SourceLocation();
2617 return Init->getLocEnd();
2620 static bool classof(const Stmt *T) {
2621 return T->getStmtClass() == CompoundLiteralExprClass;
2625 child_range children() { return child_range(&Init, &Init+1); }
2628 /// CastExpr - Base class for type casts, including both implicit
2629 /// casts (ImplicitCastExpr) and explicit casts that have some
2630 /// representation in the source code (ExplicitCastExpr's derived
2632 class CastExpr : public Expr {
2636 bool CastConsistency() const;
2638 const CXXBaseSpecifier * const *path_buffer() const {
2639 return const_cast<CastExpr*>(this)->path_buffer();
2641 CXXBaseSpecifier **path_buffer();
2643 void setBasePathSize(unsigned basePathSize) {
2644 CastExprBits.BasePathSize = basePathSize;
2645 assert(CastExprBits.BasePathSize == basePathSize &&
2646 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2650 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2651 Expr *op, unsigned BasePathSize)
2652 : Expr(SC, ty, VK, OK_Ordinary,
2653 // Cast expressions are type-dependent if the type is
2654 // dependent (C++ [temp.dep.expr]p3).
2655 ty->isDependentType(),
2656 // Cast expressions are value-dependent if the type is
2657 // dependent or if the subexpression is value-dependent.
2658 ty->isDependentType() || (op && op->isValueDependent()),
2659 (ty->isInstantiationDependentType() ||
2660 (op && op->isInstantiationDependent())),
2661 // An implicit cast expression doesn't (lexically) contain an
2662 // unexpanded pack, even if its target type does.
2663 ((SC != ImplicitCastExprClass &&
2664 ty->containsUnexpandedParameterPack()) ||
2665 (op && op->containsUnexpandedParameterPack()))),
2667 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2668 CastExprBits.Kind = kind;
2669 setBasePathSize(BasePathSize);
2670 assert(CastConsistency());
2673 /// \brief Construct an empty cast.
2674 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2676 setBasePathSize(BasePathSize);
2680 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2681 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2682 const char *getCastKindName() const;
2684 Expr *getSubExpr() { return cast<Expr>(Op); }
2685 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2686 void setSubExpr(Expr *E) { Op = E; }
2688 /// \brief Retrieve the cast subexpression as it was written in the source
2689 /// code, looking through any implicit casts or other intermediate nodes
2690 /// introduced by semantic analysis.
2691 Expr *getSubExprAsWritten();
2692 const Expr *getSubExprAsWritten() const {
2693 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2696 typedef CXXBaseSpecifier **path_iterator;
2697 typedef const CXXBaseSpecifier * const *path_const_iterator;
2698 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2699 unsigned path_size() const { return CastExprBits.BasePathSize; }
2700 path_iterator path_begin() { return path_buffer(); }
2701 path_iterator path_end() { return path_buffer() + path_size(); }
2702 path_const_iterator path_begin() const { return path_buffer(); }
2703 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2705 static bool classof(const Stmt *T) {
2706 return T->getStmtClass() >= firstCastExprConstant &&
2707 T->getStmtClass() <= lastCastExprConstant;
2711 child_range children() { return child_range(&Op, &Op+1); }
2714 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2715 /// conversions, which have no direct representation in the original
2716 /// source code. For example: converting T[]->T*, void f()->void
2717 /// (*f)(), float->double, short->int, etc.
2719 /// In C, implicit casts always produce rvalues. However, in C++, an
2720 /// implicit cast whose result is being bound to a reference will be
2721 /// an lvalue or xvalue. For example:
2725 /// class Derived : public Base { };
2726 /// Derived &&ref();
2727 /// void f(Derived d) {
2728 /// Base& b = d; // initializer is an ImplicitCastExpr
2729 /// // to an lvalue of type Base
2730 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2731 /// // to an xvalue of type Base
2734 class ImplicitCastExpr final
2736 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2738 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2739 unsigned BasePathLength, ExprValueKind VK)
2740 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2743 /// \brief Construct an empty implicit cast.
2744 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2745 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2748 enum OnStack_t { OnStack };
2749 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2751 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2754 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2755 CastKind Kind, Expr *Operand,
2756 const CXXCastPath *BasePath,
2759 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2762 SourceLocation getLocStart() const LLVM_READONLY {
2763 return getSubExpr()->getLocStart();
2765 SourceLocation getLocEnd() const LLVM_READONLY {
2766 return getSubExpr()->getLocEnd();
2769 static bool classof(const Stmt *T) {
2770 return T->getStmtClass() == ImplicitCastExprClass;
2773 friend TrailingObjects;
2774 friend class CastExpr;
2777 inline Expr *Expr::IgnoreImpCasts() {
2779 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2780 e = ice->getSubExpr();
2784 /// ExplicitCastExpr - An explicit cast written in the source
2787 /// This class is effectively an abstract class, because it provides
2788 /// the basic representation of an explicitly-written cast without
2789 /// specifying which kind of cast (C cast, functional cast, static
2790 /// cast, etc.) was written; specific derived classes represent the
2791 /// particular style of cast and its location information.
2793 /// Unlike implicit casts, explicit cast nodes have two different
2794 /// types: the type that was written into the source code, and the
2795 /// actual type of the expression as determined by semantic
2796 /// analysis. These types may differ slightly. For example, in C++ one
2797 /// can cast to a reference type, which indicates that the resulting
2798 /// expression will be an lvalue or xvalue. The reference type, however,
2799 /// will not be used as the type of the expression.
2800 class ExplicitCastExpr : public CastExpr {
2801 /// TInfo - Source type info for the (written) type
2802 /// this expression is casting to.
2803 TypeSourceInfo *TInfo;
2806 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2807 CastKind kind, Expr *op, unsigned PathSize,
2808 TypeSourceInfo *writtenTy)
2809 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2811 /// \brief Construct an empty explicit cast.
2812 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2813 : CastExpr(SC, Shell, PathSize) { }
2816 /// getTypeInfoAsWritten - Returns the type source info for the type
2817 /// that this expression is casting to.
2818 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2819 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2821 /// getTypeAsWritten - Returns the type that this expression is
2822 /// casting to, as written in the source code.
2823 QualType getTypeAsWritten() const { return TInfo->getType(); }
2825 static bool classof(const Stmt *T) {
2826 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2827 T->getStmtClass() <= lastExplicitCastExprConstant;
2831 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2832 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2833 /// (Type)expr. For example: @c (int)f.
2834 class CStyleCastExpr final
2835 : public ExplicitCastExpr,
2836 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2837 SourceLocation LPLoc; // the location of the left paren
2838 SourceLocation RPLoc; // the location of the right paren
2840 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2841 unsigned PathSize, TypeSourceInfo *writtenTy,
2842 SourceLocation l, SourceLocation r)
2843 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2844 writtenTy), LPLoc(l), RPLoc(r) {}
2846 /// \brief Construct an empty C-style explicit cast.
2847 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2848 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2851 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2852 ExprValueKind VK, CastKind K,
2853 Expr *Op, const CXXCastPath *BasePath,
2854 TypeSourceInfo *WrittenTy, SourceLocation L,
2857 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2860 SourceLocation getLParenLoc() const { return LPLoc; }
2861 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2863 SourceLocation getRParenLoc() const { return RPLoc; }
2864 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2866 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2867 SourceLocation getLocEnd() const LLVM_READONLY {
2868 return getSubExpr()->getLocEnd();
2871 static bool classof(const Stmt *T) {
2872 return T->getStmtClass() == CStyleCastExprClass;
2875 friend TrailingObjects;
2876 friend class CastExpr;
2879 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2881 /// This expression node kind describes a builtin binary operation,
2882 /// such as "x + y" for integer values "x" and "y". The operands will
2883 /// already have been converted to appropriate types (e.g., by
2884 /// performing promotions or conversions).
2886 /// In C++, where operators may be overloaded, a different kind of
2887 /// expression node (CXXOperatorCallExpr) is used to express the
2888 /// invocation of an overloaded operator with operator syntax. Within
2889 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2890 /// used to store an expression "x + y" depends on the subexpressions
2891 /// for x and y. If neither x or y is type-dependent, and the "+"
2892 /// operator resolves to a built-in operation, BinaryOperator will be
2893 /// used to express the computation (x and y may still be
2894 /// value-dependent). If either x or y is type-dependent, or if the
2895 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2896 /// be used to express the computation.
2897 class BinaryOperator : public Expr {
2899 typedef BinaryOperatorKind Opcode;
2904 // Records the FP_CONTRACT pragma status at the point that this binary
2905 // operator was parsed. This bit is only meaningful for operations on
2906 // floating point types. For all other types it should default to
2908 unsigned FPContractable : 1;
2909 SourceLocation OpLoc;
2911 enum { LHS, RHS, END_EXPR };
2912 Stmt* SubExprs[END_EXPR];
2915 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2916 ExprValueKind VK, ExprObjectKind OK,
2917 SourceLocation opLoc, bool fpContractable)
2918 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2919 lhs->isTypeDependent() || rhs->isTypeDependent(),
2920 lhs->isValueDependent() || rhs->isValueDependent(),
2921 (lhs->isInstantiationDependent() ||
2922 rhs->isInstantiationDependent()),
2923 (lhs->containsUnexpandedParameterPack() ||
2924 rhs->containsUnexpandedParameterPack())),
2925 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2926 SubExprs[LHS] = lhs;
2927 SubExprs[RHS] = rhs;
2928 assert(!isCompoundAssignmentOp() &&
2929 "Use CompoundAssignOperator for compound assignments");
2932 /// \brief Construct an empty binary operator.
2933 explicit BinaryOperator(EmptyShell Empty)
2934 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2936 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2937 SourceLocation getOperatorLoc() const { return OpLoc; }
2938 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2940 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2941 void setOpcode(Opcode O) { Opc = O; }
2943 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2944 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2945 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2946 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2948 SourceLocation getLocStart() const LLVM_READONLY {
2949 return getLHS()->getLocStart();
2951 SourceLocation getLocEnd() const LLVM_READONLY {
2952 return getRHS()->getLocEnd();
2955 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2956 /// corresponds to, e.g. "<<=".
2957 static StringRef getOpcodeStr(Opcode Op);
2959 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2961 /// \brief Retrieve the binary opcode that corresponds to the given
2962 /// overloaded operator.
2963 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2965 /// \brief Retrieve the overloaded operator kind that corresponds to
2966 /// the given binary opcode.
2967 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2969 /// predicates to categorize the respective opcodes.
2970 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2971 static bool isMultiplicativeOp(Opcode Opc) {
2972 return Opc >= BO_Mul && Opc <= BO_Rem;
2974 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
2975 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2976 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2977 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2978 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2980 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2981 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2983 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2984 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2986 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2987 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2989 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2990 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2992 static Opcode negateComparisonOp(Opcode Opc) {
2995 llvm_unreachable("Not a comparsion operator.");
2996 case BO_LT: return BO_GE;
2997 case BO_GT: return BO_LE;
2998 case BO_LE: return BO_GT;
2999 case BO_GE: return BO_LT;
3000 case BO_EQ: return BO_NE;
3001 case BO_NE: return BO_EQ;
3005 static Opcode reverseComparisonOp(Opcode Opc) {
3008 llvm_unreachable("Not a comparsion operator.");
3009 case BO_LT: return BO_GT;
3010 case BO_GT: return BO_LT;
3011 case BO_LE: return BO_GE;
3012 case BO_GE: return BO_LE;
3019 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3020 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3022 static bool isAssignmentOp(Opcode Opc) {
3023 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3025 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3027 static bool isCompoundAssignmentOp(Opcode Opc) {
3028 return Opc > BO_Assign && Opc <= BO_OrAssign;
3030 bool isCompoundAssignmentOp() const {
3031 return isCompoundAssignmentOp(getOpcode());
3033 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3034 assert(isCompoundAssignmentOp(Opc));
3035 if (Opc >= BO_AndAssign)
3036 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3038 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3041 static bool isShiftAssignOp(Opcode Opc) {
3042 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3044 bool isShiftAssignOp() const {
3045 return isShiftAssignOp(getOpcode());
3048 static bool classof(const Stmt *S) {
3049 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3050 S->getStmtClass() <= lastBinaryOperatorConstant;
3054 child_range children() {
3055 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3058 // Set the FP contractability status of this operator. Only meaningful for
3059 // operations on floating point types.
3060 void setFPContractable(bool FPC) { FPContractable = FPC; }
3062 // Get the FP contractability status of this operator. Only meaningful for
3063 // operations on floating point types.
3064 bool isFPContractable() const { return FPContractable; }
3067 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3068 ExprValueKind VK, ExprObjectKind OK,
3069 SourceLocation opLoc, bool fpContractable, bool dead2)
3070 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3071 lhs->isTypeDependent() || rhs->isTypeDependent(),
3072 lhs->isValueDependent() || rhs->isValueDependent(),
3073 (lhs->isInstantiationDependent() ||
3074 rhs->isInstantiationDependent()),
3075 (lhs->containsUnexpandedParameterPack() ||
3076 rhs->containsUnexpandedParameterPack())),
3077 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3078 SubExprs[LHS] = lhs;
3079 SubExprs[RHS] = rhs;
3082 BinaryOperator(StmtClass SC, EmptyShell Empty)
3083 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3086 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3087 /// track of the type the operation is performed in. Due to the semantics of
3088 /// these operators, the operands are promoted, the arithmetic performed, an
3089 /// implicit conversion back to the result type done, then the assignment takes
3090 /// place. This captures the intermediate type which the computation is done
3092 class CompoundAssignOperator : public BinaryOperator {
3093 QualType ComputationLHSType;
3094 QualType ComputationResultType;
3096 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3097 ExprValueKind VK, ExprObjectKind OK,
3098 QualType CompLHSType, QualType CompResultType,
3099 SourceLocation OpLoc, bool fpContractable)
3100 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3102 ComputationLHSType(CompLHSType),
3103 ComputationResultType(CompResultType) {
3104 assert(isCompoundAssignmentOp() &&
3105 "Only should be used for compound assignments");
3108 /// \brief Build an empty compound assignment operator expression.
3109 explicit CompoundAssignOperator(EmptyShell Empty)
3110 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3112 // The two computation types are the type the LHS is converted
3113 // to for the computation and the type of the result; the two are
3114 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3115 QualType getComputationLHSType() const { return ComputationLHSType; }
3116 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3118 QualType getComputationResultType() const { return ComputationResultType; }
3119 void setComputationResultType(QualType T) { ComputationResultType = T; }
3121 static bool classof(const Stmt *S) {
3122 return S->getStmtClass() == CompoundAssignOperatorClass;
3126 /// AbstractConditionalOperator - An abstract base class for
3127 /// ConditionalOperator and BinaryConditionalOperator.
3128 class AbstractConditionalOperator : public Expr {
3129 SourceLocation QuestionLoc, ColonLoc;
3130 friend class ASTStmtReader;
3133 AbstractConditionalOperator(StmtClass SC, QualType T,
3134 ExprValueKind VK, ExprObjectKind OK,
3135 bool TD, bool VD, bool ID,
3136 bool ContainsUnexpandedParameterPack,
3137 SourceLocation qloc,
3138 SourceLocation cloc)
3139 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3140 QuestionLoc(qloc), ColonLoc(cloc) {}
3142 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3143 : Expr(SC, Empty) { }
3146 // getCond - Return the expression representing the condition for
3148 Expr *getCond() const;
3150 // getTrueExpr - Return the subexpression representing the value of
3151 // the expression if the condition evaluates to true.
3152 Expr *getTrueExpr() const;
3154 // getFalseExpr - Return the subexpression representing the value of
3155 // the expression if the condition evaluates to false. This is
3156 // the same as getRHS.
3157 Expr *getFalseExpr() const;
3159 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3160 SourceLocation getColonLoc() const { return ColonLoc; }
3162 static bool classof(const Stmt *T) {
3163 return T->getStmtClass() == ConditionalOperatorClass ||
3164 T->getStmtClass() == BinaryConditionalOperatorClass;
3168 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3169 /// middle" extension is a BinaryConditionalOperator.
3170 class ConditionalOperator : public AbstractConditionalOperator {
3171 enum { COND, LHS, RHS, END_EXPR };
3172 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3174 friend class ASTStmtReader;
3176 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3177 SourceLocation CLoc, Expr *rhs,
3178 QualType t, ExprValueKind VK, ExprObjectKind OK)
3179 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3180 // FIXME: the type of the conditional operator doesn't
3181 // depend on the type of the conditional, but the standard
3182 // seems to imply that it could. File a bug!
3183 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3184 (cond->isValueDependent() || lhs->isValueDependent() ||
3185 rhs->isValueDependent()),
3186 (cond->isInstantiationDependent() ||
3187 lhs->isInstantiationDependent() ||
3188 rhs->isInstantiationDependent()),
3189 (cond->containsUnexpandedParameterPack() ||
3190 lhs->containsUnexpandedParameterPack() ||
3191 rhs->containsUnexpandedParameterPack()),
3193 SubExprs[COND] = cond;
3194 SubExprs[LHS] = lhs;
3195 SubExprs[RHS] = rhs;
3198 /// \brief Build an empty conditional operator.
3199 explicit ConditionalOperator(EmptyShell Empty)
3200 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3202 // getCond - Return the expression representing the condition for
3204 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3206 // getTrueExpr - Return the subexpression representing the value of
3207 // the expression if the condition evaluates to true.
3208 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3210 // getFalseExpr - Return the subexpression representing the value of
3211 // the expression if the condition evaluates to false. This is
3212 // the same as getRHS.
3213 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3215 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3216 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3218 SourceLocation getLocStart() const LLVM_READONLY {
3219 return getCond()->getLocStart();
3221 SourceLocation getLocEnd() const LLVM_READONLY {
3222 return getRHS()->getLocEnd();
3225 static bool classof(const Stmt *T) {
3226 return T->getStmtClass() == ConditionalOperatorClass;
3230 child_range children() {
3231 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3235 /// BinaryConditionalOperator - The GNU extension to the conditional
3236 /// operator which allows the middle operand to be omitted.
3238 /// This is a different expression kind on the assumption that almost
3239 /// every client ends up needing to know that these are different.
3240 class BinaryConditionalOperator : public AbstractConditionalOperator {
3241 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3243 /// - the common condition/left-hand-side expression, which will be
3244 /// evaluated as the opaque value
3245 /// - the condition, expressed in terms of the opaque value
3246 /// - the left-hand-side, expressed in terms of the opaque value
3247 /// - the right-hand-side
3248 Stmt *SubExprs[NUM_SUBEXPRS];
3249 OpaqueValueExpr *OpaqueValue;
3251 friend class ASTStmtReader;
3253 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3254 Expr *cond, Expr *lhs, Expr *rhs,
3255 SourceLocation qloc, SourceLocation cloc,
3256 QualType t, ExprValueKind VK, ExprObjectKind OK)
3257 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3258 (common->isTypeDependent() || rhs->isTypeDependent()),
3259 (common->isValueDependent() || rhs->isValueDependent()),
3260 (common->isInstantiationDependent() ||
3261 rhs->isInstantiationDependent()),
3262 (common->containsUnexpandedParameterPack() ||
3263 rhs->containsUnexpandedParameterPack()),
3265 OpaqueValue(opaqueValue) {
3266 SubExprs[COMMON] = common;
3267 SubExprs[COND] = cond;
3268 SubExprs[LHS] = lhs;
3269 SubExprs[RHS] = rhs;
3270 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3273 /// \brief Build an empty conditional operator.
3274 explicit BinaryConditionalOperator(EmptyShell Empty)
3275 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3277 /// \brief getCommon - Return the common expression, written to the
3278 /// left of the condition. The opaque value will be bound to the
3279 /// result of this expression.
3280 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3282 /// \brief getOpaqueValue - Return the opaque value placeholder.
3283 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3285 /// \brief getCond - Return the condition expression; this is defined
3286 /// in terms of the opaque value.
3287 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3289 /// \brief getTrueExpr - Return the subexpression which will be
3290 /// evaluated if the condition evaluates to true; this is defined
3291 /// in terms of the opaque value.
3292 Expr *getTrueExpr() const {
3293 return cast<Expr>(SubExprs[LHS]);
3296 /// \brief getFalseExpr - Return the subexpression which will be
3297 /// evaluated if the condnition evaluates to false; this is
3298 /// defined in terms of the opaque value.
3299 Expr *getFalseExpr() const {
3300 return cast<Expr>(SubExprs[RHS]);
3303 SourceLocation getLocStart() const LLVM_READONLY {
3304 return getCommon()->getLocStart();
3306 SourceLocation getLocEnd() const LLVM_READONLY {
3307 return getFalseExpr()->getLocEnd();
3310 static bool classof(const Stmt *T) {
3311 return T->getStmtClass() == BinaryConditionalOperatorClass;
3315 child_range children() {
3316 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3320 inline Expr *AbstractConditionalOperator::getCond() const {
3321 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3322 return co->getCond();
3323 return cast<BinaryConditionalOperator>(this)->getCond();
3326 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3327 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3328 return co->getTrueExpr();
3329 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3332 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3333 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3334 return co->getFalseExpr();
3335 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3338 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3339 class AddrLabelExpr : public Expr {
3340 SourceLocation AmpAmpLoc, LabelLoc;
3343 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3345 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3347 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3349 /// \brief Build an empty address of a label expression.
3350 explicit AddrLabelExpr(EmptyShell Empty)
3351 : Expr(AddrLabelExprClass, Empty) { }
3353 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3354 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3355 SourceLocation getLabelLoc() const { return LabelLoc; }
3356 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3358 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3359 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3361 LabelDecl *getLabel() const { return Label; }
3362 void setLabel(LabelDecl *L) { Label = L; }
3364 static bool classof(const Stmt *T) {
3365 return T->getStmtClass() == AddrLabelExprClass;
3369 child_range children() {
3370 return child_range(child_iterator(), child_iterator());
3374 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3375 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3376 /// takes the value of the last subexpression.
3378 /// A StmtExpr is always an r-value; values "returned" out of a
3379 /// StmtExpr will be copied.
3380 class StmtExpr : public Expr {
3382 SourceLocation LParenLoc, RParenLoc;
3384 // FIXME: Does type-dependence need to be computed differently?
3385 // FIXME: Do we need to compute instantiation instantiation-dependence for
3386 // statements? (ugh!)
3387 StmtExpr(CompoundStmt *substmt, QualType T,
3388 SourceLocation lp, SourceLocation rp) :
3389 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3390 T->isDependentType(), false, false, false),
3391 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3393 /// \brief Build an empty statement expression.
3394 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3396 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3397 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3398 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3400 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3401 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3403 SourceLocation getLParenLoc() const { return LParenLoc; }
3404 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3405 SourceLocation getRParenLoc() const { return RParenLoc; }
3406 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3408 static bool classof(const Stmt *T) {
3409 return T->getStmtClass() == StmtExprClass;
3413 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3416 /// ShuffleVectorExpr - clang-specific builtin-in function
3417 /// __builtin_shufflevector.
3418 /// This AST node represents a operator that does a constant
3419 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3420 /// two vectors and a variable number of constant indices,
3421 /// and returns the appropriately shuffled vector.
3422 class ShuffleVectorExpr : public Expr {
3423 SourceLocation BuiltinLoc, RParenLoc;
3425 // SubExprs - the list of values passed to the __builtin_shufflevector
3426 // function. The first two are vectors, and the rest are constant
3427 // indices. The number of values in this list is always
3428 // 2+the number of indices in the vector type.
3433 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3434 SourceLocation BLoc, SourceLocation RP);
3436 /// \brief Build an empty vector-shuffle expression.
3437 explicit ShuffleVectorExpr(EmptyShell Empty)
3438 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3440 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3441 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3443 SourceLocation getRParenLoc() const { return RParenLoc; }
3444 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3446 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3447 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3449 static bool classof(const Stmt *T) {
3450 return T->getStmtClass() == ShuffleVectorExprClass;
3453 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3454 /// constant expression, the actual arguments passed in, and the function
3456 unsigned getNumSubExprs() const { return NumExprs; }
3458 /// \brief Retrieve the array of expressions.
3459 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3461 /// getExpr - Return the Expr at the specified index.
3462 Expr *getExpr(unsigned Index) {
3463 assert((Index < NumExprs) && "Arg access out of range!");
3464 return cast<Expr>(SubExprs[Index]);
3466 const Expr *getExpr(unsigned Index) const {
3467 assert((Index < NumExprs) && "Arg access out of range!");
3468 return cast<Expr>(SubExprs[Index]);
3471 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3473 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3474 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3475 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3479 child_range children() {
3480 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3484 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3485 /// This AST node provides support for converting a vector type to another
3486 /// vector type of the same arity.
3487 class ConvertVectorExpr : public Expr {
3490 TypeSourceInfo *TInfo;
3491 SourceLocation BuiltinLoc, RParenLoc;
3493 friend class ASTReader;
3494 friend class ASTStmtReader;
3495 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3498 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3499 ExprValueKind VK, ExprObjectKind OK,
3500 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3501 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3502 DstType->isDependentType(),
3503 DstType->isDependentType() || SrcExpr->isValueDependent(),
3504 (DstType->isInstantiationDependentType() ||
3505 SrcExpr->isInstantiationDependent()),
3506 (DstType->containsUnexpandedParameterPack() ||
3507 SrcExpr->containsUnexpandedParameterPack())),
3508 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3510 /// getSrcExpr - Return the Expr to be converted.
3511 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3513 /// getTypeSourceInfo - Return the destination type.
3514 TypeSourceInfo *getTypeSourceInfo() const {
3517 void setTypeSourceInfo(TypeSourceInfo *ti) {
3521 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3522 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3524 /// getRParenLoc - Return the location of final right parenthesis.
3525 SourceLocation getRParenLoc() const { return RParenLoc; }
3527 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3528 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3530 static bool classof(const Stmt *T) {
3531 return T->getStmtClass() == ConvertVectorExprClass;
3535 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3538 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3539 /// This AST node is similar to the conditional operator (?:) in C, with
3540 /// the following exceptions:
3541 /// - the test expression must be a integer constant expression.
3542 /// - the expression returned acts like the chosen subexpression in every
3543 /// visible way: the type is the same as that of the chosen subexpression,
3544 /// and all predicates (whether it's an l-value, whether it's an integer
3545 /// constant expression, etc.) return the same result as for the chosen
3547 class ChooseExpr : public Expr {
3548 enum { COND, LHS, RHS, END_EXPR };
3549 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3550 SourceLocation BuiltinLoc, RParenLoc;
3553 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3554 QualType t, ExprValueKind VK, ExprObjectKind OK,
3555 SourceLocation RP, bool condIsTrue,
3556 bool TypeDependent, bool ValueDependent)
3557 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3558 (cond->isInstantiationDependent() ||
3559 lhs->isInstantiationDependent() ||
3560 rhs->isInstantiationDependent()),
3561 (cond->containsUnexpandedParameterPack() ||
3562 lhs->containsUnexpandedParameterPack() ||
3563 rhs->containsUnexpandedParameterPack())),
3564 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3565 SubExprs[COND] = cond;
3566 SubExprs[LHS] = lhs;
3567 SubExprs[RHS] = rhs;
3570 /// \brief Build an empty __builtin_choose_expr.
3571 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3573 /// isConditionTrue - Return whether the condition is true (i.e. not
3575 bool isConditionTrue() const {
3576 assert(!isConditionDependent() &&
3577 "Dependent condition isn't true or false");
3580 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3582 bool isConditionDependent() const {
3583 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3586 /// getChosenSubExpr - Return the subexpression chosen according to the
3588 Expr *getChosenSubExpr() const {
3589 return isConditionTrue() ? getLHS() : getRHS();
3592 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3593 void setCond(Expr *E) { SubExprs[COND] = E; }
3594 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3595 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3596 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3597 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3599 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3600 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3602 SourceLocation getRParenLoc() const { return RParenLoc; }
3603 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3605 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3606 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3608 static bool classof(const Stmt *T) {
3609 return T->getStmtClass() == ChooseExprClass;
3613 child_range children() {
3614 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3618 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3619 /// for a null pointer constant that has integral type (e.g., int or
3620 /// long) and is the same size and alignment as a pointer. The __null
3621 /// extension is typically only used by system headers, which define
3622 /// NULL as __null in C++ rather than using 0 (which is an integer
3623 /// that may not match the size of a pointer).
3624 class GNUNullExpr : public Expr {
3625 /// TokenLoc - The location of the __null keyword.
3626 SourceLocation TokenLoc;
3629 GNUNullExpr(QualType Ty, SourceLocation Loc)
3630 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3634 /// \brief Build an empty GNU __null expression.
3635 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3637 /// getTokenLocation - The location of the __null token.
3638 SourceLocation getTokenLocation() const { return TokenLoc; }
3639 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3641 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3642 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3644 static bool classof(const Stmt *T) {
3645 return T->getStmtClass() == GNUNullExprClass;
3649 child_range children() {
3650 return child_range(child_iterator(), child_iterator());
3654 /// Represents a call to the builtin function \c __builtin_va_arg.
3655 class VAArgExpr : public Expr {
3657 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3658 SourceLocation BuiltinLoc, RParenLoc;
3660 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3661 SourceLocation RPLoc, QualType t, bool IsMS)
3662 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3663 false, (TInfo->getType()->isInstantiationDependentType() ||
3664 e->isInstantiationDependent()),
3665 (TInfo->getType()->containsUnexpandedParameterPack() ||
3666 e->containsUnexpandedParameterPack())),
3667 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3669 /// Create an empty __builtin_va_arg expression.
3670 explicit VAArgExpr(EmptyShell Empty)
3671 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3673 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3674 Expr *getSubExpr() { return cast<Expr>(Val); }
3675 void setSubExpr(Expr *E) { Val = E; }
3677 /// Returns whether this is really a Win64 ABI va_arg expression.
3678 bool isMicrosoftABI() const { return TInfo.getInt(); }
3679 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3681 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3682 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3684 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3685 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3687 SourceLocation getRParenLoc() const { return RParenLoc; }
3688 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3690 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3691 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3693 static bool classof(const Stmt *T) {
3694 return T->getStmtClass() == VAArgExprClass;
3698 child_range children() { return child_range(&Val, &Val+1); }
3701 /// @brief Describes an C or C++ initializer list.
3703 /// InitListExpr describes an initializer list, which can be used to
3704 /// initialize objects of different types, including
3705 /// struct/class/union types, arrays, and vectors. For example:
3708 /// struct foo x = { 1, { 2, 3 } };
3711 /// Prior to semantic analysis, an initializer list will represent the
3712 /// initializer list as written by the user, but will have the
3713 /// placeholder type "void". This initializer list is called the
3714 /// syntactic form of the initializer, and may contain C99 designated
3715 /// initializers (represented as DesignatedInitExprs), initializations
3716 /// of subobject members without explicit braces, and so on. Clients
3717 /// interested in the original syntax of the initializer list should
3718 /// use the syntactic form of the initializer list.
3720 /// After semantic analysis, the initializer list will represent the
3721 /// semantic form of the initializer, where the initializations of all
3722 /// subobjects are made explicit with nested InitListExpr nodes and
3723 /// C99 designators have been eliminated by placing the designated
3724 /// initializations into the subobject they initialize. Additionally,
3725 /// any "holes" in the initialization, where no initializer has been
3726 /// specified for a particular subobject, will be replaced with
3727 /// implicitly-generated ImplicitValueInitExpr expressions that
3728 /// value-initialize the subobjects. Note, however, that the
3729 /// initializer lists may still have fewer initializers than there are
3730 /// elements to initialize within the object.
3732 /// After semantic analysis has completed, given an initializer list,
3733 /// method isSemanticForm() returns true if and only if this is the
3734 /// semantic form of the initializer list (note: the same AST node
3735 /// may at the same time be the syntactic form).
3736 /// Given the semantic form of the initializer list, one can retrieve
3737 /// the syntactic form of that initializer list (when different)
3738 /// using method getSyntacticForm(); the method returns null if applied
3739 /// to a initializer list which is already in syntactic form.
3740 /// Similarly, given the syntactic form (i.e., an initializer list such
3741 /// that isSemanticForm() returns false), one can retrieve the semantic
3742 /// form using method getSemanticForm().
3743 /// Since many initializer lists have the same syntactic and semantic forms,
3744 /// getSyntacticForm() may return NULL, indicating that the current
3745 /// semantic initializer list also serves as its syntactic form.
3746 class InitListExpr : public Expr {
3747 // FIXME: Eliminate this vector in favor of ASTContext allocation
3748 typedef ASTVector<Stmt *> InitExprsTy;
3749 InitExprsTy InitExprs;
3750 SourceLocation LBraceLoc, RBraceLoc;
3752 /// The alternative form of the initializer list (if it exists).
3753 /// The int part of the pair stores whether this initializer list is
3754 /// in semantic form. If not null, the pointer points to:
3755 /// - the syntactic form, if this is in semantic form;
3756 /// - the semantic form, if this is in syntactic form.
3757 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3760 /// If this initializer list initializes an array with more elements than
3761 /// there are initializers in the list, specifies an expression to be used
3762 /// for value initialization of the rest of the elements.
3764 /// If this initializer list initializes a union, specifies which
3765 /// field within the union will be initialized.
3766 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3769 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3770 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3772 /// \brief Build an empty initializer list.
3773 explicit InitListExpr(EmptyShell Empty)
3774 : Expr(InitListExprClass, Empty) { }
3776 unsigned getNumInits() const { return InitExprs.size(); }
3778 /// \brief Retrieve the set of initializers.
3779 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3781 ArrayRef<Expr *> inits() {
3782 return llvm::makeArrayRef(getInits(), getNumInits());
3785 const Expr *getInit(unsigned Init) const {
3786 assert(Init < getNumInits() && "Initializer access out of range!");
3787 return cast_or_null<Expr>(InitExprs[Init]);
3790 Expr *getInit(unsigned Init) {
3791 assert(Init < getNumInits() && "Initializer access out of range!");
3792 return cast_or_null<Expr>(InitExprs[Init]);
3795 void setInit(unsigned Init, Expr *expr) {
3796 assert(Init < getNumInits() && "Initializer access out of range!");
3797 InitExprs[Init] = expr;
3800 ExprBits.TypeDependent |= expr->isTypeDependent();
3801 ExprBits.ValueDependent |= expr->isValueDependent();
3802 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3803 ExprBits.ContainsUnexpandedParameterPack |=
3804 expr->containsUnexpandedParameterPack();
3808 /// \brief Reserve space for some number of initializers.
3809 void reserveInits(const ASTContext &C, unsigned NumInits);
3811 /// @brief Specify the number of initializers
3813 /// If there are more than @p NumInits initializers, the remaining
3814 /// initializers will be destroyed. If there are fewer than @p
3815 /// NumInits initializers, NULL expressions will be added for the
3816 /// unknown initializers.
3817 void resizeInits(const ASTContext &Context, unsigned NumInits);
3819 /// @brief Updates the initializer at index @p Init with the new
3820 /// expression @p expr, and returns the old expression at that
3823 /// When @p Init is out of range for this initializer list, the
3824 /// initializer list will be extended with NULL expressions to
3825 /// accommodate the new entry.
3826 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3828 /// \brief If this initializer list initializes an array with more elements
3829 /// than there are initializers in the list, specifies an expression to be
3830 /// used for value initialization of the rest of the elements.
3831 Expr *getArrayFiller() {
3832 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3834 const Expr *getArrayFiller() const {
3835 return const_cast<InitListExpr *>(this)->getArrayFiller();
3837 void setArrayFiller(Expr *filler);
3839 /// \brief Return true if this is an array initializer and its array "filler"
3841 bool hasArrayFiller() const { return getArrayFiller(); }
3843 /// \brief If this initializes a union, specifies which field in the
3844 /// union to initialize.
3846 /// Typically, this field is the first named field within the
3847 /// union. However, a designated initializer can specify the
3848 /// initialization of a different field within the union.
3849 FieldDecl *getInitializedFieldInUnion() {
3850 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3852 const FieldDecl *getInitializedFieldInUnion() const {
3853 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3855 void setInitializedFieldInUnion(FieldDecl *FD) {
3856 assert((FD == nullptr
3857 || getInitializedFieldInUnion() == nullptr
3858 || getInitializedFieldInUnion() == FD)
3859 && "Only one field of a union may be initialized at a time!");
3860 ArrayFillerOrUnionFieldInit = FD;
3863 // Explicit InitListExpr's originate from source code (and have valid source
3864 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3866 return LBraceLoc.isValid() && RBraceLoc.isValid();
3869 // Is this an initializer for an array of characters, initialized by a string
3870 // literal or an @encode?
3871 bool isStringLiteralInit() const;
3873 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3874 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3875 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3876 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3878 bool isSemanticForm() const { return AltForm.getInt(); }
3879 InitListExpr *getSemanticForm() const {
3880 return isSemanticForm() ? nullptr : AltForm.getPointer();
3882 InitListExpr *getSyntacticForm() const {
3883 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3886 void setSyntacticForm(InitListExpr *Init) {
3887 AltForm.setPointer(Init);
3888 AltForm.setInt(true);
3889 Init->AltForm.setPointer(this);
3890 Init->AltForm.setInt(false);
3893 bool hadArrayRangeDesignator() const {
3894 return InitListExprBits.HadArrayRangeDesignator != 0;
3896 void sawArrayRangeDesignator(bool ARD = true) {
3897 InitListExprBits.HadArrayRangeDesignator = ARD;
3900 SourceLocation getLocStart() const LLVM_READONLY;
3901 SourceLocation getLocEnd() const LLVM_READONLY;
3903 static bool classof(const Stmt *T) {
3904 return T->getStmtClass() == InitListExprClass;
3908 child_range children() {
3909 // FIXME: This does not include the array filler expression.
3910 if (InitExprs.empty())
3911 return child_range(child_iterator(), child_iterator());
3912 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3915 typedef InitExprsTy::iterator iterator;
3916 typedef InitExprsTy::const_iterator const_iterator;
3917 typedef InitExprsTy::reverse_iterator reverse_iterator;
3918 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3920 iterator begin() { return InitExprs.begin(); }
3921 const_iterator begin() const { return InitExprs.begin(); }
3922 iterator end() { return InitExprs.end(); }
3923 const_iterator end() const { return InitExprs.end(); }
3924 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3925 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3926 reverse_iterator rend() { return InitExprs.rend(); }
3927 const_reverse_iterator rend() const { return InitExprs.rend(); }
3929 friend class ASTStmtReader;
3930 friend class ASTStmtWriter;
3933 /// @brief Represents a C99 designated initializer expression.
3935 /// A designated initializer expression (C99 6.7.8) contains one or
3936 /// more designators (which can be field designators, array
3937 /// designators, or GNU array-range designators) followed by an
3938 /// expression that initializes the field or element(s) that the
3939 /// designators refer to. For example, given:
3946 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3949 /// The InitListExpr contains three DesignatedInitExprs, the first of
3950 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3951 /// designators, one array designator for @c [2] followed by one field
3952 /// designator for @c .y. The initialization expression will be 1.0.
3953 class DesignatedInitExpr final
3955 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
3957 /// \brief Forward declaration of the Designator class.
3961 /// The location of the '=' or ':' prior to the actual initializer
3963 SourceLocation EqualOrColonLoc;
3965 /// Whether this designated initializer used the GNU deprecated
3966 /// syntax rather than the C99 '=' syntax.
3967 unsigned GNUSyntax : 1;
3969 /// The number of designators in this initializer expression.
3970 unsigned NumDesignators : 15;
3972 /// The number of subexpressions of this initializer expression,
3973 /// which contains both the initializer and any additional
3974 /// expressions used by array and array-range designators.
3975 unsigned NumSubExprs : 16;
3977 /// \brief The designators in this designated initialization
3979 Designator *Designators;
3981 DesignatedInitExpr(const ASTContext &C, QualType Ty,
3982 llvm::ArrayRef<Designator> Designators,
3983 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3984 ArrayRef<Expr *> IndexExprs, Expr *Init);
3986 explicit DesignatedInitExpr(unsigned NumSubExprs)
3987 : Expr(DesignatedInitExprClass, EmptyShell()),
3988 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
3991 /// A field designator, e.g., ".x".
3992 struct FieldDesignator {
3993 /// Refers to the field that is being initialized. The low bit
3994 /// of this field determines whether this is actually a pointer
3995 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3996 /// initially constructed, a field designator will store an
3997 /// IdentifierInfo*. After semantic analysis has resolved that
3998 /// name, the field designator will instead store a FieldDecl*.
3999 uintptr_t NameOrField;
4001 /// The location of the '.' in the designated initializer.
4004 /// The location of the field name in the designated initializer.
4008 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4009 struct ArrayOrRangeDesignator {
4010 /// Location of the first index expression within the designated
4011 /// initializer expression's list of subexpressions.
4013 /// The location of the '[' starting the array range designator.
4014 unsigned LBracketLoc;
4015 /// The location of the ellipsis separating the start and end
4016 /// indices. Only valid for GNU array-range designators.
4017 unsigned EllipsisLoc;
4018 /// The location of the ']' terminating the array range designator.
4019 unsigned RBracketLoc;
4022 /// @brief Represents a single C99 designator.
4024 /// @todo This class is infuriatingly similar to clang::Designator,
4025 /// but minor differences (storing indices vs. storing pointers)
4026 /// keep us from reusing it. Try harder, later, to rectify these
4029 /// @brief The kind of designator this describes.
4033 ArrayRangeDesignator
4037 /// A field designator, e.g., ".x".
4038 struct FieldDesignator Field;
4039 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4040 struct ArrayOrRangeDesignator ArrayOrRange;
4042 friend class DesignatedInitExpr;
4047 /// @brief Initializes a field designator.
4048 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4049 SourceLocation FieldLoc)
4050 : Kind(FieldDesignator) {
4051 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4052 Field.DotLoc = DotLoc.getRawEncoding();
4053 Field.FieldLoc = FieldLoc.getRawEncoding();
4056 /// @brief Initializes an array designator.
4057 Designator(unsigned Index, SourceLocation LBracketLoc,
4058 SourceLocation RBracketLoc)
4059 : Kind(ArrayDesignator) {
4060 ArrayOrRange.Index = Index;
4061 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4062 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4063 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4066 /// @brief Initializes a GNU array-range designator.
4067 Designator(unsigned Index, SourceLocation LBracketLoc,
4068 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4069 : Kind(ArrayRangeDesignator) {
4070 ArrayOrRange.Index = Index;
4071 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4072 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4073 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4076 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4077 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4078 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4080 IdentifierInfo *getFieldName() const;
4082 FieldDecl *getField() const {
4083 assert(Kind == FieldDesignator && "Only valid on a field designator");
4084 if (Field.NameOrField & 0x01)
4087 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4090 void setField(FieldDecl *FD) {
4091 assert(Kind == FieldDesignator && "Only valid on a field designator");
4092 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4095 SourceLocation getDotLoc() const {
4096 assert(Kind == FieldDesignator && "Only valid on a field designator");
4097 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4100 SourceLocation getFieldLoc() const {
4101 assert(Kind == FieldDesignator && "Only valid on a field designator");
4102 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4105 SourceLocation getLBracketLoc() const {
4106 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4107 "Only valid on an array or array-range designator");
4108 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4111 SourceLocation getRBracketLoc() const {
4112 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4113 "Only valid on an array or array-range designator");
4114 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4117 SourceLocation getEllipsisLoc() const {
4118 assert(Kind == ArrayRangeDesignator &&
4119 "Only valid on an array-range designator");
4120 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4123 unsigned getFirstExprIndex() const {
4124 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4125 "Only valid on an array or array-range designator");
4126 return ArrayOrRange.Index;
4129 SourceLocation getLocStart() const LLVM_READONLY {
4130 if (Kind == FieldDesignator)
4131 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4133 return getLBracketLoc();
4135 SourceLocation getLocEnd() const LLVM_READONLY {
4136 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4138 SourceRange getSourceRange() const LLVM_READONLY {
4139 return SourceRange(getLocStart(), getLocEnd());
4143 static DesignatedInitExpr *Create(const ASTContext &C,
4144 llvm::ArrayRef<Designator> Designators,
4145 ArrayRef<Expr*> IndexExprs,
4146 SourceLocation EqualOrColonLoc,
4147 bool GNUSyntax, Expr *Init);
4149 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4150 unsigned NumIndexExprs);
4152 /// @brief Returns the number of designators in this initializer.
4153 unsigned size() const { return NumDesignators; }
4155 // Iterator access to the designators.
4156 llvm::MutableArrayRef<Designator> designators() {
4157 return {Designators, NumDesignators};
4160 llvm::ArrayRef<Designator> designators() const {
4161 return {Designators, NumDesignators};
4164 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4166 void setDesignators(const ASTContext &C, const Designator *Desigs,
4167 unsigned NumDesigs);
4169 Expr *getArrayIndex(const Designator &D) const;
4170 Expr *getArrayRangeStart(const Designator &D) const;
4171 Expr *getArrayRangeEnd(const Designator &D) const;
4173 /// @brief Retrieve the location of the '=' that precedes the
4174 /// initializer value itself, if present.
4175 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4176 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4178 /// @brief Determines whether this designated initializer used the
4179 /// deprecated GNU syntax for designated initializers.
4180 bool usesGNUSyntax() const { return GNUSyntax; }
4181 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4183 /// @brief Retrieve the initializer value.
4184 Expr *getInit() const {
4185 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4188 void setInit(Expr *init) {
4189 *child_begin() = init;
4192 /// \brief Retrieve the total number of subexpressions in this
4193 /// designated initializer expression, including the actual
4194 /// initialized value and any expressions that occur within array
4195 /// and array-range designators.
4196 unsigned getNumSubExprs() const { return NumSubExprs; }
4198 Expr *getSubExpr(unsigned Idx) const {
4199 assert(Idx < NumSubExprs && "Subscript out of range");
4200 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4203 void setSubExpr(unsigned Idx, Expr *E) {
4204 assert(Idx < NumSubExprs && "Subscript out of range");
4205 getTrailingObjects<Stmt *>()[Idx] = E;
4208 /// \brief Replaces the designator at index @p Idx with the series
4209 /// of designators in [First, Last).
4210 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4211 const Designator *First, const Designator *Last);
4213 SourceRange getDesignatorsSourceRange() const;
4215 SourceLocation getLocStart() const LLVM_READONLY;
4216 SourceLocation getLocEnd() const LLVM_READONLY;
4218 static bool classof(const Stmt *T) {
4219 return T->getStmtClass() == DesignatedInitExprClass;
4223 child_range children() {
4224 Stmt **begin = getTrailingObjects<Stmt *>();
4225 return child_range(begin, begin + NumSubExprs);
4228 friend TrailingObjects;
4231 /// \brief Represents a place-holder for an object not to be initialized by
4234 /// This only makes sense when it appears as part of an updater of a
4235 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4236 /// initializes a big object, and the NoInitExpr's mark the spots within the
4237 /// big object not to be overwritten by the updater.
4239 /// \see DesignatedInitUpdateExpr
4240 class NoInitExpr : public Expr {
4242 explicit NoInitExpr(QualType ty)
4243 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4244 false, false, ty->isInstantiationDependentType(), false) { }
4246 explicit NoInitExpr(EmptyShell Empty)
4247 : Expr(NoInitExprClass, Empty) { }
4249 static bool classof(const Stmt *T) {
4250 return T->getStmtClass() == NoInitExprClass;
4253 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4254 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4257 child_range children() {
4258 return child_range(child_iterator(), child_iterator());
4263 // struct Q { int a, b, c; };
4266 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4269 // We will have an InitListExpr for a, with type A, and then a
4270 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4271 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4273 class DesignatedInitUpdateExpr : public Expr {
4274 // BaseAndUpdaterExprs[0] is the base expression;
4275 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4276 Stmt *BaseAndUpdaterExprs[2];
4279 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4280 Expr *baseExprs, SourceLocation rBraceLoc);
4282 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4283 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4285 SourceLocation getLocStart() const LLVM_READONLY;
4286 SourceLocation getLocEnd() const LLVM_READONLY;
4288 static bool classof(const Stmt *T) {
4289 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4292 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4293 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4295 InitListExpr *getUpdater() const {
4296 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4298 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4301 // children = the base and the updater
4302 child_range children() {
4303 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4307 /// \brief Represents an implicitly-generated value initialization of
4308 /// an object of a given type.
4310 /// Implicit value initializations occur within semantic initializer
4311 /// list expressions (InitListExpr) as placeholders for subobject
4312 /// initializations not explicitly specified by the user.
4314 /// \see InitListExpr
4315 class ImplicitValueInitExpr : public Expr {
4317 explicit ImplicitValueInitExpr(QualType ty)
4318 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4319 false, false, ty->isInstantiationDependentType(), false) { }
4321 /// \brief Construct an empty implicit value initialization.
4322 explicit ImplicitValueInitExpr(EmptyShell Empty)
4323 : Expr(ImplicitValueInitExprClass, Empty) { }
4325 static bool classof(const Stmt *T) {
4326 return T->getStmtClass() == ImplicitValueInitExprClass;
4329 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4330 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4333 child_range children() {
4334 return child_range(child_iterator(), child_iterator());
4338 class ParenListExpr : public Expr {
4341 SourceLocation LParenLoc, RParenLoc;
4344 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4345 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4347 /// \brief Build an empty paren list.
4348 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4350 unsigned getNumExprs() const { return NumExprs; }
4352 const Expr* getExpr(unsigned Init) const {
4353 assert(Init < getNumExprs() && "Initializer access out of range!");
4354 return cast_or_null<Expr>(Exprs[Init]);
4357 Expr* getExpr(unsigned Init) {
4358 assert(Init < getNumExprs() && "Initializer access out of range!");
4359 return cast_or_null<Expr>(Exprs[Init]);
4362 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4364 ArrayRef<Expr *> exprs() {
4365 return llvm::makeArrayRef(getExprs(), getNumExprs());
4368 SourceLocation getLParenLoc() const { return LParenLoc; }
4369 SourceLocation getRParenLoc() const { return RParenLoc; }
4371 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4372 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4374 static bool classof(const Stmt *T) {
4375 return T->getStmtClass() == ParenListExprClass;
4379 child_range children() {
4380 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4383 friend class ASTStmtReader;
4384 friend class ASTStmtWriter;
4387 /// \brief Represents a C11 generic selection.
4389 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4390 /// expression, followed by one or more generic associations. Each generic
4391 /// association specifies a type name and an expression, or "default" and an
4392 /// expression (in which case it is known as a default generic association).
4393 /// The type and value of the generic selection are identical to those of its
4394 /// result expression, which is defined as the expression in the generic
4395 /// association with a type name that is compatible with the type of the
4396 /// controlling expression, or the expression in the default generic association
4397 /// if no types are compatible. For example:
4400 /// _Generic(X, double: 1, float: 2, default: 3)
4403 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4404 /// or 3 if "hello".
4406 /// As an extension, generic selections are allowed in C++, where the following
4407 /// additional semantics apply:
4409 /// Any generic selection whose controlling expression is type-dependent or
4410 /// which names a dependent type in its association list is result-dependent,
4411 /// which means that the choice of result expression is dependent.
4412 /// Result-dependent generic associations are both type- and value-dependent.
4413 class GenericSelectionExpr : public Expr {
4414 enum { CONTROLLING, END_EXPR };
4415 TypeSourceInfo **AssocTypes;
4417 unsigned NumAssocs, ResultIndex;
4418 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4421 GenericSelectionExpr(const ASTContext &Context,
4422 SourceLocation GenericLoc, Expr *ControllingExpr,
4423 ArrayRef<TypeSourceInfo*> AssocTypes,
4424 ArrayRef<Expr*> AssocExprs,
4425 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4426 bool ContainsUnexpandedParameterPack,
4427 unsigned ResultIndex);
4429 /// This constructor is used in the result-dependent case.
4430 GenericSelectionExpr(const ASTContext &Context,
4431 SourceLocation GenericLoc, Expr *ControllingExpr,
4432 ArrayRef<TypeSourceInfo*> AssocTypes,
4433 ArrayRef<Expr*> AssocExprs,
4434 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4435 bool ContainsUnexpandedParameterPack);
4437 explicit GenericSelectionExpr(EmptyShell Empty)
4438 : Expr(GenericSelectionExprClass, Empty) { }
4440 unsigned getNumAssocs() const { return NumAssocs; }
4442 SourceLocation getGenericLoc() const { return GenericLoc; }
4443 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4444 SourceLocation getRParenLoc() const { return RParenLoc; }
4446 const Expr *getAssocExpr(unsigned i) const {
4447 return cast<Expr>(SubExprs[END_EXPR+i]);
4449 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4451 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4452 return AssocTypes[i];
4454 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4456 QualType getAssocType(unsigned i) const {
4457 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4458 return TS->getType();
4463 const Expr *getControllingExpr() const {
4464 return cast<Expr>(SubExprs[CONTROLLING]);
4466 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4468 /// Whether this generic selection is result-dependent.
4469 bool isResultDependent() const { return ResultIndex == -1U; }
4471 /// The zero-based index of the result expression's generic association in
4472 /// the generic selection's association list. Defined only if the
4473 /// generic selection is not result-dependent.
4474 unsigned getResultIndex() const {
4475 assert(!isResultDependent() && "Generic selection is result-dependent");
4479 /// The generic selection's result expression. Defined only if the
4480 /// generic selection is not result-dependent.
4481 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4482 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4484 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4485 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4487 static bool classof(const Stmt *T) {
4488 return T->getStmtClass() == GenericSelectionExprClass;
4491 child_range children() {
4492 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4495 friend class ASTStmtReader;
4498 //===----------------------------------------------------------------------===//
4500 //===----------------------------------------------------------------------===//
4502 /// ExtVectorElementExpr - This represents access to specific elements of a
4503 /// vector, and may occur on the left hand side or right hand side. For example
4504 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4506 /// Note that the base may have either vector or pointer to vector type, just
4507 /// like a struct field reference.
4509 class ExtVectorElementExpr : public Expr {
4511 IdentifierInfo *Accessor;
4512 SourceLocation AccessorLoc;
4514 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4515 IdentifierInfo &accessor, SourceLocation loc)
4516 : Expr(ExtVectorElementExprClass, ty, VK,
4517 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4518 base->isTypeDependent(), base->isValueDependent(),
4519 base->isInstantiationDependent(),
4520 base->containsUnexpandedParameterPack()),
4521 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4523 /// \brief Build an empty vector element expression.
4524 explicit ExtVectorElementExpr(EmptyShell Empty)
4525 : Expr(ExtVectorElementExprClass, Empty) { }
4527 const Expr *getBase() const { return cast<Expr>(Base); }
4528 Expr *getBase() { return cast<Expr>(Base); }
4529 void setBase(Expr *E) { Base = E; }
4531 IdentifierInfo &getAccessor() const { return *Accessor; }
4532 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4534 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4535 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4537 /// getNumElements - Get the number of components being selected.
4538 unsigned getNumElements() const;
4540 /// containsDuplicateElements - Return true if any element access is
4542 bool containsDuplicateElements() const;
4544 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4545 /// aggregate Constant of ConstantInt(s).
4546 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4548 SourceLocation getLocStart() const LLVM_READONLY {
4549 return getBase()->getLocStart();
4551 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4553 /// isArrow - Return true if the base expression is a pointer to vector,
4554 /// return false if the base expression is a vector.
4555 bool isArrow() const;
4557 static bool classof(const Stmt *T) {
4558 return T->getStmtClass() == ExtVectorElementExprClass;
4562 child_range children() { return child_range(&Base, &Base+1); }
4565 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4566 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4567 class BlockExpr : public Expr {
4569 BlockDecl *TheBlock;
4571 BlockExpr(BlockDecl *BD, QualType ty)
4572 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4573 ty->isDependentType(), ty->isDependentType(),
4574 ty->isInstantiationDependentType() || BD->isDependentContext(),
4578 /// \brief Build an empty block expression.
4579 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4581 const BlockDecl *getBlockDecl() const { return TheBlock; }
4582 BlockDecl *getBlockDecl() { return TheBlock; }
4583 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4585 // Convenience functions for probing the underlying BlockDecl.
4586 SourceLocation getCaretLocation() const;
4587 const Stmt *getBody() const;
4590 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4591 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4593 /// getFunctionType - Return the underlying function type for this block.
4594 const FunctionProtoType *getFunctionType() const;
4596 static bool classof(const Stmt *T) {
4597 return T->getStmtClass() == BlockExprClass;
4601 child_range children() {
4602 return child_range(child_iterator(), child_iterator());
4606 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4607 /// This AST node provides support for reinterpreting a type to another
4608 /// type of the same size.
4609 class AsTypeExpr : public Expr {
4612 SourceLocation BuiltinLoc, RParenLoc;
4614 friend class ASTReader;
4615 friend class ASTStmtReader;
4616 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4619 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4620 ExprValueKind VK, ExprObjectKind OK,
4621 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4622 : Expr(AsTypeExprClass, DstType, VK, OK,
4623 DstType->isDependentType(),
4624 DstType->isDependentType() || SrcExpr->isValueDependent(),
4625 (DstType->isInstantiationDependentType() ||
4626 SrcExpr->isInstantiationDependent()),
4627 (DstType->containsUnexpandedParameterPack() ||
4628 SrcExpr->containsUnexpandedParameterPack())),
4629 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4631 /// getSrcExpr - Return the Expr to be converted.
4632 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4634 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4635 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4637 /// getRParenLoc - Return the location of final right parenthesis.
4638 SourceLocation getRParenLoc() const { return RParenLoc; }
4640 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4641 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4643 static bool classof(const Stmt *T) {
4644 return T->getStmtClass() == AsTypeExprClass;
4648 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4651 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4652 /// l-value. A pseudo-object is an abstract object, accesses to which
4653 /// are translated to calls. The pseudo-object expression has a
4654 /// syntactic form, which shows how the expression was actually
4655 /// written in the source code, and a semantic form, which is a series
4656 /// of expressions to be executed in order which detail how the
4657 /// operation is actually evaluated. Optionally, one of the semantic
4658 /// forms may also provide a result value for the expression.
4660 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4661 /// that OVE is required to have a source expression, and it is bound
4662 /// to the result of that source expression. Such OVEs may appear
4663 /// only in subsequent semantic-form expressions and as
4664 /// sub-expressions of the syntactic form.
4666 /// PseudoObjectExpr should be used only when an operation can be
4667 /// usefully described in terms of fairly simple rewrite rules on
4668 /// objects and functions that are meant to be used by end-developers.
4669 /// For example, under the Itanium ABI, dynamic casts are implemented
4670 /// as a call to a runtime function called __dynamic_cast; using this
4671 /// class to describe that would be inappropriate because that call is
4672 /// not really part of the user-visible semantics, and instead the
4673 /// cast is properly reflected in the AST and IR-generation has been
4674 /// taught to generate the call as necessary. In contrast, an
4675 /// Objective-C property access is semantically defined to be
4676 /// equivalent to a particular message send, and this is very much
4677 /// part of the user model. The name of this class encourages this
4678 /// modelling design.
4679 class PseudoObjectExpr final
4681 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
4682 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4683 // Always at least two, because the first sub-expression is the
4686 // PseudoObjectExprBits.ResultIndex - The index of the
4687 // sub-expression holding the result. 0 means the result is void,
4688 // which is unambiguous because it's the index of the syntactic
4689 // form. Note that this is therefore 1 higher than the value passed
4690 // in to Create, which is an index within the semantic forms.
4691 // Note also that ASTStmtWriter assumes this encoding.
4693 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
4694 const Expr * const *getSubExprsBuffer() const {
4695 return getTrailingObjects<Expr *>();
4698 PseudoObjectExpr(QualType type, ExprValueKind VK,
4699 Expr *syntactic, ArrayRef<Expr*> semantic,
4700 unsigned resultIndex);
4702 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4704 unsigned getNumSubExprs() const {
4705 return PseudoObjectExprBits.NumSubExprs;
4709 /// NoResult - A value for the result index indicating that there is
4710 /// no semantic result.
4711 enum : unsigned { NoResult = ~0U };
4713 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4714 ArrayRef<Expr*> semantic,
4715 unsigned resultIndex);
4717 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4718 unsigned numSemanticExprs);
4720 /// Return the syntactic form of this expression, i.e. the
4721 /// expression it actually looks like. Likely to be expressed in
4722 /// terms of OpaqueValueExprs bound in the semantic form.
4723 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4724 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4726 /// Return the index of the result-bearing expression into the semantics
4727 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4728 unsigned getResultExprIndex() const {
4729 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4730 return PseudoObjectExprBits.ResultIndex - 1;
4733 /// Return the result-bearing expression, or null if there is none.
4734 Expr *getResultExpr() {
4735 if (PseudoObjectExprBits.ResultIndex == 0)
4737 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4739 const Expr *getResultExpr() const {
4740 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4743 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4745 typedef Expr * const *semantics_iterator;
4746 typedef const Expr * const *const_semantics_iterator;
4747 semantics_iterator semantics_begin() {
4748 return getSubExprsBuffer() + 1;
4750 const_semantics_iterator semantics_begin() const {
4751 return getSubExprsBuffer() + 1;
4753 semantics_iterator semantics_end() {
4754 return getSubExprsBuffer() + getNumSubExprs();
4756 const_semantics_iterator semantics_end() const {
4757 return getSubExprsBuffer() + getNumSubExprs();
4760 llvm::iterator_range<semantics_iterator> semantics() {
4761 return llvm::make_range(semantics_begin(), semantics_end());
4763 llvm::iterator_range<const_semantics_iterator> semantics() const {
4764 return llvm::make_range(semantics_begin(), semantics_end());
4767 Expr *getSemanticExpr(unsigned index) {
4768 assert(index + 1 < getNumSubExprs());
4769 return getSubExprsBuffer()[index + 1];
4771 const Expr *getSemanticExpr(unsigned index) const {
4772 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4775 SourceLocation getExprLoc() const LLVM_READONLY {
4776 return getSyntacticForm()->getExprLoc();
4779 SourceLocation getLocStart() const LLVM_READONLY {
4780 return getSyntacticForm()->getLocStart();
4782 SourceLocation getLocEnd() const LLVM_READONLY {
4783 return getSyntacticForm()->getLocEnd();
4786 child_range children() {
4787 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4788 return child_range(cs, cs + getNumSubExprs());
4791 static bool classof(const Stmt *T) {
4792 return T->getStmtClass() == PseudoObjectExprClass;
4795 friend TrailingObjects;
4796 friend class ASTStmtReader;
4799 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4800 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4801 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4802 /// All of these instructions take one primary pointer and at least one memory
4804 class AtomicExpr : public Expr {
4807 #define BUILTIN(ID, TYPE, ATTRS)
4808 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4809 #include "clang/Basic/Builtins.def"
4810 // Avoid trailing comma
4815 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4816 Stmt* SubExprs[END_EXPR];
4817 unsigned NumSubExprs;
4818 SourceLocation BuiltinLoc, RParenLoc;
4821 friend class ASTStmtReader;
4824 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4825 AtomicOp op, SourceLocation RP);
4827 /// \brief Determine the number of arguments the specified atomic builtin
4829 static unsigned getNumSubExprs(AtomicOp Op);
4831 /// \brief Build an empty AtomicExpr.
4832 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4834 Expr *getPtr() const {
4835 return cast<Expr>(SubExprs[PTR]);
4837 Expr *getOrder() const {
4838 return cast<Expr>(SubExprs[ORDER]);
4840 Expr *getVal1() const {
4841 if (Op == AO__c11_atomic_init)
4842 return cast<Expr>(SubExprs[ORDER]);
4843 assert(NumSubExprs > VAL1);
4844 return cast<Expr>(SubExprs[VAL1]);
4846 Expr *getOrderFail() const {
4847 assert(NumSubExprs > ORDER_FAIL);
4848 return cast<Expr>(SubExprs[ORDER_FAIL]);
4850 Expr *getVal2() const {
4851 if (Op == AO__atomic_exchange)
4852 return cast<Expr>(SubExprs[ORDER_FAIL]);
4853 assert(NumSubExprs > VAL2);
4854 return cast<Expr>(SubExprs[VAL2]);
4856 Expr *getWeak() const {
4857 assert(NumSubExprs > WEAK);
4858 return cast<Expr>(SubExprs[WEAK]);
4861 AtomicOp getOp() const { return Op; }
4862 unsigned getNumSubExprs() const { return NumSubExprs; }
4864 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4865 const Expr * const *getSubExprs() const {
4866 return reinterpret_cast<Expr * const *>(SubExprs);
4869 bool isVolatile() const {
4870 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4873 bool isCmpXChg() const {
4874 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4875 getOp() == AO__c11_atomic_compare_exchange_weak ||
4876 getOp() == AO__atomic_compare_exchange ||
4877 getOp() == AO__atomic_compare_exchange_n;
4880 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4881 SourceLocation getRParenLoc() const { return RParenLoc; }
4883 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4884 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4886 static bool classof(const Stmt *T) {
4887 return T->getStmtClass() == AtomicExprClass;
4891 child_range children() {
4892 return child_range(SubExprs, SubExprs+NumSubExprs);
4896 /// TypoExpr - Internal placeholder for expressions where typo correction
4897 /// still needs to be performed and/or an error diagnostic emitted.
4898 class TypoExpr : public Expr {
4900 TypoExpr(QualType T)
4901 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4902 /*isTypeDependent*/ true,
4903 /*isValueDependent*/ true,
4904 /*isInstantiationDependent*/ true,
4905 /*containsUnexpandedParameterPack*/ false) {
4906 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4909 child_range children() {
4910 return child_range(child_iterator(), child_iterator());
4912 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4913 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4915 static bool classof(const Stmt *T) {
4916 return T->getStmtClass() == TypoExprClass;
4920 } // end namespace clang
4922 #endif // LLVM_CLANG_AST_EXPR_H