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/Compiler.h"
38 class CXXBaseSpecifier;
39 class CXXMemberCallExpr;
40 class CXXOperatorCallExpr;
44 class MaterializeTemporaryExpr;
46 class ObjCPropertyRefExpr;
47 class OpaqueValueExpr;
53 /// \brief A simple array of base specifiers.
54 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
56 /// \brief An adjustment to be made to the temporary created when emitting a
57 /// reference binding, which accesses a particular subobject of that temporary.
58 struct SubobjectAdjustment {
60 DerivedToBaseAdjustment,
62 MemberPointerAdjustment
66 const CastExpr *BasePath;
67 const CXXRecordDecl *DerivedClass;
71 const MemberPointerType *MPT;
76 struct DTB DerivedToBase;
81 SubobjectAdjustment(const CastExpr *BasePath,
82 const CXXRecordDecl *DerivedClass)
83 : Kind(DerivedToBaseAdjustment) {
84 DerivedToBase.BasePath = BasePath;
85 DerivedToBase.DerivedClass = DerivedClass;
88 SubobjectAdjustment(FieldDecl *Field)
89 : Kind(FieldAdjustment) {
93 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
94 : Kind(MemberPointerAdjustment) {
100 /// Expr - This represents one expression. Note that Expr's are subclasses of
101 /// Stmt. This allows an expression to be transparently used any place a Stmt
104 class Expr : public Stmt {
108 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
109 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112 ExprBits.TypeDependent = TD;
113 ExprBits.ValueDependent = VD;
114 ExprBits.InstantiationDependent = ID;
115 ExprBits.ValueKind = VK;
116 ExprBits.ObjectKind = OK;
117 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121 /// \brief Construct an empty expression.
122 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
125 QualType getType() const { return TR; }
126 void setType(QualType t) {
127 // In C++, the type of an expression is always adjusted so that it
128 // will not have reference type (C++ [expr]p6). Use
129 // QualType::getNonReferenceType() to retrieve the non-reference
130 // type. Additionally, inspect Expr::isLvalue to determine whether
131 // an expression that is adjusted in this manner should be
132 // considered an lvalue.
133 assert((t.isNull() || !t->isReferenceType()) &&
134 "Expressions can't have reference type");
139 /// isValueDependent - Determines whether this expression is
140 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
141 /// array bound of "Chars" in the following example is
144 /// template<int Size, char (&Chars)[Size]> struct meta_string;
146 bool isValueDependent() const { return ExprBits.ValueDependent; }
148 /// \brief Set whether this expression is value-dependent or not.
149 void setValueDependent(bool VD) {
150 ExprBits.ValueDependent = VD;
153 /// isTypeDependent - Determines whether this expression is
154 /// type-dependent (C++ [temp.dep.expr]), which means that its type
155 /// could change from one template instantiation to the next. For
156 /// example, the expressions "x" and "x + y" are type-dependent in
157 /// the following code, but "y" is not type-dependent:
159 /// template<typename T>
160 /// void add(T x, int y) {
164 bool isTypeDependent() const { return ExprBits.TypeDependent; }
166 /// \brief Set whether this expression is type-dependent or not.
167 void setTypeDependent(bool TD) {
168 ExprBits.TypeDependent = TD;
171 /// \brief Whether this expression is instantiation-dependent, meaning that
172 /// it depends in some way on a template parameter, even if neither its type
173 /// nor (constant) value can change due to the template instantiation.
175 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
176 /// instantiation-dependent (since it involves a template parameter \c T), but
177 /// is neither type- nor value-dependent, since the type of the inner
178 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
179 /// \c sizeof is known.
182 /// template<typename T>
183 /// void f(T x, T y) {
184 /// sizeof(sizeof(T() + T());
188 bool isInstantiationDependent() const {
189 return ExprBits.InstantiationDependent;
192 /// \brief Set whether this expression is instantiation-dependent or not.
193 void setInstantiationDependent(bool ID) {
194 ExprBits.InstantiationDependent = ID;
197 /// \brief Whether this expression contains an unexpanded parameter
198 /// pack (for C++11 variadic templates).
200 /// Given the following function template:
203 /// template<typename F, typename ...Types>
204 /// void forward(const F &f, Types &&...args) {
205 /// f(static_cast<Types&&>(args)...);
209 /// The expressions \c args and \c static_cast<Types&&>(args) both
210 /// contain parameter packs.
211 bool containsUnexpandedParameterPack() const {
212 return ExprBits.ContainsUnexpandedParameterPack;
215 /// \brief Set the bit that describes whether this expression
216 /// contains an unexpanded parameter pack.
217 void setContainsUnexpandedParameterPack(bool PP = true) {
218 ExprBits.ContainsUnexpandedParameterPack = PP;
221 /// getExprLoc - Return the preferred location for the arrow when diagnosing
222 /// a problem with a generic expression.
223 SourceLocation getExprLoc() const LLVM_READONLY;
225 /// isUnusedResultAWarning - Return true if this immediate expression should
226 /// be warned about if the result is unused. If so, fill in expr, location,
227 /// and ranges with expr to warn on and source locations/ranges appropriate
229 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
230 SourceRange &R1, SourceRange &R2,
231 ASTContext &Ctx) const;
233 /// isLValue - True if this expression is an "l-value" according to
234 /// the rules of the current language. C and C++ give somewhat
235 /// different rules for this concept, but in general, the result of
236 /// an l-value expression identifies a specific object whereas the
237 /// result of an r-value expression is a value detached from any
238 /// specific storage.
240 /// C++11 divides the concept of "r-value" into pure r-values
241 /// ("pr-values") and so-called expiring values ("x-values"), which
242 /// identify specific objects that can be safely cannibalized for
243 /// their resources. This is an unfortunate abuse of terminology on
244 /// the part of the C++ committee. In Clang, when we say "r-value",
245 /// we generally mean a pr-value.
246 bool isLValue() const { return getValueKind() == VK_LValue; }
247 bool isRValue() const { return getValueKind() == VK_RValue; }
248 bool isXValue() const { return getValueKind() == VK_XValue; }
249 bool isGLValue() const { return getValueKind() != VK_RValue; }
251 enum LValueClassification {
254 LV_IncompleteVoidType,
255 LV_DuplicateVectorComponents,
256 LV_InvalidExpression,
257 LV_InvalidMessageExpression,
259 LV_SubObjCPropertySetting,
263 /// Reasons why an expression might not be an l-value.
264 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
266 enum isModifiableLvalueResult {
269 MLV_IncompleteVoidType,
270 MLV_DuplicateVectorComponents,
271 MLV_InvalidExpression,
272 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
277 MLV_NoSetterProperty,
279 MLV_SubObjCPropertySetting,
280 MLV_InvalidMessageExpression,
284 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
285 /// does not have an incomplete type, does not have a const-qualified type,
286 /// and if it is a structure or union, does not have any member (including,
287 /// recursively, any member or element of all contained aggregates or unions)
288 /// with a const-qualified type.
290 /// \param Loc [in,out] - A source location which *may* be filled
291 /// in with the location of the expression making this a
292 /// non-modifiable lvalue, if specified.
293 isModifiableLvalueResult
294 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
296 /// \brief The return type of classify(). Represents the C++11 expression
298 class Classification {
300 /// \brief The various classification results. Most of these mean prvalue.
304 CL_Function, // Functions cannot be lvalues in C.
305 CL_Void, // Void cannot be an lvalue in C.
306 CL_AddressableVoid, // Void expression whose address can be taken in C.
307 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
308 CL_MemberFunction, // An expression referring to a member function
309 CL_SubObjCPropertySetting,
310 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
311 CL_ArrayTemporary, // A temporary of array type.
312 CL_ObjCMessageRValue, // ObjC message is an rvalue
313 CL_PRValue // A prvalue for any other reason, of any other type
315 /// \brief The results of modification testing.
316 enum ModifiableType {
317 CM_Untested, // testModifiable was false.
319 CM_RValue, // Not modifiable because it's an rvalue
320 CM_Function, // Not modifiable because it's a function; C++ only
321 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
322 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
333 unsigned short Modifiable;
335 explicit Classification(Kinds k, ModifiableType m)
336 : Kind(k), Modifiable(m)
342 Kinds getKind() const { return static_cast<Kinds>(Kind); }
343 ModifiableType getModifiable() const {
344 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
345 return static_cast<ModifiableType>(Modifiable);
347 bool isLValue() const { return Kind == CL_LValue; }
348 bool isXValue() const { return Kind == CL_XValue; }
349 bool isGLValue() const { return Kind <= CL_XValue; }
350 bool isPRValue() const { return Kind >= CL_Function; }
351 bool isRValue() const { return Kind >= CL_XValue; }
352 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
354 /// \brief Create a simple, modifiably lvalue
355 static Classification makeSimpleLValue() {
356 return Classification(CL_LValue, CM_Modifiable);
360 /// \brief Classify - Classify this expression according to the C++11
361 /// expression taxonomy.
363 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
364 /// old lvalue vs rvalue. This function determines the type of expression this
365 /// is. There are three expression types:
366 /// - lvalues are classical lvalues as in C++03.
367 /// - prvalues are equivalent to rvalues in C++03.
368 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
369 /// function returning an rvalue reference.
370 /// lvalues and xvalues are collectively referred to as glvalues, while
371 /// prvalues and xvalues together form rvalues.
372 Classification Classify(ASTContext &Ctx) const {
373 return ClassifyImpl(Ctx, nullptr);
376 /// \brief ClassifyModifiable - Classify this expression according to the
377 /// C++11 expression taxonomy, and see if it is valid on the left side
378 /// of an assignment.
380 /// This function extends classify in that it also tests whether the
381 /// expression is modifiable (C99 6.3.2.1p1).
382 /// \param Loc A source location that might be filled with a relevant location
383 /// if the expression is not modifiable.
384 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
385 return ClassifyImpl(Ctx, &Loc);
388 /// getValueKindForType - Given a formal return or parameter type,
389 /// give its value kind.
390 static ExprValueKind getValueKindForType(QualType T) {
391 if (const ReferenceType *RT = T->getAs<ReferenceType>())
392 return (isa<LValueReferenceType>(RT)
394 : (RT->getPointeeType()->isFunctionType()
395 ? VK_LValue : VK_XValue));
399 /// getValueKind - The value kind that this expression produces.
400 ExprValueKind getValueKind() const {
401 return static_cast<ExprValueKind>(ExprBits.ValueKind);
404 /// getObjectKind - The object kind that this expression produces.
405 /// Object kinds are meaningful only for expressions that yield an
406 /// l-value or x-value.
407 ExprObjectKind getObjectKind() const {
408 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
411 bool isOrdinaryOrBitFieldObject() const {
412 ExprObjectKind OK = getObjectKind();
413 return (OK == OK_Ordinary || OK == OK_BitField);
416 /// setValueKind - Set the value kind produced by this expression.
417 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
419 /// setObjectKind - Set the object kind produced by this expression.
420 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
423 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
427 /// \brief Returns true if this expression is a gl-value that
428 /// potentially refers to a bit-field.
430 /// In C++, whether a gl-value refers to a bitfield is essentially
431 /// an aspect of the value-kind type system.
432 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
434 /// \brief If this expression refers to a bit-field, retrieve the
435 /// declaration of that bit-field.
437 /// Note that this returns a non-null pointer in subtly different
438 /// places than refersToBitField returns true. In particular, this can
439 /// return a non-null pointer even for r-values loaded from
440 /// bit-fields, but it will return null for a conditional bit-field.
441 FieldDecl *getSourceBitField();
443 const FieldDecl *getSourceBitField() const {
444 return const_cast<Expr*>(this)->getSourceBitField();
447 /// \brief If this expression is an l-value for an Objective C
448 /// property, find the underlying property reference expression.
449 const ObjCPropertyRefExpr *getObjCProperty() const;
451 /// \brief Check if this expression is the ObjC 'self' implicit parameter.
452 bool isObjCSelfExpr() const;
454 /// \brief Returns whether this expression refers to a vector element.
455 bool refersToVectorElement() const;
457 /// \brief Returns whether this expression refers to a global register
459 bool refersToGlobalRegisterVar() const;
461 /// \brief Returns whether this expression has a placeholder type.
462 bool hasPlaceholderType() const {
463 return getType()->isPlaceholderType();
466 /// \brief Returns whether this expression has a specific placeholder type.
467 bool hasPlaceholderType(BuiltinType::Kind K) const {
468 assert(BuiltinType::isPlaceholderTypeKind(K));
469 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
470 return BT->getKind() == K;
474 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
475 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
476 /// but also int expressions which are produced by things like comparisons in
478 bool isKnownToHaveBooleanValue() const;
480 /// isIntegerConstantExpr - Return true if this expression is a valid integer
481 /// constant expression, and, if so, return its value in Result. If not a
482 /// valid i-c-e, return false and fill in Loc (if specified) with the location
483 /// of the invalid expression.
485 /// Note: This does not perform the implicit conversions required by C++11
487 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
488 SourceLocation *Loc = nullptr,
489 bool isEvaluated = true) const;
490 bool isIntegerConstantExpr(const ASTContext &Ctx,
491 SourceLocation *Loc = nullptr) const;
493 /// isCXX98IntegralConstantExpr - Return true if this expression is an
494 /// integral constant expression in C++98. Can only be used in C++.
495 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
497 /// isCXX11ConstantExpr - Return true if this expression is a constant
498 /// expression in C++11. Can only be used in C++.
500 /// Note: This does not perform the implicit conversions required by C++11
502 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
503 SourceLocation *Loc = nullptr) const;
505 /// isPotentialConstantExpr - Return true if this function's definition
506 /// might be usable in a constant expression in C++11, if it were marked
507 /// constexpr. Return false if the function can never produce a constant
508 /// expression, along with diagnostics describing why not.
509 static bool isPotentialConstantExpr(const FunctionDecl *FD,
511 PartialDiagnosticAt> &Diags);
513 /// isPotentialConstantExprUnevaluted - Return true if this expression might
514 /// be usable in a constant expression in C++11 in an unevaluated context, if
515 /// it were in function FD marked constexpr. Return false if the function can
516 /// never produce a constant expression, along with diagnostics describing
518 static bool isPotentialConstantExprUnevaluated(Expr *E,
519 const FunctionDecl *FD,
521 PartialDiagnosticAt> &Diags);
523 /// isConstantInitializer - Returns true if this expression can be emitted to
524 /// IR as a constant, and thus can be used as a constant initializer in C.
525 /// If this expression is not constant and Culprit is non-null,
526 /// it is used to store the address of first non constant expr.
527 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
528 const Expr **Culprit = nullptr) const;
530 /// EvalStatus is a struct with detailed info about an evaluation in progress.
532 /// \brief Whether the evaluated expression has side effects.
533 /// For example, (f() && 0) can be folded, but it still has side effects.
536 /// \brief Whether the evaluation hit undefined behavior.
537 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
538 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
539 bool HasUndefinedBehavior;
541 /// Diag - If this is non-null, it will be filled in with a stack of notes
542 /// indicating why evaluation failed (or why it failed to produce a constant
544 /// If the expression is unfoldable, the notes will indicate why it's not
545 /// foldable. If the expression is foldable, but not a constant expression,
546 /// the notes will describes why it isn't a constant expression. If the
547 /// expression *is* a constant expression, no notes will be produced.
548 SmallVectorImpl<PartialDiagnosticAt> *Diag;
551 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
553 // hasSideEffects - Return true if the evaluated expression has
555 bool hasSideEffects() const {
556 return HasSideEffects;
560 /// EvalResult is a struct with detailed info about an evaluated expression.
561 struct EvalResult : EvalStatus {
562 /// Val - This is the value the expression can be folded to.
565 // isGlobalLValue - Return true if the evaluated lvalue expression
567 bool isGlobalLValue() const;
570 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
571 /// an rvalue using any crazy technique (that has nothing to do with language
572 /// standards) that we want to, even if the expression has side-effects. If
573 /// this function returns true, it returns the folded constant in Result. If
574 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
576 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
578 /// EvaluateAsBooleanCondition - Return true if this is a constant
579 /// which we we can fold and convert to a boolean condition using
580 /// any crazy technique that we want to, even if the expression has
582 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
584 enum SideEffectsKind {
585 SE_NoSideEffects, ///< Strictly evaluate the expression.
586 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
587 ///< arbitrary unmodeled side effects.
588 SE_AllowSideEffects ///< Allow any unmodeled side effect.
591 /// EvaluateAsInt - Return true if this is a constant which we can fold and
592 /// convert to an integer, using any crazy technique that we want to.
593 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
594 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
596 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
597 /// constant folded without side-effects, but discard the result.
598 bool isEvaluatable(const ASTContext &Ctx,
599 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
601 /// HasSideEffects - This routine returns true for all those expressions
602 /// which have any effect other than producing a value. Example is a function
603 /// call, volatile variable read, or throwing an exception. If
604 /// IncludePossibleEffects is false, this call treats certain expressions with
605 /// potential side effects (such as function call-like expressions,
606 /// instantiation-dependent expressions, or invocations from a macro) as not
607 /// having side effects.
608 bool HasSideEffects(const ASTContext &Ctx,
609 bool IncludePossibleEffects = true) const;
611 /// \brief Determine whether this expression involves a call to any function
612 /// that is not trivial.
613 bool hasNonTrivialCall(const ASTContext &Ctx) const;
615 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
616 /// integer. This must be called on an expression that constant folds to an
618 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
619 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
621 void EvaluateForOverflow(const ASTContext &Ctx) const;
623 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
624 /// lvalue with link time known address, with no side-effects.
625 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
627 /// EvaluateAsInitializer - Evaluate an expression as if it were the
628 /// initializer of the given declaration. Returns true if the initializer
629 /// can be folded to a constant, and produces any relevant notes. In C++11,
630 /// notes will be produced if the expression is not a constant expression.
631 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
633 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
635 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
636 /// of a call to the given function with the given arguments, inside an
637 /// unevaluated context. Returns true if the expression could be folded to a
639 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
640 const FunctionDecl *Callee,
641 ArrayRef<const Expr*> Args) const;
643 /// \brief If the current Expr is a pointer, this will try to statically
644 /// determine the number of bytes available where the pointer is pointing.
645 /// Returns true if all of the above holds and we were able to figure out the
646 /// size, false otherwise.
648 /// \param Type - How to evaluate the size of the Expr, as defined by the
649 /// "type" parameter of __builtin_object_size
650 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
651 unsigned Type) const;
653 /// \brief Enumeration used to describe the kind of Null pointer constant
654 /// returned from \c isNullPointerConstant().
655 enum NullPointerConstantKind {
656 /// \brief Expression is not a Null pointer constant.
659 /// \brief Expression is a Null pointer constant built from a zero integer
660 /// expression that is not a simple, possibly parenthesized, zero literal.
661 /// C++ Core Issue 903 will classify these expressions as "not pointers"
662 /// once it is adopted.
663 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
666 /// \brief Expression is a Null pointer constant built from a literal zero.
669 /// \brief Expression is a C++11 nullptr.
672 /// \brief Expression is a GNU-style __null constant.
676 /// \brief Enumeration used to describe how \c isNullPointerConstant()
677 /// should cope with value-dependent expressions.
678 enum NullPointerConstantValueDependence {
679 /// \brief Specifies that the expression should never be value-dependent.
680 NPC_NeverValueDependent = 0,
682 /// \brief Specifies that a value-dependent expression of integral or
683 /// dependent type should be considered a null pointer constant.
684 NPC_ValueDependentIsNull,
686 /// \brief Specifies that a value-dependent expression should be considered
687 /// to never be a null pointer constant.
688 NPC_ValueDependentIsNotNull
691 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
692 /// a Null pointer constant. The return value can further distinguish the
693 /// kind of NULL pointer constant that was detected.
694 NullPointerConstantKind isNullPointerConstant(
696 NullPointerConstantValueDependence NPC) const;
698 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
700 bool isOBJCGCCandidate(ASTContext &Ctx) const;
702 /// \brief Returns true if this expression is a bound member function.
703 bool isBoundMemberFunction(ASTContext &Ctx) const;
705 /// \brief Given an expression of bound-member type, find the type
706 /// of the member. Returns null if this is an *overloaded* bound
707 /// member expression.
708 static QualType findBoundMemberType(const Expr *expr);
710 /// IgnoreImpCasts - Skip past any implicit casts which might
711 /// surround this expression. Only skips ImplicitCastExprs.
712 Expr *IgnoreImpCasts() LLVM_READONLY;
714 /// IgnoreImplicit - Skip past any implicit AST nodes which might
715 /// surround this expression.
716 Expr *IgnoreImplicit() LLVM_READONLY {
717 return cast<Expr>(Stmt::IgnoreImplicit());
720 const Expr *IgnoreImplicit() const LLVM_READONLY {
721 return const_cast<Expr*>(this)->IgnoreImplicit();
724 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
725 /// its subexpression. If that subexpression is also a ParenExpr,
726 /// then this method recursively returns its subexpression, and so forth.
727 /// Otherwise, the method returns the current Expr.
728 Expr *IgnoreParens() LLVM_READONLY;
730 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
731 /// or CastExprs, returning their operand.
732 Expr *IgnoreParenCasts() LLVM_READONLY;
734 /// Ignore casts. Strip off any CastExprs, returning their operand.
735 Expr *IgnoreCasts() LLVM_READONLY;
737 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
738 /// any ParenExpr or ImplicitCastExprs, returning their operand.
739 Expr *IgnoreParenImpCasts() LLVM_READONLY;
741 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
742 /// call to a conversion operator, return the argument.
743 Expr *IgnoreConversionOperator() LLVM_READONLY;
745 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
746 return const_cast<Expr*>(this)->IgnoreConversionOperator();
749 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
750 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
753 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
754 /// CastExprs that represent lvalue casts, returning their operand.
755 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
757 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
758 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
761 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
762 /// value (including ptr->int casts of the same size). Strip off any
763 /// ParenExpr or CastExprs, returning their operand.
764 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
766 /// Ignore parentheses and derived-to-base casts.
767 Expr *ignoreParenBaseCasts() LLVM_READONLY;
769 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
770 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
773 /// \brief Determine whether this expression is a default function argument.
775 /// Default arguments are implicitly generated in the abstract syntax tree
776 /// by semantic analysis for function calls, object constructions, etc. in
777 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
778 /// this routine also looks through any implicit casts to determine whether
779 /// the expression is a default argument.
780 bool isDefaultArgument() const;
782 /// \brief Determine whether the result of this expression is a
783 /// temporary object of the given class type.
784 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
786 /// \brief Whether this expression is an implicit reference to 'this' in C++.
787 bool isImplicitCXXThis() const;
789 const Expr *IgnoreImpCasts() const LLVM_READONLY {
790 return const_cast<Expr*>(this)->IgnoreImpCasts();
792 const Expr *IgnoreParens() const LLVM_READONLY {
793 return const_cast<Expr*>(this)->IgnoreParens();
795 const Expr *IgnoreParenCasts() const LLVM_READONLY {
796 return const_cast<Expr*>(this)->IgnoreParenCasts();
798 /// Strip off casts, but keep parentheses.
799 const Expr *IgnoreCasts() const LLVM_READONLY {
800 return const_cast<Expr*>(this)->IgnoreCasts();
803 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
804 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
807 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
809 /// \brief For an expression of class type or pointer to class type,
810 /// return the most derived class decl the expression is known to refer to.
812 /// If this expression is a cast, this method looks through it to find the
813 /// most derived decl that can be inferred from the expression.
814 /// This is valid because derived-to-base conversions have undefined
815 /// behavior if the object isn't dynamically of the derived type.
816 const CXXRecordDecl *getBestDynamicClassType() const;
818 /// Walk outwards from an expression we want to bind a reference to and
819 /// find the expression whose lifetime needs to be extended. Record
820 /// the LHSs of comma expressions and adjustments needed along the path.
821 const Expr *skipRValueSubobjectAdjustments(
822 SmallVectorImpl<const Expr *> &CommaLHS,
823 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
825 static bool classof(const Stmt *T) {
826 return T->getStmtClass() >= firstExprConstant &&
827 T->getStmtClass() <= lastExprConstant;
831 //===----------------------------------------------------------------------===//
832 // Primary Expressions.
833 //===----------------------------------------------------------------------===//
835 /// OpaqueValueExpr - An expression referring to an opaque object of a
836 /// fixed type and value class. These don't correspond to concrete
837 /// syntax; instead they're used to express operations (usually copy
838 /// operations) on values whose source is generally obvious from
840 class OpaqueValueExpr : public Expr {
841 friend class ASTStmtReader;
846 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
847 ExprObjectKind OK = OK_Ordinary,
848 Expr *SourceExpr = nullptr)
849 : Expr(OpaqueValueExprClass, T, VK, OK,
850 T->isDependentType(),
851 T->isDependentType() ||
852 (SourceExpr && SourceExpr->isValueDependent()),
853 T->isInstantiationDependentType(),
855 SourceExpr(SourceExpr), Loc(Loc) {
858 /// Given an expression which invokes a copy constructor --- i.e. a
859 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
860 /// find the OpaqueValueExpr that's the source of the construction.
861 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
863 explicit OpaqueValueExpr(EmptyShell Empty)
864 : Expr(OpaqueValueExprClass, Empty) { }
866 /// \brief Retrieve the location of this expression.
867 SourceLocation getLocation() const { return Loc; }
869 SourceLocation getLocStart() const LLVM_READONLY {
870 return SourceExpr ? SourceExpr->getLocStart() : Loc;
872 SourceLocation getLocEnd() const LLVM_READONLY {
873 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
875 SourceLocation getExprLoc() const LLVM_READONLY {
876 if (SourceExpr) return SourceExpr->getExprLoc();
880 child_range children() {
881 return child_range(child_iterator(), child_iterator());
884 /// The source expression of an opaque value expression is the
885 /// expression which originally generated the value. This is
886 /// provided as a convenience for analyses that don't wish to
887 /// precisely model the execution behavior of the program.
889 /// The source expression is typically set when building the
890 /// expression which binds the opaque value expression in the first
892 Expr *getSourceExpr() const { return SourceExpr; }
894 static bool classof(const Stmt *T) {
895 return T->getStmtClass() == OpaqueValueExprClass;
899 /// \brief A reference to a declared variable, function, enum, etc.
902 /// This encodes all the information about how a declaration is referenced
903 /// within an expression.
905 /// There are several optional constructs attached to DeclRefExprs only when
906 /// they apply in order to conserve memory. These are laid out past the end of
907 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
909 /// DeclRefExprBits.HasQualifier:
910 /// Specifies when this declaration reference expression has a C++
911 /// nested-name-specifier.
912 /// DeclRefExprBits.HasFoundDecl:
913 /// Specifies when this declaration reference expression has a record of
914 /// a NamedDecl (different from the referenced ValueDecl) which was found
915 /// during name lookup and/or overload resolution.
916 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
917 /// Specifies when this declaration reference expression has an explicit
918 /// C++ template keyword and/or template argument list.
919 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
920 /// Specifies when this declaration reference expression (validly)
921 /// refers to an enclosed local or a captured variable.
922 class DeclRefExpr final
924 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
925 NamedDecl *, ASTTemplateKWAndArgsInfo,
926 TemplateArgumentLoc> {
927 /// \brief The declaration that we are referencing.
930 /// \brief The location of the declaration name itself.
933 /// \brief Provides source/type location info for the declaration name
935 DeclarationNameLoc DNLoc;
937 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
938 return hasQualifier() ? 1 : 0;
941 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
942 return hasFoundDecl() ? 1 : 0;
945 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
946 return hasTemplateKWAndArgsInfo() ? 1 : 0;
949 /// \brief Test whether there is a distinct FoundDecl attached to the end of
951 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
953 DeclRefExpr(const ASTContext &Ctx,
954 NestedNameSpecifierLoc QualifierLoc,
955 SourceLocation TemplateKWLoc,
956 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
957 const DeclarationNameInfo &NameInfo,
959 const TemplateArgumentListInfo *TemplateArgs,
960 QualType T, ExprValueKind VK);
962 /// \brief Construct an empty declaration reference expression.
963 explicit DeclRefExpr(EmptyShell Empty)
964 : Expr(DeclRefExprClass, Empty) { }
966 /// \brief Computes the type- and value-dependence flags for this
967 /// declaration reference expression.
968 void computeDependence(const ASTContext &C);
971 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
972 ExprValueKind VK, SourceLocation L,
973 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
974 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
975 D(D), Loc(L), DNLoc(LocInfo) {
976 DeclRefExprBits.HasQualifier = 0;
977 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
978 DeclRefExprBits.HasFoundDecl = 0;
979 DeclRefExprBits.HadMultipleCandidates = 0;
980 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
981 RefersToEnclosingVariableOrCapture;
982 computeDependence(D->getASTContext());
986 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
987 SourceLocation TemplateKWLoc, ValueDecl *D,
988 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
989 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
990 const TemplateArgumentListInfo *TemplateArgs = nullptr);
993 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
994 SourceLocation TemplateKWLoc, ValueDecl *D,
995 bool RefersToEnclosingVariableOrCapture,
996 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
997 NamedDecl *FoundD = nullptr,
998 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1000 /// \brief Construct an empty declaration reference expression.
1001 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1004 bool HasTemplateKWAndArgsInfo,
1005 unsigned NumTemplateArgs);
1007 ValueDecl *getDecl() { return D; }
1008 const ValueDecl *getDecl() const { return D; }
1009 void setDecl(ValueDecl *NewD) { D = NewD; }
1011 DeclarationNameInfo getNameInfo() const {
1012 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1015 SourceLocation getLocation() const { return Loc; }
1016 void setLocation(SourceLocation L) { Loc = L; }
1017 SourceLocation getLocStart() const LLVM_READONLY;
1018 SourceLocation getLocEnd() const LLVM_READONLY;
1020 /// \brief Determine whether this declaration reference was preceded by a
1021 /// C++ nested-name-specifier, e.g., \c N::foo.
1022 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1024 /// \brief If the name was qualified, retrieves the nested-name-specifier
1025 /// that precedes the name, with source-location information.
1026 NestedNameSpecifierLoc getQualifierLoc() const {
1027 if (!hasQualifier())
1028 return NestedNameSpecifierLoc();
1029 return *getTrailingObjects<NestedNameSpecifierLoc>();
1032 /// \brief If the name was qualified, retrieves the nested-name-specifier
1033 /// that precedes the name. Otherwise, returns NULL.
1034 NestedNameSpecifier *getQualifier() const {
1035 return getQualifierLoc().getNestedNameSpecifier();
1038 /// \brief Get the NamedDecl through which this reference occurred.
1040 /// This Decl may be different from the ValueDecl actually referred to in the
1041 /// presence of using declarations, etc. It always returns non-NULL, and may
1042 /// simple return the ValueDecl when appropriate.
1044 NamedDecl *getFoundDecl() {
1045 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1048 /// \brief Get the NamedDecl through which this reference occurred.
1049 /// See non-const variant.
1050 const NamedDecl *getFoundDecl() const {
1051 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1054 bool hasTemplateKWAndArgsInfo() const {
1055 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1058 /// \brief Retrieve the location of the template keyword preceding
1059 /// this name, if any.
1060 SourceLocation getTemplateKeywordLoc() const {
1061 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1062 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1065 /// \brief Retrieve the location of the left angle bracket starting the
1066 /// explicit template argument list following the name, if any.
1067 SourceLocation getLAngleLoc() const {
1068 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1069 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1072 /// \brief Retrieve the location of the right angle bracket ending the
1073 /// explicit template argument list following the name, if any.
1074 SourceLocation getRAngleLoc() const {
1075 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1076 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1079 /// \brief Determines whether the name in this declaration reference
1080 /// was preceded by the template keyword.
1081 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1083 /// \brief Determines whether this declaration reference was followed by an
1084 /// explicit template argument list.
1085 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1087 /// \brief Copies the template arguments (if present) into the given
1089 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1090 if (hasExplicitTemplateArgs())
1091 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1092 getTrailingObjects<TemplateArgumentLoc>(), List);
1095 /// \brief Retrieve the template arguments provided as part of this
1097 const TemplateArgumentLoc *getTemplateArgs() const {
1098 if (!hasExplicitTemplateArgs())
1101 return getTrailingObjects<TemplateArgumentLoc>();
1104 /// \brief Retrieve the number of template arguments provided as part of this
1106 unsigned getNumTemplateArgs() const {
1107 if (!hasExplicitTemplateArgs())
1110 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1113 /// \brief Returns true if this expression refers to a function that
1114 /// was resolved from an overloaded set having size greater than 1.
1115 bool hadMultipleCandidates() const {
1116 return DeclRefExprBits.HadMultipleCandidates;
1118 /// \brief Sets the flag telling whether this expression refers to
1119 /// a function that was resolved from an overloaded set having size
1121 void setHadMultipleCandidates(bool V = true) {
1122 DeclRefExprBits.HadMultipleCandidates = V;
1125 /// \brief Does this DeclRefExpr refer to an enclosing local or a captured
1127 bool refersToEnclosingVariableOrCapture() const {
1128 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1131 static bool classof(const Stmt *T) {
1132 return T->getStmtClass() == DeclRefExprClass;
1136 child_range children() {
1137 return child_range(child_iterator(), child_iterator());
1140 friend TrailingObjects;
1141 friend class ASTStmtReader;
1142 friend class ASTStmtWriter;
1145 /// \brief [C99 6.4.2.2] - A predefined identifier such as __func__.
1146 class PredefinedExpr : public Expr {
1151 LFunction, // Same as Function, but as wide string.
1155 /// \brief The same as PrettyFunction, except that the
1156 /// 'virtual' keyword is omitted for virtual member functions.
1157 PrettyFunctionNoVirtual
1166 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1169 /// \brief Construct an empty predefined expression.
1170 explicit PredefinedExpr(EmptyShell Empty)
1171 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1173 IdentType getIdentType() const { return Type; }
1175 SourceLocation getLocation() const { return Loc; }
1176 void setLocation(SourceLocation L) { Loc = L; }
1178 StringLiteral *getFunctionName();
1179 const StringLiteral *getFunctionName() const {
1180 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1183 static StringRef getIdentTypeName(IdentType IT);
1184 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1186 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1187 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1189 static bool classof(const Stmt *T) {
1190 return T->getStmtClass() == PredefinedExprClass;
1194 child_range children() { return child_range(&FnName, &FnName + 1); }
1196 friend class ASTStmtReader;
1199 /// \brief Used by IntegerLiteral/FloatingLiteral to store the numeric without
1202 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1203 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1204 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1205 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1206 /// ASTContext's allocator for memory allocation.
1207 class APNumericStorage {
1209 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1210 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1214 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1216 APNumericStorage(const APNumericStorage &) = delete;
1217 void operator=(const APNumericStorage &) = delete;
1220 APNumericStorage() : VAL(0), BitWidth(0) { }
1222 llvm::APInt getIntValue() const {
1223 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1225 return llvm::APInt(BitWidth, NumWords, pVal);
1227 return llvm::APInt(BitWidth, VAL);
1229 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1232 class APIntStorage : private APNumericStorage {
1234 llvm::APInt getValue() const { return getIntValue(); }
1235 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1236 setIntValue(C, Val);
1240 class APFloatStorage : private APNumericStorage {
1242 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1243 return llvm::APFloat(Semantics, getIntValue());
1245 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1246 setIntValue(C, Val.bitcastToAPInt());
1250 class IntegerLiteral : public Expr, public APIntStorage {
1253 /// \brief Construct an empty integer literal.
1254 explicit IntegerLiteral(EmptyShell Empty)
1255 : Expr(IntegerLiteralClass, Empty) { }
1258 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1259 // or UnsignedLongLongTy
1260 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1263 /// \brief Returns a new integer literal with value 'V' and type 'type'.
1264 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1265 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1266 /// \param V - the value that the returned integer literal contains.
1267 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1268 QualType type, SourceLocation l);
1269 /// \brief Returns a new empty integer literal.
1270 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1272 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1273 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1275 /// \brief Retrieve the location of the literal.
1276 SourceLocation getLocation() const { return Loc; }
1278 void setLocation(SourceLocation Location) { Loc = Location; }
1280 static bool classof(const Stmt *T) {
1281 return T->getStmtClass() == IntegerLiteralClass;
1285 child_range children() {
1286 return child_range(child_iterator(), child_iterator());
1290 class CharacterLiteral : public Expr {
1292 enum CharacterKind {
1303 // type should be IntTy
1304 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1306 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1308 Value(value), Loc(l) {
1309 CharacterLiteralBits.Kind = kind;
1312 /// \brief Construct an empty character literal.
1313 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1315 SourceLocation getLocation() const { return Loc; }
1316 CharacterKind getKind() const {
1317 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1320 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1321 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1323 unsigned getValue() const { return Value; }
1325 void setLocation(SourceLocation Location) { Loc = Location; }
1326 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1327 void setValue(unsigned Val) { Value = Val; }
1329 static bool classof(const Stmt *T) {
1330 return T->getStmtClass() == CharacterLiteralClass;
1334 child_range children() {
1335 return child_range(child_iterator(), child_iterator());
1339 class FloatingLiteral : public Expr, private APFloatStorage {
1342 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1343 QualType Type, SourceLocation L);
1345 /// \brief Construct an empty floating-point literal.
1346 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1349 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1350 bool isexact, QualType Type, SourceLocation L);
1351 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1353 llvm::APFloat getValue() const {
1354 return APFloatStorage::getValue(getSemantics());
1356 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1357 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1358 APFloatStorage::setValue(C, Val);
1361 /// Get a raw enumeration value representing the floating-point semantics of
1362 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1363 APFloatSemantics getRawSemantics() const {
1364 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1367 /// Set the raw enumeration value representing the floating-point semantics of
1368 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1369 void setRawSemantics(APFloatSemantics Sem) {
1370 FloatingLiteralBits.Semantics = Sem;
1373 /// Return the APFloat semantics this literal uses.
1374 const llvm::fltSemantics &getSemantics() const;
1376 /// Set the APFloat semantics this literal uses.
1377 void setSemantics(const llvm::fltSemantics &Sem);
1379 bool isExact() const { return FloatingLiteralBits.IsExact; }
1380 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1382 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1383 /// double. Note that this may cause loss of precision, but is useful for
1384 /// debugging dumps, etc.
1385 double getValueAsApproximateDouble() const;
1387 SourceLocation getLocation() const { return Loc; }
1388 void setLocation(SourceLocation L) { Loc = L; }
1390 SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1391 SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1393 static bool classof(const Stmt *T) {
1394 return T->getStmtClass() == FloatingLiteralClass;
1398 child_range children() {
1399 return child_range(child_iterator(), child_iterator());
1403 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1404 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1405 /// IntegerLiteral classes. Instances of this class always have a Complex type
1406 /// whose element type matches the subexpression.
1408 class ImaginaryLiteral : public Expr {
1411 ImaginaryLiteral(Expr *val, QualType Ty)
1412 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1416 /// \brief Build an empty imaginary literal.
1417 explicit ImaginaryLiteral(EmptyShell Empty)
1418 : Expr(ImaginaryLiteralClass, Empty) { }
1420 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1421 Expr *getSubExpr() { return cast<Expr>(Val); }
1422 void setSubExpr(Expr *E) { Val = E; }
1424 SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1425 SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1427 static bool classof(const Stmt *T) {
1428 return T->getStmtClass() == ImaginaryLiteralClass;
1432 child_range children() { return child_range(&Val, &Val+1); }
1435 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1436 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1437 /// is NOT null-terminated, and the length of the string is determined by
1438 /// calling getByteLength(). The C type for a string is always a
1439 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1442 /// Note that strings in C can be formed by concatenation of multiple string
1443 /// literal pptokens in translation phase #6. This keeps track of the locations
1444 /// of each of these pieces.
1446 /// Strings in C can also be truncated and extended by assigning into arrays,
1447 /// e.g. with constructs like:
1448 /// char X[2] = "foobar";
1449 /// In this case, getByteLength() will return 6, but the string literal will
1450 /// have type "char[2]".
1451 class StringLiteral : public Expr {
1462 friend class ASTStmtReader;
1466 const uint16_t *asUInt16;
1467 const uint32_t *asUInt32;
1470 unsigned CharByteWidth : 4;
1472 unsigned IsPascal : 1;
1473 unsigned NumConcatenated;
1474 SourceLocation TokLocs[1];
1476 StringLiteral(QualType Ty) :
1477 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1480 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1483 /// This is the "fully general" constructor that allows representation of
1484 /// strings formed from multiple concatenated tokens.
1485 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1486 StringKind Kind, bool Pascal, QualType Ty,
1487 const SourceLocation *Loc, unsigned NumStrs);
1489 /// Simple constructor for string literals made from one token.
1490 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1491 StringKind Kind, bool Pascal, QualType Ty,
1492 SourceLocation Loc) {
1493 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1496 /// \brief Construct an empty string literal.
1497 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1499 StringRef getString() const {
1500 assert(CharByteWidth==1
1501 && "This function is used in places that assume strings use char");
1502 return StringRef(StrData.asChar, getByteLength());
1505 /// Allow access to clients that need the byte representation, such as
1506 /// ASTWriterStmt::VisitStringLiteral().
1507 StringRef getBytes() const {
1508 // FIXME: StringRef may not be the right type to use as a result for this.
1509 if (CharByteWidth == 1)
1510 return StringRef(StrData.asChar, getByteLength());
1511 if (CharByteWidth == 4)
1512 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1514 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1515 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1519 void outputString(raw_ostream &OS) const;
1521 uint32_t getCodeUnit(size_t i) const {
1522 assert(i < Length && "out of bounds access");
1523 if (CharByteWidth == 1)
1524 return static_cast<unsigned char>(StrData.asChar[i]);
1525 if (CharByteWidth == 4)
1526 return StrData.asUInt32[i];
1527 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1528 return StrData.asUInt16[i];
1531 unsigned getByteLength() const { return CharByteWidth*Length; }
1532 unsigned getLength() const { return Length; }
1533 unsigned getCharByteWidth() const { return CharByteWidth; }
1535 /// \brief Sets the string data to the given string data.
1536 void setString(const ASTContext &C, StringRef Str,
1537 StringKind Kind, bool IsPascal);
1539 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1542 bool isAscii() const { return Kind == Ascii; }
1543 bool isWide() const { return Kind == Wide; }
1544 bool isUTF8() const { return Kind == UTF8; }
1545 bool isUTF16() const { return Kind == UTF16; }
1546 bool isUTF32() const { return Kind == UTF32; }
1547 bool isPascal() const { return IsPascal; }
1549 bool containsNonAsciiOrNull() const {
1550 StringRef Str = getString();
1551 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1552 if (!isASCII(Str[i]) || !Str[i])
1557 /// getNumConcatenated - Get the number of string literal tokens that were
1558 /// concatenated in translation phase #6 to form this string literal.
1559 unsigned getNumConcatenated() const { return NumConcatenated; }
1561 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1562 assert(TokNum < NumConcatenated && "Invalid tok number");
1563 return TokLocs[TokNum];
1565 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1566 assert(TokNum < NumConcatenated && "Invalid tok number");
1567 TokLocs[TokNum] = L;
1570 /// getLocationOfByte - Return a source location that points to the specified
1571 /// byte of this string literal.
1573 /// Strings are amazingly complex. They can be formed from multiple tokens
1574 /// and can have escape sequences in them in addition to the usual trigraph
1575 /// and escaped newline business. This routine handles this complexity.
1578 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1579 const LangOptions &Features, const TargetInfo &Target,
1580 unsigned *StartToken = nullptr,
1581 unsigned *StartTokenByteOffset = nullptr) const;
1583 typedef const SourceLocation *tokloc_iterator;
1584 tokloc_iterator tokloc_begin() const { return TokLocs; }
1585 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1587 SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1588 SourceLocation getLocEnd() const LLVM_READONLY {
1589 return TokLocs[NumConcatenated - 1];
1592 static bool classof(const Stmt *T) {
1593 return T->getStmtClass() == StringLiteralClass;
1597 child_range children() {
1598 return child_range(child_iterator(), child_iterator());
1602 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1603 /// AST node is only formed if full location information is requested.
1604 class ParenExpr : public Expr {
1605 SourceLocation L, R;
1608 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1609 : Expr(ParenExprClass, val->getType(),
1610 val->getValueKind(), val->getObjectKind(),
1611 val->isTypeDependent(), val->isValueDependent(),
1612 val->isInstantiationDependent(),
1613 val->containsUnexpandedParameterPack()),
1614 L(l), R(r), Val(val) {}
1616 /// \brief Construct an empty parenthesized expression.
1617 explicit ParenExpr(EmptyShell Empty)
1618 : Expr(ParenExprClass, Empty) { }
1620 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1621 Expr *getSubExpr() { return cast<Expr>(Val); }
1622 void setSubExpr(Expr *E) { Val = E; }
1624 SourceLocation getLocStart() const LLVM_READONLY { return L; }
1625 SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1627 /// \brief Get the location of the left parentheses '('.
1628 SourceLocation getLParen() const { return L; }
1629 void setLParen(SourceLocation Loc) { L = Loc; }
1631 /// \brief Get the location of the right parentheses ')'.
1632 SourceLocation getRParen() const { return R; }
1633 void setRParen(SourceLocation Loc) { R = Loc; }
1635 static bool classof(const Stmt *T) {
1636 return T->getStmtClass() == ParenExprClass;
1640 child_range children() { return child_range(&Val, &Val+1); }
1643 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1644 /// alignof), the postinc/postdec operators from postfix-expression, and various
1647 /// Notes on various nodes:
1649 /// Real/Imag - These return the real/imag part of a complex operand. If
1650 /// applied to a non-complex value, the former returns its operand and the
1651 /// later returns zero in the type of the operand.
1653 class UnaryOperator : public Expr {
1655 typedef UnaryOperatorKind Opcode;
1663 UnaryOperator(Expr *input, Opcode opc, QualType type,
1664 ExprValueKind VK, ExprObjectKind OK, SourceLocation l)
1665 : Expr(UnaryOperatorClass, type, VK, OK,
1666 input->isTypeDependent() || type->isDependentType(),
1667 input->isValueDependent(),
1668 (input->isInstantiationDependent() ||
1669 type->isInstantiationDependentType()),
1670 input->containsUnexpandedParameterPack()),
1671 Opc(opc), Loc(l), Val(input) {}
1673 /// \brief Build an empty unary operator.
1674 explicit UnaryOperator(EmptyShell Empty)
1675 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1677 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1678 void setOpcode(Opcode O) { Opc = O; }
1680 Expr *getSubExpr() const { return cast<Expr>(Val); }
1681 void setSubExpr(Expr *E) { Val = E; }
1683 /// getOperatorLoc - Return the location of the operator.
1684 SourceLocation getOperatorLoc() const { return Loc; }
1685 void setOperatorLoc(SourceLocation L) { Loc = L; }
1687 /// isPostfix - Return true if this is a postfix operation, like x++.
1688 static bool isPostfix(Opcode Op) {
1689 return Op == UO_PostInc || Op == UO_PostDec;
1692 /// isPrefix - Return true if this is a prefix operation, like --x.
1693 static bool isPrefix(Opcode Op) {
1694 return Op == UO_PreInc || Op == UO_PreDec;
1697 bool isPrefix() const { return isPrefix(getOpcode()); }
1698 bool isPostfix() const { return isPostfix(getOpcode()); }
1700 static bool isIncrementOp(Opcode Op) {
1701 return Op == UO_PreInc || Op == UO_PostInc;
1703 bool isIncrementOp() const {
1704 return isIncrementOp(getOpcode());
1707 static bool isDecrementOp(Opcode Op) {
1708 return Op == UO_PreDec || Op == UO_PostDec;
1710 bool isDecrementOp() const {
1711 return isDecrementOp(getOpcode());
1714 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1715 bool isIncrementDecrementOp() const {
1716 return isIncrementDecrementOp(getOpcode());
1719 static bool isArithmeticOp(Opcode Op) {
1720 return Op >= UO_Plus && Op <= UO_LNot;
1722 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1724 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1725 /// corresponds to, e.g. "sizeof" or "[pre]++"
1726 static StringRef getOpcodeStr(Opcode Op);
1728 /// \brief Retrieve the unary opcode that corresponds to the given
1729 /// overloaded operator.
1730 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1732 /// \brief Retrieve the overloaded operator kind that corresponds to
1733 /// the given unary opcode.
1734 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1736 SourceLocation getLocStart() const LLVM_READONLY {
1737 return isPostfix() ? Val->getLocStart() : Loc;
1739 SourceLocation getLocEnd() const LLVM_READONLY {
1740 return isPostfix() ? Loc : Val->getLocEnd();
1742 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1744 static bool classof(const Stmt *T) {
1745 return T->getStmtClass() == UnaryOperatorClass;
1749 child_range children() { return child_range(&Val, &Val+1); }
1752 /// Helper class for OffsetOfExpr.
1754 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1755 class OffsetOfNode {
1757 /// \brief The kind of offsetof node we have.
1759 /// \brief An index into an array.
1763 /// \brief A field in a dependent type, known only by its name.
1765 /// \brief An implicit indirection through a C++ base class, when the
1766 /// field found is in a base class.
1771 enum { MaskBits = 2, Mask = 0x03 };
1773 /// \brief The source range that covers this part of the designator.
1776 /// \brief The data describing the designator, which comes in three
1777 /// different forms, depending on the lower two bits.
1778 /// - An unsigned index into the array of Expr*'s stored after this node
1779 /// in memory, for [constant-expression] designators.
1780 /// - A FieldDecl*, for references to a known field.
1781 /// - An IdentifierInfo*, for references to a field with a given name
1782 /// when the class type is dependent.
1783 /// - A CXXBaseSpecifier*, for references that look at a field in a
1788 /// \brief Create an offsetof node that refers to an array element.
1789 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1790 SourceLocation RBracketLoc)
1791 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1793 /// \brief Create an offsetof node that refers to a field.
1794 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1795 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1796 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1798 /// \brief Create an offsetof node that refers to an identifier.
1799 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1800 SourceLocation NameLoc)
1801 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1802 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1804 /// \brief Create an offsetof node that refers into a C++ base class.
1805 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1806 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1808 /// \brief Determine what kind of offsetof node this is.
1809 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1811 /// \brief For an array element node, returns the index into the array
1813 unsigned getArrayExprIndex() const {
1814 assert(getKind() == Array);
1818 /// \brief For a field offsetof node, returns the field.
1819 FieldDecl *getField() const {
1820 assert(getKind() == Field);
1821 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1824 /// \brief For a field or identifier offsetof node, returns the name of
1826 IdentifierInfo *getFieldName() const;
1828 /// \brief For a base class node, returns the base specifier.
1829 CXXBaseSpecifier *getBase() const {
1830 assert(getKind() == Base);
1831 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1834 /// \brief Retrieve the source range that covers this offsetof node.
1836 /// For an array element node, the source range contains the locations of
1837 /// the square brackets. For a field or identifier node, the source range
1838 /// contains the location of the period (if there is one) and the
1840 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1841 SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1842 SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1845 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1846 /// offsetof(record-type, member-designator). For example, given:
1857 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1859 class OffsetOfExpr final
1861 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
1862 SourceLocation OperatorLoc, RParenLoc;
1864 TypeSourceInfo *TSInfo;
1865 // Number of sub-components (i.e. instances of OffsetOfNode).
1867 // Number of sub-expressions (i.e. array subscript expressions).
1870 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
1874 OffsetOfExpr(const ASTContext &C, QualType type,
1875 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1876 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1877 SourceLocation RParenLoc);
1879 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
1880 : Expr(OffsetOfExprClass, EmptyShell()),
1881 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
1885 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
1886 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1887 ArrayRef<OffsetOfNode> comps,
1888 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
1890 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
1891 unsigned NumComps, unsigned NumExprs);
1893 /// getOperatorLoc - Return the location of the operator.
1894 SourceLocation getOperatorLoc() const { return OperatorLoc; }
1895 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
1897 /// \brief Return the location of the right parentheses.
1898 SourceLocation getRParenLoc() const { return RParenLoc; }
1899 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
1901 TypeSourceInfo *getTypeSourceInfo() const {
1904 void setTypeSourceInfo(TypeSourceInfo *tsi) {
1908 const OffsetOfNode &getComponent(unsigned Idx) const {
1909 assert(Idx < NumComps && "Subscript out of range");
1910 return getTrailingObjects<OffsetOfNode>()[Idx];
1913 void setComponent(unsigned Idx, OffsetOfNode ON) {
1914 assert(Idx < NumComps && "Subscript out of range");
1915 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
1918 unsigned getNumComponents() const {
1922 Expr* getIndexExpr(unsigned Idx) {
1923 assert(Idx < NumExprs && "Subscript out of range");
1924 return getTrailingObjects<Expr *>()[Idx];
1927 const Expr *getIndexExpr(unsigned Idx) const {
1928 assert(Idx < NumExprs && "Subscript out of range");
1929 return getTrailingObjects<Expr *>()[Idx];
1932 void setIndexExpr(unsigned Idx, Expr* E) {
1933 assert(Idx < NumComps && "Subscript out of range");
1934 getTrailingObjects<Expr *>()[Idx] = E;
1937 unsigned getNumExpressions() const {
1941 SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
1942 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
1944 static bool classof(const Stmt *T) {
1945 return T->getStmtClass() == OffsetOfExprClass;
1949 child_range children() {
1950 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
1951 return child_range(begin, begin + NumExprs);
1953 friend TrailingObjects;
1956 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
1957 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
1958 /// vec_step (OpenCL 1.1 6.11.12).
1959 class UnaryExprOrTypeTraitExpr : public Expr {
1964 SourceLocation OpLoc, RParenLoc;
1967 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
1968 QualType resultType, SourceLocation op,
1969 SourceLocation rp) :
1970 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1971 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1972 // Value-dependent if the argument is type-dependent.
1973 TInfo->getType()->isDependentType(),
1974 TInfo->getType()->isInstantiationDependentType(),
1975 TInfo->getType()->containsUnexpandedParameterPack()),
1976 OpLoc(op), RParenLoc(rp) {
1977 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1978 UnaryExprOrTypeTraitExprBits.IsType = true;
1979 Argument.Ty = TInfo;
1982 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
1983 QualType resultType, SourceLocation op,
1986 /// \brief Construct an empty sizeof/alignof expression.
1987 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
1988 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
1990 UnaryExprOrTypeTrait getKind() const {
1991 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
1993 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
1995 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
1996 QualType getArgumentType() const {
1997 return getArgumentTypeInfo()->getType();
1999 TypeSourceInfo *getArgumentTypeInfo() const {
2000 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2003 Expr *getArgumentExpr() {
2004 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2005 return static_cast<Expr*>(Argument.Ex);
2007 const Expr *getArgumentExpr() const {
2008 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2011 void setArgument(Expr *E) {
2013 UnaryExprOrTypeTraitExprBits.IsType = false;
2015 void setArgument(TypeSourceInfo *TInfo) {
2016 Argument.Ty = TInfo;
2017 UnaryExprOrTypeTraitExprBits.IsType = true;
2020 /// Gets the argument type, or the type of the argument expression, whichever
2022 QualType getTypeOfArgument() const {
2023 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2026 SourceLocation getOperatorLoc() const { return OpLoc; }
2027 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2029 SourceLocation getRParenLoc() const { return RParenLoc; }
2030 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2032 SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2033 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2035 static bool classof(const Stmt *T) {
2036 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2040 child_range children();
2043 //===----------------------------------------------------------------------===//
2044 // Postfix Operators.
2045 //===----------------------------------------------------------------------===//
2047 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2048 class ArraySubscriptExpr : public Expr {
2049 enum { LHS, RHS, END_EXPR=2 };
2050 Stmt* SubExprs[END_EXPR];
2051 SourceLocation RBracketLoc;
2053 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2054 ExprValueKind VK, ExprObjectKind OK,
2055 SourceLocation rbracketloc)
2056 : Expr(ArraySubscriptExprClass, t, VK, OK,
2057 lhs->isTypeDependent() || rhs->isTypeDependent(),
2058 lhs->isValueDependent() || rhs->isValueDependent(),
2059 (lhs->isInstantiationDependent() ||
2060 rhs->isInstantiationDependent()),
2061 (lhs->containsUnexpandedParameterPack() ||
2062 rhs->containsUnexpandedParameterPack())),
2063 RBracketLoc(rbracketloc) {
2064 SubExprs[LHS] = lhs;
2065 SubExprs[RHS] = rhs;
2068 /// \brief Create an empty array subscript expression.
2069 explicit ArraySubscriptExpr(EmptyShell Shell)
2070 : Expr(ArraySubscriptExprClass, Shell) { }
2072 /// An array access can be written A[4] or 4[A] (both are equivalent).
2073 /// - getBase() and getIdx() always present the normalized view: A[4].
2074 /// In this case getBase() returns "A" and getIdx() returns "4".
2075 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2076 /// 4[A] getLHS() returns "4".
2077 /// Note: Because vector element access is also written A[4] we must
2078 /// predicate the format conversion in getBase and getIdx only on the
2079 /// the type of the RHS, as it is possible for the LHS to be a vector of
2081 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2082 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2083 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2085 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2086 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2087 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2090 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2093 const Expr *getBase() const {
2094 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getLHS():getRHS());
2098 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2101 const Expr *getIdx() const {
2102 return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getLHS());
2105 SourceLocation getLocStart() const LLVM_READONLY {
2106 return getLHS()->getLocStart();
2108 SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2110 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2111 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2113 SourceLocation getExprLoc() const LLVM_READONLY {
2114 return getBase()->getExprLoc();
2117 static bool classof(const Stmt *T) {
2118 return T->getStmtClass() == ArraySubscriptExprClass;
2122 child_range children() {
2123 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2127 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2128 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2129 /// while its subclasses may represent alternative syntax that (semantically)
2130 /// results in a function call. For example, CXXOperatorCallExpr is
2131 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2132 /// "str1 + str2" to resolve to a function call.
2133 class CallExpr : public Expr {
2134 enum { FN=0, PREARGS_START=1 };
2137 SourceLocation RParenLoc;
2140 // These versions of the constructor are for derived classes.
2141 CallExpr(const ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
2142 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
2143 SourceLocation rparenloc);
2144 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2147 Stmt *getPreArg(unsigned i) {
2148 assert(i < getNumPreArgs() && "Prearg access out of range!");
2149 return SubExprs[PREARGS_START+i];
2151 const Stmt *getPreArg(unsigned i) const {
2152 assert(i < getNumPreArgs() && "Prearg access out of range!");
2153 return SubExprs[PREARGS_START+i];
2155 void setPreArg(unsigned i, Stmt *PreArg) {
2156 assert(i < getNumPreArgs() && "Prearg access out of range!");
2157 SubExprs[PREARGS_START+i] = PreArg;
2160 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2163 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2164 ExprValueKind VK, SourceLocation rparenloc);
2166 /// \brief Build an empty call expression.
2167 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2169 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2170 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2171 void setCallee(Expr *F) { SubExprs[FN] = F; }
2173 Decl *getCalleeDecl();
2174 const Decl *getCalleeDecl() const {
2175 return const_cast<CallExpr*>(this)->getCalleeDecl();
2178 /// \brief If the callee is a FunctionDecl, return it. Otherwise return 0.
2179 FunctionDecl *getDirectCallee();
2180 const FunctionDecl *getDirectCallee() const {
2181 return const_cast<CallExpr*>(this)->getDirectCallee();
2184 /// getNumArgs - Return the number of actual arguments to this call.
2186 unsigned getNumArgs() const { return NumArgs; }
2188 /// \brief Retrieve the call arguments.
2190 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2192 const Expr *const *getArgs() const {
2193 return const_cast<CallExpr*>(this)->getArgs();
2196 /// getArg - Return the specified argument.
2197 Expr *getArg(unsigned Arg) {
2198 assert(Arg < NumArgs && "Arg access out of range!");
2199 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2201 const Expr *getArg(unsigned Arg) const {
2202 assert(Arg < NumArgs && "Arg access out of range!");
2203 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2206 /// setArg - Set the specified argument.
2207 void setArg(unsigned Arg, Expr *ArgExpr) {
2208 assert(Arg < NumArgs && "Arg access out of range!");
2209 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2212 /// setNumArgs - This changes the number of arguments present in this call.
2213 /// Any orphaned expressions are deleted by this, and any new operands are set
2215 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2217 typedef ExprIterator arg_iterator;
2218 typedef ConstExprIterator const_arg_iterator;
2219 typedef llvm::iterator_range<arg_iterator> arg_range;
2220 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2222 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2223 arg_const_range arguments() const {
2224 return arg_const_range(arg_begin(), arg_end());
2227 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2228 arg_iterator arg_end() {
2229 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2231 const_arg_iterator arg_begin() const {
2232 return SubExprs+PREARGS_START+getNumPreArgs();
2234 const_arg_iterator arg_end() const {
2235 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2238 /// This method provides fast access to all the subexpressions of
2239 /// a CallExpr without going through the slower virtual child_iterator
2240 /// interface. This provides efficient reverse iteration of the
2241 /// subexpressions. This is currently used for CFG construction.
2242 ArrayRef<Stmt*> getRawSubExprs() {
2243 return llvm::makeArrayRef(SubExprs,
2244 getNumPreArgs() + PREARGS_START + getNumArgs());
2247 /// getNumCommas - Return the number of commas that must have been present in
2248 /// this function call.
2249 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2251 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2252 /// of the callee. If not, return 0.
2253 unsigned getBuiltinCallee() const;
2255 /// \brief Returns \c true if this is a call to a builtin which does not
2256 /// evaluate side-effects within its arguments.
2257 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2259 /// getCallReturnType - Get the return type of the call expr. This is not
2260 /// always the type of the expr itself, if the return type is a reference
2262 QualType getCallReturnType(const ASTContext &Ctx) const;
2264 SourceLocation getRParenLoc() const { return RParenLoc; }
2265 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2267 SourceLocation getLocStart() const LLVM_READONLY;
2268 SourceLocation getLocEnd() const LLVM_READONLY;
2270 static bool classof(const Stmt *T) {
2271 return T->getStmtClass() >= firstCallExprConstant &&
2272 T->getStmtClass() <= lastCallExprConstant;
2276 child_range children() {
2277 return child_range(&SubExprs[0],
2278 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2282 /// Extra data stored in some MemberExpr objects.
2283 struct MemberExprNameQualifier {
2284 /// \brief The nested-name-specifier that qualifies the name, including
2285 /// source-location information.
2286 NestedNameSpecifierLoc QualifierLoc;
2288 /// \brief The DeclAccessPair through which the MemberDecl was found due to
2289 /// name qualifiers.
2290 DeclAccessPair FoundDecl;
2293 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2295 class MemberExpr final
2297 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2298 ASTTemplateKWAndArgsInfo,
2299 TemplateArgumentLoc> {
2300 /// Base - the expression for the base pointer or structure references. In
2301 /// X.F, this is "X".
2304 /// MemberDecl - This is the decl being referenced by the field/member name.
2305 /// In X.F, this is the decl referenced by F.
2306 ValueDecl *MemberDecl;
2308 /// MemberDNLoc - Provides source/type location info for the
2309 /// declaration name embedded in MemberDecl.
2310 DeclarationNameLoc MemberDNLoc;
2312 /// MemberLoc - This is the location of the member name.
2313 SourceLocation MemberLoc;
2315 /// This is the location of the -> or . in the expression.
2316 SourceLocation OperatorLoc;
2318 /// IsArrow - True if this is "X->F", false if this is "X.F".
2321 /// \brief True if this member expression used a nested-name-specifier to
2322 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2323 /// declaration. When true, a MemberExprNameQualifier
2324 /// structure is allocated immediately after the MemberExpr.
2325 bool HasQualifierOrFoundDecl : 1;
2327 /// \brief True if this member expression specified a template keyword
2328 /// and/or a template argument list explicitly, e.g., x->f<int>,
2329 /// x->template f, x->template f<int>.
2330 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2331 /// TemplateArguments (if any) are present.
2332 bool HasTemplateKWAndArgsInfo : 1;
2334 /// \brief True if this member expression refers to a method that
2335 /// was resolved from an overloaded set having size greater than 1.
2336 bool HadMultipleCandidates : 1;
2338 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2339 return HasQualifierOrFoundDecl ? 1 : 0;
2342 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2343 return HasTemplateKWAndArgsInfo ? 1 : 0;
2347 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2348 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2349 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2350 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2351 base->isValueDependent(), base->isInstantiationDependent(),
2352 base->containsUnexpandedParameterPack()),
2353 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2354 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2355 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2356 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2357 assert(memberdecl->getDeclName() == NameInfo.getName());
2360 // NOTE: this constructor should be used only when it is known that
2361 // the member name can not provide additional syntactic info
2362 // (i.e., source locations for C++ operator names or type source info
2363 // for constructors, destructors and conversion operators).
2364 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2365 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2366 ExprValueKind VK, ExprObjectKind OK)
2367 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2368 base->isValueDependent(), base->isInstantiationDependent(),
2369 base->containsUnexpandedParameterPack()),
2370 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2371 OperatorLoc(operatorloc), IsArrow(isarrow),
2372 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2373 HadMultipleCandidates(false) {}
2375 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2376 SourceLocation OperatorLoc,
2377 NestedNameSpecifierLoc QualifierLoc,
2378 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2379 DeclAccessPair founddecl,
2380 DeclarationNameInfo MemberNameInfo,
2381 const TemplateArgumentListInfo *targs, QualType ty,
2382 ExprValueKind VK, ExprObjectKind OK);
2384 void setBase(Expr *E) { Base = E; }
2385 Expr *getBase() const { return cast<Expr>(Base); }
2387 /// \brief Retrieve the member declaration to which this expression refers.
2389 /// The returned declaration will either be a FieldDecl or (in C++)
2390 /// a CXXMethodDecl.
2391 ValueDecl *getMemberDecl() const { return MemberDecl; }
2392 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2394 /// \brief Retrieves the declaration found by lookup.
2395 DeclAccessPair getFoundDecl() const {
2396 if (!HasQualifierOrFoundDecl)
2397 return DeclAccessPair::make(getMemberDecl(),
2398 getMemberDecl()->getAccess());
2399 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2402 /// \brief Determines whether this member expression actually had
2403 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2405 bool hasQualifier() const { return getQualifier() != nullptr; }
2407 /// \brief If the member name was qualified, retrieves the
2408 /// nested-name-specifier that precedes the member name, with source-location
2410 NestedNameSpecifierLoc getQualifierLoc() const {
2411 if (!HasQualifierOrFoundDecl)
2412 return NestedNameSpecifierLoc();
2414 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2417 /// \brief If the member name was qualified, retrieves the
2418 /// nested-name-specifier that precedes the member name. Otherwise, returns
2420 NestedNameSpecifier *getQualifier() const {
2421 return getQualifierLoc().getNestedNameSpecifier();
2424 /// \brief Retrieve the location of the template keyword preceding
2425 /// the member name, if any.
2426 SourceLocation getTemplateKeywordLoc() const {
2427 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2428 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2431 /// \brief Retrieve the location of the left angle bracket starting the
2432 /// explicit template argument list following the member name, if any.
2433 SourceLocation getLAngleLoc() const {
2434 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2435 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2438 /// \brief Retrieve the location of the right angle bracket ending the
2439 /// explicit template argument list following the member name, if any.
2440 SourceLocation getRAngleLoc() const {
2441 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2442 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2445 /// Determines whether the member name was preceded by the template keyword.
2446 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2448 /// \brief Determines whether the member name was followed by an
2449 /// explicit template argument list.
2450 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2452 /// \brief Copies the template arguments (if present) into the given
2454 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2455 if (hasExplicitTemplateArgs())
2456 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2457 getTrailingObjects<TemplateArgumentLoc>(), List);
2460 /// \brief Retrieve the template arguments provided as part of this
2462 const TemplateArgumentLoc *getTemplateArgs() const {
2463 if (!hasExplicitTemplateArgs())
2466 return getTrailingObjects<TemplateArgumentLoc>();
2469 /// \brief Retrieve the number of template arguments provided as part of this
2471 unsigned getNumTemplateArgs() const {
2472 if (!hasExplicitTemplateArgs())
2475 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2478 /// \brief Retrieve the member declaration name info.
2479 DeclarationNameInfo getMemberNameInfo() const {
2480 return DeclarationNameInfo(MemberDecl->getDeclName(),
2481 MemberLoc, MemberDNLoc);
2484 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2486 bool isArrow() const { return IsArrow; }
2487 void setArrow(bool A) { IsArrow = A; }
2489 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2490 /// location of 'F'.
2491 SourceLocation getMemberLoc() const { return MemberLoc; }
2492 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2494 SourceLocation getLocStart() const LLVM_READONLY;
2495 SourceLocation getLocEnd() const LLVM_READONLY;
2497 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2499 /// \brief Determine whether the base of this explicit is implicit.
2500 bool isImplicitAccess() const {
2501 return getBase() && getBase()->isImplicitCXXThis();
2504 /// \brief Returns true if this member expression refers to a method that
2505 /// was resolved from an overloaded set having size greater than 1.
2506 bool hadMultipleCandidates() const {
2507 return HadMultipleCandidates;
2509 /// \brief Sets the flag telling whether this expression refers to
2510 /// a method that was resolved from an overloaded set having size
2512 void setHadMultipleCandidates(bool V = true) {
2513 HadMultipleCandidates = V;
2516 /// \brief Returns true if virtual dispatch is performed.
2517 /// If the member access is fully qualified, (i.e. X::f()), virtual
2518 /// dispatching is not performed. In -fapple-kext mode qualified
2519 /// calls to virtual method will still go through the vtable.
2520 bool performsVirtualDispatch(const LangOptions &LO) const {
2521 return LO.AppleKext || !hasQualifier();
2524 static bool classof(const Stmt *T) {
2525 return T->getStmtClass() == MemberExprClass;
2529 child_range children() { return child_range(&Base, &Base+1); }
2531 friend TrailingObjects;
2532 friend class ASTReader;
2533 friend class ASTStmtWriter;
2536 /// CompoundLiteralExpr - [C99 6.5.2.5]
2538 class CompoundLiteralExpr : public Expr {
2539 /// LParenLoc - If non-null, this is the location of the left paren in a
2540 /// compound literal like "(int){4}". This can be null if this is a
2541 /// synthesized compound expression.
2542 SourceLocation LParenLoc;
2544 /// The type as written. This can be an incomplete array type, in
2545 /// which case the actual expression type will be different.
2546 /// The int part of the pair stores whether this expr is file scope.
2547 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2550 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2551 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2552 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2553 tinfo->getType()->isDependentType(),
2554 init->isValueDependent(),
2555 (init->isInstantiationDependent() ||
2556 tinfo->getType()->isInstantiationDependentType()),
2557 init->containsUnexpandedParameterPack()),
2558 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2560 /// \brief Construct an empty compound literal.
2561 explicit CompoundLiteralExpr(EmptyShell Empty)
2562 : Expr(CompoundLiteralExprClass, Empty) { }
2564 const Expr *getInitializer() const { return cast<Expr>(Init); }
2565 Expr *getInitializer() { return cast<Expr>(Init); }
2566 void setInitializer(Expr *E) { Init = E; }
2568 bool isFileScope() const { return TInfoAndScope.getInt(); }
2569 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2571 SourceLocation getLParenLoc() const { return LParenLoc; }
2572 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2574 TypeSourceInfo *getTypeSourceInfo() const {
2575 return TInfoAndScope.getPointer();
2577 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2578 TInfoAndScope.setPointer(tinfo);
2581 SourceLocation getLocStart() const LLVM_READONLY {
2582 // FIXME: Init should never be null.
2584 return SourceLocation();
2585 if (LParenLoc.isInvalid())
2586 return Init->getLocStart();
2589 SourceLocation getLocEnd() const LLVM_READONLY {
2590 // FIXME: Init should never be null.
2592 return SourceLocation();
2593 return Init->getLocEnd();
2596 static bool classof(const Stmt *T) {
2597 return T->getStmtClass() == CompoundLiteralExprClass;
2601 child_range children() { return child_range(&Init, &Init+1); }
2604 /// CastExpr - Base class for type casts, including both implicit
2605 /// casts (ImplicitCastExpr) and explicit casts that have some
2606 /// representation in the source code (ExplicitCastExpr's derived
2608 class CastExpr : public Expr {
2612 bool CastConsistency() const;
2614 const CXXBaseSpecifier * const *path_buffer() const {
2615 return const_cast<CastExpr*>(this)->path_buffer();
2617 CXXBaseSpecifier **path_buffer();
2619 void setBasePathSize(unsigned basePathSize) {
2620 CastExprBits.BasePathSize = basePathSize;
2621 assert(CastExprBits.BasePathSize == basePathSize &&
2622 "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2626 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2627 Expr *op, unsigned BasePathSize)
2628 : Expr(SC, ty, VK, OK_Ordinary,
2629 // Cast expressions are type-dependent if the type is
2630 // dependent (C++ [temp.dep.expr]p3).
2631 ty->isDependentType(),
2632 // Cast expressions are value-dependent if the type is
2633 // dependent or if the subexpression is value-dependent.
2634 ty->isDependentType() || (op && op->isValueDependent()),
2635 (ty->isInstantiationDependentType() ||
2636 (op && op->isInstantiationDependent())),
2637 // An implicit cast expression doesn't (lexically) contain an
2638 // unexpanded pack, even if its target type does.
2639 ((SC != ImplicitCastExprClass &&
2640 ty->containsUnexpandedParameterPack()) ||
2641 (op && op->containsUnexpandedParameterPack()))),
2643 assert(kind != CK_Invalid && "creating cast with invalid cast kind");
2644 CastExprBits.Kind = kind;
2645 setBasePathSize(BasePathSize);
2646 assert(CastConsistency());
2649 /// \brief Construct an empty cast.
2650 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2652 setBasePathSize(BasePathSize);
2656 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2657 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2658 const char *getCastKindName() const;
2660 Expr *getSubExpr() { return cast<Expr>(Op); }
2661 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2662 void setSubExpr(Expr *E) { Op = E; }
2664 /// \brief Retrieve the cast subexpression as it was written in the source
2665 /// code, looking through any implicit casts or other intermediate nodes
2666 /// introduced by semantic analysis.
2667 Expr *getSubExprAsWritten();
2668 const Expr *getSubExprAsWritten() const {
2669 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2672 typedef CXXBaseSpecifier **path_iterator;
2673 typedef const CXXBaseSpecifier * const *path_const_iterator;
2674 bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2675 unsigned path_size() const { return CastExprBits.BasePathSize; }
2676 path_iterator path_begin() { return path_buffer(); }
2677 path_iterator path_end() { return path_buffer() + path_size(); }
2678 path_const_iterator path_begin() const { return path_buffer(); }
2679 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2681 static bool classof(const Stmt *T) {
2682 return T->getStmtClass() >= firstCastExprConstant &&
2683 T->getStmtClass() <= lastCastExprConstant;
2687 child_range children() { return child_range(&Op, &Op+1); }
2690 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2691 /// conversions, which have no direct representation in the original
2692 /// source code. For example: converting T[]->T*, void f()->void
2693 /// (*f)(), float->double, short->int, etc.
2695 /// In C, implicit casts always produce rvalues. However, in C++, an
2696 /// implicit cast whose result is being bound to a reference will be
2697 /// an lvalue or xvalue. For example:
2701 /// class Derived : public Base { };
2702 /// Derived &&ref();
2703 /// void f(Derived d) {
2704 /// Base& b = d; // initializer is an ImplicitCastExpr
2705 /// // to an lvalue of type Base
2706 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2707 /// // to an xvalue of type Base
2710 class ImplicitCastExpr final
2712 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2714 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2715 unsigned BasePathLength, ExprValueKind VK)
2716 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2719 /// \brief Construct an empty implicit cast.
2720 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2721 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2724 enum OnStack_t { OnStack };
2725 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2727 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2730 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2731 CastKind Kind, Expr *Operand,
2732 const CXXCastPath *BasePath,
2735 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2738 SourceLocation getLocStart() const LLVM_READONLY {
2739 return getSubExpr()->getLocStart();
2741 SourceLocation getLocEnd() const LLVM_READONLY {
2742 return getSubExpr()->getLocEnd();
2745 static bool classof(const Stmt *T) {
2746 return T->getStmtClass() == ImplicitCastExprClass;
2749 friend TrailingObjects;
2750 friend class CastExpr;
2753 inline Expr *Expr::IgnoreImpCasts() {
2755 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2756 e = ice->getSubExpr();
2760 /// ExplicitCastExpr - An explicit cast written in the source
2763 /// This class is effectively an abstract class, because it provides
2764 /// the basic representation of an explicitly-written cast without
2765 /// specifying which kind of cast (C cast, functional cast, static
2766 /// cast, etc.) was written; specific derived classes represent the
2767 /// particular style of cast and its location information.
2769 /// Unlike implicit casts, explicit cast nodes have two different
2770 /// types: the type that was written into the source code, and the
2771 /// actual type of the expression as determined by semantic
2772 /// analysis. These types may differ slightly. For example, in C++ one
2773 /// can cast to a reference type, which indicates that the resulting
2774 /// expression will be an lvalue or xvalue. The reference type, however,
2775 /// will not be used as the type of the expression.
2776 class ExplicitCastExpr : public CastExpr {
2777 /// TInfo - Source type info for the (written) type
2778 /// this expression is casting to.
2779 TypeSourceInfo *TInfo;
2782 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2783 CastKind kind, Expr *op, unsigned PathSize,
2784 TypeSourceInfo *writtenTy)
2785 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2787 /// \brief Construct an empty explicit cast.
2788 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2789 : CastExpr(SC, Shell, PathSize) { }
2792 /// getTypeInfoAsWritten - Returns the type source info for the type
2793 /// that this expression is casting to.
2794 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2795 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2797 /// getTypeAsWritten - Returns the type that this expression is
2798 /// casting to, as written in the source code.
2799 QualType getTypeAsWritten() const { return TInfo->getType(); }
2801 static bool classof(const Stmt *T) {
2802 return T->getStmtClass() >= firstExplicitCastExprConstant &&
2803 T->getStmtClass() <= lastExplicitCastExprConstant;
2807 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
2808 /// cast in C++ (C++ [expr.cast]), which uses the syntax
2809 /// (Type)expr. For example: @c (int)f.
2810 class CStyleCastExpr final
2811 : public ExplicitCastExpr,
2812 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
2813 SourceLocation LPLoc; // the location of the left paren
2814 SourceLocation RPLoc; // the location of the right paren
2816 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
2817 unsigned PathSize, TypeSourceInfo *writtenTy,
2818 SourceLocation l, SourceLocation r)
2819 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
2820 writtenTy), LPLoc(l), RPLoc(r) {}
2822 /// \brief Construct an empty C-style explicit cast.
2823 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
2824 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
2827 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
2828 ExprValueKind VK, CastKind K,
2829 Expr *Op, const CXXCastPath *BasePath,
2830 TypeSourceInfo *WrittenTy, SourceLocation L,
2833 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
2836 SourceLocation getLParenLoc() const { return LPLoc; }
2837 void setLParenLoc(SourceLocation L) { LPLoc = L; }
2839 SourceLocation getRParenLoc() const { return RPLoc; }
2840 void setRParenLoc(SourceLocation L) { RPLoc = L; }
2842 SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
2843 SourceLocation getLocEnd() const LLVM_READONLY {
2844 return getSubExpr()->getLocEnd();
2847 static bool classof(const Stmt *T) {
2848 return T->getStmtClass() == CStyleCastExprClass;
2851 friend TrailingObjects;
2852 friend class CastExpr;
2855 /// \brief A builtin binary operation expression such as "x + y" or "x <= y".
2857 /// This expression node kind describes a builtin binary operation,
2858 /// such as "x + y" for integer values "x" and "y". The operands will
2859 /// already have been converted to appropriate types (e.g., by
2860 /// performing promotions or conversions).
2862 /// In C++, where operators may be overloaded, a different kind of
2863 /// expression node (CXXOperatorCallExpr) is used to express the
2864 /// invocation of an overloaded operator with operator syntax. Within
2865 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
2866 /// used to store an expression "x + y" depends on the subexpressions
2867 /// for x and y. If neither x or y is type-dependent, and the "+"
2868 /// operator resolves to a built-in operation, BinaryOperator will be
2869 /// used to express the computation (x and y may still be
2870 /// value-dependent). If either x or y is type-dependent, or if the
2871 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
2872 /// be used to express the computation.
2873 class BinaryOperator : public Expr {
2875 typedef BinaryOperatorKind Opcode;
2880 // Records the FP_CONTRACT pragma status at the point that this binary
2881 // operator was parsed. This bit is only meaningful for operations on
2882 // floating point types. For all other types it should default to
2884 unsigned FPContractable : 1;
2885 SourceLocation OpLoc;
2887 enum { LHS, RHS, END_EXPR };
2888 Stmt* SubExprs[END_EXPR];
2891 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
2892 ExprValueKind VK, ExprObjectKind OK,
2893 SourceLocation opLoc, bool fpContractable)
2894 : Expr(BinaryOperatorClass, ResTy, VK, OK,
2895 lhs->isTypeDependent() || rhs->isTypeDependent(),
2896 lhs->isValueDependent() || rhs->isValueDependent(),
2897 (lhs->isInstantiationDependent() ||
2898 rhs->isInstantiationDependent()),
2899 (lhs->containsUnexpandedParameterPack() ||
2900 rhs->containsUnexpandedParameterPack())),
2901 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
2902 SubExprs[LHS] = lhs;
2903 SubExprs[RHS] = rhs;
2904 assert(!isCompoundAssignmentOp() &&
2905 "Use CompoundAssignOperator for compound assignments");
2908 /// \brief Construct an empty binary operator.
2909 explicit BinaryOperator(EmptyShell Empty)
2910 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
2912 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
2913 SourceLocation getOperatorLoc() const { return OpLoc; }
2914 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2916 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
2917 void setOpcode(Opcode O) { Opc = O; }
2919 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2920 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2921 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2922 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2924 SourceLocation getLocStart() const LLVM_READONLY {
2925 return getLHS()->getLocStart();
2927 SourceLocation getLocEnd() const LLVM_READONLY {
2928 return getRHS()->getLocEnd();
2931 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2932 /// corresponds to, e.g. "<<=".
2933 static StringRef getOpcodeStr(Opcode Op);
2935 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
2937 /// \brief Retrieve the binary opcode that corresponds to the given
2938 /// overloaded operator.
2939 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
2941 /// \brief Retrieve the overloaded operator kind that corresponds to
2942 /// the given binary opcode.
2943 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2945 /// predicates to categorize the respective opcodes.
2946 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
2947 static bool isMultiplicativeOp(Opcode Opc) {
2948 return Opc >= BO_Mul && Opc <= BO_Rem;
2950 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
2951 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
2952 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
2953 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
2954 bool isShiftOp() const { return isShiftOp(getOpcode()); }
2956 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
2957 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
2959 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
2960 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
2962 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
2963 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
2965 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_NE; }
2966 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
2968 static Opcode negateComparisonOp(Opcode Opc) {
2971 llvm_unreachable("Not a comparsion operator.");
2972 case BO_LT: return BO_GE;
2973 case BO_GT: return BO_LE;
2974 case BO_LE: return BO_GT;
2975 case BO_GE: return BO_LT;
2976 case BO_EQ: return BO_NE;
2977 case BO_NE: return BO_EQ;
2981 static Opcode reverseComparisonOp(Opcode Opc) {
2984 llvm_unreachable("Not a comparsion operator.");
2985 case BO_LT: return BO_GT;
2986 case BO_GT: return BO_LT;
2987 case BO_LE: return BO_GE;
2988 case BO_GE: return BO_LE;
2995 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
2996 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
2998 static bool isAssignmentOp(Opcode Opc) {
2999 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3001 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3003 static bool isCompoundAssignmentOp(Opcode Opc) {
3004 return Opc > BO_Assign && Opc <= BO_OrAssign;
3006 bool isCompoundAssignmentOp() const {
3007 return isCompoundAssignmentOp(getOpcode());
3009 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3010 assert(isCompoundAssignmentOp(Opc));
3011 if (Opc >= BO_AndAssign)
3012 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3014 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3017 static bool isShiftAssignOp(Opcode Opc) {
3018 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3020 bool isShiftAssignOp() const {
3021 return isShiftAssignOp(getOpcode());
3024 static bool classof(const Stmt *S) {
3025 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3026 S->getStmtClass() <= lastBinaryOperatorConstant;
3030 child_range children() {
3031 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3034 // Set the FP contractability status of this operator. Only meaningful for
3035 // operations on floating point types.
3036 void setFPContractable(bool FPC) { FPContractable = FPC; }
3038 // Get the FP contractability status of this operator. Only meaningful for
3039 // operations on floating point types.
3040 bool isFPContractable() const { return FPContractable; }
3043 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3044 ExprValueKind VK, ExprObjectKind OK,
3045 SourceLocation opLoc, bool fpContractable, bool dead2)
3046 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3047 lhs->isTypeDependent() || rhs->isTypeDependent(),
3048 lhs->isValueDependent() || rhs->isValueDependent(),
3049 (lhs->isInstantiationDependent() ||
3050 rhs->isInstantiationDependent()),
3051 (lhs->containsUnexpandedParameterPack() ||
3052 rhs->containsUnexpandedParameterPack())),
3053 Opc(opc), FPContractable(fpContractable), OpLoc(opLoc) {
3054 SubExprs[LHS] = lhs;
3055 SubExprs[RHS] = rhs;
3058 BinaryOperator(StmtClass SC, EmptyShell Empty)
3059 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3062 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3063 /// track of the type the operation is performed in. Due to the semantics of
3064 /// these operators, the operands are promoted, the arithmetic performed, an
3065 /// implicit conversion back to the result type done, then the assignment takes
3066 /// place. This captures the intermediate type which the computation is done
3068 class CompoundAssignOperator : public BinaryOperator {
3069 QualType ComputationLHSType;
3070 QualType ComputationResultType;
3072 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3073 ExprValueKind VK, ExprObjectKind OK,
3074 QualType CompLHSType, QualType CompResultType,
3075 SourceLocation OpLoc, bool fpContractable)
3076 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, fpContractable,
3078 ComputationLHSType(CompLHSType),
3079 ComputationResultType(CompResultType) {
3080 assert(isCompoundAssignmentOp() &&
3081 "Only should be used for compound assignments");
3084 /// \brief Build an empty compound assignment operator expression.
3085 explicit CompoundAssignOperator(EmptyShell Empty)
3086 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3088 // The two computation types are the type the LHS is converted
3089 // to for the computation and the type of the result; the two are
3090 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3091 QualType getComputationLHSType() const { return ComputationLHSType; }
3092 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3094 QualType getComputationResultType() const { return ComputationResultType; }
3095 void setComputationResultType(QualType T) { ComputationResultType = T; }
3097 static bool classof(const Stmt *S) {
3098 return S->getStmtClass() == CompoundAssignOperatorClass;
3102 /// AbstractConditionalOperator - An abstract base class for
3103 /// ConditionalOperator and BinaryConditionalOperator.
3104 class AbstractConditionalOperator : public Expr {
3105 SourceLocation QuestionLoc, ColonLoc;
3106 friend class ASTStmtReader;
3109 AbstractConditionalOperator(StmtClass SC, QualType T,
3110 ExprValueKind VK, ExprObjectKind OK,
3111 bool TD, bool VD, bool ID,
3112 bool ContainsUnexpandedParameterPack,
3113 SourceLocation qloc,
3114 SourceLocation cloc)
3115 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3116 QuestionLoc(qloc), ColonLoc(cloc) {}
3118 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3119 : Expr(SC, Empty) { }
3122 // getCond - Return the expression representing the condition for
3124 Expr *getCond() const;
3126 // getTrueExpr - Return the subexpression representing the value of
3127 // the expression if the condition evaluates to true.
3128 Expr *getTrueExpr() const;
3130 // getFalseExpr - Return the subexpression representing the value of
3131 // the expression if the condition evaluates to false. This is
3132 // the same as getRHS.
3133 Expr *getFalseExpr() const;
3135 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3136 SourceLocation getColonLoc() const { return ColonLoc; }
3138 static bool classof(const Stmt *T) {
3139 return T->getStmtClass() == ConditionalOperatorClass ||
3140 T->getStmtClass() == BinaryConditionalOperatorClass;
3144 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3145 /// middle" extension is a BinaryConditionalOperator.
3146 class ConditionalOperator : public AbstractConditionalOperator {
3147 enum { COND, LHS, RHS, END_EXPR };
3148 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3150 friend class ASTStmtReader;
3152 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3153 SourceLocation CLoc, Expr *rhs,
3154 QualType t, ExprValueKind VK, ExprObjectKind OK)
3155 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3156 // FIXME: the type of the conditional operator doesn't
3157 // depend on the type of the conditional, but the standard
3158 // seems to imply that it could. File a bug!
3159 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3160 (cond->isValueDependent() || lhs->isValueDependent() ||
3161 rhs->isValueDependent()),
3162 (cond->isInstantiationDependent() ||
3163 lhs->isInstantiationDependent() ||
3164 rhs->isInstantiationDependent()),
3165 (cond->containsUnexpandedParameterPack() ||
3166 lhs->containsUnexpandedParameterPack() ||
3167 rhs->containsUnexpandedParameterPack()),
3169 SubExprs[COND] = cond;
3170 SubExprs[LHS] = lhs;
3171 SubExprs[RHS] = rhs;
3174 /// \brief Build an empty conditional operator.
3175 explicit ConditionalOperator(EmptyShell Empty)
3176 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3178 // getCond - Return the expression representing the condition for
3180 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3182 // getTrueExpr - Return the subexpression representing the value of
3183 // the expression if the condition evaluates to true.
3184 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3186 // getFalseExpr - Return the subexpression representing the value of
3187 // the expression if the condition evaluates to false. This is
3188 // the same as getRHS.
3189 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3191 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3192 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3194 SourceLocation getLocStart() const LLVM_READONLY {
3195 return getCond()->getLocStart();
3197 SourceLocation getLocEnd() const LLVM_READONLY {
3198 return getRHS()->getLocEnd();
3201 static bool classof(const Stmt *T) {
3202 return T->getStmtClass() == ConditionalOperatorClass;
3206 child_range children() {
3207 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3211 /// BinaryConditionalOperator - The GNU extension to the conditional
3212 /// operator which allows the middle operand to be omitted.
3214 /// This is a different expression kind on the assumption that almost
3215 /// every client ends up needing to know that these are different.
3216 class BinaryConditionalOperator : public AbstractConditionalOperator {
3217 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3219 /// - the common condition/left-hand-side expression, which will be
3220 /// evaluated as the opaque value
3221 /// - the condition, expressed in terms of the opaque value
3222 /// - the left-hand-side, expressed in terms of the opaque value
3223 /// - the right-hand-side
3224 Stmt *SubExprs[NUM_SUBEXPRS];
3225 OpaqueValueExpr *OpaqueValue;
3227 friend class ASTStmtReader;
3229 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3230 Expr *cond, Expr *lhs, Expr *rhs,
3231 SourceLocation qloc, SourceLocation cloc,
3232 QualType t, ExprValueKind VK, ExprObjectKind OK)
3233 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3234 (common->isTypeDependent() || rhs->isTypeDependent()),
3235 (common->isValueDependent() || rhs->isValueDependent()),
3236 (common->isInstantiationDependent() ||
3237 rhs->isInstantiationDependent()),
3238 (common->containsUnexpandedParameterPack() ||
3239 rhs->containsUnexpandedParameterPack()),
3241 OpaqueValue(opaqueValue) {
3242 SubExprs[COMMON] = common;
3243 SubExprs[COND] = cond;
3244 SubExprs[LHS] = lhs;
3245 SubExprs[RHS] = rhs;
3246 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3249 /// \brief Build an empty conditional operator.
3250 explicit BinaryConditionalOperator(EmptyShell Empty)
3251 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3253 /// \brief getCommon - Return the common expression, written to the
3254 /// left of the condition. The opaque value will be bound to the
3255 /// result of this expression.
3256 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3258 /// \brief getOpaqueValue - Return the opaque value placeholder.
3259 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3261 /// \brief getCond - Return the condition expression; this is defined
3262 /// in terms of the opaque value.
3263 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3265 /// \brief getTrueExpr - Return the subexpression which will be
3266 /// evaluated if the condition evaluates to true; this is defined
3267 /// in terms of the opaque value.
3268 Expr *getTrueExpr() const {
3269 return cast<Expr>(SubExprs[LHS]);
3272 /// \brief getFalseExpr - Return the subexpression which will be
3273 /// evaluated if the condnition evaluates to false; this is
3274 /// defined in terms of the opaque value.
3275 Expr *getFalseExpr() const {
3276 return cast<Expr>(SubExprs[RHS]);
3279 SourceLocation getLocStart() const LLVM_READONLY {
3280 return getCommon()->getLocStart();
3282 SourceLocation getLocEnd() const LLVM_READONLY {
3283 return getFalseExpr()->getLocEnd();
3286 static bool classof(const Stmt *T) {
3287 return T->getStmtClass() == BinaryConditionalOperatorClass;
3291 child_range children() {
3292 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3296 inline Expr *AbstractConditionalOperator::getCond() const {
3297 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3298 return co->getCond();
3299 return cast<BinaryConditionalOperator>(this)->getCond();
3302 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3303 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3304 return co->getTrueExpr();
3305 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3308 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3309 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3310 return co->getFalseExpr();
3311 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3314 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3315 class AddrLabelExpr : public Expr {
3316 SourceLocation AmpAmpLoc, LabelLoc;
3319 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3321 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3323 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3325 /// \brief Build an empty address of a label expression.
3326 explicit AddrLabelExpr(EmptyShell Empty)
3327 : Expr(AddrLabelExprClass, Empty) { }
3329 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3330 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3331 SourceLocation getLabelLoc() const { return LabelLoc; }
3332 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3334 SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3335 SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3337 LabelDecl *getLabel() const { return Label; }
3338 void setLabel(LabelDecl *L) { Label = L; }
3340 static bool classof(const Stmt *T) {
3341 return T->getStmtClass() == AddrLabelExprClass;
3345 child_range children() {
3346 return child_range(child_iterator(), child_iterator());
3350 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3351 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3352 /// takes the value of the last subexpression.
3354 /// A StmtExpr is always an r-value; values "returned" out of a
3355 /// StmtExpr will be copied.
3356 class StmtExpr : public Expr {
3358 SourceLocation LParenLoc, RParenLoc;
3360 // FIXME: Does type-dependence need to be computed differently?
3361 // FIXME: Do we need to compute instantiation instantiation-dependence for
3362 // statements? (ugh!)
3363 StmtExpr(CompoundStmt *substmt, QualType T,
3364 SourceLocation lp, SourceLocation rp) :
3365 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3366 T->isDependentType(), false, false, false),
3367 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3369 /// \brief Build an empty statement expression.
3370 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3372 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3373 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3374 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3376 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3377 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3379 SourceLocation getLParenLoc() const { return LParenLoc; }
3380 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3381 SourceLocation getRParenLoc() const { return RParenLoc; }
3382 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3384 static bool classof(const Stmt *T) {
3385 return T->getStmtClass() == StmtExprClass;
3389 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3392 /// ShuffleVectorExpr - clang-specific builtin-in function
3393 /// __builtin_shufflevector.
3394 /// This AST node represents a operator that does a constant
3395 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3396 /// two vectors and a variable number of constant indices,
3397 /// and returns the appropriately shuffled vector.
3398 class ShuffleVectorExpr : public Expr {
3399 SourceLocation BuiltinLoc, RParenLoc;
3401 // SubExprs - the list of values passed to the __builtin_shufflevector
3402 // function. The first two are vectors, and the rest are constant
3403 // indices. The number of values in this list is always
3404 // 2+the number of indices in the vector type.
3409 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3410 SourceLocation BLoc, SourceLocation RP);
3412 /// \brief Build an empty vector-shuffle expression.
3413 explicit ShuffleVectorExpr(EmptyShell Empty)
3414 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3416 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3417 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3419 SourceLocation getRParenLoc() const { return RParenLoc; }
3420 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3422 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3423 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3425 static bool classof(const Stmt *T) {
3426 return T->getStmtClass() == ShuffleVectorExprClass;
3429 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3430 /// constant expression, the actual arguments passed in, and the function
3432 unsigned getNumSubExprs() const { return NumExprs; }
3434 /// \brief Retrieve the array of expressions.
3435 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3437 /// getExpr - Return the Expr at the specified index.
3438 Expr *getExpr(unsigned Index) {
3439 assert((Index < NumExprs) && "Arg access out of range!");
3440 return cast<Expr>(SubExprs[Index]);
3442 const Expr *getExpr(unsigned Index) const {
3443 assert((Index < NumExprs) && "Arg access out of range!");
3444 return cast<Expr>(SubExprs[Index]);
3447 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3449 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3450 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3451 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3455 child_range children() {
3456 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3460 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3461 /// This AST node provides support for converting a vector type to another
3462 /// vector type of the same arity.
3463 class ConvertVectorExpr : public Expr {
3466 TypeSourceInfo *TInfo;
3467 SourceLocation BuiltinLoc, RParenLoc;
3469 friend class ASTReader;
3470 friend class ASTStmtReader;
3471 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3474 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3475 ExprValueKind VK, ExprObjectKind OK,
3476 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3477 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3478 DstType->isDependentType(),
3479 DstType->isDependentType() || SrcExpr->isValueDependent(),
3480 (DstType->isInstantiationDependentType() ||
3481 SrcExpr->isInstantiationDependent()),
3482 (DstType->containsUnexpandedParameterPack() ||
3483 SrcExpr->containsUnexpandedParameterPack())),
3484 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3486 /// getSrcExpr - Return the Expr to be converted.
3487 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3489 /// getTypeSourceInfo - Return the destination type.
3490 TypeSourceInfo *getTypeSourceInfo() const {
3493 void setTypeSourceInfo(TypeSourceInfo *ti) {
3497 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3498 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3500 /// getRParenLoc - Return the location of final right parenthesis.
3501 SourceLocation getRParenLoc() const { return RParenLoc; }
3503 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3504 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3506 static bool classof(const Stmt *T) {
3507 return T->getStmtClass() == ConvertVectorExprClass;
3511 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3514 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3515 /// This AST node is similar to the conditional operator (?:) in C, with
3516 /// the following exceptions:
3517 /// - the test expression must be a integer constant expression.
3518 /// - the expression returned acts like the chosen subexpression in every
3519 /// visible way: the type is the same as that of the chosen subexpression,
3520 /// and all predicates (whether it's an l-value, whether it's an integer
3521 /// constant expression, etc.) return the same result as for the chosen
3523 class ChooseExpr : public Expr {
3524 enum { COND, LHS, RHS, END_EXPR };
3525 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3526 SourceLocation BuiltinLoc, RParenLoc;
3529 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3530 QualType t, ExprValueKind VK, ExprObjectKind OK,
3531 SourceLocation RP, bool condIsTrue,
3532 bool TypeDependent, bool ValueDependent)
3533 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3534 (cond->isInstantiationDependent() ||
3535 lhs->isInstantiationDependent() ||
3536 rhs->isInstantiationDependent()),
3537 (cond->containsUnexpandedParameterPack() ||
3538 lhs->containsUnexpandedParameterPack() ||
3539 rhs->containsUnexpandedParameterPack())),
3540 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3541 SubExprs[COND] = cond;
3542 SubExprs[LHS] = lhs;
3543 SubExprs[RHS] = rhs;
3546 /// \brief Build an empty __builtin_choose_expr.
3547 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3549 /// isConditionTrue - Return whether the condition is true (i.e. not
3551 bool isConditionTrue() const {
3552 assert(!isConditionDependent() &&
3553 "Dependent condition isn't true or false");
3556 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3558 bool isConditionDependent() const {
3559 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3562 /// getChosenSubExpr - Return the subexpression chosen according to the
3564 Expr *getChosenSubExpr() const {
3565 return isConditionTrue() ? getLHS() : getRHS();
3568 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3569 void setCond(Expr *E) { SubExprs[COND] = E; }
3570 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3571 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3572 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3573 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3575 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3576 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3578 SourceLocation getRParenLoc() const { return RParenLoc; }
3579 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3581 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3582 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3584 static bool classof(const Stmt *T) {
3585 return T->getStmtClass() == ChooseExprClass;
3589 child_range children() {
3590 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3594 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3595 /// for a null pointer constant that has integral type (e.g., int or
3596 /// long) and is the same size and alignment as a pointer. The __null
3597 /// extension is typically only used by system headers, which define
3598 /// NULL as __null in C++ rather than using 0 (which is an integer
3599 /// that may not match the size of a pointer).
3600 class GNUNullExpr : public Expr {
3601 /// TokenLoc - The location of the __null keyword.
3602 SourceLocation TokenLoc;
3605 GNUNullExpr(QualType Ty, SourceLocation Loc)
3606 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3610 /// \brief Build an empty GNU __null expression.
3611 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3613 /// getTokenLocation - The location of the __null token.
3614 SourceLocation getTokenLocation() const { return TokenLoc; }
3615 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3617 SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3618 SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3620 static bool classof(const Stmt *T) {
3621 return T->getStmtClass() == GNUNullExprClass;
3625 child_range children() {
3626 return child_range(child_iterator(), child_iterator());
3630 /// Represents a call to the builtin function \c __builtin_va_arg.
3631 class VAArgExpr : public Expr {
3633 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3634 SourceLocation BuiltinLoc, RParenLoc;
3636 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3637 SourceLocation RPLoc, QualType t, bool IsMS)
3638 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3639 false, (TInfo->getType()->isInstantiationDependentType() ||
3640 e->isInstantiationDependent()),
3641 (TInfo->getType()->containsUnexpandedParameterPack() ||
3642 e->containsUnexpandedParameterPack())),
3643 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3645 /// Create an empty __builtin_va_arg expression.
3646 explicit VAArgExpr(EmptyShell Empty)
3647 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3649 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3650 Expr *getSubExpr() { return cast<Expr>(Val); }
3651 void setSubExpr(Expr *E) { Val = E; }
3653 /// Returns whether this is really a Win64 ABI va_arg expression.
3654 bool isMicrosoftABI() const { return TInfo.getInt(); }
3655 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3657 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3658 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3660 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3661 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3663 SourceLocation getRParenLoc() const { return RParenLoc; }
3664 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3666 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3667 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3669 static bool classof(const Stmt *T) {
3670 return T->getStmtClass() == VAArgExprClass;
3674 child_range children() { return child_range(&Val, &Val+1); }
3677 /// @brief Describes an C or C++ initializer list.
3679 /// InitListExpr describes an initializer list, which can be used to
3680 /// initialize objects of different types, including
3681 /// struct/class/union types, arrays, and vectors. For example:
3684 /// struct foo x = { 1, { 2, 3 } };
3687 /// Prior to semantic analysis, an initializer list will represent the
3688 /// initializer list as written by the user, but will have the
3689 /// placeholder type "void". This initializer list is called the
3690 /// syntactic form of the initializer, and may contain C99 designated
3691 /// initializers (represented as DesignatedInitExprs), initializations
3692 /// of subobject members without explicit braces, and so on. Clients
3693 /// interested in the original syntax of the initializer list should
3694 /// use the syntactic form of the initializer list.
3696 /// After semantic analysis, the initializer list will represent the
3697 /// semantic form of the initializer, where the initializations of all
3698 /// subobjects are made explicit with nested InitListExpr nodes and
3699 /// C99 designators have been eliminated by placing the designated
3700 /// initializations into the subobject they initialize. Additionally,
3701 /// any "holes" in the initialization, where no initializer has been
3702 /// specified for a particular subobject, will be replaced with
3703 /// implicitly-generated ImplicitValueInitExpr expressions that
3704 /// value-initialize the subobjects. Note, however, that the
3705 /// initializer lists may still have fewer initializers than there are
3706 /// elements to initialize within the object.
3708 /// After semantic analysis has completed, given an initializer list,
3709 /// method isSemanticForm() returns true if and only if this is the
3710 /// semantic form of the initializer list (note: the same AST node
3711 /// may at the same time be the syntactic form).
3712 /// Given the semantic form of the initializer list, one can retrieve
3713 /// the syntactic form of that initializer list (when different)
3714 /// using method getSyntacticForm(); the method returns null if applied
3715 /// to a initializer list which is already in syntactic form.
3716 /// Similarly, given the syntactic form (i.e., an initializer list such
3717 /// that isSemanticForm() returns false), one can retrieve the semantic
3718 /// form using method getSemanticForm().
3719 /// Since many initializer lists have the same syntactic and semantic forms,
3720 /// getSyntacticForm() may return NULL, indicating that the current
3721 /// semantic initializer list also serves as its syntactic form.
3722 class InitListExpr : public Expr {
3723 // FIXME: Eliminate this vector in favor of ASTContext allocation
3724 typedef ASTVector<Stmt *> InitExprsTy;
3725 InitExprsTy InitExprs;
3726 SourceLocation LBraceLoc, RBraceLoc;
3728 /// The alternative form of the initializer list (if it exists).
3729 /// The int part of the pair stores whether this initializer list is
3730 /// in semantic form. If not null, the pointer points to:
3731 /// - the syntactic form, if this is in semantic form;
3732 /// - the semantic form, if this is in syntactic form.
3733 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3736 /// If this initializer list initializes an array with more elements than
3737 /// there are initializers in the list, specifies an expression to be used
3738 /// for value initialization of the rest of the elements.
3740 /// If this initializer list initializes a union, specifies which
3741 /// field within the union will be initialized.
3742 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3745 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3746 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3748 /// \brief Build an empty initializer list.
3749 explicit InitListExpr(EmptyShell Empty)
3750 : Expr(InitListExprClass, Empty) { }
3752 unsigned getNumInits() const { return InitExprs.size(); }
3754 /// \brief Retrieve the set of initializers.
3755 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3757 ArrayRef<Expr *> inits() {
3758 return llvm::makeArrayRef(getInits(), getNumInits());
3761 const Expr *getInit(unsigned Init) const {
3762 assert(Init < getNumInits() && "Initializer access out of range!");
3763 return cast_or_null<Expr>(InitExprs[Init]);
3766 Expr *getInit(unsigned Init) {
3767 assert(Init < getNumInits() && "Initializer access out of range!");
3768 return cast_or_null<Expr>(InitExprs[Init]);
3771 void setInit(unsigned Init, Expr *expr) {
3772 assert(Init < getNumInits() && "Initializer access out of range!");
3773 InitExprs[Init] = expr;
3776 ExprBits.TypeDependent |= expr->isTypeDependent();
3777 ExprBits.ValueDependent |= expr->isValueDependent();
3778 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
3779 ExprBits.ContainsUnexpandedParameterPack |=
3780 expr->containsUnexpandedParameterPack();
3784 /// \brief Reserve space for some number of initializers.
3785 void reserveInits(const ASTContext &C, unsigned NumInits);
3787 /// @brief Specify the number of initializers
3789 /// If there are more than @p NumInits initializers, the remaining
3790 /// initializers will be destroyed. If there are fewer than @p
3791 /// NumInits initializers, NULL expressions will be added for the
3792 /// unknown initializers.
3793 void resizeInits(const ASTContext &Context, unsigned NumInits);
3795 /// @brief Updates the initializer at index @p Init with the new
3796 /// expression @p expr, and returns the old expression at that
3799 /// When @p Init is out of range for this initializer list, the
3800 /// initializer list will be extended with NULL expressions to
3801 /// accommodate the new entry.
3802 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
3804 /// \brief If this initializer list initializes an array with more elements
3805 /// than there are initializers in the list, specifies an expression to be
3806 /// used for value initialization of the rest of the elements.
3807 Expr *getArrayFiller() {
3808 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
3810 const Expr *getArrayFiller() const {
3811 return const_cast<InitListExpr *>(this)->getArrayFiller();
3813 void setArrayFiller(Expr *filler);
3815 /// \brief Return true if this is an array initializer and its array "filler"
3817 bool hasArrayFiller() const { return getArrayFiller(); }
3819 /// \brief If this initializes a union, specifies which field in the
3820 /// union to initialize.
3822 /// Typically, this field is the first named field within the
3823 /// union. However, a designated initializer can specify the
3824 /// initialization of a different field within the union.
3825 FieldDecl *getInitializedFieldInUnion() {
3826 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
3828 const FieldDecl *getInitializedFieldInUnion() const {
3829 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
3831 void setInitializedFieldInUnion(FieldDecl *FD) {
3832 assert((FD == nullptr
3833 || getInitializedFieldInUnion() == nullptr
3834 || getInitializedFieldInUnion() == FD)
3835 && "Only one field of a union may be initialized at a time!");
3836 ArrayFillerOrUnionFieldInit = FD;
3839 // Explicit InitListExpr's originate from source code (and have valid source
3840 // locations). Implicit InitListExpr's are created by the semantic analyzer.
3842 return LBraceLoc.isValid() && RBraceLoc.isValid();
3845 // Is this an initializer for an array of characters, initialized by a string
3846 // literal or an @encode?
3847 bool isStringLiteralInit() const;
3849 SourceLocation getLBraceLoc() const { return LBraceLoc; }
3850 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
3851 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3852 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
3854 bool isSemanticForm() const { return AltForm.getInt(); }
3855 InitListExpr *getSemanticForm() const {
3856 return isSemanticForm() ? nullptr : AltForm.getPointer();
3858 InitListExpr *getSyntacticForm() const {
3859 return isSemanticForm() ? AltForm.getPointer() : nullptr;
3862 void setSyntacticForm(InitListExpr *Init) {
3863 AltForm.setPointer(Init);
3864 AltForm.setInt(true);
3865 Init->AltForm.setPointer(this);
3866 Init->AltForm.setInt(false);
3869 bool hadArrayRangeDesignator() const {
3870 return InitListExprBits.HadArrayRangeDesignator != 0;
3872 void sawArrayRangeDesignator(bool ARD = true) {
3873 InitListExprBits.HadArrayRangeDesignator = ARD;
3876 SourceLocation getLocStart() const LLVM_READONLY;
3877 SourceLocation getLocEnd() const LLVM_READONLY;
3879 static bool classof(const Stmt *T) {
3880 return T->getStmtClass() == InitListExprClass;
3884 child_range children() {
3885 // FIXME: This does not include the array filler expression.
3886 if (InitExprs.empty())
3887 return child_range(child_iterator(), child_iterator());
3888 return child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
3891 typedef InitExprsTy::iterator iterator;
3892 typedef InitExprsTy::const_iterator const_iterator;
3893 typedef InitExprsTy::reverse_iterator reverse_iterator;
3894 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
3896 iterator begin() { return InitExprs.begin(); }
3897 const_iterator begin() const { return InitExprs.begin(); }
3898 iterator end() { return InitExprs.end(); }
3899 const_iterator end() const { return InitExprs.end(); }
3900 reverse_iterator rbegin() { return InitExprs.rbegin(); }
3901 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
3902 reverse_iterator rend() { return InitExprs.rend(); }
3903 const_reverse_iterator rend() const { return InitExprs.rend(); }
3905 friend class ASTStmtReader;
3906 friend class ASTStmtWriter;
3909 /// @brief Represents a C99 designated initializer expression.
3911 /// A designated initializer expression (C99 6.7.8) contains one or
3912 /// more designators (which can be field designators, array
3913 /// designators, or GNU array-range designators) followed by an
3914 /// expression that initializes the field or element(s) that the
3915 /// designators refer to. For example, given:
3922 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
3925 /// The InitListExpr contains three DesignatedInitExprs, the first of
3926 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
3927 /// designators, one array designator for @c [2] followed by one field
3928 /// designator for @c .y. The initialization expression will be 1.0.
3929 class DesignatedInitExpr : public Expr {
3931 /// \brief Forward declaration of the Designator class.
3935 /// The location of the '=' or ':' prior to the actual initializer
3937 SourceLocation EqualOrColonLoc;
3939 /// Whether this designated initializer used the GNU deprecated
3940 /// syntax rather than the C99 '=' syntax.
3943 /// The number of designators in this initializer expression.
3944 unsigned NumDesignators : 15;
3946 /// The number of subexpressions of this initializer expression,
3947 /// which contains both the initializer and any additional
3948 /// expressions used by array and array-range designators.
3949 unsigned NumSubExprs : 16;
3951 /// \brief The designators in this designated initialization
3953 Designator *Designators;
3956 DesignatedInitExpr(const ASTContext &C, QualType Ty, unsigned NumDesignators,
3957 const Designator *Designators,
3958 SourceLocation EqualOrColonLoc, bool GNUSyntax,
3959 ArrayRef<Expr*> IndexExprs, Expr *Init);
3961 explicit DesignatedInitExpr(unsigned NumSubExprs)
3962 : Expr(DesignatedInitExprClass, EmptyShell()),
3963 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
3966 /// A field designator, e.g., ".x".
3967 struct FieldDesignator {
3968 /// Refers to the field that is being initialized. The low bit
3969 /// of this field determines whether this is actually a pointer
3970 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
3971 /// initially constructed, a field designator will store an
3972 /// IdentifierInfo*. After semantic analysis has resolved that
3973 /// name, the field designator will instead store a FieldDecl*.
3974 uintptr_t NameOrField;
3976 /// The location of the '.' in the designated initializer.
3979 /// The location of the field name in the designated initializer.
3983 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
3984 struct ArrayOrRangeDesignator {
3985 /// Location of the first index expression within the designated
3986 /// initializer expression's list of subexpressions.
3988 /// The location of the '[' starting the array range designator.
3989 unsigned LBracketLoc;
3990 /// The location of the ellipsis separating the start and end
3991 /// indices. Only valid for GNU array-range designators.
3992 unsigned EllipsisLoc;
3993 /// The location of the ']' terminating the array range designator.
3994 unsigned RBracketLoc;
3997 /// @brief Represents a single C99 designator.
3999 /// @todo This class is infuriatingly similar to clang::Designator,
4000 /// but minor differences (storing indices vs. storing pointers)
4001 /// keep us from reusing it. Try harder, later, to rectify these
4004 /// @brief The kind of designator this describes.
4008 ArrayRangeDesignator
4012 /// A field designator, e.g., ".x".
4013 struct FieldDesignator Field;
4014 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4015 struct ArrayOrRangeDesignator ArrayOrRange;
4017 friend class DesignatedInitExpr;
4022 /// @brief Initializes a field designator.
4023 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4024 SourceLocation FieldLoc)
4025 : Kind(FieldDesignator) {
4026 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4027 Field.DotLoc = DotLoc.getRawEncoding();
4028 Field.FieldLoc = FieldLoc.getRawEncoding();
4031 /// @brief Initializes an array designator.
4032 Designator(unsigned Index, SourceLocation LBracketLoc,
4033 SourceLocation RBracketLoc)
4034 : Kind(ArrayDesignator) {
4035 ArrayOrRange.Index = Index;
4036 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4037 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4038 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4041 /// @brief Initializes a GNU array-range designator.
4042 Designator(unsigned Index, SourceLocation LBracketLoc,
4043 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4044 : Kind(ArrayRangeDesignator) {
4045 ArrayOrRange.Index = Index;
4046 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4047 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4048 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4051 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4052 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4053 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4055 IdentifierInfo *getFieldName() const;
4057 FieldDecl *getField() const {
4058 assert(Kind == FieldDesignator && "Only valid on a field designator");
4059 if (Field.NameOrField & 0x01)
4062 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4065 void setField(FieldDecl *FD) {
4066 assert(Kind == FieldDesignator && "Only valid on a field designator");
4067 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4070 SourceLocation getDotLoc() const {
4071 assert(Kind == FieldDesignator && "Only valid on a field designator");
4072 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4075 SourceLocation getFieldLoc() const {
4076 assert(Kind == FieldDesignator && "Only valid on a field designator");
4077 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4080 SourceLocation getLBracketLoc() const {
4081 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4082 "Only valid on an array or array-range designator");
4083 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4086 SourceLocation getRBracketLoc() const {
4087 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4088 "Only valid on an array or array-range designator");
4089 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4092 SourceLocation getEllipsisLoc() const {
4093 assert(Kind == ArrayRangeDesignator &&
4094 "Only valid on an array-range designator");
4095 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4098 unsigned getFirstExprIndex() const {
4099 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4100 "Only valid on an array or array-range designator");
4101 return ArrayOrRange.Index;
4104 SourceLocation getLocStart() const LLVM_READONLY {
4105 if (Kind == FieldDesignator)
4106 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4108 return getLBracketLoc();
4110 SourceLocation getLocEnd() const LLVM_READONLY {
4111 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4113 SourceRange getSourceRange() const LLVM_READONLY {
4114 return SourceRange(getLocStart(), getLocEnd());
4118 static DesignatedInitExpr *Create(const ASTContext &C,
4119 Designator *Designators,
4120 unsigned NumDesignators,
4121 ArrayRef<Expr*> IndexExprs,
4122 SourceLocation EqualOrColonLoc,
4123 bool GNUSyntax, Expr *Init);
4125 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4126 unsigned NumIndexExprs);
4128 /// @brief Returns the number of designators in this initializer.
4129 unsigned size() const { return NumDesignators; }
4131 // Iterator access to the designators.
4132 typedef Designator *designators_iterator;
4133 designators_iterator designators_begin() { return Designators; }
4134 designators_iterator designators_end() {
4135 return Designators + NumDesignators;
4138 typedef const Designator *const_designators_iterator;
4139 const_designators_iterator designators_begin() const { return Designators; }
4140 const_designators_iterator designators_end() const {
4141 return Designators + NumDesignators;
4144 typedef llvm::iterator_range<designators_iterator> designators_range;
4145 designators_range designators() {
4146 return designators_range(designators_begin(), designators_end());
4149 typedef llvm::iterator_range<const_designators_iterator>
4150 designators_const_range;
4151 designators_const_range designators() const {
4152 return designators_const_range(designators_begin(), designators_end());
4155 typedef std::reverse_iterator<designators_iterator>
4156 reverse_designators_iterator;
4157 reverse_designators_iterator designators_rbegin() {
4158 return reverse_designators_iterator(designators_end());
4160 reverse_designators_iterator designators_rend() {
4161 return reverse_designators_iterator(designators_begin());
4164 typedef std::reverse_iterator<const_designators_iterator>
4165 const_reverse_designators_iterator;
4166 const_reverse_designators_iterator designators_rbegin() const {
4167 return const_reverse_designators_iterator(designators_end());
4169 const_reverse_designators_iterator designators_rend() const {
4170 return const_reverse_designators_iterator(designators_begin());
4173 Designator *getDesignator(unsigned Idx) { return &designators_begin()[Idx]; }
4175 void setDesignators(const ASTContext &C, const Designator *Desigs,
4176 unsigned NumDesigs);
4178 Expr *getArrayIndex(const Designator &D) const;
4179 Expr *getArrayRangeStart(const Designator &D) const;
4180 Expr *getArrayRangeEnd(const Designator &D) const;
4182 /// @brief Retrieve the location of the '=' that precedes the
4183 /// initializer value itself, if present.
4184 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4185 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4187 /// @brief Determines whether this designated initializer used the
4188 /// deprecated GNU syntax for designated initializers.
4189 bool usesGNUSyntax() const { return GNUSyntax; }
4190 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4192 /// @brief Retrieve the initializer value.
4193 Expr *getInit() const {
4194 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4197 void setInit(Expr *init) {
4198 *child_begin() = init;
4201 /// \brief Retrieve the total number of subexpressions in this
4202 /// designated initializer expression, including the actual
4203 /// initialized value and any expressions that occur within array
4204 /// and array-range designators.
4205 unsigned getNumSubExprs() const { return NumSubExprs; }
4207 Expr *getSubExpr(unsigned Idx) const {
4208 assert(Idx < NumSubExprs && "Subscript out of range");
4209 return cast<Expr>(reinterpret_cast<Stmt *const *>(this + 1)[Idx]);
4212 void setSubExpr(unsigned Idx, Expr *E) {
4213 assert(Idx < NumSubExprs && "Subscript out of range");
4214 reinterpret_cast<Stmt **>(this + 1)[Idx] = E;
4217 /// \brief Replaces the designator at index @p Idx with the series
4218 /// of designators in [First, Last).
4219 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4220 const Designator *First, const Designator *Last);
4222 SourceRange getDesignatorsSourceRange() const;
4224 SourceLocation getLocStart() const LLVM_READONLY;
4225 SourceLocation getLocEnd() const LLVM_READONLY;
4227 static bool classof(const Stmt *T) {
4228 return T->getStmtClass() == DesignatedInitExprClass;
4232 child_range children() {
4233 Stmt **begin = reinterpret_cast<Stmt**>(this + 1);
4234 return child_range(begin, begin + NumSubExprs);
4238 /// \brief Represents a place-holder for an object not to be initialized by
4241 /// This only makes sense when it appears as part of an updater of a
4242 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4243 /// initializes a big object, and the NoInitExpr's mark the spots within the
4244 /// big object not to be overwritten by the updater.
4246 /// \see DesignatedInitUpdateExpr
4247 class NoInitExpr : public Expr {
4249 explicit NoInitExpr(QualType ty)
4250 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4251 false, false, ty->isInstantiationDependentType(), false) { }
4253 explicit NoInitExpr(EmptyShell Empty)
4254 : Expr(NoInitExprClass, Empty) { }
4256 static bool classof(const Stmt *T) {
4257 return T->getStmtClass() == NoInitExprClass;
4260 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4261 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4264 child_range children() {
4265 return child_range(child_iterator(), child_iterator());
4270 // struct Q { int a, b, c; };
4273 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4276 // We will have an InitListExpr for a, with type A, and then a
4277 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4278 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4280 class DesignatedInitUpdateExpr : public Expr {
4281 // BaseAndUpdaterExprs[0] is the base expression;
4282 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4283 Stmt *BaseAndUpdaterExprs[2];
4286 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4287 Expr *baseExprs, SourceLocation rBraceLoc);
4289 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4290 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4292 SourceLocation getLocStart() const LLVM_READONLY;
4293 SourceLocation getLocEnd() const LLVM_READONLY;
4295 static bool classof(const Stmt *T) {
4296 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4299 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4300 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4302 InitListExpr *getUpdater() const {
4303 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4305 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4308 // children = the base and the updater
4309 child_range children() {
4310 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4314 /// \brief Represents an implicitly-generated value initialization of
4315 /// an object of a given type.
4317 /// Implicit value initializations occur within semantic initializer
4318 /// list expressions (InitListExpr) as placeholders for subobject
4319 /// initializations not explicitly specified by the user.
4321 /// \see InitListExpr
4322 class ImplicitValueInitExpr : public Expr {
4324 explicit ImplicitValueInitExpr(QualType ty)
4325 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4326 false, false, ty->isInstantiationDependentType(), false) { }
4328 /// \brief Construct an empty implicit value initialization.
4329 explicit ImplicitValueInitExpr(EmptyShell Empty)
4330 : Expr(ImplicitValueInitExprClass, Empty) { }
4332 static bool classof(const Stmt *T) {
4333 return T->getStmtClass() == ImplicitValueInitExprClass;
4336 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4337 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4340 child_range children() {
4341 return child_range(child_iterator(), child_iterator());
4345 class ParenListExpr : public Expr {
4348 SourceLocation LParenLoc, RParenLoc;
4351 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4352 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4354 /// \brief Build an empty paren list.
4355 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4357 unsigned getNumExprs() const { return NumExprs; }
4359 const Expr* getExpr(unsigned Init) const {
4360 assert(Init < getNumExprs() && "Initializer access out of range!");
4361 return cast_or_null<Expr>(Exprs[Init]);
4364 Expr* getExpr(unsigned Init) {
4365 assert(Init < getNumExprs() && "Initializer access out of range!");
4366 return cast_or_null<Expr>(Exprs[Init]);
4369 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4371 ArrayRef<Expr *> exprs() {
4372 return llvm::makeArrayRef(getExprs(), getNumExprs());
4375 SourceLocation getLParenLoc() const { return LParenLoc; }
4376 SourceLocation getRParenLoc() const { return RParenLoc; }
4378 SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4379 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4381 static bool classof(const Stmt *T) {
4382 return T->getStmtClass() == ParenListExprClass;
4386 child_range children() {
4387 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4390 friend class ASTStmtReader;
4391 friend class ASTStmtWriter;
4394 /// \brief Represents a C11 generic selection.
4396 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4397 /// expression, followed by one or more generic associations. Each generic
4398 /// association specifies a type name and an expression, or "default" and an
4399 /// expression (in which case it is known as a default generic association).
4400 /// The type and value of the generic selection are identical to those of its
4401 /// result expression, which is defined as the expression in the generic
4402 /// association with a type name that is compatible with the type of the
4403 /// controlling expression, or the expression in the default generic association
4404 /// if no types are compatible. For example:
4407 /// _Generic(X, double: 1, float: 2, default: 3)
4410 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4411 /// or 3 if "hello".
4413 /// As an extension, generic selections are allowed in C++, where the following
4414 /// additional semantics apply:
4416 /// Any generic selection whose controlling expression is type-dependent or
4417 /// which names a dependent type in its association list is result-dependent,
4418 /// which means that the choice of result expression is dependent.
4419 /// Result-dependent generic associations are both type- and value-dependent.
4420 class GenericSelectionExpr : public Expr {
4421 enum { CONTROLLING, END_EXPR };
4422 TypeSourceInfo **AssocTypes;
4424 unsigned NumAssocs, ResultIndex;
4425 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4428 GenericSelectionExpr(const ASTContext &Context,
4429 SourceLocation GenericLoc, Expr *ControllingExpr,
4430 ArrayRef<TypeSourceInfo*> AssocTypes,
4431 ArrayRef<Expr*> AssocExprs,
4432 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4433 bool ContainsUnexpandedParameterPack,
4434 unsigned ResultIndex);
4436 /// This constructor is used in the result-dependent case.
4437 GenericSelectionExpr(const ASTContext &Context,
4438 SourceLocation GenericLoc, Expr *ControllingExpr,
4439 ArrayRef<TypeSourceInfo*> AssocTypes,
4440 ArrayRef<Expr*> AssocExprs,
4441 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4442 bool ContainsUnexpandedParameterPack);
4444 explicit GenericSelectionExpr(EmptyShell Empty)
4445 : Expr(GenericSelectionExprClass, Empty) { }
4447 unsigned getNumAssocs() const { return NumAssocs; }
4449 SourceLocation getGenericLoc() const { return GenericLoc; }
4450 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4451 SourceLocation getRParenLoc() const { return RParenLoc; }
4453 const Expr *getAssocExpr(unsigned i) const {
4454 return cast<Expr>(SubExprs[END_EXPR+i]);
4456 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4458 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4459 return AssocTypes[i];
4461 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4463 QualType getAssocType(unsigned i) const {
4464 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4465 return TS->getType();
4470 const Expr *getControllingExpr() const {
4471 return cast<Expr>(SubExprs[CONTROLLING]);
4473 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4475 /// Whether this generic selection is result-dependent.
4476 bool isResultDependent() const { return ResultIndex == -1U; }
4478 /// The zero-based index of the result expression's generic association in
4479 /// the generic selection's association list. Defined only if the
4480 /// generic selection is not result-dependent.
4481 unsigned getResultIndex() const {
4482 assert(!isResultDependent() && "Generic selection is result-dependent");
4486 /// The generic selection's result expression. Defined only if the
4487 /// generic selection is not result-dependent.
4488 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4489 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4491 SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4492 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4494 static bool classof(const Stmt *T) {
4495 return T->getStmtClass() == GenericSelectionExprClass;
4498 child_range children() {
4499 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4502 friend class ASTStmtReader;
4505 //===----------------------------------------------------------------------===//
4507 //===----------------------------------------------------------------------===//
4509 /// ExtVectorElementExpr - This represents access to specific elements of a
4510 /// vector, and may occur on the left hand side or right hand side. For example
4511 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4513 /// Note that the base may have either vector or pointer to vector type, just
4514 /// like a struct field reference.
4516 class ExtVectorElementExpr : public Expr {
4518 IdentifierInfo *Accessor;
4519 SourceLocation AccessorLoc;
4521 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4522 IdentifierInfo &accessor, SourceLocation loc)
4523 : Expr(ExtVectorElementExprClass, ty, VK,
4524 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4525 base->isTypeDependent(), base->isValueDependent(),
4526 base->isInstantiationDependent(),
4527 base->containsUnexpandedParameterPack()),
4528 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4530 /// \brief Build an empty vector element expression.
4531 explicit ExtVectorElementExpr(EmptyShell Empty)
4532 : Expr(ExtVectorElementExprClass, Empty) { }
4534 const Expr *getBase() const { return cast<Expr>(Base); }
4535 Expr *getBase() { return cast<Expr>(Base); }
4536 void setBase(Expr *E) { Base = E; }
4538 IdentifierInfo &getAccessor() const { return *Accessor; }
4539 void setAccessor(IdentifierInfo *II) { Accessor = II; }
4541 SourceLocation getAccessorLoc() const { return AccessorLoc; }
4542 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4544 /// getNumElements - Get the number of components being selected.
4545 unsigned getNumElements() const;
4547 /// containsDuplicateElements - Return true if any element access is
4549 bool containsDuplicateElements() const;
4551 /// getEncodedElementAccess - Encode the elements accessed into an llvm
4552 /// aggregate Constant of ConstantInt(s).
4553 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4555 SourceLocation getLocStart() const LLVM_READONLY {
4556 return getBase()->getLocStart();
4558 SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4560 /// isArrow - Return true if the base expression is a pointer to vector,
4561 /// return false if the base expression is a vector.
4562 bool isArrow() const;
4564 static bool classof(const Stmt *T) {
4565 return T->getStmtClass() == ExtVectorElementExprClass;
4569 child_range children() { return child_range(&Base, &Base+1); }
4572 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4573 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4574 class BlockExpr : public Expr {
4576 BlockDecl *TheBlock;
4578 BlockExpr(BlockDecl *BD, QualType ty)
4579 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4580 ty->isDependentType(), ty->isDependentType(),
4581 ty->isInstantiationDependentType() || BD->isDependentContext(),
4585 /// \brief Build an empty block expression.
4586 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4588 const BlockDecl *getBlockDecl() const { return TheBlock; }
4589 BlockDecl *getBlockDecl() { return TheBlock; }
4590 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4592 // Convenience functions for probing the underlying BlockDecl.
4593 SourceLocation getCaretLocation() const;
4594 const Stmt *getBody() const;
4597 SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4598 SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4600 /// getFunctionType - Return the underlying function type for this block.
4601 const FunctionProtoType *getFunctionType() const;
4603 static bool classof(const Stmt *T) {
4604 return T->getStmtClass() == BlockExprClass;
4608 child_range children() {
4609 return child_range(child_iterator(), child_iterator());
4613 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4614 /// This AST node provides support for reinterpreting a type to another
4615 /// type of the same size.
4616 class AsTypeExpr : public Expr {
4619 SourceLocation BuiltinLoc, RParenLoc;
4621 friend class ASTReader;
4622 friend class ASTStmtReader;
4623 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4626 AsTypeExpr(Expr* SrcExpr, QualType DstType,
4627 ExprValueKind VK, ExprObjectKind OK,
4628 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4629 : Expr(AsTypeExprClass, DstType, VK, OK,
4630 DstType->isDependentType(),
4631 DstType->isDependentType() || SrcExpr->isValueDependent(),
4632 (DstType->isInstantiationDependentType() ||
4633 SrcExpr->isInstantiationDependent()),
4634 (DstType->containsUnexpandedParameterPack() ||
4635 SrcExpr->containsUnexpandedParameterPack())),
4636 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
4638 /// getSrcExpr - Return the Expr to be converted.
4639 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4641 /// getBuiltinLoc - Return the location of the __builtin_astype token.
4642 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4644 /// getRParenLoc - Return the location of final right parenthesis.
4645 SourceLocation getRParenLoc() const { return RParenLoc; }
4647 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4648 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4650 static bool classof(const Stmt *T) {
4651 return T->getStmtClass() == AsTypeExprClass;
4655 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4658 /// PseudoObjectExpr - An expression which accesses a pseudo-object
4659 /// l-value. A pseudo-object is an abstract object, accesses to which
4660 /// are translated to calls. The pseudo-object expression has a
4661 /// syntactic form, which shows how the expression was actually
4662 /// written in the source code, and a semantic form, which is a series
4663 /// of expressions to be executed in order which detail how the
4664 /// operation is actually evaluated. Optionally, one of the semantic
4665 /// forms may also provide a result value for the expression.
4667 /// If any of the semantic-form expressions is an OpaqueValueExpr,
4668 /// that OVE is required to have a source expression, and it is bound
4669 /// to the result of that source expression. Such OVEs may appear
4670 /// only in subsequent semantic-form expressions and as
4671 /// sub-expressions of the syntactic form.
4673 /// PseudoObjectExpr should be used only when an operation can be
4674 /// usefully described in terms of fairly simple rewrite rules on
4675 /// objects and functions that are meant to be used by end-developers.
4676 /// For example, under the Itanium ABI, dynamic casts are implemented
4677 /// as a call to a runtime function called __dynamic_cast; using this
4678 /// class to describe that would be inappropriate because that call is
4679 /// not really part of the user-visible semantics, and instead the
4680 /// cast is properly reflected in the AST and IR-generation has been
4681 /// taught to generate the call as necessary. In contrast, an
4682 /// Objective-C property access is semantically defined to be
4683 /// equivalent to a particular message send, and this is very much
4684 /// part of the user model. The name of this class encourages this
4685 /// modelling design.
4686 class PseudoObjectExpr : public Expr {
4687 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
4688 // Always at least two, because the first sub-expression is the
4691 // PseudoObjectExprBits.ResultIndex - The index of the
4692 // sub-expression holding the result. 0 means the result is void,
4693 // which is unambiguous because it's the index of the syntactic
4694 // form. Note that this is therefore 1 higher than the value passed
4695 // in to Create, which is an index within the semantic forms.
4696 // Note also that ASTStmtWriter assumes this encoding.
4698 Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
4699 const Expr * const *getSubExprsBuffer() const {
4700 return reinterpret_cast<const Expr * const *>(this + 1);
4703 friend class ASTStmtReader;
4705 PseudoObjectExpr(QualType type, ExprValueKind VK,
4706 Expr *syntactic, ArrayRef<Expr*> semantic,
4707 unsigned resultIndex);
4709 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
4711 unsigned getNumSubExprs() const {
4712 return PseudoObjectExprBits.NumSubExprs;
4716 /// NoResult - A value for the result index indicating that there is
4717 /// no semantic result.
4718 enum : unsigned { NoResult = ~0U };
4720 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
4721 ArrayRef<Expr*> semantic,
4722 unsigned resultIndex);
4724 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
4725 unsigned numSemanticExprs);
4727 /// Return the syntactic form of this expression, i.e. the
4728 /// expression it actually looks like. Likely to be expressed in
4729 /// terms of OpaqueValueExprs bound in the semantic form.
4730 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
4731 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
4733 /// Return the index of the result-bearing expression into the semantics
4734 /// expressions, or PseudoObjectExpr::NoResult if there is none.
4735 unsigned getResultExprIndex() const {
4736 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
4737 return PseudoObjectExprBits.ResultIndex - 1;
4740 /// Return the result-bearing expression, or null if there is none.
4741 Expr *getResultExpr() {
4742 if (PseudoObjectExprBits.ResultIndex == 0)
4744 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
4746 const Expr *getResultExpr() const {
4747 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
4750 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
4752 typedef Expr * const *semantics_iterator;
4753 typedef const Expr * const *const_semantics_iterator;
4754 semantics_iterator semantics_begin() {
4755 return getSubExprsBuffer() + 1;
4757 const_semantics_iterator semantics_begin() const {
4758 return getSubExprsBuffer() + 1;
4760 semantics_iterator semantics_end() {
4761 return getSubExprsBuffer() + getNumSubExprs();
4763 const_semantics_iterator semantics_end() const {
4764 return getSubExprsBuffer() + getNumSubExprs();
4767 llvm::iterator_range<semantics_iterator> semantics() {
4768 return llvm::make_range(semantics_begin(), semantics_end());
4770 llvm::iterator_range<const_semantics_iterator> semantics() const {
4771 return llvm::make_range(semantics_begin(), semantics_end());
4774 Expr *getSemanticExpr(unsigned index) {
4775 assert(index + 1 < getNumSubExprs());
4776 return getSubExprsBuffer()[index + 1];
4778 const Expr *getSemanticExpr(unsigned index) const {
4779 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
4782 SourceLocation getExprLoc() const LLVM_READONLY {
4783 return getSyntacticForm()->getExprLoc();
4786 SourceLocation getLocStart() const LLVM_READONLY {
4787 return getSyntacticForm()->getLocStart();
4789 SourceLocation getLocEnd() const LLVM_READONLY {
4790 return getSyntacticForm()->getLocEnd();
4793 child_range children() {
4794 Stmt **cs = reinterpret_cast<Stmt**>(getSubExprsBuffer());
4795 return child_range(cs, cs + getNumSubExprs());
4798 static bool classof(const Stmt *T) {
4799 return T->getStmtClass() == PseudoObjectExprClass;
4803 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
4804 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
4805 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
4806 /// All of these instructions take one primary pointer and at least one memory
4808 class AtomicExpr : public Expr {
4811 #define BUILTIN(ID, TYPE, ATTRS)
4812 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
4813 #include "clang/Basic/Builtins.def"
4814 // Avoid trailing comma
4818 // The ABI values for various atomic memory orderings.
4819 enum AtomicOrderingKind {
4820 AO_ABI_memory_order_relaxed = 0,
4821 AO_ABI_memory_order_consume = 1,
4822 AO_ABI_memory_order_acquire = 2,
4823 AO_ABI_memory_order_release = 3,
4824 AO_ABI_memory_order_acq_rel = 4,
4825 AO_ABI_memory_order_seq_cst = 5
4829 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
4830 Stmt* SubExprs[END_EXPR];
4831 unsigned NumSubExprs;
4832 SourceLocation BuiltinLoc, RParenLoc;
4835 friend class ASTStmtReader;
4838 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
4839 AtomicOp op, SourceLocation RP);
4841 /// \brief Determine the number of arguments the specified atomic builtin
4843 static unsigned getNumSubExprs(AtomicOp Op);
4845 /// \brief Build an empty AtomicExpr.
4846 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
4848 Expr *getPtr() const {
4849 return cast<Expr>(SubExprs[PTR]);
4851 Expr *getOrder() const {
4852 return cast<Expr>(SubExprs[ORDER]);
4854 Expr *getVal1() const {
4855 if (Op == AO__c11_atomic_init)
4856 return cast<Expr>(SubExprs[ORDER]);
4857 assert(NumSubExprs > VAL1);
4858 return cast<Expr>(SubExprs[VAL1]);
4860 Expr *getOrderFail() const {
4861 assert(NumSubExprs > ORDER_FAIL);
4862 return cast<Expr>(SubExprs[ORDER_FAIL]);
4864 Expr *getVal2() const {
4865 if (Op == AO__atomic_exchange)
4866 return cast<Expr>(SubExprs[ORDER_FAIL]);
4867 assert(NumSubExprs > VAL2);
4868 return cast<Expr>(SubExprs[VAL2]);
4870 Expr *getWeak() const {
4871 assert(NumSubExprs > WEAK);
4872 return cast<Expr>(SubExprs[WEAK]);
4875 AtomicOp getOp() const { return Op; }
4876 unsigned getNumSubExprs() { return NumSubExprs; }
4878 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4880 bool isVolatile() const {
4881 return getPtr()->getType()->getPointeeType().isVolatileQualified();
4884 bool isCmpXChg() const {
4885 return getOp() == AO__c11_atomic_compare_exchange_strong ||
4886 getOp() == AO__c11_atomic_compare_exchange_weak ||
4887 getOp() == AO__atomic_compare_exchange ||
4888 getOp() == AO__atomic_compare_exchange_n;
4891 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4892 SourceLocation getRParenLoc() const { return RParenLoc; }
4894 SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
4895 SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4897 static bool classof(const Stmt *T) {
4898 return T->getStmtClass() == AtomicExprClass;
4902 child_range children() {
4903 return child_range(SubExprs, SubExprs+NumSubExprs);
4907 /// TypoExpr - Internal placeholder for expressions where typo correction
4908 /// still needs to be performed and/or an error diagnostic emitted.
4909 class TypoExpr : public Expr {
4911 TypoExpr(QualType T)
4912 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
4913 /*isTypeDependent*/ true,
4914 /*isValueDependent*/ true,
4915 /*isInstantiationDependent*/ true,
4916 /*containsUnexpandedParameterPack*/ false) {
4917 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
4920 child_range children() {
4921 return child_range(child_iterator(), child_iterator());
4923 SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4924 SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4926 static bool classof(const Stmt *T) {
4927 return T->getStmtClass() == TypoExprClass;
4931 } // end namespace clang
4933 #endif // LLVM_CLANG_AST_EXPR_H