1 //===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Expr interface and subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_EXPR_H
15 #define LLVM_CLANG_AST_EXPR_H
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/ASTVector.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclAccessPair.h"
21 #include "clang/AST/OperationKinds.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/SyncScope.h"
28 #include "clang/Basic/TypeTraits.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/AtomicOrdering.h"
34 #include "llvm/Support/Compiler.h"
40 class CXXBaseSpecifier;
41 class CXXMemberCallExpr;
42 class CXXOperatorCallExpr;
46 class MaterializeTemporaryExpr;
48 class ObjCPropertyRefExpr;
49 class OpaqueValueExpr;
55 /// A simple array of base specifiers.
56 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
58 /// An adjustment to be made to the temporary created when emitting a
59 /// reference binding, which accesses a particular subobject of that temporary.
60 struct SubobjectAdjustment {
62 DerivedToBaseAdjustment,
64 MemberPointerAdjustment
68 const CastExpr *BasePath;
69 const CXXRecordDecl *DerivedClass;
73 const MemberPointerType *MPT;
78 struct DTB DerivedToBase;
83 SubobjectAdjustment(const CastExpr *BasePath,
84 const CXXRecordDecl *DerivedClass)
85 : Kind(DerivedToBaseAdjustment) {
86 DerivedToBase.BasePath = BasePath;
87 DerivedToBase.DerivedClass = DerivedClass;
90 SubobjectAdjustment(FieldDecl *Field)
91 : Kind(FieldAdjustment) {
95 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
96 : Kind(MemberPointerAdjustment) {
102 /// Expr - This represents one expression. Note that Expr's are subclasses of
103 /// Stmt. This allows an expression to be transparently used any place a Stmt
106 class Expr : public Stmt {
110 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
111 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
114 ExprBits.TypeDependent = TD;
115 ExprBits.ValueDependent = VD;
116 ExprBits.InstantiationDependent = ID;
117 ExprBits.ValueKind = VK;
118 ExprBits.ObjectKind = OK;
119 assert(ExprBits.ObjectKind == OK && "truncated kind");
120 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
124 /// Construct an empty expression.
125 explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
128 QualType getType() const { return TR; }
129 void setType(QualType t) {
130 // In C++, the type of an expression is always adjusted so that it
131 // will not have reference type (C++ [expr]p6). Use
132 // QualType::getNonReferenceType() to retrieve the non-reference
133 // type. Additionally, inspect Expr::isLvalue to determine whether
134 // an expression that is adjusted in this manner should be
135 // considered an lvalue.
136 assert((t.isNull() || !t->isReferenceType()) &&
137 "Expressions can't have reference type");
142 /// isValueDependent - Determines whether this expression is
143 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
144 /// array bound of "Chars" in the following example is
147 /// template<int Size, char (&Chars)[Size]> struct meta_string;
149 bool isValueDependent() const { return ExprBits.ValueDependent; }
151 /// Set whether this expression is value-dependent or not.
152 void setValueDependent(bool VD) {
153 ExprBits.ValueDependent = VD;
156 /// isTypeDependent - Determines whether this expression is
157 /// type-dependent (C++ [temp.dep.expr]), which means that its type
158 /// could change from one template instantiation to the next. For
159 /// example, the expressions "x" and "x + y" are type-dependent in
160 /// the following code, but "y" is not type-dependent:
162 /// template<typename T>
163 /// void add(T x, int y) {
167 bool isTypeDependent() const { return ExprBits.TypeDependent; }
169 /// Set whether this expression is type-dependent or not.
170 void setTypeDependent(bool TD) {
171 ExprBits.TypeDependent = TD;
174 /// Whether this expression is instantiation-dependent, meaning that
175 /// it depends in some way on a template parameter, even if neither its type
176 /// nor (constant) value can change due to the template instantiation.
178 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
179 /// instantiation-dependent (since it involves a template parameter \c T), but
180 /// is neither type- nor value-dependent, since the type of the inner
181 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
182 /// \c sizeof is known.
185 /// template<typename T>
186 /// void f(T x, T y) {
187 /// sizeof(sizeof(T() + T());
191 bool isInstantiationDependent() const {
192 return ExprBits.InstantiationDependent;
195 /// Set whether this expression is instantiation-dependent or not.
196 void setInstantiationDependent(bool ID) {
197 ExprBits.InstantiationDependent = ID;
200 /// Whether this expression contains an unexpanded parameter
201 /// pack (for C++11 variadic templates).
203 /// Given the following function template:
206 /// template<typename F, typename ...Types>
207 /// void forward(const F &f, Types &&...args) {
208 /// f(static_cast<Types&&>(args)...);
212 /// The expressions \c args and \c static_cast<Types&&>(args) both
213 /// contain parameter packs.
214 bool containsUnexpandedParameterPack() const {
215 return ExprBits.ContainsUnexpandedParameterPack;
218 /// Set the bit that describes whether this expression
219 /// contains an unexpanded parameter pack.
220 void setContainsUnexpandedParameterPack(bool PP = true) {
221 ExprBits.ContainsUnexpandedParameterPack = PP;
224 /// getExprLoc - Return the preferred location for the arrow when diagnosing
225 /// a problem with a generic expression.
226 SourceLocation getExprLoc() const LLVM_READONLY;
228 /// isUnusedResultAWarning - Return true if this immediate expression should
229 /// be warned about if the result is unused. If so, fill in expr, location,
230 /// and ranges with expr to warn on and source locations/ranges appropriate
232 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
233 SourceRange &R1, SourceRange &R2,
234 ASTContext &Ctx) const;
236 /// isLValue - True if this expression is an "l-value" according to
237 /// the rules of the current language. C and C++ give somewhat
238 /// different rules for this concept, but in general, the result of
239 /// an l-value expression identifies a specific object whereas the
240 /// result of an r-value expression is a value detached from any
241 /// specific storage.
243 /// C++11 divides the concept of "r-value" into pure r-values
244 /// ("pr-values") and so-called expiring values ("x-values"), which
245 /// identify specific objects that can be safely cannibalized for
246 /// their resources. This is an unfortunate abuse of terminology on
247 /// the part of the C++ committee. In Clang, when we say "r-value",
248 /// we generally mean a pr-value.
249 bool isLValue() const { return getValueKind() == VK_LValue; }
250 bool isRValue() const { return getValueKind() == VK_RValue; }
251 bool isXValue() const { return getValueKind() == VK_XValue; }
252 bool isGLValue() const { return getValueKind() != VK_RValue; }
254 enum LValueClassification {
257 LV_IncompleteVoidType,
258 LV_DuplicateVectorComponents,
259 LV_InvalidExpression,
260 LV_InvalidMessageExpression,
262 LV_SubObjCPropertySetting,
266 /// Reasons why an expression might not be an l-value.
267 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
269 enum isModifiableLvalueResult {
272 MLV_IncompleteVoidType,
273 MLV_DuplicateVectorComponents,
274 MLV_InvalidExpression,
275 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
278 MLV_ConstQualifiedField,
281 MLV_NoSetterProperty,
283 MLV_SubObjCPropertySetting,
284 MLV_InvalidMessageExpression,
288 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289 /// does not have an incomplete type, does not have a const-qualified type,
290 /// and if it is a structure or union, does not have any member (including,
291 /// recursively, any member or element of all contained aggregates or unions)
292 /// with a const-qualified type.
294 /// \param Loc [in,out] - A source location which *may* be filled
295 /// in with the location of the expression making this a
296 /// non-modifiable lvalue, if specified.
297 isModifiableLvalueResult
298 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
300 /// The return type of classify(). Represents the C++11 expression
302 class Classification {
304 /// The various classification results. Most of these mean prvalue.
308 CL_Function, // Functions cannot be lvalues in C.
309 CL_Void, // Void cannot be an lvalue in C.
310 CL_AddressableVoid, // Void expression whose address can be taken in C.
311 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312 CL_MemberFunction, // An expression referring to a member function
313 CL_SubObjCPropertySetting,
314 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315 CL_ArrayTemporary, // A temporary of array type.
316 CL_ObjCMessageRValue, // ObjC message is an rvalue
317 CL_PRValue // A prvalue for any other reason, of any other type
319 /// The results of modification testing.
320 enum ModifiableType {
321 CM_Untested, // testModifiable was false.
323 CM_RValue, // Not modifiable because it's an rvalue
324 CM_Function, // Not modifiable because it's a function; C++ only
325 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
328 CM_ConstQualifiedField,
338 unsigned short Modifiable;
340 explicit Classification(Kinds k, ModifiableType m)
341 : Kind(k), Modifiable(m)
347 Kinds getKind() const { return static_cast<Kinds>(Kind); }
348 ModifiableType getModifiable() const {
349 assert(Modifiable != CM_Untested && "Did not test for modifiability.");
350 return static_cast<ModifiableType>(Modifiable);
352 bool isLValue() const { return Kind == CL_LValue; }
353 bool isXValue() const { return Kind == CL_XValue; }
354 bool isGLValue() const { return Kind <= CL_XValue; }
355 bool isPRValue() const { return Kind >= CL_Function; }
356 bool isRValue() const { return Kind >= CL_XValue; }
357 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
359 /// Create a simple, modifiably lvalue
360 static Classification makeSimpleLValue() {
361 return Classification(CL_LValue, CM_Modifiable);
365 /// Classify - Classify this expression according to the C++11
366 /// expression taxonomy.
368 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
369 /// old lvalue vs rvalue. This function determines the type of expression this
370 /// is. There are three expression types:
371 /// - lvalues are classical lvalues as in C++03.
372 /// - prvalues are equivalent to rvalues in C++03.
373 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
374 /// function returning an rvalue reference.
375 /// lvalues and xvalues are collectively referred to as glvalues, while
376 /// prvalues and xvalues together form rvalues.
377 Classification Classify(ASTContext &Ctx) const {
378 return ClassifyImpl(Ctx, nullptr);
381 /// ClassifyModifiable - Classify this expression according to the
382 /// C++11 expression taxonomy, and see if it is valid on the left side
383 /// of an assignment.
385 /// This function extends classify in that it also tests whether the
386 /// expression is modifiable (C99 6.3.2.1p1).
387 /// \param Loc A source location that might be filled with a relevant location
388 /// if the expression is not modifiable.
389 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
390 return ClassifyImpl(Ctx, &Loc);
393 /// getValueKindForType - Given a formal return or parameter type,
394 /// give its value kind.
395 static ExprValueKind getValueKindForType(QualType T) {
396 if (const ReferenceType *RT = T->getAs<ReferenceType>())
397 return (isa<LValueReferenceType>(RT)
399 : (RT->getPointeeType()->isFunctionType()
400 ? VK_LValue : VK_XValue));
404 /// getValueKind - The value kind that this expression produces.
405 ExprValueKind getValueKind() const {
406 return static_cast<ExprValueKind>(ExprBits.ValueKind);
409 /// getObjectKind - The object kind that this expression produces.
410 /// Object kinds are meaningful only for expressions that yield an
411 /// l-value or x-value.
412 ExprObjectKind getObjectKind() const {
413 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
416 bool isOrdinaryOrBitFieldObject() const {
417 ExprObjectKind OK = getObjectKind();
418 return (OK == OK_Ordinary || OK == OK_BitField);
421 /// setValueKind - Set the value kind produced by this expression.
422 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
424 /// setObjectKind - Set the object kind produced by this expression.
425 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
428 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
432 /// Returns true if this expression is a gl-value that
433 /// potentially refers to a bit-field.
435 /// In C++, whether a gl-value refers to a bitfield is essentially
436 /// an aspect of the value-kind type system.
437 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
439 /// If this expression refers to a bit-field, retrieve the
440 /// declaration of that bit-field.
442 /// Note that this returns a non-null pointer in subtly different
443 /// places than refersToBitField returns true. In particular, this can
444 /// return a non-null pointer even for r-values loaded from
445 /// bit-fields, but it will return null for a conditional bit-field.
446 FieldDecl *getSourceBitField();
448 const FieldDecl *getSourceBitField() const {
449 return const_cast<Expr*>(this)->getSourceBitField();
452 Decl *getReferencedDeclOfCallee();
453 const Decl *getReferencedDeclOfCallee() const {
454 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
457 /// If this expression is an l-value for an Objective C
458 /// property, find the underlying property reference expression.
459 const ObjCPropertyRefExpr *getObjCProperty() const;
461 /// Check if this expression is the ObjC 'self' implicit parameter.
462 bool isObjCSelfExpr() const;
464 /// Returns whether this expression refers to a vector element.
465 bool refersToVectorElement() const;
467 /// Returns whether this expression refers to a global register
469 bool refersToGlobalRegisterVar() const;
471 /// Returns whether this expression has a placeholder type.
472 bool hasPlaceholderType() const {
473 return getType()->isPlaceholderType();
476 /// Returns whether this expression has a specific placeholder type.
477 bool hasPlaceholderType(BuiltinType::Kind K) const {
478 assert(BuiltinType::isPlaceholderTypeKind(K));
479 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
480 return BT->getKind() == K;
484 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
485 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
486 /// but also int expressions which are produced by things like comparisons in
488 bool isKnownToHaveBooleanValue() const;
490 /// isIntegerConstantExpr - Return true if this expression is a valid integer
491 /// constant expression, and, if so, return its value in Result. If not a
492 /// valid i-c-e, return false and fill in Loc (if specified) with the location
493 /// of the invalid expression.
495 /// Note: This does not perform the implicit conversions required by C++11
497 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
498 SourceLocation *Loc = nullptr,
499 bool isEvaluated = true) const;
500 bool isIntegerConstantExpr(const ASTContext &Ctx,
501 SourceLocation *Loc = nullptr) const;
503 /// isCXX98IntegralConstantExpr - Return true if this expression is an
504 /// integral constant expression in C++98. Can only be used in C++.
505 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
507 /// isCXX11ConstantExpr - Return true if this expression is a constant
508 /// expression in C++11. Can only be used in C++.
510 /// Note: This does not perform the implicit conversions required by C++11
512 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
513 SourceLocation *Loc = nullptr) const;
515 /// isPotentialConstantExpr - Return true if this function's definition
516 /// might be usable in a constant expression in C++11, if it were marked
517 /// constexpr. Return false if the function can never produce a constant
518 /// expression, along with diagnostics describing why not.
519 static bool isPotentialConstantExpr(const FunctionDecl *FD,
521 PartialDiagnosticAt> &Diags);
523 /// isPotentialConstantExprUnevaluted - Return true if this expression might
524 /// be usable in a constant expression in C++11 in an unevaluated context, if
525 /// it were in function FD marked constexpr. Return false if the function can
526 /// never produce a constant expression, along with diagnostics describing
528 static bool isPotentialConstantExprUnevaluated(Expr *E,
529 const FunctionDecl *FD,
531 PartialDiagnosticAt> &Diags);
533 /// isConstantInitializer - Returns true if this expression can be emitted to
534 /// IR as a constant, and thus can be used as a constant initializer in C.
535 /// If this expression is not constant and Culprit is non-null,
536 /// it is used to store the address of first non constant expr.
537 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
538 const Expr **Culprit = nullptr) const;
540 /// EvalStatus is a struct with detailed info about an evaluation in progress.
542 /// Whether the evaluated expression has side effects.
543 /// For example, (f() && 0) can be folded, but it still has side effects.
546 /// Whether the evaluation hit undefined behavior.
547 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
548 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
549 bool HasUndefinedBehavior;
551 /// Diag - If this is non-null, it will be filled in with a stack of notes
552 /// indicating why evaluation failed (or why it failed to produce a constant
554 /// If the expression is unfoldable, the notes will indicate why it's not
555 /// foldable. If the expression is foldable, but not a constant expression,
556 /// the notes will describes why it isn't a constant expression. If the
557 /// expression *is* a constant expression, no notes will be produced.
558 SmallVectorImpl<PartialDiagnosticAt> *Diag;
561 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
563 // hasSideEffects - Return true if the evaluated expression has
565 bool hasSideEffects() const {
566 return HasSideEffects;
570 /// EvalResult is a struct with detailed info about an evaluated expression.
571 struct EvalResult : EvalStatus {
572 /// Val - This is the value the expression can be folded to.
575 // isGlobalLValue - Return true if the evaluated lvalue expression
577 bool isGlobalLValue() const;
580 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
581 /// an rvalue using any crazy technique (that has nothing to do with language
582 /// standards) that we want to, even if the expression has side-effects. If
583 /// this function returns true, it returns the folded constant in Result. If
584 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
586 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
588 /// EvaluateAsBooleanCondition - Return true if this is a constant
589 /// which we can fold and convert to a boolean condition using
590 /// any crazy technique that we want to, even if the expression has
592 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
594 enum SideEffectsKind {
595 SE_NoSideEffects, ///< Strictly evaluate the expression.
596 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
597 ///< arbitrary unmodeled side effects.
598 SE_AllowSideEffects ///< Allow any unmodeled side effect.
601 /// EvaluateAsInt - Return true if this is a constant which we can fold and
602 /// convert to an integer, using any crazy technique that we want to.
603 bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
604 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
606 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
607 /// convert to a floating point value, using any crazy technique that we
610 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
611 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
613 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
614 /// constant folded without side-effects, but discard the result.
615 bool isEvaluatable(const ASTContext &Ctx,
616 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
618 /// HasSideEffects - This routine returns true for all those expressions
619 /// which have any effect other than producing a value. Example is a function
620 /// call, volatile variable read, or throwing an exception. If
621 /// IncludePossibleEffects is false, this call treats certain expressions with
622 /// potential side effects (such as function call-like expressions,
623 /// instantiation-dependent expressions, or invocations from a macro) as not
624 /// having side effects.
625 bool HasSideEffects(const ASTContext &Ctx,
626 bool IncludePossibleEffects = true) const;
628 /// Determine whether this expression involves a call to any function
629 /// that is not trivial.
630 bool hasNonTrivialCall(const ASTContext &Ctx) const;
632 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
633 /// integer. This must be called on an expression that constant folds to an
635 llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
636 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
638 void EvaluateForOverflow(const ASTContext &Ctx) const;
640 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
641 /// lvalue with link time known address, with no side-effects.
642 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
644 /// EvaluateAsInitializer - Evaluate an expression as if it were the
645 /// initializer of the given declaration. Returns true if the initializer
646 /// can be folded to a constant, and produces any relevant notes. In C++11,
647 /// notes will be produced if the expression is not a constant expression.
648 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
650 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
652 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
653 /// of a call to the given function with the given arguments, inside an
654 /// unevaluated context. Returns true if the expression could be folded to a
656 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
657 const FunctionDecl *Callee,
658 ArrayRef<const Expr*> Args,
659 const Expr *This = nullptr) const;
661 /// Indicates how the constant expression will be used.
662 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
664 /// Evaluate an expression that is required to be a constant expression.
665 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
666 const ASTContext &Ctx) const;
668 /// If the current Expr is a pointer, this will try to statically
669 /// determine the number of bytes available where the pointer is pointing.
670 /// Returns true if all of the above holds and we were able to figure out the
671 /// size, false otherwise.
673 /// \param Type - How to evaluate the size of the Expr, as defined by the
674 /// "type" parameter of __builtin_object_size
675 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
676 unsigned Type) const;
678 /// Enumeration used to describe the kind of Null pointer constant
679 /// returned from \c isNullPointerConstant().
680 enum NullPointerConstantKind {
681 /// Expression is not a Null pointer constant.
684 /// Expression is a Null pointer constant built from a zero integer
685 /// expression that is not a simple, possibly parenthesized, zero literal.
686 /// C++ Core Issue 903 will classify these expressions as "not pointers"
687 /// once it is adopted.
688 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
691 /// Expression is a Null pointer constant built from a literal zero.
694 /// Expression is a C++11 nullptr.
697 /// Expression is a GNU-style __null constant.
701 /// Enumeration used to describe how \c isNullPointerConstant()
702 /// should cope with value-dependent expressions.
703 enum NullPointerConstantValueDependence {
704 /// Specifies that the expression should never be value-dependent.
705 NPC_NeverValueDependent = 0,
707 /// Specifies that a value-dependent expression of integral or
708 /// dependent type should be considered a null pointer constant.
709 NPC_ValueDependentIsNull,
711 /// Specifies that a value-dependent expression should be considered
712 /// to never be a null pointer constant.
713 NPC_ValueDependentIsNotNull
716 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
717 /// a Null pointer constant. The return value can further distinguish the
718 /// kind of NULL pointer constant that was detected.
719 NullPointerConstantKind isNullPointerConstant(
721 NullPointerConstantValueDependence NPC) const;
723 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
725 bool isOBJCGCCandidate(ASTContext &Ctx) const;
727 /// Returns true if this expression is a bound member function.
728 bool isBoundMemberFunction(ASTContext &Ctx) const;
730 /// Given an expression of bound-member type, find the type
731 /// of the member. Returns null if this is an *overloaded* bound
732 /// member expression.
733 static QualType findBoundMemberType(const Expr *expr);
735 /// IgnoreImpCasts - Skip past any implicit casts which might
736 /// surround this expression. Only skips ImplicitCastExprs.
737 Expr *IgnoreImpCasts() LLVM_READONLY;
739 /// IgnoreImplicit - Skip past any implicit AST nodes which might
740 /// surround this expression.
741 Expr *IgnoreImplicit() LLVM_READONLY {
742 return cast<Expr>(Stmt::IgnoreImplicit());
745 const Expr *IgnoreImplicit() const LLVM_READONLY {
746 return const_cast<Expr*>(this)->IgnoreImplicit();
749 /// IgnoreParens - Ignore parentheses. If this Expr is a ParenExpr, return
750 /// its subexpression. If that subexpression is also a ParenExpr,
751 /// then this method recursively returns its subexpression, and so forth.
752 /// Otherwise, the method returns the current Expr.
753 Expr *IgnoreParens() LLVM_READONLY;
755 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
756 /// or CastExprs, returning their operand.
757 Expr *IgnoreParenCasts() LLVM_READONLY;
759 /// Ignore casts. Strip off any CastExprs, returning their operand.
760 Expr *IgnoreCasts() LLVM_READONLY;
762 /// IgnoreParenImpCasts - Ignore parentheses and implicit casts. Strip off
763 /// any ParenExpr or ImplicitCastExprs, returning their operand.
764 Expr *IgnoreParenImpCasts() LLVM_READONLY;
766 /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
767 /// call to a conversion operator, return the argument.
768 Expr *IgnoreConversionOperator() LLVM_READONLY;
770 const Expr *IgnoreConversionOperator() const LLVM_READONLY {
771 return const_cast<Expr*>(this)->IgnoreConversionOperator();
774 const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
775 return const_cast<Expr*>(this)->IgnoreParenImpCasts();
778 /// Ignore parentheses and lvalue casts. Strip off any ParenExpr and
779 /// CastExprs that represent lvalue casts, returning their operand.
780 Expr *IgnoreParenLValueCasts() LLVM_READONLY;
782 const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
783 return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
786 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
787 /// value (including ptr->int casts of the same size). Strip off any
788 /// ParenExpr or CastExprs, returning their operand.
789 Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
791 /// Ignore parentheses and derived-to-base casts.
792 Expr *ignoreParenBaseCasts() LLVM_READONLY;
794 const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
795 return const_cast<Expr*>(this)->ignoreParenBaseCasts();
798 /// Determine whether this expression is a default function argument.
800 /// Default arguments are implicitly generated in the abstract syntax tree
801 /// by semantic analysis for function calls, object constructions, etc. in
802 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
803 /// this routine also looks through any implicit casts to determine whether
804 /// the expression is a default argument.
805 bool isDefaultArgument() const;
807 /// Determine whether the result of this expression is a
808 /// temporary object of the given class type.
809 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
811 /// Whether this expression is an implicit reference to 'this' in C++.
812 bool isImplicitCXXThis() const;
814 const Expr *IgnoreImpCasts() const LLVM_READONLY {
815 return const_cast<Expr*>(this)->IgnoreImpCasts();
817 const Expr *IgnoreParens() const LLVM_READONLY {
818 return const_cast<Expr*>(this)->IgnoreParens();
820 const Expr *IgnoreParenCasts() const LLVM_READONLY {
821 return const_cast<Expr*>(this)->IgnoreParenCasts();
823 /// Strip off casts, but keep parentheses.
824 const Expr *IgnoreCasts() const LLVM_READONLY {
825 return const_cast<Expr*>(this)->IgnoreCasts();
828 const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
829 return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
832 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
834 /// For an expression of class type or pointer to class type,
835 /// return the most derived class decl the expression is known to refer to.
837 /// If this expression is a cast, this method looks through it to find the
838 /// most derived decl that can be inferred from the expression.
839 /// This is valid because derived-to-base conversions have undefined
840 /// behavior if the object isn't dynamically of the derived type.
841 const CXXRecordDecl *getBestDynamicClassType() const;
843 /// Get the inner expression that determines the best dynamic class.
844 /// If this is a prvalue, we guarantee that it is of the most-derived type
845 /// for the object itself.
846 const Expr *getBestDynamicClassTypeExpr() const;
848 /// Walk outwards from an expression we want to bind a reference to and
849 /// find the expression whose lifetime needs to be extended. Record
850 /// the LHSs of comma expressions and adjustments needed along the path.
851 const Expr *skipRValueSubobjectAdjustments(
852 SmallVectorImpl<const Expr *> &CommaLHS,
853 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
854 const Expr *skipRValueSubobjectAdjustments() const {
855 SmallVector<const Expr *, 8> CommaLHSs;
856 SmallVector<SubobjectAdjustment, 8> Adjustments;
857 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
860 static bool classof(const Stmt *T) {
861 return T->getStmtClass() >= firstExprConstant &&
862 T->getStmtClass() <= lastExprConstant;
866 //===----------------------------------------------------------------------===//
867 // Primary Expressions.
868 //===----------------------------------------------------------------------===//
870 /// OpaqueValueExpr - An expression referring to an opaque object of a
871 /// fixed type and value class. These don't correspond to concrete
872 /// syntax; instead they're used to express operations (usually copy
873 /// operations) on values whose source is generally obvious from
875 class OpaqueValueExpr : public Expr {
876 friend class ASTStmtReader;
881 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
882 ExprObjectKind OK = OK_Ordinary,
883 Expr *SourceExpr = nullptr)
884 : Expr(OpaqueValueExprClass, T, VK, OK,
885 T->isDependentType() ||
886 (SourceExpr && SourceExpr->isTypeDependent()),
887 T->isDependentType() ||
888 (SourceExpr && SourceExpr->isValueDependent()),
889 T->isInstantiationDependentType() ||
890 (SourceExpr && SourceExpr->isInstantiationDependent()),
892 SourceExpr(SourceExpr), Loc(Loc) {
896 /// Given an expression which invokes a copy constructor --- i.e. a
897 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
898 /// find the OpaqueValueExpr that's the source of the construction.
899 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
901 explicit OpaqueValueExpr(EmptyShell Empty)
902 : Expr(OpaqueValueExprClass, Empty) { }
904 /// Retrieve the location of this expression.
905 SourceLocation getLocation() const { return Loc; }
907 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
908 SourceLocation getBeginLoc() const LLVM_READONLY {
909 return SourceExpr ? SourceExpr->getLocStart() : Loc;
911 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
912 SourceLocation getEndLoc() const LLVM_READONLY {
913 return SourceExpr ? SourceExpr->getLocEnd() : Loc;
915 SourceLocation getExprLoc() const LLVM_READONLY {
916 if (SourceExpr) return SourceExpr->getExprLoc();
920 child_range children() {
921 return child_range(child_iterator(), child_iterator());
924 const_child_range children() const {
925 return const_child_range(const_child_iterator(), const_child_iterator());
928 /// The source expression of an opaque value expression is the
929 /// expression which originally generated the value. This is
930 /// provided as a convenience for analyses that don't wish to
931 /// precisely model the execution behavior of the program.
933 /// The source expression is typically set when building the
934 /// expression which binds the opaque value expression in the first
936 Expr *getSourceExpr() const { return SourceExpr; }
938 void setIsUnique(bool V) {
939 assert((!V || SourceExpr) &&
940 "unique OVEs are expected to have source expressions");
941 OpaqueValueExprBits.IsUnique = V;
944 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
946 static bool classof(const Stmt *T) {
947 return T->getStmtClass() == OpaqueValueExprClass;
951 /// A reference to a declared variable, function, enum, etc.
954 /// This encodes all the information about how a declaration is referenced
955 /// within an expression.
957 /// There are several optional constructs attached to DeclRefExprs only when
958 /// they apply in order to conserve memory. These are laid out past the end of
959 /// the object, and flags in the DeclRefExprBitfield track whether they exist:
961 /// DeclRefExprBits.HasQualifier:
962 /// Specifies when this declaration reference expression has a C++
963 /// nested-name-specifier.
964 /// DeclRefExprBits.HasFoundDecl:
965 /// Specifies when this declaration reference expression has a record of
966 /// a NamedDecl (different from the referenced ValueDecl) which was found
967 /// during name lookup and/or overload resolution.
968 /// DeclRefExprBits.HasTemplateKWAndArgsInfo:
969 /// Specifies when this declaration reference expression has an explicit
970 /// C++ template keyword and/or template argument list.
971 /// DeclRefExprBits.RefersToEnclosingVariableOrCapture
972 /// Specifies when this declaration reference expression (validly)
973 /// refers to an enclosed local or a captured variable.
974 class DeclRefExpr final
976 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
977 NamedDecl *, ASTTemplateKWAndArgsInfo,
978 TemplateArgumentLoc> {
979 /// The declaration that we are referencing.
982 /// The location of the declaration name itself.
985 /// Provides source/type location info for the declaration name
987 DeclarationNameLoc DNLoc;
989 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
990 return hasQualifier() ? 1 : 0;
993 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
994 return hasFoundDecl() ? 1 : 0;
997 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
998 return hasTemplateKWAndArgsInfo() ? 1 : 0;
1001 /// Test whether there is a distinct FoundDecl attached to the end of
1003 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1005 DeclRefExpr(const ASTContext &Ctx,
1006 NestedNameSpecifierLoc QualifierLoc,
1007 SourceLocation TemplateKWLoc,
1008 ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
1009 const DeclarationNameInfo &NameInfo,
1011 const TemplateArgumentListInfo *TemplateArgs,
1012 QualType T, ExprValueKind VK);
1014 /// Construct an empty declaration reference expression.
1015 explicit DeclRefExpr(EmptyShell Empty)
1016 : Expr(DeclRefExprClass, Empty) { }
1018 /// Computes the type- and value-dependence flags for this
1019 /// declaration reference expression.
1020 void computeDependence(const ASTContext &C);
1023 DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1024 ExprValueKind VK, SourceLocation L,
1025 const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1026 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1027 D(D), Loc(L), DNLoc(LocInfo) {
1028 DeclRefExprBits.HasQualifier = 0;
1029 DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1030 DeclRefExprBits.HasFoundDecl = 0;
1031 DeclRefExprBits.HadMultipleCandidates = 0;
1032 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1033 RefersToEnclosingVariableOrCapture;
1034 computeDependence(D->getASTContext());
1037 static DeclRefExpr *
1038 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1039 SourceLocation TemplateKWLoc, ValueDecl *D,
1040 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1041 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1042 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1044 static DeclRefExpr *
1045 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1046 SourceLocation TemplateKWLoc, ValueDecl *D,
1047 bool RefersToEnclosingVariableOrCapture,
1048 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1049 NamedDecl *FoundD = nullptr,
1050 const TemplateArgumentListInfo *TemplateArgs = nullptr);
1052 /// Construct an empty declaration reference expression.
1053 static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1056 bool HasTemplateKWAndArgsInfo,
1057 unsigned NumTemplateArgs);
1059 ValueDecl *getDecl() { return D; }
1060 const ValueDecl *getDecl() const { return D; }
1061 void setDecl(ValueDecl *NewD) { D = NewD; }
1063 DeclarationNameInfo getNameInfo() const {
1064 return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1067 SourceLocation getLocation() const { return Loc; }
1068 void setLocation(SourceLocation L) { Loc = L; }
1069 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1070 SourceLocation getBeginLoc() const LLVM_READONLY;
1071 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1072 SourceLocation getEndLoc() const LLVM_READONLY;
1074 /// Determine whether this declaration reference was preceded by a
1075 /// C++ nested-name-specifier, e.g., \c N::foo.
1076 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1078 /// If the name was qualified, retrieves the nested-name-specifier
1079 /// that precedes the name, with source-location information.
1080 NestedNameSpecifierLoc getQualifierLoc() const {
1081 if (!hasQualifier())
1082 return NestedNameSpecifierLoc();
1083 return *getTrailingObjects<NestedNameSpecifierLoc>();
1086 /// If the name was qualified, retrieves the nested-name-specifier
1087 /// that precedes the name. Otherwise, returns NULL.
1088 NestedNameSpecifier *getQualifier() const {
1089 return getQualifierLoc().getNestedNameSpecifier();
1092 /// Get the NamedDecl through which this reference occurred.
1094 /// This Decl may be different from the ValueDecl actually referred to in the
1095 /// presence of using declarations, etc. It always returns non-NULL, and may
1096 /// simple return the ValueDecl when appropriate.
1098 NamedDecl *getFoundDecl() {
1099 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1102 /// Get the NamedDecl through which this reference occurred.
1103 /// See non-const variant.
1104 const NamedDecl *getFoundDecl() const {
1105 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1108 bool hasTemplateKWAndArgsInfo() const {
1109 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1112 /// Retrieve the location of the template keyword preceding
1113 /// this name, if any.
1114 SourceLocation getTemplateKeywordLoc() const {
1115 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1116 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1119 /// Retrieve the location of the left angle bracket starting the
1120 /// explicit template argument list following the name, if any.
1121 SourceLocation getLAngleLoc() const {
1122 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1123 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1126 /// Retrieve the location of the right angle bracket ending the
1127 /// explicit template argument list following the name, if any.
1128 SourceLocation getRAngleLoc() const {
1129 if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
1130 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1133 /// Determines whether the name in this declaration reference
1134 /// was preceded by the template keyword.
1135 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1137 /// Determines whether this declaration reference was followed by an
1138 /// explicit template argument list.
1139 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1141 /// Copies the template arguments (if present) into the given
1143 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1144 if (hasExplicitTemplateArgs())
1145 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1146 getTrailingObjects<TemplateArgumentLoc>(), List);
1149 /// Retrieve the template arguments provided as part of this
1151 const TemplateArgumentLoc *getTemplateArgs() const {
1152 if (!hasExplicitTemplateArgs())
1155 return getTrailingObjects<TemplateArgumentLoc>();
1158 /// Retrieve the number of template arguments provided as part of this
1160 unsigned getNumTemplateArgs() const {
1161 if (!hasExplicitTemplateArgs())
1164 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1167 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1168 return {getTemplateArgs(), getNumTemplateArgs()};
1171 /// Returns true if this expression refers to a function that
1172 /// was resolved from an overloaded set having size greater than 1.
1173 bool hadMultipleCandidates() const {
1174 return DeclRefExprBits.HadMultipleCandidates;
1176 /// Sets the flag telling whether this expression refers to
1177 /// a function that was resolved from an overloaded set having size
1179 void setHadMultipleCandidates(bool V = true) {
1180 DeclRefExprBits.HadMultipleCandidates = V;
1183 /// Does this DeclRefExpr refer to an enclosing local or a captured
1185 bool refersToEnclosingVariableOrCapture() const {
1186 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1189 static bool classof(const Stmt *T) {
1190 return T->getStmtClass() == DeclRefExprClass;
1194 child_range children() {
1195 return child_range(child_iterator(), child_iterator());
1198 const_child_range children() const {
1199 return const_child_range(const_child_iterator(), const_child_iterator());
1202 friend TrailingObjects;
1203 friend class ASTStmtReader;
1204 friend class ASTStmtWriter;
1207 /// [C99 6.4.2.2] - A predefined identifier such as __func__.
1208 class PredefinedExpr : public Expr {
1213 LFunction, // Same as Function, but as wide string.
1216 LFuncSig, // Same as FuncSig, but as as wide string
1218 /// The same as PrettyFunction, except that the
1219 /// 'virtual' keyword is omitted for virtual member functions.
1220 PrettyFunctionNoVirtual
1229 PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1232 /// Construct an empty predefined expression.
1233 explicit PredefinedExpr(EmptyShell Empty)
1234 : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1236 IdentType getIdentType() const { return Type; }
1238 SourceLocation getLocation() const { return Loc; }
1239 void setLocation(SourceLocation L) { Loc = L; }
1241 StringLiteral *getFunctionName();
1242 const StringLiteral *getFunctionName() const {
1243 return const_cast<PredefinedExpr *>(this)->getFunctionName();
1246 static StringRef getIdentTypeName(IdentType IT);
1247 static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1249 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1250 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1251 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1252 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1254 static bool classof(const Stmt *T) {
1255 return T->getStmtClass() == PredefinedExprClass;
1259 child_range children() { return child_range(&FnName, &FnName + 1); }
1260 const_child_range children() const {
1261 return const_child_range(&FnName, &FnName + 1);
1264 friend class ASTStmtReader;
1267 /// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1270 /// For large floats/integers, APFloat/APInt will allocate memory from the heap
1271 /// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1272 /// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1273 /// the APFloat/APInt values will never get freed. APNumericStorage uses
1274 /// ASTContext's allocator for memory allocation.
1275 class APNumericStorage {
1277 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1278 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1282 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1284 APNumericStorage(const APNumericStorage &) = delete;
1285 void operator=(const APNumericStorage &) = delete;
1288 APNumericStorage() : VAL(0), BitWidth(0) { }
1290 llvm::APInt getIntValue() const {
1291 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1293 return llvm::APInt(BitWidth, NumWords, pVal);
1295 return llvm::APInt(BitWidth, VAL);
1297 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1300 class APIntStorage : private APNumericStorage {
1302 llvm::APInt getValue() const { return getIntValue(); }
1303 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1304 setIntValue(C, Val);
1308 class APFloatStorage : private APNumericStorage {
1310 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1311 return llvm::APFloat(Semantics, getIntValue());
1313 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1314 setIntValue(C, Val.bitcastToAPInt());
1318 class IntegerLiteral : public Expr, public APIntStorage {
1321 /// Construct an empty integer literal.
1322 explicit IntegerLiteral(EmptyShell Empty)
1323 : Expr(IntegerLiteralClass, Empty) { }
1326 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1327 // or UnsignedLongLongTy
1328 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1331 /// Returns a new integer literal with value 'V' and type 'type'.
1332 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1333 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1334 /// \param V - the value that the returned integer literal contains.
1335 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1336 QualType type, SourceLocation l);
1337 /// Returns a new empty integer literal.
1338 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1340 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1341 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1342 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1343 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1345 /// Retrieve the location of the literal.
1346 SourceLocation getLocation() const { return Loc; }
1348 void setLocation(SourceLocation Location) { Loc = Location; }
1350 static bool classof(const Stmt *T) {
1351 return T->getStmtClass() == IntegerLiteralClass;
1355 child_range children() {
1356 return child_range(child_iterator(), child_iterator());
1358 const_child_range children() const {
1359 return const_child_range(const_child_iterator(), const_child_iterator());
1363 class FixedPointLiteral : public Expr, public APIntStorage {
1367 /// \brief Construct an empty integer literal.
1368 explicit FixedPointLiteral(EmptyShell Empty)
1369 : Expr(FixedPointLiteralClass, Empty) {}
1372 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1373 SourceLocation l, unsigned Scale);
1375 // Store the int as is without any bit shifting.
1376 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1377 const llvm::APInt &V,
1378 QualType type, SourceLocation l,
1381 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1382 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1383 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1384 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1386 /// \brief Retrieve the location of the literal.
1387 SourceLocation getLocation() const { return Loc; }
1389 void setLocation(SourceLocation Location) { Loc = Location; }
1391 static bool classof(const Stmt *T) {
1392 return T->getStmtClass() == FixedPointLiteralClass;
1395 std::string getValueAsString(unsigned Radix) const;
1398 child_range children() {
1399 return child_range(child_iterator(), child_iterator());
1401 const_child_range children() const {
1402 return const_child_range(const_child_iterator(), const_child_iterator());
1406 class CharacterLiteral : public Expr {
1408 enum CharacterKind {
1420 // type should be IntTy
1421 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1423 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1425 Value(value), Loc(l) {
1426 CharacterLiteralBits.Kind = kind;
1429 /// Construct an empty character literal.
1430 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1432 SourceLocation getLocation() const { return Loc; }
1433 CharacterKind getKind() const {
1434 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1437 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1438 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1439 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1440 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1442 unsigned getValue() const { return Value; }
1444 void setLocation(SourceLocation Location) { Loc = Location; }
1445 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1446 void setValue(unsigned Val) { Value = Val; }
1448 static bool classof(const Stmt *T) {
1449 return T->getStmtClass() == CharacterLiteralClass;
1453 child_range children() {
1454 return child_range(child_iterator(), child_iterator());
1456 const_child_range children() const {
1457 return const_child_range(const_child_iterator(), const_child_iterator());
1461 class FloatingLiteral : public Expr, private APFloatStorage {
1464 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1465 QualType Type, SourceLocation L);
1467 /// Construct an empty floating-point literal.
1468 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1471 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1472 bool isexact, QualType Type, SourceLocation L);
1473 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1475 llvm::APFloat getValue() const {
1476 return APFloatStorage::getValue(getSemantics());
1478 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1479 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1480 APFloatStorage::setValue(C, Val);
1483 /// Get a raw enumeration value representing the floating-point semantics of
1484 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1485 APFloatSemantics getRawSemantics() const {
1486 return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1489 /// Set the raw enumeration value representing the floating-point semantics of
1490 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1491 void setRawSemantics(APFloatSemantics Sem) {
1492 FloatingLiteralBits.Semantics = Sem;
1495 /// Return the APFloat semantics this literal uses.
1496 const llvm::fltSemantics &getSemantics() const;
1498 /// Set the APFloat semantics this literal uses.
1499 void setSemantics(const llvm::fltSemantics &Sem);
1501 bool isExact() const { return FloatingLiteralBits.IsExact; }
1502 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1504 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1505 /// double. Note that this may cause loss of precision, but is useful for
1506 /// debugging dumps, etc.
1507 double getValueAsApproximateDouble() const;
1509 SourceLocation getLocation() const { return Loc; }
1510 void setLocation(SourceLocation L) { Loc = L; }
1512 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1513 SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1514 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1515 SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1517 static bool classof(const Stmt *T) {
1518 return T->getStmtClass() == FloatingLiteralClass;
1522 child_range children() {
1523 return child_range(child_iterator(), child_iterator());
1525 const_child_range children() const {
1526 return const_child_range(const_child_iterator(), const_child_iterator());
1530 /// ImaginaryLiteral - We support imaginary integer and floating point literals,
1531 /// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1532 /// IntegerLiteral classes. Instances of this class always have a Complex type
1533 /// whose element type matches the subexpression.
1535 class ImaginaryLiteral : public Expr {
1538 ImaginaryLiteral(Expr *val, QualType Ty)
1539 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1543 /// Build an empty imaginary literal.
1544 explicit ImaginaryLiteral(EmptyShell Empty)
1545 : Expr(ImaginaryLiteralClass, Empty) { }
1547 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1548 Expr *getSubExpr() { return cast<Expr>(Val); }
1549 void setSubExpr(Expr *E) { Val = E; }
1551 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1552 SourceLocation getBeginLoc() const LLVM_READONLY {
1553 return Val->getLocStart();
1555 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1556 SourceLocation getEndLoc() const LLVM_READONLY { return Val->getLocEnd(); }
1558 static bool classof(const Stmt *T) {
1559 return T->getStmtClass() == ImaginaryLiteralClass;
1563 child_range children() { return child_range(&Val, &Val+1); }
1564 const_child_range children() const {
1565 return const_child_range(&Val, &Val + 1);
1569 /// StringLiteral - This represents a string literal expression, e.g. "foo"
1570 /// or L"bar" (wide strings). The actual string is returned by getBytes()
1571 /// is NOT null-terminated, and the length of the string is determined by
1572 /// calling getByteLength(). The C type for a string is always a
1573 /// ConstantArrayType. In C++, the char type is const qualified, in C it is
1576 /// Note that strings in C can be formed by concatenation of multiple string
1577 /// literal pptokens in translation phase #6. This keeps track of the locations
1578 /// of each of these pieces.
1580 /// Strings in C can also be truncated and extended by assigning into arrays,
1581 /// e.g. with constructs like:
1582 /// char X[2] = "foobar";
1583 /// In this case, getByteLength() will return 6, but the string literal will
1584 /// have type "char[2]".
1585 class StringLiteral : public Expr {
1596 friend class ASTStmtReader;
1600 const uint16_t *asUInt16;
1601 const uint32_t *asUInt32;
1604 unsigned CharByteWidth : 4;
1606 unsigned IsPascal : 1;
1607 unsigned NumConcatenated;
1608 SourceLocation TokLocs[1];
1610 StringLiteral(QualType Ty) :
1611 Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1614 static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1617 /// This is the "fully general" constructor that allows representation of
1618 /// strings formed from multiple concatenated tokens.
1619 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1620 StringKind Kind, bool Pascal, QualType Ty,
1621 const SourceLocation *Loc, unsigned NumStrs);
1623 /// Simple constructor for string literals made from one token.
1624 static StringLiteral *Create(const ASTContext &C, StringRef Str,
1625 StringKind Kind, bool Pascal, QualType Ty,
1626 SourceLocation Loc) {
1627 return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1630 /// Construct an empty string literal.
1631 static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1633 StringRef getString() const {
1634 assert(CharByteWidth==1
1635 && "This function is used in places that assume strings use char");
1636 return StringRef(StrData.asChar, getByteLength());
1639 /// Allow access to clients that need the byte representation, such as
1640 /// ASTWriterStmt::VisitStringLiteral().
1641 StringRef getBytes() const {
1642 // FIXME: StringRef may not be the right type to use as a result for this.
1643 if (CharByteWidth == 1)
1644 return StringRef(StrData.asChar, getByteLength());
1645 if (CharByteWidth == 4)
1646 return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1648 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1649 return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1653 void outputString(raw_ostream &OS) const;
1655 uint32_t getCodeUnit(size_t i) const {
1656 assert(i < Length && "out of bounds access");
1657 if (CharByteWidth == 1)
1658 return static_cast<unsigned char>(StrData.asChar[i]);
1659 if (CharByteWidth == 4)
1660 return StrData.asUInt32[i];
1661 assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1662 return StrData.asUInt16[i];
1665 unsigned getByteLength() const { return CharByteWidth*Length; }
1666 unsigned getLength() const { return Length; }
1667 unsigned getCharByteWidth() const { return CharByteWidth; }
1669 /// Sets the string data to the given string data.
1670 void setString(const ASTContext &C, StringRef Str,
1671 StringKind Kind, bool IsPascal);
1673 StringKind getKind() const { return static_cast<StringKind>(Kind); }
1676 bool isAscii() const { return Kind == Ascii; }
1677 bool isWide() const { return Kind == Wide; }
1678 bool isUTF8() const { return Kind == UTF8; }
1679 bool isUTF16() const { return Kind == UTF16; }
1680 bool isUTF32() const { return Kind == UTF32; }
1681 bool isPascal() const { return IsPascal; }
1683 bool containsNonAscii() const {
1684 StringRef Str = getString();
1685 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1686 if (!isASCII(Str[i]))
1691 bool containsNonAsciiOrNull() const {
1692 StringRef Str = getString();
1693 for (unsigned i = 0, e = Str.size(); i != e; ++i)
1694 if (!isASCII(Str[i]) || !Str[i])
1699 /// getNumConcatenated - Get the number of string literal tokens that were
1700 /// concatenated in translation phase #6 to form this string literal.
1701 unsigned getNumConcatenated() const { return NumConcatenated; }
1703 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1704 assert(TokNum < NumConcatenated && "Invalid tok number");
1705 return TokLocs[TokNum];
1707 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1708 assert(TokNum < NumConcatenated && "Invalid tok number");
1709 TokLocs[TokNum] = L;
1712 /// getLocationOfByte - Return a source location that points to the specified
1713 /// byte of this string literal.
1715 /// Strings are amazingly complex. They can be formed from multiple tokens
1716 /// and can have escape sequences in them in addition to the usual trigraph
1717 /// and escaped newline business. This routine handles this complexity.
1720 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1721 const LangOptions &Features, const TargetInfo &Target,
1722 unsigned *StartToken = nullptr,
1723 unsigned *StartTokenByteOffset = nullptr) const;
1725 typedef const SourceLocation *tokloc_iterator;
1726 tokloc_iterator tokloc_begin() const { return TokLocs; }
1727 tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1729 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1730 SourceLocation getBeginLoc() const LLVM_READONLY { return TokLocs[0]; }
1731 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1732 SourceLocation getEndLoc() const LLVM_READONLY {
1733 return TokLocs[NumConcatenated - 1];
1736 static bool classof(const Stmt *T) {
1737 return T->getStmtClass() == StringLiteralClass;
1741 child_range children() {
1742 return child_range(child_iterator(), child_iterator());
1744 const_child_range children() const {
1745 return const_child_range(const_child_iterator(), const_child_iterator());
1749 /// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1750 /// AST node is only formed if full location information is requested.
1751 class ParenExpr : public Expr {
1752 SourceLocation L, R;
1755 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1756 : Expr(ParenExprClass, val->getType(),
1757 val->getValueKind(), val->getObjectKind(),
1758 val->isTypeDependent(), val->isValueDependent(),
1759 val->isInstantiationDependent(),
1760 val->containsUnexpandedParameterPack()),
1761 L(l), R(r), Val(val) {}
1763 /// Construct an empty parenthesized expression.
1764 explicit ParenExpr(EmptyShell Empty)
1765 : Expr(ParenExprClass, Empty) { }
1767 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1768 Expr *getSubExpr() { return cast<Expr>(Val); }
1769 void setSubExpr(Expr *E) { Val = E; }
1771 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1772 SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
1773 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1774 SourceLocation getEndLoc() const LLVM_READONLY { return R; }
1776 /// Get the location of the left parentheses '('.
1777 SourceLocation getLParen() const { return L; }
1778 void setLParen(SourceLocation Loc) { L = Loc; }
1780 /// Get the location of the right parentheses ')'.
1781 SourceLocation getRParen() const { return R; }
1782 void setRParen(SourceLocation Loc) { R = Loc; }
1784 static bool classof(const Stmt *T) {
1785 return T->getStmtClass() == ParenExprClass;
1789 child_range children() { return child_range(&Val, &Val+1); }
1790 const_child_range children() const {
1791 return const_child_range(&Val, &Val + 1);
1795 /// UnaryOperator - This represents the unary-expression's (except sizeof and
1796 /// alignof), the postinc/postdec operators from postfix-expression, and various
1799 /// Notes on various nodes:
1801 /// Real/Imag - These return the real/imag part of a complex operand. If
1802 /// applied to a non-complex value, the former returns its operand and the
1803 /// later returns zero in the type of the operand.
1805 class UnaryOperator : public Expr {
1807 typedef UnaryOperatorKind Opcode;
1811 unsigned CanOverflow : 1;
1815 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
1816 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
1817 : Expr(UnaryOperatorClass, type, VK, OK,
1818 input->isTypeDependent() || type->isDependentType(),
1819 input->isValueDependent(),
1820 (input->isInstantiationDependent() ||
1821 type->isInstantiationDependentType()),
1822 input->containsUnexpandedParameterPack()),
1823 Opc(opc), CanOverflow(CanOverflow), Loc(l), Val(input) {}
1825 /// Build an empty unary operator.
1826 explicit UnaryOperator(EmptyShell Empty)
1827 : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1829 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1830 void setOpcode(Opcode O) { Opc = O; }
1832 Expr *getSubExpr() const { return cast<Expr>(Val); }
1833 void setSubExpr(Expr *E) { Val = E; }
1835 /// getOperatorLoc - Return the location of the operator.
1836 SourceLocation getOperatorLoc() const { return Loc; }
1837 void setOperatorLoc(SourceLocation L) { Loc = L; }
1839 /// Returns true if the unary operator can cause an overflow. For instance,
1840 /// signed int i = INT_MAX; i++;
1841 /// signed char c = CHAR_MAX; c++;
1842 /// Due to integer promotions, c++ is promoted to an int before the postfix
1843 /// increment, and the result is an int that cannot overflow. However, i++
1845 bool canOverflow() const { return CanOverflow; }
1846 void setCanOverflow(bool C) { CanOverflow = C; }
1848 /// isPostfix - Return true if this is a postfix operation, like x++.
1849 static bool isPostfix(Opcode Op) {
1850 return Op == UO_PostInc || Op == UO_PostDec;
1853 /// isPrefix - Return true if this is a prefix operation, like --x.
1854 static bool isPrefix(Opcode Op) {
1855 return Op == UO_PreInc || Op == UO_PreDec;
1858 bool isPrefix() const { return isPrefix(getOpcode()); }
1859 bool isPostfix() const { return isPostfix(getOpcode()); }
1861 static bool isIncrementOp(Opcode Op) {
1862 return Op == UO_PreInc || Op == UO_PostInc;
1864 bool isIncrementOp() const {
1865 return isIncrementOp(getOpcode());
1868 static bool isDecrementOp(Opcode Op) {
1869 return Op == UO_PreDec || Op == UO_PostDec;
1871 bool isDecrementOp() const {
1872 return isDecrementOp(getOpcode());
1875 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1876 bool isIncrementDecrementOp() const {
1877 return isIncrementDecrementOp(getOpcode());
1880 static bool isArithmeticOp(Opcode Op) {
1881 return Op >= UO_Plus && Op <= UO_LNot;
1883 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1885 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1886 /// corresponds to, e.g. "sizeof" or "[pre]++"
1887 static StringRef getOpcodeStr(Opcode Op);
1889 /// Retrieve the unary opcode that corresponds to the given
1890 /// overloaded operator.
1891 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1893 /// Retrieve the overloaded operator kind that corresponds to
1894 /// the given unary opcode.
1895 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1897 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
1898 SourceLocation getBeginLoc() const LLVM_READONLY {
1899 return isPostfix() ? Val->getLocStart() : Loc;
1901 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
1902 SourceLocation getEndLoc() const LLVM_READONLY {
1903 return isPostfix() ? Loc : Val->getLocEnd();
1905 SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1907 static bool classof(const Stmt *T) {
1908 return T->getStmtClass() == UnaryOperatorClass;
1912 child_range children() { return child_range(&Val, &Val+1); }
1913 const_child_range children() const {
1914 return const_child_range(&Val, &Val + 1);
1918 /// Helper class for OffsetOfExpr.
1920 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
1921 class OffsetOfNode {
1923 /// The kind of offsetof node we have.
1925 /// An index into an array.
1929 /// A field in a dependent type, known only by its name.
1931 /// An implicit indirection through a C++ base class, when the
1932 /// field found is in a base class.
1937 enum { MaskBits = 2, Mask = 0x03 };
1939 /// The source range that covers this part of the designator.
1942 /// The data describing the designator, which comes in three
1943 /// different forms, depending on the lower two bits.
1944 /// - An unsigned index into the array of Expr*'s stored after this node
1945 /// in memory, for [constant-expression] designators.
1946 /// - A FieldDecl*, for references to a known field.
1947 /// - An IdentifierInfo*, for references to a field with a given name
1948 /// when the class type is dependent.
1949 /// - A CXXBaseSpecifier*, for references that look at a field in a
1954 /// Create an offsetof node that refers to an array element.
1955 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1956 SourceLocation RBracketLoc)
1957 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1959 /// Create an offsetof node that refers to a field.
1960 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1961 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1962 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1964 /// Create an offsetof node that refers to an identifier.
1965 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1966 SourceLocation NameLoc)
1967 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1968 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1970 /// Create an offsetof node that refers into a C++ base class.
1971 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1972 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1974 /// Determine what kind of offsetof node this is.
1975 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1977 /// For an array element node, returns the index into the array
1979 unsigned getArrayExprIndex() const {
1980 assert(getKind() == Array);
1984 /// For a field offsetof node, returns the field.
1985 FieldDecl *getField() const {
1986 assert(getKind() == Field);
1987 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1990 /// For a field or identifier offsetof node, returns the name of
1992 IdentifierInfo *getFieldName() const;
1994 /// For a base class node, returns the base specifier.
1995 CXXBaseSpecifier *getBase() const {
1996 assert(getKind() == Base);
1997 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2000 /// Retrieve the source range that covers this offsetof node.
2002 /// For an array element node, the source range contains the locations of
2003 /// the square brackets. For a field or identifier node, the source range
2004 /// contains the location of the period (if there is one) and the
2006 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2007 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2008 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2009 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2010 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2013 /// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2014 /// offsetof(record-type, member-designator). For example, given:
2025 /// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2027 class OffsetOfExpr final
2029 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2030 SourceLocation OperatorLoc, RParenLoc;
2032 TypeSourceInfo *TSInfo;
2033 // Number of sub-components (i.e. instances of OffsetOfNode).
2035 // Number of sub-expressions (i.e. array subscript expressions).
2038 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2042 OffsetOfExpr(const ASTContext &C, QualType type,
2043 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2044 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2045 SourceLocation RParenLoc);
2047 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2048 : Expr(OffsetOfExprClass, EmptyShell()),
2049 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2053 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2054 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2055 ArrayRef<OffsetOfNode> comps,
2056 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2058 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2059 unsigned NumComps, unsigned NumExprs);
2061 /// getOperatorLoc - Return the location of the operator.
2062 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2063 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2065 /// Return the location of the right parentheses.
2066 SourceLocation getRParenLoc() const { return RParenLoc; }
2067 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2069 TypeSourceInfo *getTypeSourceInfo() const {
2072 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2076 const OffsetOfNode &getComponent(unsigned Idx) const {
2077 assert(Idx < NumComps && "Subscript out of range");
2078 return getTrailingObjects<OffsetOfNode>()[Idx];
2081 void setComponent(unsigned Idx, OffsetOfNode ON) {
2082 assert(Idx < NumComps && "Subscript out of range");
2083 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2086 unsigned getNumComponents() const {
2090 Expr* getIndexExpr(unsigned Idx) {
2091 assert(Idx < NumExprs && "Subscript out of range");
2092 return getTrailingObjects<Expr *>()[Idx];
2095 const Expr *getIndexExpr(unsigned Idx) const {
2096 assert(Idx < NumExprs && "Subscript out of range");
2097 return getTrailingObjects<Expr *>()[Idx];
2100 void setIndexExpr(unsigned Idx, Expr* E) {
2101 assert(Idx < NumComps && "Subscript out of range");
2102 getTrailingObjects<Expr *>()[Idx] = E;
2105 unsigned getNumExpressions() const {
2109 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2110 SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2111 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2112 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2114 static bool classof(const Stmt *T) {
2115 return T->getStmtClass() == OffsetOfExprClass;
2119 child_range children() {
2120 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2121 return child_range(begin, begin + NumExprs);
2123 const_child_range children() const {
2124 Stmt *const *begin =
2125 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2126 return const_child_range(begin, begin + NumExprs);
2128 friend TrailingObjects;
2131 /// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2132 /// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2133 /// vec_step (OpenCL 1.1 6.11.12).
2134 class UnaryExprOrTypeTraitExpr : public Expr {
2139 SourceLocation OpLoc, RParenLoc;
2142 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2143 QualType resultType, SourceLocation op,
2144 SourceLocation rp) :
2145 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2146 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2147 // Value-dependent if the argument is type-dependent.
2148 TInfo->getType()->isDependentType(),
2149 TInfo->getType()->isInstantiationDependentType(),
2150 TInfo->getType()->containsUnexpandedParameterPack()),
2151 OpLoc(op), RParenLoc(rp) {
2152 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2153 UnaryExprOrTypeTraitExprBits.IsType = true;
2154 Argument.Ty = TInfo;
2157 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2158 QualType resultType, SourceLocation op,
2161 /// Construct an empty sizeof/alignof expression.
2162 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2163 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2165 UnaryExprOrTypeTrait getKind() const {
2166 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2168 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2170 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2171 QualType getArgumentType() const {
2172 return getArgumentTypeInfo()->getType();
2174 TypeSourceInfo *getArgumentTypeInfo() const {
2175 assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2178 Expr *getArgumentExpr() {
2179 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2180 return static_cast<Expr*>(Argument.Ex);
2182 const Expr *getArgumentExpr() const {
2183 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2186 void setArgument(Expr *E) {
2188 UnaryExprOrTypeTraitExprBits.IsType = false;
2190 void setArgument(TypeSourceInfo *TInfo) {
2191 Argument.Ty = TInfo;
2192 UnaryExprOrTypeTraitExprBits.IsType = true;
2195 /// Gets the argument type, or the type of the argument expression, whichever
2197 QualType getTypeOfArgument() const {
2198 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2201 SourceLocation getOperatorLoc() const { return OpLoc; }
2202 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2204 SourceLocation getRParenLoc() const { return RParenLoc; }
2205 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2207 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2208 SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2209 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2210 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2212 static bool classof(const Stmt *T) {
2213 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2217 child_range children();
2218 const_child_range children() const;
2221 //===----------------------------------------------------------------------===//
2222 // Postfix Operators.
2223 //===----------------------------------------------------------------------===//
2225 /// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2226 class ArraySubscriptExpr : public Expr {
2227 enum { LHS, RHS, END_EXPR=2 };
2228 Stmt* SubExprs[END_EXPR];
2229 SourceLocation RBracketLoc;
2231 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2232 ExprValueKind VK, ExprObjectKind OK,
2233 SourceLocation rbracketloc)
2234 : Expr(ArraySubscriptExprClass, t, VK, OK,
2235 lhs->isTypeDependent() || rhs->isTypeDependent(),
2236 lhs->isValueDependent() || rhs->isValueDependent(),
2237 (lhs->isInstantiationDependent() ||
2238 rhs->isInstantiationDependent()),
2239 (lhs->containsUnexpandedParameterPack() ||
2240 rhs->containsUnexpandedParameterPack())),
2241 RBracketLoc(rbracketloc) {
2242 SubExprs[LHS] = lhs;
2243 SubExprs[RHS] = rhs;
2246 /// Create an empty array subscript expression.
2247 explicit ArraySubscriptExpr(EmptyShell Shell)
2248 : Expr(ArraySubscriptExprClass, Shell) { }
2250 /// An array access can be written A[4] or 4[A] (both are equivalent).
2251 /// - getBase() and getIdx() always present the normalized view: A[4].
2252 /// In this case getBase() returns "A" and getIdx() returns "4".
2253 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2254 /// 4[A] getLHS() returns "4".
2255 /// Note: Because vector element access is also written A[4] we must
2256 /// predicate the format conversion in getBase and getIdx only on the
2257 /// the type of the RHS, as it is possible for the LHS to be a vector of
2259 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2260 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2261 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2263 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2264 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2265 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2268 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2271 const Expr *getBase() const {
2272 return getRHS()->getType()->isIntegerType() ? getLHS() : getRHS();
2276 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2279 const Expr *getIdx() const {
2280 return getRHS()->getType()->isIntegerType() ? getRHS() : getLHS();
2283 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2284 SourceLocation getBeginLoc() const LLVM_READONLY {
2285 return getLHS()->getLocStart();
2287 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2288 SourceLocation getEndLoc() const LLVM_READONLY { return RBracketLoc; }
2290 SourceLocation getRBracketLoc() const { return RBracketLoc; }
2291 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2293 SourceLocation getExprLoc() const LLVM_READONLY {
2294 return getBase()->getExprLoc();
2297 static bool classof(const Stmt *T) {
2298 return T->getStmtClass() == ArraySubscriptExprClass;
2302 child_range children() {
2303 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2305 const_child_range children() const {
2306 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2310 /// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2311 /// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2312 /// while its subclasses may represent alternative syntax that (semantically)
2313 /// results in a function call. For example, CXXOperatorCallExpr is
2314 /// a subclass for overloaded operator calls that use operator syntax, e.g.,
2315 /// "str1 + str2" to resolve to a function call.
2316 class CallExpr : public Expr {
2317 enum { FN=0, PREARGS_START=1 };
2320 SourceLocation RParenLoc;
2322 void updateDependenciesFromArg(Expr *Arg);
2325 // These versions of the constructor are for derived classes.
2326 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2327 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2328 ExprValueKind VK, SourceLocation rparenloc);
2329 CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2330 QualType t, ExprValueKind VK, SourceLocation rparenloc);
2331 CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2334 Stmt *getPreArg(unsigned i) {
2335 assert(i < getNumPreArgs() && "Prearg access out of range!");
2336 return SubExprs[PREARGS_START+i];
2338 const Stmt *getPreArg(unsigned i) const {
2339 assert(i < getNumPreArgs() && "Prearg access out of range!");
2340 return SubExprs[PREARGS_START+i];
2342 void setPreArg(unsigned i, Stmt *PreArg) {
2343 assert(i < getNumPreArgs() && "Prearg access out of range!");
2344 SubExprs[PREARGS_START+i] = PreArg;
2347 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2350 CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2351 ExprValueKind VK, SourceLocation rparenloc);
2353 /// Build an empty call expression.
2354 CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2356 const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2357 Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2358 void setCallee(Expr *F) { SubExprs[FN] = F; }
2360 Decl *getCalleeDecl();
2361 const Decl *getCalleeDecl() const {
2362 return const_cast<CallExpr*>(this)->getCalleeDecl();
2365 /// If the callee is a FunctionDecl, return it. Otherwise return 0.
2366 FunctionDecl *getDirectCallee();
2367 const FunctionDecl *getDirectCallee() const {
2368 return const_cast<CallExpr*>(this)->getDirectCallee();
2371 /// getNumArgs - Return the number of actual arguments to this call.
2373 unsigned getNumArgs() const { return NumArgs; }
2375 /// Retrieve the call arguments.
2377 return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2379 const Expr *const *getArgs() const {
2380 return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2384 /// getArg - Return the specified argument.
2385 Expr *getArg(unsigned Arg) {
2386 assert(Arg < NumArgs && "Arg access out of range!");
2387 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2389 const Expr *getArg(unsigned Arg) const {
2390 assert(Arg < NumArgs && "Arg access out of range!");
2391 return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2394 /// setArg - Set the specified argument.
2395 void setArg(unsigned Arg, Expr *ArgExpr) {
2396 assert(Arg < NumArgs && "Arg access out of range!");
2397 SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2400 /// setNumArgs - This changes the number of arguments present in this call.
2401 /// Any orphaned expressions are deleted by this, and any new operands are set
2403 void setNumArgs(const ASTContext& C, unsigned NumArgs);
2405 typedef ExprIterator arg_iterator;
2406 typedef ConstExprIterator const_arg_iterator;
2407 typedef llvm::iterator_range<arg_iterator> arg_range;
2408 typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2410 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2411 arg_const_range arguments() const {
2412 return arg_const_range(arg_begin(), arg_end());
2415 arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2416 arg_iterator arg_end() {
2417 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2419 const_arg_iterator arg_begin() const {
2420 return SubExprs+PREARGS_START+getNumPreArgs();
2422 const_arg_iterator arg_end() const {
2423 return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2426 /// This method provides fast access to all the subexpressions of
2427 /// a CallExpr without going through the slower virtual child_iterator
2428 /// interface. This provides efficient reverse iteration of the
2429 /// subexpressions. This is currently used for CFG construction.
2430 ArrayRef<Stmt*> getRawSubExprs() {
2431 return llvm::makeArrayRef(SubExprs,
2432 getNumPreArgs() + PREARGS_START + getNumArgs());
2435 /// getNumCommas - Return the number of commas that must have been present in
2436 /// this function call.
2437 unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2439 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2440 /// of the callee. If not, return 0.
2441 unsigned getBuiltinCallee() const;
2443 /// Returns \c true if this is a call to a builtin which does not
2444 /// evaluate side-effects within its arguments.
2445 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2447 /// getCallReturnType - Get the return type of the call expr. This is not
2448 /// always the type of the expr itself, if the return type is a reference
2450 QualType getCallReturnType(const ASTContext &Ctx) const;
2452 SourceLocation getRParenLoc() const { return RParenLoc; }
2453 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2455 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2456 SourceLocation getBeginLoc() const LLVM_READONLY;
2457 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2458 SourceLocation getEndLoc() const LLVM_READONLY;
2460 /// Return true if this is a call to __assume() or __builtin_assume() with
2461 /// a non-value-dependent constant parameter evaluating as false.
2462 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2464 bool isCallToStdMove() const {
2465 const FunctionDecl* FD = getDirectCallee();
2466 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2467 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2470 static bool classof(const Stmt *T) {
2471 return T->getStmtClass() >= firstCallExprConstant &&
2472 T->getStmtClass() <= lastCallExprConstant;
2476 child_range children() {
2477 return child_range(&SubExprs[0],
2478 &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2481 const_child_range children() const {
2482 return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2483 getNumPreArgs() + PREARGS_START);
2487 /// Extra data stored in some MemberExpr objects.
2488 struct MemberExprNameQualifier {
2489 /// The nested-name-specifier that qualifies the name, including
2490 /// source-location information.
2491 NestedNameSpecifierLoc QualifierLoc;
2493 /// The DeclAccessPair through which the MemberDecl was found due to
2494 /// name qualifiers.
2495 DeclAccessPair FoundDecl;
2498 /// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2500 class MemberExpr final
2502 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2503 ASTTemplateKWAndArgsInfo,
2504 TemplateArgumentLoc> {
2505 /// Base - the expression for the base pointer or structure references. In
2506 /// X.F, this is "X".
2509 /// MemberDecl - This is the decl being referenced by the field/member name.
2510 /// In X.F, this is the decl referenced by F.
2511 ValueDecl *MemberDecl;
2513 /// MemberDNLoc - Provides source/type location info for the
2514 /// declaration name embedded in MemberDecl.
2515 DeclarationNameLoc MemberDNLoc;
2517 /// MemberLoc - This is the location of the member name.
2518 SourceLocation MemberLoc;
2520 /// This is the location of the -> or . in the expression.
2521 SourceLocation OperatorLoc;
2523 /// IsArrow - True if this is "X->F", false if this is "X.F".
2526 /// True if this member expression used a nested-name-specifier to
2527 /// refer to the member, e.g., "x->Base::f", or found its member via a using
2528 /// declaration. When true, a MemberExprNameQualifier
2529 /// structure is allocated immediately after the MemberExpr.
2530 bool HasQualifierOrFoundDecl : 1;
2532 /// True if this member expression specified a template keyword
2533 /// and/or a template argument list explicitly, e.g., x->f<int>,
2534 /// x->template f, x->template f<int>.
2535 /// When true, an ASTTemplateKWAndArgsInfo structure and its
2536 /// TemplateArguments (if any) are present.
2537 bool HasTemplateKWAndArgsInfo : 1;
2539 /// True if this member expression refers to a method that
2540 /// was resolved from an overloaded set having size greater than 1.
2541 bool HadMultipleCandidates : 1;
2543 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2544 return HasQualifierOrFoundDecl ? 1 : 0;
2547 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2548 return HasTemplateKWAndArgsInfo ? 1 : 0;
2552 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2553 ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2554 QualType ty, ExprValueKind VK, ExprObjectKind OK)
2555 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2556 base->isValueDependent(), base->isInstantiationDependent(),
2557 base->containsUnexpandedParameterPack()),
2558 Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2559 MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2560 IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2561 HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2562 assert(memberdecl->getDeclName() == NameInfo.getName());
2565 // NOTE: this constructor should be used only when it is known that
2566 // the member name can not provide additional syntactic info
2567 // (i.e., source locations for C++ operator names or type source info
2568 // for constructors, destructors and conversion operators).
2569 MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2570 ValueDecl *memberdecl, SourceLocation l, QualType ty,
2571 ExprValueKind VK, ExprObjectKind OK)
2572 : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2573 base->isValueDependent(), base->isInstantiationDependent(),
2574 base->containsUnexpandedParameterPack()),
2575 Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2576 OperatorLoc(operatorloc), IsArrow(isarrow),
2577 HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2578 HadMultipleCandidates(false) {}
2580 static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2581 SourceLocation OperatorLoc,
2582 NestedNameSpecifierLoc QualifierLoc,
2583 SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2584 DeclAccessPair founddecl,
2585 DeclarationNameInfo MemberNameInfo,
2586 const TemplateArgumentListInfo *targs, QualType ty,
2587 ExprValueKind VK, ExprObjectKind OK);
2589 void setBase(Expr *E) { Base = E; }
2590 Expr *getBase() const { return cast<Expr>(Base); }
2592 /// Retrieve the member declaration to which this expression refers.
2594 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2595 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2596 ValueDecl *getMemberDecl() const { return MemberDecl; }
2597 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2599 /// Retrieves the declaration found by lookup.
2600 DeclAccessPair getFoundDecl() const {
2601 if (!HasQualifierOrFoundDecl)
2602 return DeclAccessPair::make(getMemberDecl(),
2603 getMemberDecl()->getAccess());
2604 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2607 /// Determines whether this member expression actually had
2608 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2610 bool hasQualifier() const { return getQualifier() != nullptr; }
2612 /// If the member name was qualified, retrieves the
2613 /// nested-name-specifier that precedes the member name, with source-location
2615 NestedNameSpecifierLoc getQualifierLoc() const {
2616 if (!HasQualifierOrFoundDecl)
2617 return NestedNameSpecifierLoc();
2619 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2622 /// If the member name was qualified, retrieves the
2623 /// nested-name-specifier that precedes the member name. Otherwise, returns
2625 NestedNameSpecifier *getQualifier() const {
2626 return getQualifierLoc().getNestedNameSpecifier();
2629 /// Retrieve the location of the template keyword preceding
2630 /// the member name, if any.
2631 SourceLocation getTemplateKeywordLoc() const {
2632 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2633 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2636 /// Retrieve the location of the left angle bracket starting the
2637 /// explicit template argument list following the member name, if any.
2638 SourceLocation getLAngleLoc() const {
2639 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2640 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2643 /// Retrieve the location of the right angle bracket ending the
2644 /// explicit template argument list following the member name, if any.
2645 SourceLocation getRAngleLoc() const {
2646 if (!HasTemplateKWAndArgsInfo) return SourceLocation();
2647 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2650 /// Determines whether the member name was preceded by the template keyword.
2651 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2653 /// Determines whether the member name was followed by an
2654 /// explicit template argument list.
2655 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2657 /// Copies the template arguments (if present) into the given
2659 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2660 if (hasExplicitTemplateArgs())
2661 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2662 getTrailingObjects<TemplateArgumentLoc>(), List);
2665 /// Retrieve the template arguments provided as part of this
2667 const TemplateArgumentLoc *getTemplateArgs() const {
2668 if (!hasExplicitTemplateArgs())
2671 return getTrailingObjects<TemplateArgumentLoc>();
2674 /// Retrieve the number of template arguments provided as part of this
2676 unsigned getNumTemplateArgs() const {
2677 if (!hasExplicitTemplateArgs())
2680 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2683 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2684 return {getTemplateArgs(), getNumTemplateArgs()};
2687 /// Retrieve the member declaration name info.
2688 DeclarationNameInfo getMemberNameInfo() const {
2689 return DeclarationNameInfo(MemberDecl->getDeclName(),
2690 MemberLoc, MemberDNLoc);
2693 SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2695 bool isArrow() const { return IsArrow; }
2696 void setArrow(bool A) { IsArrow = A; }
2698 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2699 /// location of 'F'.
2700 SourceLocation getMemberLoc() const { return MemberLoc; }
2701 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2703 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2704 SourceLocation getBeginLoc() const LLVM_READONLY;
2705 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2706 SourceLocation getEndLoc() const LLVM_READONLY;
2708 SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2710 /// Determine whether the base of this explicit is implicit.
2711 bool isImplicitAccess() const {
2712 return getBase() && getBase()->isImplicitCXXThis();
2715 /// Returns true if this member expression refers to a method that
2716 /// was resolved from an overloaded set having size greater than 1.
2717 bool hadMultipleCandidates() const {
2718 return HadMultipleCandidates;
2720 /// Sets the flag telling whether this expression refers to
2721 /// a method that was resolved from an overloaded set having size
2723 void setHadMultipleCandidates(bool V = true) {
2724 HadMultipleCandidates = V;
2727 /// Returns true if virtual dispatch is performed.
2728 /// If the member access is fully qualified, (i.e. X::f()), virtual
2729 /// dispatching is not performed. In -fapple-kext mode qualified
2730 /// calls to virtual method will still go through the vtable.
2731 bool performsVirtualDispatch(const LangOptions &LO) const {
2732 return LO.AppleKext || !hasQualifier();
2735 static bool classof(const Stmt *T) {
2736 return T->getStmtClass() == MemberExprClass;
2740 child_range children() { return child_range(&Base, &Base+1); }
2741 const_child_range children() const {
2742 return const_child_range(&Base, &Base + 1);
2745 friend TrailingObjects;
2746 friend class ASTReader;
2747 friend class ASTStmtWriter;
2750 /// CompoundLiteralExpr - [C99 6.5.2.5]
2752 class CompoundLiteralExpr : public Expr {
2753 /// LParenLoc - If non-null, this is the location of the left paren in a
2754 /// compound literal like "(int){4}". This can be null if this is a
2755 /// synthesized compound expression.
2756 SourceLocation LParenLoc;
2758 /// The type as written. This can be an incomplete array type, in
2759 /// which case the actual expression type will be different.
2760 /// The int part of the pair stores whether this expr is file scope.
2761 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2764 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2765 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2766 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2767 tinfo->getType()->isDependentType(),
2768 init->isValueDependent(),
2769 (init->isInstantiationDependent() ||
2770 tinfo->getType()->isInstantiationDependentType()),
2771 init->containsUnexpandedParameterPack()),
2772 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2774 /// Construct an empty compound literal.
2775 explicit CompoundLiteralExpr(EmptyShell Empty)
2776 : Expr(CompoundLiteralExprClass, Empty) { }
2778 const Expr *getInitializer() const { return cast<Expr>(Init); }
2779 Expr *getInitializer() { return cast<Expr>(Init); }
2780 void setInitializer(Expr *E) { Init = E; }
2782 bool isFileScope() const { return TInfoAndScope.getInt(); }
2783 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2785 SourceLocation getLParenLoc() const { return LParenLoc; }
2786 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2788 TypeSourceInfo *getTypeSourceInfo() const {
2789 return TInfoAndScope.getPointer();
2791 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2792 TInfoAndScope.setPointer(tinfo);
2795 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
2796 SourceLocation getBeginLoc() const LLVM_READONLY {
2797 // FIXME: Init should never be null.
2799 return SourceLocation();
2800 if (LParenLoc.isInvalid())
2801 return Init->getLocStart();
2804 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2805 SourceLocation getEndLoc() const LLVM_READONLY {
2806 // FIXME: Init should never be null.
2808 return SourceLocation();
2809 return Init->getLocEnd();
2812 static bool classof(const Stmt *T) {
2813 return T->getStmtClass() == CompoundLiteralExprClass;
2817 child_range children() { return child_range(&Init, &Init+1); }
2818 const_child_range children() const {
2819 return const_child_range(&Init, &Init + 1);
2823 /// CastExpr - Base class for type casts, including both implicit
2824 /// casts (ImplicitCastExpr) and explicit casts that have some
2825 /// representation in the source code (ExplicitCastExpr's derived
2827 class CastExpr : public Expr {
2829 using BasePathSizeTy = unsigned int;
2830 static_assert(std::numeric_limits<BasePathSizeTy>::max() >= 16384,
2831 "[implimits] Direct and indirect base classes [16384].");
2836 bool CastConsistency() const;
2838 BasePathSizeTy *BasePathSize();
2840 const CXXBaseSpecifier * const *path_buffer() const {
2841 return const_cast<CastExpr*>(this)->path_buffer();
2843 CXXBaseSpecifier **path_buffer();
2845 void setBasePathSize(BasePathSizeTy basePathSize) {
2846 assert(!path_empty() && basePathSize != 0);
2847 *(BasePathSize()) = basePathSize;
2851 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2852 Expr *op, unsigned BasePathSize)
2853 : Expr(SC, ty, VK, OK_Ordinary,
2854 // Cast expressions are type-dependent if the type is
2855 // dependent (C++ [temp.dep.expr]p3).
2856 ty->isDependentType(),
2857 // Cast expressions are value-dependent if the type is
2858 // dependent or if the subexpression is value-dependent.
2859 ty->isDependentType() || (op && op->isValueDependent()),
2860 (ty->isInstantiationDependentType() ||
2861 (op && op->isInstantiationDependent())),
2862 // An implicit cast expression doesn't (lexically) contain an
2863 // unexpanded pack, even if its target type does.
2864 ((SC != ImplicitCastExprClass &&
2865 ty->containsUnexpandedParameterPack()) ||
2866 (op && op->containsUnexpandedParameterPack()))),
2868 CastExprBits.Kind = kind;
2869 CastExprBits.PartOfExplicitCast = false;
2870 CastExprBits.BasePathIsEmpty = BasePathSize == 0;
2872 setBasePathSize(BasePathSize);
2873 assert(CastConsistency());
2876 /// Construct an empty cast.
2877 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2879 CastExprBits.PartOfExplicitCast = false;
2880 CastExprBits.BasePathIsEmpty = BasePathSize == 0;
2882 setBasePathSize(BasePathSize);
2886 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2887 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2889 static const char *getCastKindName(CastKind CK);
2890 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
2892 Expr *getSubExpr() { return cast<Expr>(Op); }
2893 const Expr *getSubExpr() const { return cast<Expr>(Op); }
2894 void setSubExpr(Expr *E) { Op = E; }
2896 /// Retrieve the cast subexpression as it was written in the source
2897 /// code, looking through any implicit casts or other intermediate nodes
2898 /// introduced by semantic analysis.
2899 Expr *getSubExprAsWritten();
2900 const Expr *getSubExprAsWritten() const {
2901 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2904 /// If this cast applies a user-defined conversion, retrieve the conversion
2905 /// function that it invokes.
2906 NamedDecl *getConversionFunction() const;
2908 typedef CXXBaseSpecifier **path_iterator;
2909 typedef const CXXBaseSpecifier * const *path_const_iterator;
2910 bool path_empty() const { return CastExprBits.BasePathIsEmpty; }
2911 unsigned path_size() const {
2914 return *(const_cast<CastExpr *>(this)->BasePathSize());
2916 path_iterator path_begin() { return path_buffer(); }
2917 path_iterator path_end() { return path_buffer() + path_size(); }
2918 path_const_iterator path_begin() const { return path_buffer(); }
2919 path_const_iterator path_end() const { return path_buffer() + path_size(); }
2921 const FieldDecl *getTargetUnionField() const {
2922 assert(getCastKind() == CK_ToUnion);
2923 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2926 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2928 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2931 static bool classof(const Stmt *T) {
2932 return T->getStmtClass() >= firstCastExprConstant &&
2933 T->getStmtClass() <= lastCastExprConstant;
2937 child_range children() { return child_range(&Op, &Op+1); }
2938 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2941 /// ImplicitCastExpr - Allows us to explicitly represent implicit type
2942 /// conversions, which have no direct representation in the original
2943 /// source code. For example: converting T[]->T*, void f()->void
2944 /// (*f)(), float->double, short->int, etc.
2946 /// In C, implicit casts always produce rvalues. However, in C++, an
2947 /// implicit cast whose result is being bound to a reference will be
2948 /// an lvalue or xvalue. For example:
2952 /// class Derived : public Base { };
2953 /// Derived &&ref();
2954 /// void f(Derived d) {
2955 /// Base& b = d; // initializer is an ImplicitCastExpr
2956 /// // to an lvalue of type Base
2957 /// Base&& r = ref(); // initializer is an ImplicitCastExpr
2958 /// // to an xvalue of type Base
2961 class ImplicitCastExpr final
2963 private llvm::TrailingObjects<ImplicitCastExpr, CastExpr::BasePathSizeTy,
2964 CXXBaseSpecifier *> {
2965 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
2966 return path_empty() ? 0 : 1;
2970 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2971 unsigned BasePathLength, ExprValueKind VK)
2972 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2975 /// Construct an empty implicit cast.
2976 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2977 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2980 enum OnStack_t { OnStack };
2981 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2983 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2986 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
2987 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
2988 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
2991 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2992 CastKind Kind, Expr *Operand,
2993 const CXXCastPath *BasePath,
2996 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2999 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3000 SourceLocation getBeginLoc() const LLVM_READONLY {
3001 return getSubExpr()->getLocStart();
3003 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3004 SourceLocation getEndLoc() const LLVM_READONLY {
3005 return getSubExpr()->getLocEnd();
3008 static bool classof(const Stmt *T) {
3009 return T->getStmtClass() == ImplicitCastExprClass;
3012 friend TrailingObjects;
3013 friend class CastExpr;
3016 inline Expr *Expr::IgnoreImpCasts() {
3018 while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3019 e = ice->getSubExpr();
3023 /// ExplicitCastExpr - An explicit cast written in the source
3026 /// This class is effectively an abstract class, because it provides
3027 /// the basic representation of an explicitly-written cast without
3028 /// specifying which kind of cast (C cast, functional cast, static
3029 /// cast, etc.) was written; specific derived classes represent the
3030 /// particular style of cast and its location information.
3032 /// Unlike implicit casts, explicit cast nodes have two different
3033 /// types: the type that was written into the source code, and the
3034 /// actual type of the expression as determined by semantic
3035 /// analysis. These types may differ slightly. For example, in C++ one
3036 /// can cast to a reference type, which indicates that the resulting
3037 /// expression will be an lvalue or xvalue. The reference type, however,
3038 /// will not be used as the type of the expression.
3039 class ExplicitCastExpr : public CastExpr {
3040 /// TInfo - Source type info for the (written) type
3041 /// this expression is casting to.
3042 TypeSourceInfo *TInfo;
3045 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3046 CastKind kind, Expr *op, unsigned PathSize,
3047 TypeSourceInfo *writtenTy)
3048 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
3050 /// Construct an empty explicit cast.
3051 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
3052 : CastExpr(SC, Shell, PathSize) { }
3055 /// getTypeInfoAsWritten - Returns the type source info for the type
3056 /// that this expression is casting to.
3057 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3058 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3060 /// getTypeAsWritten - Returns the type that this expression is
3061 /// casting to, as written in the source code.
3062 QualType getTypeAsWritten() const { return TInfo->getType(); }
3064 static bool classof(const Stmt *T) {
3065 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3066 T->getStmtClass() <= lastExplicitCastExprConstant;
3070 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3071 /// cast in C++ (C++ [expr.cast]), which uses the syntax
3072 /// (Type)expr. For example: @c (int)f.
3073 class CStyleCastExpr final
3074 : public ExplicitCastExpr,
3075 private llvm::TrailingObjects<CStyleCastExpr, CastExpr::BasePathSizeTy,
3076 CXXBaseSpecifier *> {
3077 SourceLocation LPLoc; // the location of the left paren
3078 SourceLocation RPLoc; // the location of the right paren
3080 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3081 unsigned PathSize, TypeSourceInfo *writtenTy,
3082 SourceLocation l, SourceLocation r)
3083 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3084 writtenTy), LPLoc(l), RPLoc(r) {}
3086 /// Construct an empty C-style explicit cast.
3087 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3088 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
3090 size_t numTrailingObjects(OverloadToken<CastExpr::BasePathSizeTy>) const {
3091 return path_empty() ? 0 : 1;
3095 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3096 ExprValueKind VK, CastKind K,
3097 Expr *Op, const CXXCastPath *BasePath,
3098 TypeSourceInfo *WrittenTy, SourceLocation L,
3101 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3104 SourceLocation getLParenLoc() const { return LPLoc; }
3105 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3107 SourceLocation getRParenLoc() const { return RPLoc; }
3108 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3110 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3111 SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3112 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3113 SourceLocation getEndLoc() const LLVM_READONLY {
3114 return getSubExpr()->getLocEnd();
3117 static bool classof(const Stmt *T) {
3118 return T->getStmtClass() == CStyleCastExprClass;
3121 friend TrailingObjects;
3122 friend class CastExpr;
3125 /// A builtin binary operation expression such as "x + y" or "x <= y".
3127 /// This expression node kind describes a builtin binary operation,
3128 /// such as "x + y" for integer values "x" and "y". The operands will
3129 /// already have been converted to appropriate types (e.g., by
3130 /// performing promotions or conversions).
3132 /// In C++, where operators may be overloaded, a different kind of
3133 /// expression node (CXXOperatorCallExpr) is used to express the
3134 /// invocation of an overloaded operator with operator syntax. Within
3135 /// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3136 /// used to store an expression "x + y" depends on the subexpressions
3137 /// for x and y. If neither x or y is type-dependent, and the "+"
3138 /// operator resolves to a built-in operation, BinaryOperator will be
3139 /// used to express the computation (x and y may still be
3140 /// value-dependent). If either x or y is type-dependent, or if the
3141 /// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3142 /// be used to express the computation.
3143 class BinaryOperator : public Expr {
3145 typedef BinaryOperatorKind Opcode;
3150 // This is only meaningful for operations on floating point types and 0
3152 unsigned FPFeatures : 2;
3153 SourceLocation OpLoc;
3155 enum { LHS, RHS, END_EXPR };
3156 Stmt* SubExprs[END_EXPR];
3159 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3160 ExprValueKind VK, ExprObjectKind OK,
3161 SourceLocation opLoc, FPOptions FPFeatures)
3162 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3163 lhs->isTypeDependent() || rhs->isTypeDependent(),
3164 lhs->isValueDependent() || rhs->isValueDependent(),
3165 (lhs->isInstantiationDependent() ||
3166 rhs->isInstantiationDependent()),
3167 (lhs->containsUnexpandedParameterPack() ||
3168 rhs->containsUnexpandedParameterPack())),
3169 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3170 SubExprs[LHS] = lhs;
3171 SubExprs[RHS] = rhs;
3172 assert(!isCompoundAssignmentOp() &&
3173 "Use CompoundAssignOperator for compound assignments");
3176 /// Construct an empty binary operator.
3177 explicit BinaryOperator(EmptyShell Empty)
3178 : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
3180 SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
3181 SourceLocation getOperatorLoc() const { return OpLoc; }
3182 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3184 Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3185 void setOpcode(Opcode O) { Opc = O; }
3187 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3188 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3189 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3190 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3192 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3193 SourceLocation getBeginLoc() const LLVM_READONLY {
3194 return getLHS()->getLocStart();
3196 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3197 SourceLocation getEndLoc() const LLVM_READONLY {
3198 return getRHS()->getLocEnd();
3201 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3202 /// corresponds to, e.g. "<<=".
3203 static StringRef getOpcodeStr(Opcode Op);
3205 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3207 /// Retrieve the binary opcode that corresponds to the given
3208 /// overloaded operator.
3209 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3211 /// Retrieve the overloaded operator kind that corresponds to
3212 /// the given binary opcode.
3213 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3215 /// predicates to categorize the respective opcodes.
3216 bool isPtrMemOp() const { return Opc == BO_PtrMemD || Opc == BO_PtrMemI; }
3217 static bool isMultiplicativeOp(Opcode Opc) {
3218 return Opc >= BO_Mul && Opc <= BO_Rem;
3220 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3221 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3222 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3223 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3224 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3226 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3227 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3229 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3230 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3232 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3233 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3235 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3236 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3238 static Opcode negateComparisonOp(Opcode Opc) {
3241 llvm_unreachable("Not a comparison operator.");
3242 case BO_LT: return BO_GE;
3243 case BO_GT: return BO_LE;
3244 case BO_LE: return BO_GT;
3245 case BO_GE: return BO_LT;
3246 case BO_EQ: return BO_NE;
3247 case BO_NE: return BO_EQ;
3251 static Opcode reverseComparisonOp(Opcode Opc) {
3254 llvm_unreachable("Not a comparison operator.");
3255 case BO_LT: return BO_GT;
3256 case BO_GT: return BO_LT;
3257 case BO_LE: return BO_GE;
3258 case BO_GE: return BO_LE;
3265 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3266 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3268 static bool isAssignmentOp(Opcode Opc) {
3269 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3271 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3273 static bool isCompoundAssignmentOp(Opcode Opc) {
3274 return Opc > BO_Assign && Opc <= BO_OrAssign;
3276 bool isCompoundAssignmentOp() const {
3277 return isCompoundAssignmentOp(getOpcode());
3279 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3280 assert(isCompoundAssignmentOp(Opc));
3281 if (Opc >= BO_AndAssign)
3282 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3284 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3287 static bool isShiftAssignOp(Opcode Opc) {
3288 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3290 bool isShiftAssignOp() const {
3291 return isShiftAssignOp(getOpcode());
3294 // Return true if a binary operator using the specified opcode and operands
3295 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3296 // integer to a pointer.
3297 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3298 Expr *LHS, Expr *RHS);
3300 static bool classof(const Stmt *S) {
3301 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3302 S->getStmtClass() <= lastBinaryOperatorConstant;
3306 child_range children() {
3307 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3309 const_child_range children() const {
3310 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3313 // Set the FP contractability status of this operator. Only meaningful for
3314 // operations on floating point types.
3315 void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3317 FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3319 // Get the FP contractability status of this operator. Only meaningful for
3320 // operations on floating point types.
3321 bool isFPContractableWithinStatement() const {
3322 return FPOptions(FPFeatures).allowFPContractWithinStatement();
3326 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3327 ExprValueKind VK, ExprObjectKind OK,
3328 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3329 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3330 lhs->isTypeDependent() || rhs->isTypeDependent(),
3331 lhs->isValueDependent() || rhs->isValueDependent(),
3332 (lhs->isInstantiationDependent() ||
3333 rhs->isInstantiationDependent()),
3334 (lhs->containsUnexpandedParameterPack() ||
3335 rhs->containsUnexpandedParameterPack())),
3336 Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3337 SubExprs[LHS] = lhs;
3338 SubExprs[RHS] = rhs;
3341 BinaryOperator(StmtClass SC, EmptyShell Empty)
3342 : Expr(SC, Empty), Opc(BO_MulAssign) { }
3345 /// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3346 /// track of the type the operation is performed in. Due to the semantics of
3347 /// these operators, the operands are promoted, the arithmetic performed, an
3348 /// implicit conversion back to the result type done, then the assignment takes
3349 /// place. This captures the intermediate type which the computation is done
3351 class CompoundAssignOperator : public BinaryOperator {
3352 QualType ComputationLHSType;
3353 QualType ComputationResultType;
3355 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3356 ExprValueKind VK, ExprObjectKind OK,
3357 QualType CompLHSType, QualType CompResultType,
3358 SourceLocation OpLoc, FPOptions FPFeatures)
3359 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3361 ComputationLHSType(CompLHSType),
3362 ComputationResultType(CompResultType) {
3363 assert(isCompoundAssignmentOp() &&
3364 "Only should be used for compound assignments");
3367 /// Build an empty compound assignment operator expression.
3368 explicit CompoundAssignOperator(EmptyShell Empty)
3369 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3371 // The two computation types are the type the LHS is converted
3372 // to for the computation and the type of the result; the two are
3373 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3374 QualType getComputationLHSType() const { return ComputationLHSType; }
3375 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3377 QualType getComputationResultType() const { return ComputationResultType; }
3378 void setComputationResultType(QualType T) { ComputationResultType = T; }
3380 static bool classof(const Stmt *S) {
3381 return S->getStmtClass() == CompoundAssignOperatorClass;
3385 /// AbstractConditionalOperator - An abstract base class for
3386 /// ConditionalOperator and BinaryConditionalOperator.
3387 class AbstractConditionalOperator : public Expr {
3388 SourceLocation QuestionLoc, ColonLoc;
3389 friend class ASTStmtReader;
3392 AbstractConditionalOperator(StmtClass SC, QualType T,
3393 ExprValueKind VK, ExprObjectKind OK,
3394 bool TD, bool VD, bool ID,
3395 bool ContainsUnexpandedParameterPack,
3396 SourceLocation qloc,
3397 SourceLocation cloc)
3398 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3399 QuestionLoc(qloc), ColonLoc(cloc) {}
3401 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3402 : Expr(SC, Empty) { }
3405 // getCond - Return the expression representing the condition for
3407 Expr *getCond() const;
3409 // getTrueExpr - Return the subexpression representing the value of
3410 // the expression if the condition evaluates to true.
3411 Expr *getTrueExpr() const;
3413 // getFalseExpr - Return the subexpression representing the value of
3414 // the expression if the condition evaluates to false. This is
3415 // the same as getRHS.
3416 Expr *getFalseExpr() const;
3418 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3419 SourceLocation getColonLoc() const { return ColonLoc; }
3421 static bool classof(const Stmt *T) {
3422 return T->getStmtClass() == ConditionalOperatorClass ||
3423 T->getStmtClass() == BinaryConditionalOperatorClass;
3427 /// ConditionalOperator - The ?: ternary operator. The GNU "missing
3428 /// middle" extension is a BinaryConditionalOperator.
3429 class ConditionalOperator : public AbstractConditionalOperator {
3430 enum { COND, LHS, RHS, END_EXPR };
3431 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3433 friend class ASTStmtReader;
3435 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3436 SourceLocation CLoc, Expr *rhs,
3437 QualType t, ExprValueKind VK, ExprObjectKind OK)
3438 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3439 // FIXME: the type of the conditional operator doesn't
3440 // depend on the type of the conditional, but the standard
3441 // seems to imply that it could. File a bug!
3442 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3443 (cond->isValueDependent() || lhs->isValueDependent() ||
3444 rhs->isValueDependent()),
3445 (cond->isInstantiationDependent() ||
3446 lhs->isInstantiationDependent() ||
3447 rhs->isInstantiationDependent()),
3448 (cond->containsUnexpandedParameterPack() ||
3449 lhs->containsUnexpandedParameterPack() ||
3450 rhs->containsUnexpandedParameterPack()),
3452 SubExprs[COND] = cond;
3453 SubExprs[LHS] = lhs;
3454 SubExprs[RHS] = rhs;
3457 /// Build an empty conditional operator.
3458 explicit ConditionalOperator(EmptyShell Empty)
3459 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3461 // getCond - Return the expression representing the condition for
3463 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3465 // getTrueExpr - Return the subexpression representing the value of
3466 // the expression if the condition evaluates to true.
3467 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3469 // getFalseExpr - Return the subexpression representing the value of
3470 // the expression if the condition evaluates to false. This is
3471 // the same as getRHS.
3472 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3474 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3475 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3477 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3478 SourceLocation getBeginLoc() const LLVM_READONLY {
3479 return getCond()->getLocStart();
3481 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3482 SourceLocation getEndLoc() const LLVM_READONLY {
3483 return getRHS()->getLocEnd();
3486 static bool classof(const Stmt *T) {
3487 return T->getStmtClass() == ConditionalOperatorClass;
3491 child_range children() {
3492 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3494 const_child_range children() const {
3495 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3499 /// BinaryConditionalOperator - The GNU extension to the conditional
3500 /// operator which allows the middle operand to be omitted.
3502 /// This is a different expression kind on the assumption that almost
3503 /// every client ends up needing to know that these are different.
3504 class BinaryConditionalOperator : public AbstractConditionalOperator {
3505 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3507 /// - the common condition/left-hand-side expression, which will be
3508 /// evaluated as the opaque value
3509 /// - the condition, expressed in terms of the opaque value
3510 /// - the left-hand-side, expressed in terms of the opaque value
3511 /// - the right-hand-side
3512 Stmt *SubExprs[NUM_SUBEXPRS];
3513 OpaqueValueExpr *OpaqueValue;
3515 friend class ASTStmtReader;
3517 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3518 Expr *cond, Expr *lhs, Expr *rhs,
3519 SourceLocation qloc, SourceLocation cloc,
3520 QualType t, ExprValueKind VK, ExprObjectKind OK)
3521 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3522 (common->isTypeDependent() || rhs->isTypeDependent()),
3523 (common->isValueDependent() || rhs->isValueDependent()),
3524 (common->isInstantiationDependent() ||
3525 rhs->isInstantiationDependent()),
3526 (common->containsUnexpandedParameterPack() ||
3527 rhs->containsUnexpandedParameterPack()),
3529 OpaqueValue(opaqueValue) {
3530 SubExprs[COMMON] = common;
3531 SubExprs[COND] = cond;
3532 SubExprs[LHS] = lhs;
3533 SubExprs[RHS] = rhs;
3534 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3537 /// Build an empty conditional operator.
3538 explicit BinaryConditionalOperator(EmptyShell Empty)
3539 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3541 /// getCommon - Return the common expression, written to the
3542 /// left of the condition. The opaque value will be bound to the
3543 /// result of this expression.
3544 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3546 /// getOpaqueValue - Return the opaque value placeholder.
3547 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3549 /// getCond - Return the condition expression; this is defined
3550 /// in terms of the opaque value.
3551 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3553 /// getTrueExpr - Return the subexpression which will be
3554 /// evaluated if the condition evaluates to true; this is defined
3555 /// in terms of the opaque value.
3556 Expr *getTrueExpr() const {
3557 return cast<Expr>(SubExprs[LHS]);
3560 /// getFalseExpr - Return the subexpression which will be
3561 /// evaluated if the condnition evaluates to false; this is
3562 /// defined in terms of the opaque value.
3563 Expr *getFalseExpr() const {
3564 return cast<Expr>(SubExprs[RHS]);
3567 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3568 SourceLocation getBeginLoc() const LLVM_READONLY {
3569 return getCommon()->getLocStart();
3571 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3572 SourceLocation getEndLoc() const LLVM_READONLY {
3573 return getFalseExpr()->getLocEnd();
3576 static bool classof(const Stmt *T) {
3577 return T->getStmtClass() == BinaryConditionalOperatorClass;
3581 child_range children() {
3582 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3584 const_child_range children() const {
3585 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3589 inline Expr *AbstractConditionalOperator::getCond() const {
3590 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3591 return co->getCond();
3592 return cast<BinaryConditionalOperator>(this)->getCond();
3595 inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3596 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3597 return co->getTrueExpr();
3598 return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3601 inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3602 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3603 return co->getFalseExpr();
3604 return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3607 /// AddrLabelExpr - The GNU address of label extension, representing &&label.
3608 class AddrLabelExpr : public Expr {
3609 SourceLocation AmpAmpLoc, LabelLoc;
3612 AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3614 : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3616 AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3618 /// Build an empty address of a label expression.
3619 explicit AddrLabelExpr(EmptyShell Empty)
3620 : Expr(AddrLabelExprClass, Empty) { }
3622 SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3623 void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3624 SourceLocation getLabelLoc() const { return LabelLoc; }
3625 void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3627 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3628 SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
3629 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3630 SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
3632 LabelDecl *getLabel() const { return Label; }
3633 void setLabel(LabelDecl *L) { Label = L; }
3635 static bool classof(const Stmt *T) {
3636 return T->getStmtClass() == AddrLabelExprClass;
3640 child_range children() {
3641 return child_range(child_iterator(), child_iterator());
3643 const_child_range children() const {
3644 return const_child_range(const_child_iterator(), const_child_iterator());
3648 /// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3649 /// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3650 /// takes the value of the last subexpression.
3652 /// A StmtExpr is always an r-value; values "returned" out of a
3653 /// StmtExpr will be copied.
3654 class StmtExpr : public Expr {
3656 SourceLocation LParenLoc, RParenLoc;
3658 // FIXME: Does type-dependence need to be computed differently?
3659 // FIXME: Do we need to compute instantiation instantiation-dependence for
3660 // statements? (ugh!)
3661 StmtExpr(CompoundStmt *substmt, QualType T,
3662 SourceLocation lp, SourceLocation rp) :
3663 Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3664 T->isDependentType(), false, false, false),
3665 SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3667 /// Build an empty statement expression.
3668 explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3670 CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3671 const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3672 void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3674 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3675 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
3676 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3677 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3679 SourceLocation getLParenLoc() const { return LParenLoc; }
3680 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3681 SourceLocation getRParenLoc() const { return RParenLoc; }
3682 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3684 static bool classof(const Stmt *T) {
3685 return T->getStmtClass() == StmtExprClass;
3689 child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3690 const_child_range children() const {
3691 return const_child_range(&SubStmt, &SubStmt + 1);
3695 /// ShuffleVectorExpr - clang-specific builtin-in function
3696 /// __builtin_shufflevector.
3697 /// This AST node represents a operator that does a constant
3698 /// shuffle, similar to LLVM's shufflevector instruction. It takes
3699 /// two vectors and a variable number of constant indices,
3700 /// and returns the appropriately shuffled vector.
3701 class ShuffleVectorExpr : public Expr {
3702 SourceLocation BuiltinLoc, RParenLoc;
3704 // SubExprs - the list of values passed to the __builtin_shufflevector
3705 // function. The first two are vectors, and the rest are constant
3706 // indices. The number of values in this list is always
3707 // 2+the number of indices in the vector type.
3712 ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3713 SourceLocation BLoc, SourceLocation RP);
3715 /// Build an empty vector-shuffle expression.
3716 explicit ShuffleVectorExpr(EmptyShell Empty)
3717 : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3719 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3720 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3722 SourceLocation getRParenLoc() const { return RParenLoc; }
3723 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3725 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3726 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
3727 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3728 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3730 static bool classof(const Stmt *T) {
3731 return T->getStmtClass() == ShuffleVectorExprClass;
3734 /// getNumSubExprs - Return the size of the SubExprs array. This includes the
3735 /// constant expression, the actual arguments passed in, and the function
3737 unsigned getNumSubExprs() const { return NumExprs; }
3739 /// Retrieve the array of expressions.
3740 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3742 /// getExpr - Return the Expr at the specified index.
3743 Expr *getExpr(unsigned Index) {
3744 assert((Index < NumExprs) && "Arg access out of range!");
3745 return cast<Expr>(SubExprs[Index]);
3747 const Expr *getExpr(unsigned Index) const {
3748 assert((Index < NumExprs) && "Arg access out of range!");
3749 return cast<Expr>(SubExprs[Index]);
3752 void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3754 llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3755 assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3756 return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3760 child_range children() {
3761 return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3763 const_child_range children() const {
3764 return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
3768 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3769 /// This AST node provides support for converting a vector type to another
3770 /// vector type of the same arity.
3771 class ConvertVectorExpr : public Expr {
3774 TypeSourceInfo *TInfo;
3775 SourceLocation BuiltinLoc, RParenLoc;
3777 friend class ASTReader;
3778 friend class ASTStmtReader;
3779 explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3782 ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3783 ExprValueKind VK, ExprObjectKind OK,
3784 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3785 : Expr(ConvertVectorExprClass, DstType, VK, OK,
3786 DstType->isDependentType(),
3787 DstType->isDependentType() || SrcExpr->isValueDependent(),
3788 (DstType->isInstantiationDependentType() ||
3789 SrcExpr->isInstantiationDependent()),
3790 (DstType->containsUnexpandedParameterPack() ||
3791 SrcExpr->containsUnexpandedParameterPack())),
3792 SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3794 /// getSrcExpr - Return the Expr to be converted.
3795 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3797 /// getTypeSourceInfo - Return the destination type.
3798 TypeSourceInfo *getTypeSourceInfo() const {
3801 void setTypeSourceInfo(TypeSourceInfo *ti) {
3805 /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3806 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3808 /// getRParenLoc - Return the location of final right parenthesis.
3809 SourceLocation getRParenLoc() const { return RParenLoc; }
3811 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3812 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
3813 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3814 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3816 static bool classof(const Stmt *T) {
3817 return T->getStmtClass() == ConvertVectorExprClass;
3821 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3822 const_child_range children() const {
3823 return const_child_range(&SrcExpr, &SrcExpr + 1);
3827 /// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3828 /// This AST node is similar to the conditional operator (?:) in C, with
3829 /// the following exceptions:
3830 /// - the test expression must be a integer constant expression.
3831 /// - the expression returned acts like the chosen subexpression in every
3832 /// visible way: the type is the same as that of the chosen subexpression,
3833 /// and all predicates (whether it's an l-value, whether it's an integer
3834 /// constant expression, etc.) return the same result as for the chosen
3836 class ChooseExpr : public Expr {
3837 enum { COND, LHS, RHS, END_EXPR };
3838 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3839 SourceLocation BuiltinLoc, RParenLoc;
3842 ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3843 QualType t, ExprValueKind VK, ExprObjectKind OK,
3844 SourceLocation RP, bool condIsTrue,
3845 bool TypeDependent, bool ValueDependent)
3846 : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3847 (cond->isInstantiationDependent() ||
3848 lhs->isInstantiationDependent() ||
3849 rhs->isInstantiationDependent()),
3850 (cond->containsUnexpandedParameterPack() ||
3851 lhs->containsUnexpandedParameterPack() ||
3852 rhs->containsUnexpandedParameterPack())),
3853 BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3854 SubExprs[COND] = cond;
3855 SubExprs[LHS] = lhs;
3856 SubExprs[RHS] = rhs;
3859 /// Build an empty __builtin_choose_expr.
3860 explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3862 /// isConditionTrue - Return whether the condition is true (i.e. not
3864 bool isConditionTrue() const {
3865 assert(!isConditionDependent() &&
3866 "Dependent condition isn't true or false");
3869 void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3871 bool isConditionDependent() const {
3872 return getCond()->isTypeDependent() || getCond()->isValueDependent();
3875 /// getChosenSubExpr - Return the subexpression chosen according to the
3877 Expr *getChosenSubExpr() const {
3878 return isConditionTrue() ? getLHS() : getRHS();
3881 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3882 void setCond(Expr *E) { SubExprs[COND] = E; }
3883 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3884 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3885 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3886 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3888 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3889 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3891 SourceLocation getRParenLoc() const { return RParenLoc; }
3892 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3894 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3895 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
3896 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3897 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3899 static bool classof(const Stmt *T) {
3900 return T->getStmtClass() == ChooseExprClass;
3904 child_range children() {
3905 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3907 const_child_range children() const {
3908 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3912 /// GNUNullExpr - Implements the GNU __null extension, which is a name
3913 /// for a null pointer constant that has integral type (e.g., int or
3914 /// long) and is the same size and alignment as a pointer. The __null
3915 /// extension is typically only used by system headers, which define
3916 /// NULL as __null in C++ rather than using 0 (which is an integer
3917 /// that may not match the size of a pointer).
3918 class GNUNullExpr : public Expr {
3919 /// TokenLoc - The location of the __null keyword.
3920 SourceLocation TokenLoc;
3923 GNUNullExpr(QualType Ty, SourceLocation Loc)
3924 : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3928 /// Build an empty GNU __null expression.
3929 explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3931 /// getTokenLocation - The location of the __null token.
3932 SourceLocation getTokenLocation() const { return TokenLoc; }
3933 void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3935 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3936 SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
3937 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3938 SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
3940 static bool classof(const Stmt *T) {
3941 return T->getStmtClass() == GNUNullExprClass;
3945 child_range children() {
3946 return child_range(child_iterator(), child_iterator());
3948 const_child_range children() const {
3949 return const_child_range(const_child_iterator(), const_child_iterator());
3953 /// Represents a call to the builtin function \c __builtin_va_arg.
3954 class VAArgExpr : public Expr {
3956 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3957 SourceLocation BuiltinLoc, RParenLoc;
3959 VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3960 SourceLocation RPLoc, QualType t, bool IsMS)
3961 : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3962 false, (TInfo->getType()->isInstantiationDependentType() ||
3963 e->isInstantiationDependent()),
3964 (TInfo->getType()->containsUnexpandedParameterPack() ||
3965 e->containsUnexpandedParameterPack())),
3966 Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3968 /// Create an empty __builtin_va_arg expression.
3969 explicit VAArgExpr(EmptyShell Empty)
3970 : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3972 const Expr *getSubExpr() const { return cast<Expr>(Val); }
3973 Expr *getSubExpr() { return cast<Expr>(Val); }
3974 void setSubExpr(Expr *E) { Val = E; }
3976 /// Returns whether this is really a Win64 ABI va_arg expression.
3977 bool isMicrosoftABI() const { return TInfo.getInt(); }
3978 void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3980 TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3981 void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3983 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3984 void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3986 SourceLocation getRParenLoc() const { return RParenLoc; }
3987 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3989 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
3990 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
3991 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
3992 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
3994 static bool classof(const Stmt *T) {
3995 return T->getStmtClass() == VAArgExprClass;
3999 child_range children() { return child_range(&Val, &Val+1); }
4000 const_child_range children() const {
4001 return const_child_range(&Val, &Val + 1);
4005 /// Describes an C or C++ initializer list.
4007 /// InitListExpr describes an initializer list, which can be used to
4008 /// initialize objects of different types, including
4009 /// struct/class/union types, arrays, and vectors. For example:
4012 /// struct foo x = { 1, { 2, 3 } };
4015 /// Prior to semantic analysis, an initializer list will represent the
4016 /// initializer list as written by the user, but will have the
4017 /// placeholder type "void". This initializer list is called the
4018 /// syntactic form of the initializer, and may contain C99 designated
4019 /// initializers (represented as DesignatedInitExprs), initializations
4020 /// of subobject members without explicit braces, and so on. Clients
4021 /// interested in the original syntax of the initializer list should
4022 /// use the syntactic form of the initializer list.
4024 /// After semantic analysis, the initializer list will represent the
4025 /// semantic form of the initializer, where the initializations of all
4026 /// subobjects are made explicit with nested InitListExpr nodes and
4027 /// C99 designators have been eliminated by placing the designated
4028 /// initializations into the subobject they initialize. Additionally,
4029 /// any "holes" in the initialization, where no initializer has been
4030 /// specified for a particular subobject, will be replaced with
4031 /// implicitly-generated ImplicitValueInitExpr expressions that
4032 /// value-initialize the subobjects. Note, however, that the
4033 /// initializer lists may still have fewer initializers than there are
4034 /// elements to initialize within the object.
4036 /// After semantic analysis has completed, given an initializer list,
4037 /// method isSemanticForm() returns true if and only if this is the
4038 /// semantic form of the initializer list (note: the same AST node
4039 /// may at the same time be the syntactic form).
4040 /// Given the semantic form of the initializer list, one can retrieve
4041 /// the syntactic form of that initializer list (when different)
4042 /// using method getSyntacticForm(); the method returns null if applied
4043 /// to a initializer list which is already in syntactic form.
4044 /// Similarly, given the syntactic form (i.e., an initializer list such
4045 /// that isSemanticForm() returns false), one can retrieve the semantic
4046 /// form using method getSemanticForm().
4047 /// Since many initializer lists have the same syntactic and semantic forms,
4048 /// getSyntacticForm() may return NULL, indicating that the current
4049 /// semantic initializer list also serves as its syntactic form.
4050 class InitListExpr : public Expr {
4051 // FIXME: Eliminate this vector in favor of ASTContext allocation
4052 typedef ASTVector<Stmt *> InitExprsTy;
4053 InitExprsTy InitExprs;
4054 SourceLocation LBraceLoc, RBraceLoc;
4056 /// The alternative form of the initializer list (if it exists).
4057 /// The int part of the pair stores whether this initializer list is
4058 /// in semantic form. If not null, the pointer points to:
4059 /// - the syntactic form, if this is in semantic form;
4060 /// - the semantic form, if this is in syntactic form.
4061 llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4064 /// If this initializer list initializes an array with more elements than
4065 /// there are initializers in the list, specifies an expression to be used
4066 /// for value initialization of the rest of the elements.
4068 /// If this initializer list initializes a union, specifies which
4069 /// field within the union will be initialized.
4070 llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4073 InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4074 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4076 /// Build an empty initializer list.
4077 explicit InitListExpr(EmptyShell Empty)
4078 : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4080 unsigned getNumInits() const { return InitExprs.size(); }
4082 /// Retrieve the set of initializers.
4083 Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4085 /// Retrieve the set of initializers.
4086 Expr * const *getInits() const {
4087 return reinterpret_cast<Expr * const *>(InitExprs.data());
4090 ArrayRef<Expr *> inits() {
4091 return llvm::makeArrayRef(getInits(), getNumInits());
4094 ArrayRef<Expr *> inits() const {
4095 return llvm::makeArrayRef(getInits(), getNumInits());
4098 const Expr *getInit(unsigned Init) const {
4099 assert(Init < getNumInits() && "Initializer access out of range!");
4100 return cast_or_null<Expr>(InitExprs[Init]);
4103 Expr *getInit(unsigned Init) {
4104 assert(Init < getNumInits() && "Initializer access out of range!");
4105 return cast_or_null<Expr>(InitExprs[Init]);
4108 void setInit(unsigned Init, Expr *expr) {
4109 assert(Init < getNumInits() && "Initializer access out of range!");
4110 InitExprs[Init] = expr;
4113 ExprBits.TypeDependent |= expr->isTypeDependent();
4114 ExprBits.ValueDependent |= expr->isValueDependent();
4115 ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
4116 ExprBits.ContainsUnexpandedParameterPack |=
4117 expr->containsUnexpandedParameterPack();
4121 /// Reserve space for some number of initializers.
4122 void reserveInits(const ASTContext &C, unsigned NumInits);
4124 /// Specify the number of initializers
4126 /// If there are more than @p NumInits initializers, the remaining
4127 /// initializers will be destroyed. If there are fewer than @p
4128 /// NumInits initializers, NULL expressions will be added for the
4129 /// unknown initializers.
4130 void resizeInits(const ASTContext &Context, unsigned NumInits);
4132 /// Updates the initializer at index @p Init with the new
4133 /// expression @p expr, and returns the old expression at that
4136 /// When @p Init is out of range for this initializer list, the
4137 /// initializer list will be extended with NULL expressions to
4138 /// accommodate the new entry.
4139 Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4141 /// If this initializer list initializes an array with more elements
4142 /// than there are initializers in the list, specifies an expression to be
4143 /// used for value initialization of the rest of the elements.
4144 Expr *getArrayFiller() {
4145 return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4147 const Expr *getArrayFiller() const {
4148 return const_cast<InitListExpr *>(this)->getArrayFiller();
4150 void setArrayFiller(Expr *filler);
4152 /// Return true if this is an array initializer and its array "filler"
4154 bool hasArrayFiller() const { return getArrayFiller(); }
4156 /// If this initializes a union, specifies which field in the
4157 /// union to initialize.
4159 /// Typically, this field is the first named field within the
4160 /// union. However, a designated initializer can specify the
4161 /// initialization of a different field within the union.
4162 FieldDecl *getInitializedFieldInUnion() {
4163 return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4165 const FieldDecl *getInitializedFieldInUnion() const {
4166 return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4168 void setInitializedFieldInUnion(FieldDecl *FD) {
4169 assert((FD == nullptr
4170 || getInitializedFieldInUnion() == nullptr
4171 || getInitializedFieldInUnion() == FD)
4172 && "Only one field of a union may be initialized at a time!");
4173 ArrayFillerOrUnionFieldInit = FD;
4176 // Explicit InitListExpr's originate from source code (and have valid source
4177 // locations). Implicit InitListExpr's are created by the semantic analyzer.
4178 bool isExplicit() const {
4179 return LBraceLoc.isValid() && RBraceLoc.isValid();
4182 // Is this an initializer for an array of characters, initialized by a string
4183 // literal or an @encode?
4184 bool isStringLiteralInit() const;
4186 /// Is this a transparent initializer list (that is, an InitListExpr that is
4187 /// purely syntactic, and whose semantics are that of the sole contained
4189 bool isTransparent() const;
4191 /// Is this the zero initializer {0} in a language which considers it
4193 bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4195 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4196 void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4197 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4198 void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4200 bool isSemanticForm() const { return AltForm.getInt(); }
4201 InitListExpr *getSemanticForm() const {
4202 return isSemanticForm() ? nullptr : AltForm.getPointer();
4204 bool isSyntacticForm() const {
4205 return !AltForm.getInt() || !AltForm.getPointer();
4207 InitListExpr *getSyntacticForm() const {
4208 return isSemanticForm() ? AltForm.getPointer() : nullptr;
4211 void setSyntacticForm(InitListExpr *Init) {
4212 AltForm.setPointer(Init);
4213 AltForm.setInt(true);
4214 Init->AltForm.setPointer(this);
4215 Init->AltForm.setInt(false);
4218 bool hadArrayRangeDesignator() const {
4219 return InitListExprBits.HadArrayRangeDesignator != 0;
4221 void sawArrayRangeDesignator(bool ARD = true) {
4222 InitListExprBits.HadArrayRangeDesignator = ARD;
4225 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4226 SourceLocation getBeginLoc() const LLVM_READONLY;
4227 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4228 SourceLocation getEndLoc() const LLVM_READONLY;
4230 static bool classof(const Stmt *T) {
4231 return T->getStmtClass() == InitListExprClass;
4235 child_range children() {
4236 const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4237 return child_range(cast_away_const(CCR.begin()),
4238 cast_away_const(CCR.end()));
4241 const_child_range children() const {
4242 // FIXME: This does not include the array filler expression.
4243 if (InitExprs.empty())
4244 return const_child_range(const_child_iterator(), const_child_iterator());
4245 return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4248 typedef InitExprsTy::iterator iterator;
4249 typedef InitExprsTy::const_iterator const_iterator;
4250 typedef InitExprsTy::reverse_iterator reverse_iterator;
4251 typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4253 iterator begin() { return InitExprs.begin(); }
4254 const_iterator begin() const { return InitExprs.begin(); }
4255 iterator end() { return InitExprs.end(); }
4256 const_iterator end() const { return InitExprs.end(); }
4257 reverse_iterator rbegin() { return InitExprs.rbegin(); }
4258 const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4259 reverse_iterator rend() { return InitExprs.rend(); }
4260 const_reverse_iterator rend() const { return InitExprs.rend(); }
4262 friend class ASTStmtReader;
4263 friend class ASTStmtWriter;
4266 /// Represents a C99 designated initializer expression.
4268 /// A designated initializer expression (C99 6.7.8) contains one or
4269 /// more designators (which can be field designators, array
4270 /// designators, or GNU array-range designators) followed by an
4271 /// expression that initializes the field or element(s) that the
4272 /// designators refer to. For example, given:
4279 /// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4282 /// The InitListExpr contains three DesignatedInitExprs, the first of
4283 /// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4284 /// designators, one array designator for @c [2] followed by one field
4285 /// designator for @c .y. The initialization expression will be 1.0.
4286 class DesignatedInitExpr final
4288 private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4290 /// Forward declaration of the Designator class.
4294 /// The location of the '=' or ':' prior to the actual initializer
4296 SourceLocation EqualOrColonLoc;
4298 /// Whether this designated initializer used the GNU deprecated
4299 /// syntax rather than the C99 '=' syntax.
4300 unsigned GNUSyntax : 1;
4302 /// The number of designators in this initializer expression.
4303 unsigned NumDesignators : 15;
4305 /// The number of subexpressions of this initializer expression,
4306 /// which contains both the initializer and any additional
4307 /// expressions used by array and array-range designators.
4308 unsigned NumSubExprs : 16;
4310 /// The designators in this designated initialization
4312 Designator *Designators;
4314 DesignatedInitExpr(const ASTContext &C, QualType Ty,
4315 llvm::ArrayRef<Designator> Designators,
4316 SourceLocation EqualOrColonLoc, bool GNUSyntax,
4317 ArrayRef<Expr *> IndexExprs, Expr *Init);
4319 explicit DesignatedInitExpr(unsigned NumSubExprs)
4320 : Expr(DesignatedInitExprClass, EmptyShell()),
4321 NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4324 /// A field designator, e.g., ".x".
4325 struct FieldDesignator {
4326 /// Refers to the field that is being initialized. The low bit
4327 /// of this field determines whether this is actually a pointer
4328 /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4329 /// initially constructed, a field designator will store an
4330 /// IdentifierInfo*. After semantic analysis has resolved that
4331 /// name, the field designator will instead store a FieldDecl*.
4332 uintptr_t NameOrField;
4334 /// The location of the '.' in the designated initializer.
4337 /// The location of the field name in the designated initializer.
4341 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4342 struct ArrayOrRangeDesignator {
4343 /// Location of the first index expression within the designated
4344 /// initializer expression's list of subexpressions.
4346 /// The location of the '[' starting the array range designator.
4347 unsigned LBracketLoc;
4348 /// The location of the ellipsis separating the start and end
4349 /// indices. Only valid for GNU array-range designators.
4350 unsigned EllipsisLoc;
4351 /// The location of the ']' terminating the array range designator.
4352 unsigned RBracketLoc;
4355 /// Represents a single C99 designator.
4357 /// @todo This class is infuriatingly similar to clang::Designator,
4358 /// but minor differences (storing indices vs. storing pointers)
4359 /// keep us from reusing it. Try harder, later, to rectify these
4362 /// The kind of designator this describes.
4366 ArrayRangeDesignator
4370 /// A field designator, e.g., ".x".
4371 struct FieldDesignator Field;
4372 /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4373 struct ArrayOrRangeDesignator ArrayOrRange;
4375 friend class DesignatedInitExpr;
4380 /// Initializes a field designator.
4381 Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4382 SourceLocation FieldLoc)
4383 : Kind(FieldDesignator) {
4384 Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4385 Field.DotLoc = DotLoc.getRawEncoding();
4386 Field.FieldLoc = FieldLoc.getRawEncoding();
4389 /// Initializes an array designator.
4390 Designator(unsigned Index, SourceLocation LBracketLoc,
4391 SourceLocation RBracketLoc)
4392 : Kind(ArrayDesignator) {
4393 ArrayOrRange.Index = Index;
4394 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4395 ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4396 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4399 /// Initializes a GNU array-range designator.
4400 Designator(unsigned Index, SourceLocation LBracketLoc,
4401 SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4402 : Kind(ArrayRangeDesignator) {
4403 ArrayOrRange.Index = Index;
4404 ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4405 ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4406 ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4409 bool isFieldDesignator() const { return Kind == FieldDesignator; }
4410 bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4411 bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4413 IdentifierInfo *getFieldName() const;
4415 FieldDecl *getField() const {
4416 assert(Kind == FieldDesignator && "Only valid on a field designator");
4417 if (Field.NameOrField & 0x01)
4420 return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4423 void setField(FieldDecl *FD) {
4424 assert(Kind == FieldDesignator && "Only valid on a field designator");
4425 Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4428 SourceLocation getDotLoc() const {
4429 assert(Kind == FieldDesignator && "Only valid on a field designator");
4430 return SourceLocation::getFromRawEncoding(Field.DotLoc);
4433 SourceLocation getFieldLoc() const {
4434 assert(Kind == FieldDesignator && "Only valid on a field designator");
4435 return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4438 SourceLocation getLBracketLoc() const {
4439 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4440 "Only valid on an array or array-range designator");
4441 return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4444 SourceLocation getRBracketLoc() const {
4445 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4446 "Only valid on an array or array-range designator");
4447 return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4450 SourceLocation getEllipsisLoc() const {
4451 assert(Kind == ArrayRangeDesignator &&
4452 "Only valid on an array-range designator");
4453 return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4456 unsigned getFirstExprIndex() const {
4457 assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4458 "Only valid on an array or array-range designator");
4459 return ArrayOrRange.Index;
4462 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4463 SourceLocation getBeginLoc() const LLVM_READONLY {
4464 if (Kind == FieldDesignator)
4465 return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
4467 return getLBracketLoc();
4469 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4470 SourceLocation getEndLoc() const LLVM_READONLY {
4471 return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
4473 SourceRange getSourceRange() const LLVM_READONLY {
4474 return SourceRange(getLocStart(), getLocEnd());
4478 static DesignatedInitExpr *Create(const ASTContext &C,
4479 llvm::ArrayRef<Designator> Designators,
4480 ArrayRef<Expr*> IndexExprs,
4481 SourceLocation EqualOrColonLoc,
4482 bool GNUSyntax, Expr *Init);
4484 static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4485 unsigned NumIndexExprs);
4487 /// Returns the number of designators in this initializer.
4488 unsigned size() const { return NumDesignators; }
4490 // Iterator access to the designators.
4491 llvm::MutableArrayRef<Designator> designators() {
4492 return {Designators, NumDesignators};
4495 llvm::ArrayRef<Designator> designators() const {
4496 return {Designators, NumDesignators};
4499 Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4500 const Designator *getDesignator(unsigned Idx) const {
4501 return &designators()[Idx];
4504 void setDesignators(const ASTContext &C, const Designator *Desigs,
4505 unsigned NumDesigs);
4507 Expr *getArrayIndex(const Designator &D) const;
4508 Expr *getArrayRangeStart(const Designator &D) const;
4509 Expr *getArrayRangeEnd(const Designator &D) const;
4511 /// Retrieve the location of the '=' that precedes the
4512 /// initializer value itself, if present.
4513 SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4514 void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4516 /// Determines whether this designated initializer used the
4517 /// deprecated GNU syntax for designated initializers.
4518 bool usesGNUSyntax() const { return GNUSyntax; }
4519 void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4521 /// Retrieve the initializer value.
4522 Expr *getInit() const {
4523 return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4526 void setInit(Expr *init) {
4527 *child_begin() = init;
4530 /// Retrieve the total number of subexpressions in this
4531 /// designated initializer expression, including the actual
4532 /// initialized value and any expressions that occur within array
4533 /// and array-range designators.
4534 unsigned getNumSubExprs() const { return NumSubExprs; }
4536 Expr *getSubExpr(unsigned Idx) const {
4537 assert(Idx < NumSubExprs && "Subscript out of range");
4538 return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4541 void setSubExpr(unsigned Idx, Expr *E) {
4542 assert(Idx < NumSubExprs && "Subscript out of range");
4543 getTrailingObjects<Stmt *>()[Idx] = E;
4546 /// Replaces the designator at index @p Idx with the series
4547 /// of designators in [First, Last).
4548 void ExpandDesignator(const ASTContext &C, unsigned Idx,
4549 const Designator *First, const Designator *Last);
4551 SourceRange getDesignatorsSourceRange() const;
4553 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4554 SourceLocation getBeginLoc() const LLVM_READONLY;
4555 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4556 SourceLocation getEndLoc() const LLVM_READONLY;
4558 static bool classof(const Stmt *T) {
4559 return T->getStmtClass() == DesignatedInitExprClass;
4563 child_range children() {
4564 Stmt **begin = getTrailingObjects<Stmt *>();
4565 return child_range(begin, begin + NumSubExprs);
4567 const_child_range children() const {
4568 Stmt * const *begin = getTrailingObjects<Stmt *>();
4569 return const_child_range(begin, begin + NumSubExprs);
4572 friend TrailingObjects;
4575 /// Represents a place-holder for an object not to be initialized by
4578 /// This only makes sense when it appears as part of an updater of a
4579 /// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4580 /// initializes a big object, and the NoInitExpr's mark the spots within the
4581 /// big object not to be overwritten by the updater.
4583 /// \see DesignatedInitUpdateExpr
4584 class NoInitExpr : public Expr {
4586 explicit NoInitExpr(QualType ty)
4587 : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4588 false, false, ty->isInstantiationDependentType(), false) { }
4590 explicit NoInitExpr(EmptyShell Empty)
4591 : Expr(NoInitExprClass, Empty) { }
4593 static bool classof(const Stmt *T) {
4594 return T->getStmtClass() == NoInitExprClass;
4597 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4598 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
4599 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4600 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
4603 child_range children() {
4604 return child_range(child_iterator(), child_iterator());
4606 const_child_range children() const {
4607 return const_child_range(const_child_iterator(), const_child_iterator());
4612 // struct Q { int a, b, c; };
4615 // struct A { Q q; } a = { *getQ(), .q.b = 3 };
4618 // We will have an InitListExpr for a, with type A, and then a
4619 // DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4620 // is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4622 class DesignatedInitUpdateExpr : public Expr {
4623 // BaseAndUpdaterExprs[0] is the base expression;
4624 // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4625 Stmt *BaseAndUpdaterExprs[2];
4628 DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4629 Expr *baseExprs, SourceLocation rBraceLoc);
4631 explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4632 : Expr(DesignatedInitUpdateExprClass, Empty) { }
4634 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4635 SourceLocation getBeginLoc() const LLVM_READONLY;
4636 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4637 SourceLocation getEndLoc() const LLVM_READONLY;
4639 static bool classof(const Stmt *T) {
4640 return T->getStmtClass() == DesignatedInitUpdateExprClass;
4643 Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4644 void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4646 InitListExpr *getUpdater() const {
4647 return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4649 void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4652 // children = the base and the updater
4653 child_range children() {
4654 return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4656 const_child_range children() const {
4657 return const_child_range(&BaseAndUpdaterExprs[0],
4658 &BaseAndUpdaterExprs[0] + 2);
4662 /// Represents a loop initializing the elements of an array.
4664 /// The need to initialize the elements of an array occurs in a number of
4667 /// * in the implicit copy/move constructor for a class with an array member
4668 /// * when a lambda-expression captures an array by value
4669 /// * when a decomposition declaration decomposes an array
4671 /// There are two subexpressions: a common expression (the source array)
4672 /// that is evaluated once up-front, and a per-element initializer that
4673 /// runs once for each array element.
4675 /// Within the per-element initializer, the common expression may be referenced
4676 /// via an OpaqueValueExpr, and the current index may be obtained via an
4677 /// ArrayInitIndexExpr.
4678 class ArrayInitLoopExpr : public Expr {
4681 explicit ArrayInitLoopExpr(EmptyShell Empty)
4682 : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4685 explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4686 : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4687 CommonInit->isValueDependent() || ElementInit->isValueDependent(),
4688 T->isInstantiationDependentType(),
4689 CommonInit->containsUnexpandedParameterPack() ||
4690 ElementInit->containsUnexpandedParameterPack()),
4691 SubExprs{CommonInit, ElementInit} {}
4693 /// Get the common subexpression shared by all initializations (the source
4695 OpaqueValueExpr *getCommonExpr() const {
4696 return cast<OpaqueValueExpr>(SubExprs[0]);
4699 /// Get the initializer to use for each array element.
4700 Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
4702 llvm::APInt getArraySize() const {
4703 return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
4707 static bool classof(const Stmt *S) {
4708 return S->getStmtClass() == ArrayInitLoopExprClass;
4711 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4712 SourceLocation getBeginLoc() const LLVM_READONLY {
4713 return getCommonExpr()->getLocStart();
4715 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4716 SourceLocation getEndLoc() const LLVM_READONLY {
4717 return getCommonExpr()->getLocEnd();
4720 child_range children() {
4721 return child_range(SubExprs, SubExprs + 2);
4723 const_child_range children() const {
4724 return const_child_range(SubExprs, SubExprs + 2);
4727 friend class ASTReader;
4728 friend class ASTStmtReader;
4729 friend class ASTStmtWriter;
4732 /// Represents the index of the current element of an array being
4733 /// initialized by an ArrayInitLoopExpr. This can only appear within the
4734 /// subexpression of an ArrayInitLoopExpr.
4735 class ArrayInitIndexExpr : public Expr {
4736 explicit ArrayInitIndexExpr(EmptyShell Empty)
4737 : Expr(ArrayInitIndexExprClass, Empty) {}
4740 explicit ArrayInitIndexExpr(QualType T)
4741 : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
4742 false, false, false, false) {}
4744 static bool classof(const Stmt *S) {
4745 return S->getStmtClass() == ArrayInitIndexExprClass;
4748 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4749 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
4750 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4751 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
4753 child_range children() {
4754 return child_range(child_iterator(), child_iterator());
4756 const_child_range children() const {
4757 return const_child_range(const_child_iterator(), const_child_iterator());
4760 friend class ASTReader;
4761 friend class ASTStmtReader;
4764 /// Represents an implicitly-generated value initialization of
4765 /// an object of a given type.
4767 /// Implicit value initializations occur within semantic initializer
4768 /// list expressions (InitListExpr) as placeholders for subobject
4769 /// initializations not explicitly specified by the user.
4771 /// \see InitListExpr
4772 class ImplicitValueInitExpr : public Expr {
4774 explicit ImplicitValueInitExpr(QualType ty)
4775 : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4776 false, false, ty->isInstantiationDependentType(), false) { }
4778 /// Construct an empty implicit value initialization.
4779 explicit ImplicitValueInitExpr(EmptyShell Empty)
4780 : Expr(ImplicitValueInitExprClass, Empty) { }
4782 static bool classof(const Stmt *T) {
4783 return T->getStmtClass() == ImplicitValueInitExprClass;
4786 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4787 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
4788 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4789 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
4792 child_range children() {
4793 return child_range(child_iterator(), child_iterator());
4795 const_child_range children() const {
4796 return const_child_range(const_child_iterator(), const_child_iterator());
4800 class ParenListExpr : public Expr {
4803 SourceLocation LParenLoc, RParenLoc;
4806 ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4807 ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4809 /// Build an empty paren list.
4810 explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4812 unsigned getNumExprs() const { return NumExprs; }
4814 const Expr* getExpr(unsigned Init) const {
4815 assert(Init < getNumExprs() && "Initializer access out of range!");
4816 return cast_or_null<Expr>(Exprs[Init]);
4819 Expr* getExpr(unsigned Init) {
4820 assert(Init < getNumExprs() && "Initializer access out of range!");
4821 return cast_or_null<Expr>(Exprs[Init]);
4824 Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4826 ArrayRef<Expr *> exprs() {
4827 return llvm::makeArrayRef(getExprs(), getNumExprs());
4830 SourceLocation getLParenLoc() const { return LParenLoc; }
4831 SourceLocation getRParenLoc() const { return RParenLoc; }
4833 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4834 SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
4835 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4836 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4838 static bool classof(const Stmt *T) {
4839 return T->getStmtClass() == ParenListExprClass;
4843 child_range children() {
4844 return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4846 const_child_range children() const {
4847 return const_child_range(&Exprs[0], &Exprs[0] + NumExprs);
4850 friend class ASTStmtReader;
4851 friend class ASTStmtWriter;
4854 /// Represents a C11 generic selection.
4856 /// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4857 /// expression, followed by one or more generic associations. Each generic
4858 /// association specifies a type name and an expression, or "default" and an
4859 /// expression (in which case it is known as a default generic association).
4860 /// The type and value of the generic selection are identical to those of its
4861 /// result expression, which is defined as the expression in the generic
4862 /// association with a type name that is compatible with the type of the
4863 /// controlling expression, or the expression in the default generic association
4864 /// if no types are compatible. For example:
4867 /// _Generic(X, double: 1, float: 2, default: 3)
4870 /// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4871 /// or 3 if "hello".
4873 /// As an extension, generic selections are allowed in C++, where the following
4874 /// additional semantics apply:
4876 /// Any generic selection whose controlling expression is type-dependent or
4877 /// which names a dependent type in its association list is result-dependent,
4878 /// which means that the choice of result expression is dependent.
4879 /// Result-dependent generic associations are both type- and value-dependent.
4880 class GenericSelectionExpr : public Expr {
4881 enum { CONTROLLING, END_EXPR };
4882 TypeSourceInfo **AssocTypes;
4884 unsigned NumAssocs, ResultIndex;
4885 SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4888 GenericSelectionExpr(const ASTContext &Context,
4889 SourceLocation GenericLoc, Expr *ControllingExpr,
4890 ArrayRef<TypeSourceInfo*> AssocTypes,
4891 ArrayRef<Expr*> AssocExprs,
4892 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4893 bool ContainsUnexpandedParameterPack,
4894 unsigned ResultIndex);
4896 /// This constructor is used in the result-dependent case.
4897 GenericSelectionExpr(const ASTContext &Context,
4898 SourceLocation GenericLoc, Expr *ControllingExpr,
4899 ArrayRef<TypeSourceInfo*> AssocTypes,
4900 ArrayRef<Expr*> AssocExprs,
4901 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4902 bool ContainsUnexpandedParameterPack);
4904 explicit GenericSelectionExpr(EmptyShell Empty)
4905 : Expr(GenericSelectionExprClass, Empty) { }
4907 unsigned getNumAssocs() const { return NumAssocs; }
4909 SourceLocation getGenericLoc() const { return GenericLoc; }
4910 SourceLocation getDefaultLoc() const { return DefaultLoc; }
4911 SourceLocation getRParenLoc() const { return RParenLoc; }
4913 const Expr *getAssocExpr(unsigned i) const {
4914 return cast<Expr>(SubExprs[END_EXPR+i]);
4916 Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4917 ArrayRef<Expr *> getAssocExprs() const {
4919 ? llvm::makeArrayRef(
4920 &reinterpret_cast<Expr **>(SubExprs)[END_EXPR], NumAssocs)
4923 const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4924 return AssocTypes[i];
4926 TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4927 ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
4928 return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : None;
4931 QualType getAssocType(unsigned i) const {
4932 if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4933 return TS->getType();
4938 const Expr *getControllingExpr() const {
4939 return cast<Expr>(SubExprs[CONTROLLING]);
4941 Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4943 /// Whether this generic selection is result-dependent.
4944 bool isResultDependent() const { return ResultIndex == -1U; }
4946 /// The zero-based index of the result expression's generic association in
4947 /// the generic selection's association list. Defined only if the
4948 /// generic selection is not result-dependent.
4949 unsigned getResultIndex() const {
4950 assert(!isResultDependent() && "Generic selection is result-dependent");
4954 /// The generic selection's result expression. Defined only if the
4955 /// generic selection is not result-dependent.
4956 const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4957 Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4959 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
4960 SourceLocation getBeginLoc() const LLVM_READONLY { return GenericLoc; }
4961 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
4962 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4964 static bool classof(const Stmt *T) {
4965 return T->getStmtClass() == GenericSelectionExprClass;
4968 child_range children() {
4969 return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4971 const_child_range children() const {
4972 return const_child_range(SubExprs, SubExprs + END_EXPR + NumAssocs);
4974 friend class ASTStmtReader;
4977 //===----------------------------------------------------------------------===//
4979 //===----------------------------------------------------------------------===//
4981 /// ExtVectorElementExpr - This represents access to specific elements of a
4982 /// vector, and may occur on the left hand side or right hand side. For example
4983 /// the following is legal: "V.xy = V.zw" if V is a 4 element extended vector.
4985 /// Note that the base may have either vector or pointer to vector type, just
4986 /// like a struct field reference.
4988 class ExtVectorElementExpr : public Expr {
4990 IdentifierInfo *Accessor;
4991 SourceLocation AccessorLoc;
4993 ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4994 IdentifierInfo &accessor, SourceLocation loc)
4995 : Expr(ExtVectorElementExprClass, ty, VK,
4996 (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4997 base->isTypeDependent(), base->isValueDependent(),
4998 base->isInstantiationDependent(),
4999 base->containsUnexpandedParameterPack()),
5000 Base(base), Accessor(&accessor), AccessorLoc(loc) {}
5002 /// Build an empty vector element expression.
5003 explicit ExtVectorElementExpr(EmptyShell Empty)
5004 : Expr(ExtVectorElementExprClass, Empty) { }
5006 const Expr *getBase() const { return cast<Expr>(Base); }
5007 Expr *getBase() { return cast<Expr>(Base); }
5008 void setBase(Expr *E) { Base = E; }
5010 IdentifierInfo &getAccessor() const { return *Accessor; }
5011 void setAccessor(IdentifierInfo *II) { Accessor = II; }
5013 SourceLocation getAccessorLoc() const { return AccessorLoc; }
5014 void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
5016 /// getNumElements - Get the number of components being selected.
5017 unsigned getNumElements() const;
5019 /// containsDuplicateElements - Return true if any element access is
5021 bool containsDuplicateElements() const;
5023 /// getEncodedElementAccess - Encode the elements accessed into an llvm
5024 /// aggregate Constant of ConstantInt(s).
5025 void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
5027 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
5028 SourceLocation getBeginLoc() const LLVM_READONLY {
5029 return getBase()->getLocStart();
5031 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
5032 SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
5034 /// isArrow - Return true if the base expression is a pointer to vector,
5035 /// return false if the base expression is a vector.
5036 bool isArrow() const;
5038 static bool classof(const Stmt *T) {
5039 return T->getStmtClass() == ExtVectorElementExprClass;
5043 child_range children() { return child_range(&Base, &Base+1); }
5044 const_child_range children() const {
5045 return const_child_range(&Base, &Base + 1);
5049 /// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
5050 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
5051 class BlockExpr : public Expr {
5053 BlockDecl *TheBlock;
5055 BlockExpr(BlockDecl *BD, QualType ty)
5056 : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
5057 ty->isDependentType(), ty->isDependentType(),
5058 ty->isInstantiationDependentType() || BD->isDependentContext(),
5062 /// Build an empty block expression.
5063 explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
5065 const BlockDecl *getBlockDecl() const { return TheBlock; }
5066 BlockDecl *getBlockDecl() { return TheBlock; }
5067 void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
5069 // Convenience functions for probing the underlying BlockDecl.
5070 SourceLocation getCaretLocation() const;
5071 const Stmt *getBody() const;
5074 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
5075 SourceLocation getBeginLoc() const LLVM_READONLY {
5076 return getCaretLocation();
5078 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
5079 SourceLocation getEndLoc() const LLVM_READONLY {
5080 return getBody()->getLocEnd();
5083 /// getFunctionType - Return the underlying function type for this block.
5084 const FunctionProtoType *getFunctionType() const;
5086 static bool classof(const Stmt *T) {
5087 return T->getStmtClass() == BlockExprClass;
5091 child_range children() {
5092 return child_range(child_iterator(), child_iterator());
5094 const_child_range children() const {
5095 return const_child_range(const_child_iterator(), const_child_iterator());
5099 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
5100 /// This AST node provides support for reinterpreting a type to another
5101 /// type of the same size.
5102 class AsTypeExpr : public Expr {
5105 SourceLocation BuiltinLoc, RParenLoc;
5107 friend class ASTReader;
5108 friend class ASTStmtReader;
5109 explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
5112 AsTypeExpr(Expr* SrcExpr, QualType DstType,
5113 ExprValueKind VK, ExprObjectKind OK,
5114 SourceLocation BuiltinLoc, SourceLocation RParenLoc)
5115 : Expr(AsTypeExprClass, DstType, VK, OK,
5116 DstType->isDependentType(),
5117 DstType->isDependentType() || SrcExpr->isValueDependent(),
5118 (DstType->isInstantiationDependentType() ||
5119 SrcExpr->isInstantiationDependent()),
5120 (DstType->containsUnexpandedParameterPack() ||
5121 SrcExpr->containsUnexpandedParameterPack())),
5122 SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
5124 /// getSrcExpr - Return the Expr to be converted.
5125 Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
5127 /// getBuiltinLoc - Return the location of the __builtin_astype token.
5128 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5130 /// getRParenLoc - Return the location of final right parenthesis.
5131 SourceLocation getRParenLoc() const { return RParenLoc; }
5133 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
5134 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
5135 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
5136 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
5138 static bool classof(const Stmt *T) {
5139 return T->getStmtClass() == AsTypeExprClass;
5143 child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
5144 const_child_range children() const {
5145 return const_child_range(&SrcExpr, &SrcExpr + 1);
5149 /// PseudoObjectExpr - An expression which accesses a pseudo-object
5150 /// l-value. A pseudo-object is an abstract object, accesses to which
5151 /// are translated to calls. The pseudo-object expression has a
5152 /// syntactic form, which shows how the expression was actually
5153 /// written in the source code, and a semantic form, which is a series
5154 /// of expressions to be executed in order which detail how the
5155 /// operation is actually evaluated. Optionally, one of the semantic
5156 /// forms may also provide a result value for the expression.
5158 /// If any of the semantic-form expressions is an OpaqueValueExpr,
5159 /// that OVE is required to have a source expression, and it is bound
5160 /// to the result of that source expression. Such OVEs may appear
5161 /// only in subsequent semantic-form expressions and as
5162 /// sub-expressions of the syntactic form.
5164 /// PseudoObjectExpr should be used only when an operation can be
5165 /// usefully described in terms of fairly simple rewrite rules on
5166 /// objects and functions that are meant to be used by end-developers.
5167 /// For example, under the Itanium ABI, dynamic casts are implemented
5168 /// as a call to a runtime function called __dynamic_cast; using this
5169 /// class to describe that would be inappropriate because that call is
5170 /// not really part of the user-visible semantics, and instead the
5171 /// cast is properly reflected in the AST and IR-generation has been
5172 /// taught to generate the call as necessary. In contrast, an
5173 /// Objective-C property access is semantically defined to be
5174 /// equivalent to a particular message send, and this is very much
5175 /// part of the user model. The name of this class encourages this
5176 /// modelling design.
5177 class PseudoObjectExpr final
5179 private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
5180 // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
5181 // Always at least two, because the first sub-expression is the
5184 // PseudoObjectExprBits.ResultIndex - The index of the
5185 // sub-expression holding the result. 0 means the result is void,
5186 // which is unambiguous because it's the index of the syntactic
5187 // form. Note that this is therefore 1 higher than the value passed
5188 // in to Create, which is an index within the semantic forms.
5189 // Note also that ASTStmtWriter assumes this encoding.
5191 Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
5192 const Expr * const *getSubExprsBuffer() const {
5193 return getTrailingObjects<Expr *>();
5196 PseudoObjectExpr(QualType type, ExprValueKind VK,
5197 Expr *syntactic, ArrayRef<Expr*> semantic,
5198 unsigned resultIndex);
5200 PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
5202 unsigned getNumSubExprs() const {
5203 return PseudoObjectExprBits.NumSubExprs;
5207 /// NoResult - A value for the result index indicating that there is
5208 /// no semantic result.
5209 enum : unsigned { NoResult = ~0U };
5211 static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
5212 ArrayRef<Expr*> semantic,
5213 unsigned resultIndex);
5215 static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
5216 unsigned numSemanticExprs);
5218 /// Return the syntactic form of this expression, i.e. the
5219 /// expression it actually looks like. Likely to be expressed in
5220 /// terms of OpaqueValueExprs bound in the semantic form.
5221 Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
5222 const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
5224 /// Return the index of the result-bearing expression into the semantics
5225 /// expressions, or PseudoObjectExpr::NoResult if there is none.
5226 unsigned getResultExprIndex() const {
5227 if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
5228 return PseudoObjectExprBits.ResultIndex - 1;
5231 /// Return the result-bearing expression, or null if there is none.
5232 Expr *getResultExpr() {
5233 if (PseudoObjectExprBits.ResultIndex == 0)
5235 return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
5237 const Expr *getResultExpr() const {
5238 return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
5241 unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
5243 typedef Expr * const *semantics_iterator;
5244 typedef const Expr * const *const_semantics_iterator;
5245 semantics_iterator semantics_begin() {
5246 return getSubExprsBuffer() + 1;
5248 const_semantics_iterator semantics_begin() const {
5249 return getSubExprsBuffer() + 1;
5251 semantics_iterator semantics_end() {
5252 return getSubExprsBuffer() + getNumSubExprs();
5254 const_semantics_iterator semantics_end() const {
5255 return getSubExprsBuffer() + getNumSubExprs();
5258 llvm::iterator_range<semantics_iterator> semantics() {
5259 return llvm::make_range(semantics_begin(), semantics_end());
5261 llvm::iterator_range<const_semantics_iterator> semantics() const {
5262 return llvm::make_range(semantics_begin(), semantics_end());
5265 Expr *getSemanticExpr(unsigned index) {
5266 assert(index + 1 < getNumSubExprs());
5267 return getSubExprsBuffer()[index + 1];
5269 const Expr *getSemanticExpr(unsigned index) const {
5270 return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
5273 SourceLocation getExprLoc() const LLVM_READONLY {
5274 return getSyntacticForm()->getExprLoc();
5277 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
5278 SourceLocation getBeginLoc() const LLVM_READONLY {
5279 return getSyntacticForm()->getLocStart();
5281 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
5282 SourceLocation getEndLoc() const LLVM_READONLY {
5283 return getSyntacticForm()->getLocEnd();
5286 child_range children() {
5287 const_child_range CCR =
5288 const_cast<const PseudoObjectExpr *>(this)->children();
5289 return child_range(cast_away_const(CCR.begin()),
5290 cast_away_const(CCR.end()));
5292 const_child_range children() const {
5293 Stmt *const *cs = const_cast<Stmt *const *>(
5294 reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
5295 return const_child_range(cs, cs + getNumSubExprs());
5298 static bool classof(const Stmt *T) {
5299 return T->getStmtClass() == PseudoObjectExprClass;
5302 friend TrailingObjects;
5303 friend class ASTStmtReader;
5306 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
5307 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
5308 /// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
5309 /// and corresponding __opencl_atomic_* for OpenCL 2.0.
5310 /// All of these instructions take one primary pointer, at least one memory
5311 /// order. The instructions for which getScopeModel returns non-null value
5312 /// take one synch scope.
5313 class AtomicExpr : public Expr {
5316 #define BUILTIN(ID, TYPE, ATTRS)
5317 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
5318 #include "clang/Basic/Builtins.def"
5319 // Avoid trailing comma
5324 /// Location of sub-expressions.
5325 /// The location of Scope sub-expression is NumSubExprs - 1, which is
5326 /// not fixed, therefore is not defined in enum.
5327 enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
5328 Stmt *SubExprs[END_EXPR + 1];
5329 unsigned NumSubExprs;
5330 SourceLocation BuiltinLoc, RParenLoc;
5333 friend class ASTStmtReader;
5335 AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
5336 AtomicOp op, SourceLocation RP);
5338 /// Determine the number of arguments the specified atomic builtin
5340 static unsigned getNumSubExprs(AtomicOp Op);
5342 /// Build an empty AtomicExpr.
5343 explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
5345 Expr *getPtr() const {
5346 return cast<Expr>(SubExprs[PTR]);
5348 Expr *getOrder() const {
5349 return cast<Expr>(SubExprs[ORDER]);
5351 Expr *getScope() const {
5352 assert(getScopeModel() && "No scope");
5353 return cast<Expr>(SubExprs[NumSubExprs - 1]);
5355 Expr *getVal1() const {
5356 if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
5357 return cast<Expr>(SubExprs[ORDER]);
5358 assert(NumSubExprs > VAL1);
5359 return cast<Expr>(SubExprs[VAL1]);
5361 Expr *getOrderFail() const {
5362 assert(NumSubExprs > ORDER_FAIL);
5363 return cast<Expr>(SubExprs[ORDER_FAIL]);
5365 Expr *getVal2() const {
5366 if (Op == AO__atomic_exchange)
5367 return cast<Expr>(SubExprs[ORDER_FAIL]);
5368 assert(NumSubExprs > VAL2);
5369 return cast<Expr>(SubExprs[VAL2]);
5371 Expr *getWeak() const {
5372 assert(NumSubExprs > WEAK);
5373 return cast<Expr>(SubExprs[WEAK]);
5375 QualType getValueType() const;
5377 AtomicOp getOp() const { return Op; }
5378 unsigned getNumSubExprs() const { return NumSubExprs; }
5380 Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
5381 const Expr * const *getSubExprs() const {
5382 return reinterpret_cast<Expr * const *>(SubExprs);
5385 bool isVolatile() const {
5386 return getPtr()->getType()->getPointeeType().isVolatileQualified();
5389 bool isCmpXChg() const {
5390 return getOp() == AO__c11_atomic_compare_exchange_strong ||
5391 getOp() == AO__c11_atomic_compare_exchange_weak ||
5392 getOp() == AO__opencl_atomic_compare_exchange_strong ||
5393 getOp() == AO__opencl_atomic_compare_exchange_weak ||
5394 getOp() == AO__atomic_compare_exchange ||
5395 getOp() == AO__atomic_compare_exchange_n;
5398 bool isOpenCL() const {
5399 return getOp() >= AO__opencl_atomic_init &&
5400 getOp() <= AO__opencl_atomic_fetch_max;
5403 SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5404 SourceLocation getRParenLoc() const { return RParenLoc; }
5406 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
5407 SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
5408 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
5409 SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
5411 static bool classof(const Stmt *T) {
5412 return T->getStmtClass() == AtomicExprClass;
5416 child_range children() {
5417 return child_range(SubExprs, SubExprs+NumSubExprs);
5419 const_child_range children() const {
5420 return const_child_range(SubExprs, SubExprs + NumSubExprs);
5423 /// Get atomic scope model for the atomic op code.
5424 /// \return empty atomic scope model if the atomic op code does not have
5426 static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
5428 (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
5429 ? AtomicScopeModelKind::OpenCL
5430 : AtomicScopeModelKind::None;
5431 return AtomicScopeModel::create(Kind);
5434 /// Get atomic scope model.
5435 /// \return empty atomic scope model if this atomic expression does not have
5437 std::unique_ptr<AtomicScopeModel> getScopeModel() const {
5438 return getScopeModel(getOp());
5442 /// TypoExpr - Internal placeholder for expressions where typo correction
5443 /// still needs to be performed and/or an error diagnostic emitted.
5444 class TypoExpr : public Expr {
5446 TypoExpr(QualType T)
5447 : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5448 /*isTypeDependent*/ true,
5449 /*isValueDependent*/ true,
5450 /*isInstantiationDependent*/ true,
5451 /*containsUnexpandedParameterPack*/ false) {
5452 assert(T->isDependentType() && "TypoExpr given a non-dependent type");
5455 child_range children() {
5456 return child_range(child_iterator(), child_iterator());
5458 const_child_range children() const {
5459 return const_child_range(const_child_iterator(), const_child_iterator());
5462 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
5463 SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5464 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
5465 SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5467 static bool classof(const Stmt *T) {
5468 return T->getStmtClass() == TypoExprClass;
5472 } // end namespace clang
5474 #endif // LLVM_CLANG_AST_EXPR_H