1 //===- Initialization.h - Semantic Analysis for Initializers ----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file provides supporting data types for initialization of objects.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
14 #define LLVM_CLANG_SEMA_INITIALIZATION_H
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclAccessPair.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/IdentifierTable.h"
24 #include "clang/Basic/LLVM.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/Ownership.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/iterator_range.h"
34 #include "llvm/Support/Casting.h"
42 class CXXBaseSpecifier;
43 class CXXConstructorDecl;
47 /// Describes an entity that is being initialized.
48 class alignas(8) InitializedEntity {
50 /// Specifies the kind of entity being initialized.
52 /// The entity being initialized is a variable.
55 /// The entity being initialized is a function parameter.
58 /// The entity being initialized is the result of a function call.
61 /// The entity being initialized is the result of a statement expression.
64 /// The entity being initialized is an exception object that
68 /// The entity being initialized is a non-static data member
72 /// The entity being initialized is an element of an array.
75 /// The entity being initialized is an object (or array of
76 /// objects) allocated via new.
79 /// The entity being initialized is a temporary object.
82 /// The entity being initialized is a base member subobject.
85 /// The initialization is being done by a delegating constructor.
88 /// The entity being initialized is an element of a vector.
92 /// The entity being initialized is a field of block descriptor for
93 /// the copied-in c++ object.
96 /// The entity being initialized is a field of block descriptor for the
97 /// copied-in lambda object that's used in the lambda to block conversion.
98 EK_LambdaToBlockConversionBlockElement,
100 /// The entity being initialized is the real or imaginary part of a
104 /// The entity being initialized is the field that captures a
105 /// variable in a lambda.
108 /// The entity being initialized is the initializer for a compound
110 EK_CompoundLiteralInit,
112 /// The entity being implicitly initialized back to the formal
116 /// The entity being initialized is a function parameter; function
117 /// is member of group of audited CF APIs.
118 EK_Parameter_CF_Audited,
120 /// The entity being initialized is a structured binding of a
121 /// decomposition declaration.
124 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
125 // enum as an index for its first %select. When modifying this list,
126 // that diagnostic text needs to be updated as well.
130 /// The kind of entity being initialized.
133 /// If non-NULL, the parent entity in which this
134 /// initialization occurs.
135 const InitializedEntity *Parent = nullptr;
137 /// The type of the object or reference being initialized.
140 /// The mangling number for the next reference temporary to be created.
141 mutable unsigned ManglingNumber = 0;
144 /// When Kind == EK_Result, EK_Exception, EK_New, the
145 /// location of the 'return', 'throw', or 'new' keyword,
146 /// respectively. When Kind == EK_Temporary, the location where
147 /// the temporary is being created.
150 /// Whether the entity being initialized may end up using the
151 /// named return value optimization (NRVO).
156 /// The VarDecl, FieldDecl, or BindingDecl being initialized.
157 ValueDecl *VariableOrMember;
159 /// When Kind == EK_Member, whether this is an implicit member
160 /// initialization in a copy or move constructor. These can perform array
162 bool IsImplicitFieldInit;
164 /// When Kind == EK_Member, whether this is the initial initialization
165 /// check for a default member initializer.
166 bool IsDefaultMemberInit;
170 /// The name of the variable being captured by an EK_LambdaCapture.
171 IdentifierInfo *VarID;
173 /// The source location at which the capture occurs.
178 /// When Kind == EK_Variable, EK_Member or EK_Binding, the variable.
181 /// When Kind == EK_RelatedResult, the ObjectiveC method where
182 /// result type was implicitly changed to accommodate ARC semantics.
183 ObjCMethodDecl *MethodDecl;
185 /// When Kind == EK_Parameter, the ParmVarDecl, with the
186 /// low bit indicating whether the parameter is "consumed".
189 /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
190 /// source information for the temporary.
191 TypeSourceInfo *TypeInfo;
193 struct LN LocAndNRVO;
195 /// When Kind == EK_Base, the base specifier that provides the
196 /// base class. The lower bit specifies whether the base is an inherited
200 /// When Kind == EK_ArrayElement, EK_VectorElement, or
201 /// EK_ComplexElement, the index of the array or vector element being
208 InitializedEntity() = default;
210 /// Create the initialization entity for a variable.
211 InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
212 : Kind(EK), Type(Var->getType()), Variable{Var, false, false} {}
214 /// Create the initialization entity for the result of a
215 /// function, throwing an object, performing an explicit cast, or
216 /// initializing a parameter for which there is no declaration.
217 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
219 : Kind(Kind), Type(Type) {
220 LocAndNRVO.Location = Loc.getRawEncoding();
221 LocAndNRVO.NRVO = NRVO;
224 /// Create the initialization entity for a member subobject.
225 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
226 bool Implicit, bool DefaultMemberInit)
227 : Kind(EK_Member), Parent(Parent), Type(Member->getType()),
228 Variable{Member, Implicit, DefaultMemberInit} {}
230 /// Create the initialization entity for an array element.
231 InitializedEntity(ASTContext &Context, unsigned Index,
232 const InitializedEntity &Parent);
234 /// Create the initialization entity for a lambda capture.
235 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
236 : Kind(EK_LambdaCapture), Type(FieldType) {
237 Capture.VarID = VarID;
238 Capture.Location = Loc.getRawEncoding();
242 /// Create the initialization entity for a variable.
243 static InitializedEntity InitializeVariable(VarDecl *Var) {
244 return InitializedEntity(Var);
247 /// Create the initialization entity for a parameter.
248 static InitializedEntity InitializeParameter(ASTContext &Context,
249 const ParmVarDecl *Parm) {
250 return InitializeParameter(Context, Parm, Parm->getType());
253 /// Create the initialization entity for a parameter, but use
255 static InitializedEntity InitializeParameter(ASTContext &Context,
256 const ParmVarDecl *Parm,
258 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
259 Parm->hasAttr<NSConsumedAttr>());
261 InitializedEntity Entity;
262 Entity.Kind = EK_Parameter;
264 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
265 Entity.Parent = nullptr;
267 = (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
271 /// Create the initialization entity for a parameter that is
272 /// only known by its type.
273 static InitializedEntity InitializeParameter(ASTContext &Context,
276 InitializedEntity Entity;
277 Entity.Kind = EK_Parameter;
278 Entity.Type = Context.getVariableArrayDecayedType(Type);
279 Entity.Parent = nullptr;
280 Entity.Parameter = (Consumed);
284 /// Create the initialization entity for the result of a function.
285 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
286 QualType Type, bool NRVO) {
287 return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
290 static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc,
292 return InitializedEntity(EK_StmtExprResult, ReturnLoc, Type);
295 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
296 QualType Type, bool NRVO) {
297 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
300 static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
301 QualType Type, bool NRVO) {
302 return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
303 BlockVarLoc, Type, NRVO);
306 /// Create the initialization entity for an exception object.
307 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
308 QualType Type, bool NRVO) {
309 return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
312 /// Create the initialization entity for an object allocated via new.
313 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
314 return InitializedEntity(EK_New, NewLoc, Type);
317 /// Create the initialization entity for a temporary.
318 static InitializedEntity InitializeTemporary(QualType Type) {
319 return InitializeTemporary(nullptr, Type);
322 /// Create the initialization entity for a temporary.
323 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
324 return InitializeTemporary(TypeInfo, TypeInfo->getType());
327 /// Create the initialization entity for a temporary.
328 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo,
330 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
331 Result.TypeInfo = TypeInfo;
335 /// Create the initialization entity for a related result.
336 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
338 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
339 Result.MethodDecl = MD;
343 /// Create the initialization entity for a base class subobject.
344 static InitializedEntity
345 InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base,
346 bool IsInheritedVirtualBase,
347 const InitializedEntity *Parent = nullptr);
349 /// Create the initialization entity for a delegated constructor.
350 static InitializedEntity InitializeDelegation(QualType Type) {
351 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
354 /// Create the initialization entity for a member subobject.
355 static InitializedEntity
356 InitializeMember(FieldDecl *Member,
357 const InitializedEntity *Parent = nullptr,
358 bool Implicit = false) {
359 return InitializedEntity(Member, Parent, Implicit, false);
362 /// Create the initialization entity for a member subobject.
363 static InitializedEntity
364 InitializeMember(IndirectFieldDecl *Member,
365 const InitializedEntity *Parent = nullptr,
366 bool Implicit = false) {
367 return InitializedEntity(Member->getAnonField(), Parent, Implicit, false);
370 /// Create the initialization entity for a default member initializer.
371 static InitializedEntity
372 InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member) {
373 return InitializedEntity(Member, nullptr, false, true);
376 /// Create the initialization entity for an array element.
377 static InitializedEntity InitializeElement(ASTContext &Context,
379 const InitializedEntity &Parent) {
380 return InitializedEntity(Context, Index, Parent);
383 /// Create the initialization entity for a structured binding.
384 static InitializedEntity InitializeBinding(VarDecl *Binding) {
385 return InitializedEntity(Binding, EK_Binding);
388 /// Create the initialization entity for a lambda capture.
390 /// \p VarID The name of the entity being captured, or nullptr for 'this'.
391 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
393 SourceLocation Loc) {
394 return InitializedEntity(VarID, FieldType, Loc);
397 /// Create the entity for a compound literal initializer.
398 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
399 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
401 Result.TypeInfo = TSI;
405 /// Determine the kind of initialization.
406 EntityKind getKind() const { return Kind; }
408 /// Retrieve the parent of the entity being initialized, when
409 /// the initialization itself is occurring within the context of a
410 /// larger initialization.
411 const InitializedEntity *getParent() const { return Parent; }
413 /// Retrieve type being initialized.
414 QualType getType() const { return Type; }
416 /// Retrieve complete type-source information for the object being
417 /// constructed, if known.
418 TypeSourceInfo *getTypeSourceInfo() const {
419 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
425 /// Retrieve the name of the entity being initialized.
426 DeclarationName getName() const;
428 /// Retrieve the variable, parameter, or field being
430 ValueDecl *getDecl() const;
432 /// Retrieve the ObjectiveC method being initialized.
433 ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
435 /// Determine whether this initialization allows the named return
436 /// value optimization, which also applies to thrown objects.
437 bool allowsNRVO() const;
439 bool isParameterKind() const {
440 return (getKind() == EK_Parameter ||
441 getKind() == EK_Parameter_CF_Audited);
444 /// Determine whether this initialization consumes the
446 bool isParameterConsumed() const {
447 assert(isParameterKind() && "Not a parameter");
448 return (Parameter & 1);
451 /// Retrieve the base specifier.
452 const CXXBaseSpecifier *getBaseSpecifier() const {
453 assert(getKind() == EK_Base && "Not a base specifier");
454 return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
457 /// Return whether the base is an inherited virtual base.
458 bool isInheritedVirtualBase() const {
459 assert(getKind() == EK_Base && "Not a base specifier");
463 /// Determine whether this is an array new with an unknown bound.
464 bool isVariableLengthArrayNew() const {
465 return getKind() == EK_New && dyn_cast_or_null<IncompleteArrayType>(
466 getType()->getAsArrayTypeUnsafe());
469 /// Is this the implicit initialization of a member of a class from
470 /// a defaulted constructor?
471 bool isImplicitMemberInitializer() const {
472 return getKind() == EK_Member && Variable.IsImplicitFieldInit;
475 /// Is this the default member initializer of a member (specified inside
476 /// the class definition)?
477 bool isDefaultMemberInitializer() const {
478 return getKind() == EK_Member && Variable.IsDefaultMemberInit;
481 /// Determine the location of the 'return' keyword when initializing
482 /// the result of a function call.
483 SourceLocation getReturnLoc() const {
484 assert(getKind() == EK_Result && "No 'return' location!");
485 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
488 /// Determine the location of the 'throw' keyword when initializing
489 /// an exception object.
490 SourceLocation getThrowLoc() const {
491 assert(getKind() == EK_Exception && "No 'throw' location!");
492 return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
495 /// If this is an array, vector, or complex number element, get the
497 unsigned getElementIndex() const {
498 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
499 getKind() == EK_ComplexElement);
503 /// If this is already the initializer for an array or vector
504 /// element, sets the element index.
505 void setElementIndex(unsigned Index) {
506 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
507 getKind() == EK_ComplexElement);
511 /// For a lambda capture, return the capture's name.
512 StringRef getCapturedVarName() const {
513 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
514 return Capture.VarID ? Capture.VarID->getName() : "this";
517 /// Determine the location of the capture when initializing
518 /// field from a captured variable in a lambda.
519 SourceLocation getCaptureLoc() const {
520 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
521 return SourceLocation::getFromRawEncoding(Capture.Location);
524 void setParameterCFAudited() {
525 Kind = EK_Parameter_CF_Audited;
528 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
530 /// Dump a representation of the initialized entity to standard error,
531 /// for debugging purposes.
535 unsigned dumpImpl(raw_ostream &OS) const;
538 /// Describes the kind of initialization being performed, along with
539 /// location information for tokens related to the initialization (equal sign,
541 class InitializationKind {
543 /// The kind of initialization being performed.
545 /// Direct initialization
548 /// Direct list-initialization
551 /// Copy initialization
554 /// Default initialization
557 /// Value initialization
562 /// The context of the initialization.
567 /// Normal context, but allows explicit conversion functionss
570 /// Implicit context (value initialization)
573 /// Static cast context
576 /// C-style cast context
579 /// Functional cast context
583 /// The kind of initialization being performed.
586 /// The context of the initialization.
587 InitContext Context : 8;
589 /// The source locations involved in the initialization.
590 SourceLocation Locations[3];
592 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
593 SourceLocation Loc2, SourceLocation Loc3)
594 : Kind(Kind), Context(Context) {
601 /// Create a direct initialization.
602 static InitializationKind CreateDirect(SourceLocation InitLoc,
603 SourceLocation LParenLoc,
604 SourceLocation RParenLoc) {
605 return InitializationKind(IK_Direct, IC_Normal,
606 InitLoc, LParenLoc, RParenLoc);
609 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
610 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc,
614 static InitializationKind CreateDirectList(SourceLocation InitLoc,
615 SourceLocation LBraceLoc,
616 SourceLocation RBraceLoc) {
617 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc,
621 /// Create a direct initialization due to a cast that isn't a C-style
622 /// or functional cast.
623 static InitializationKind CreateCast(SourceRange TypeRange) {
624 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
625 TypeRange.getBegin(), TypeRange.getEnd());
628 /// Create a direct initialization for a C-style cast.
629 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
630 SourceRange TypeRange,
632 // C++ cast syntax doesn't permit init lists, but C compound literals are
634 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
635 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
639 /// Create a direct initialization for a functional cast.
640 static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
642 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
643 IC_FunctionalCast, TypeRange.getBegin(),
644 TypeRange.getBegin(), TypeRange.getEnd());
647 /// Create a copy initialization.
648 static InitializationKind CreateCopy(SourceLocation InitLoc,
649 SourceLocation EqualLoc,
650 bool AllowExplicitConvs = false) {
651 return InitializationKind(IK_Copy,
652 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
653 InitLoc, EqualLoc, EqualLoc);
656 /// Create a default initialization.
657 static InitializationKind CreateDefault(SourceLocation InitLoc) {
658 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
661 /// Create a value initialization.
662 static InitializationKind CreateValue(SourceLocation InitLoc,
663 SourceLocation LParenLoc,
664 SourceLocation RParenLoc,
665 bool isImplicit = false) {
666 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
667 InitLoc, LParenLoc, RParenLoc);
670 /// Create an initialization from an initializer (which, for direct
671 /// initialization from a parenthesized list, will be a ParenListExpr).
672 static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit,
674 if (!Init) return CreateDefault(Loc);
676 return CreateCopy(Loc, Init->getBeginLoc());
677 if (isa<InitListExpr>(Init))
678 return CreateDirectList(Loc, Init->getBeginLoc(), Init->getEndLoc());
679 return CreateDirect(Loc, Init->getBeginLoc(), Init->getEndLoc());
682 /// Determine the initialization kind.
683 InitKind getKind() const {
687 /// Determine whether this initialization is an explicit cast.
688 bool isExplicitCast() const {
689 return Context >= IC_StaticCast;
692 /// Determine whether this initialization is a C-style cast.
693 bool isCStyleOrFunctionalCast() const {
694 return Context >= IC_CStyleCast;
697 /// Determine whether this is a C-style cast.
698 bool isCStyleCast() const {
699 return Context == IC_CStyleCast;
702 /// Determine whether this is a functional-style cast.
703 bool isFunctionalCast() const {
704 return Context == IC_FunctionalCast;
707 /// Determine whether this initialization is an implicit
708 /// value-initialization, e.g., as occurs during aggregate
710 bool isImplicitValueInit() const { return Context == IC_Implicit; }
712 /// Retrieve the location at which initialization is occurring.
713 SourceLocation getLocation() const { return Locations[0]; }
715 /// Retrieve the source range that covers the initialization.
716 SourceRange getRange() const {
717 return SourceRange(Locations[0], Locations[2]);
720 /// Retrieve the location of the equal sign for copy initialization
722 SourceLocation getEqualLoc() const {
723 assert(Kind == IK_Copy && "Only copy initialization has an '='");
727 bool isCopyInit() const { return Kind == IK_Copy; }
729 /// Retrieve whether this initialization allows the use of explicit
731 bool AllowExplicit() const { return !isCopyInit(); }
733 /// Retrieve whether this initialization allows the use of explicit
734 /// conversion functions when binding a reference. If the reference is the
735 /// first parameter in a copy or move constructor, such conversions are
736 /// permitted even though we are performing copy-initialization.
737 bool allowExplicitConversionFunctionsInRefBinding() const {
738 return !isCopyInit() || Context == IC_ExplicitConvs;
741 /// Determine whether this initialization has a source range containing the
742 /// locations of open and closing parentheses or braces.
743 bool hasParenOrBraceRange() const {
744 return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList;
747 /// Retrieve the source range containing the locations of the open
748 /// and closing parentheses or braces for value, direct, and direct list
750 SourceRange getParenOrBraceRange() const {
751 assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "
752 "initialization have parentheses or "
754 return SourceRange(Locations[1], Locations[2]);
758 /// Describes the sequence of initializations required to initialize
759 /// a given object or reference with a set of arguments.
760 class InitializationSequence {
762 /// Describes the kind of initialization sequence computed.
764 /// A failed initialization sequence. The failure kind tells what
768 /// A dependent initialization, which could not be
769 /// type-checked due to the presence of dependent types or
770 /// dependently-typed expressions.
773 /// A normal sequence.
777 /// Describes the kind of a particular step in an initialization
780 /// Resolve the address of an overloaded function to a specific
781 /// function declaration.
782 SK_ResolveAddressOfOverloadedFunction,
784 /// Perform a derived-to-base cast, producing an rvalue.
785 SK_CastDerivedToBaseRValue,
787 /// Perform a derived-to-base cast, producing an xvalue.
788 SK_CastDerivedToBaseXValue,
790 /// Perform a derived-to-base cast, producing an lvalue.
791 SK_CastDerivedToBaseLValue,
793 /// Reference binding to an lvalue.
796 /// Reference binding to a temporary.
797 SK_BindReferenceToTemporary,
799 /// An optional copy of a temporary object to another
800 /// temporary object, which is permitted (but not required) by
801 /// C++98/03 but not C++0x.
802 SK_ExtraneousCopyToTemporary,
804 /// Direct-initialization from a reference-related object in the
805 /// final stage of class copy-initialization.
808 /// Perform a user-defined conversion, either via a conversion
809 /// function or via a constructor.
812 /// Perform a qualification conversion, producing an rvalue.
813 SK_QualificationConversionRValue,
815 /// Perform a qualification conversion, producing an xvalue.
816 SK_QualificationConversionXValue,
818 /// Perform a qualification conversion, producing an lvalue.
819 SK_QualificationConversionLValue,
821 /// Perform a conversion adding _Atomic to a type.
824 /// Perform an implicit conversion sequence.
825 SK_ConversionSequence,
827 /// Perform an implicit conversion sequence without narrowing.
828 SK_ConversionSequenceNoNarrowing,
830 /// Perform list-initialization without a constructor.
831 SK_ListInitialization,
833 /// Unwrap the single-element initializer list for a reference.
836 /// Rewrap the single-element initializer list for a reference.
839 /// Perform initialization via a constructor.
840 SK_ConstructorInitialization,
842 /// Perform initialization via a constructor, taking arguments from
843 /// a single InitListExpr.
844 SK_ConstructorInitializationFromList,
846 /// Zero-initialize the object
847 SK_ZeroInitialization,
852 /// Initialization by string
855 /// An initialization that "converts" an Objective-C object
856 /// (not a point to an object) to another Objective-C object type.
857 SK_ObjCObjectConversion,
859 /// Array indexing for initialization by elementwise copy.
862 /// Array initialization by elementwise copy.
865 /// Array initialization (from an array rvalue).
868 /// Array initialization (from an array rvalue) as a GNU extension.
871 /// Array initialization from a parenthesized initializer list.
872 /// This is a GNU C++ extension.
873 SK_ParenthesizedArrayInit,
875 /// Pass an object by indirect copy-and-restore.
876 SK_PassByIndirectCopyRestore,
878 /// Pass an object by indirect restore.
879 SK_PassByIndirectRestore,
881 /// Produce an Objective-C object pointer.
882 SK_ProduceObjCObject,
884 /// Construct a std::initializer_list from an initializer list.
885 SK_StdInitializerList,
887 /// Perform initialization via a constructor taking a single
888 /// std::initializer_list argument.
889 SK_StdInitializerListConstructorCall,
891 /// Initialize an OpenCL sampler from an integer.
894 /// Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero
898 /// A single step in the initialization sequence.
901 /// The kind of conversion or initialization step we are taking.
904 // The type that results from this initialization.
908 bool HadMultipleCandidates;
909 FunctionDecl *Function;
910 DeclAccessPair FoundDecl;
914 /// When Kind == SK_ResolvedOverloadedFunction or Kind ==
915 /// SK_UserConversion, the function that the expression should be
916 /// resolved to or the conversion function to call, respectively.
917 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
918 /// the constructor to be called.
920 /// Always a FunctionDecl, plus a Boolean flag telling if it was
921 /// selected from an overloaded set having size greater than 1.
922 /// For conversion decls, the naming class is the source type.
923 /// For construct decls, the naming class is the target type.
926 /// When Kind = SK_ConversionSequence, the implicit conversion
928 ImplicitConversionSequence *ICS;
930 /// When Kind = SK_RewrapInitList, the syntactic form of the
932 InitListExpr *WrappingSyntacticList;
939 /// The kind of initialization sequence computed.
940 enum SequenceKind SequenceKind;
942 /// Steps taken by this initialization.
943 SmallVector<Step, 4> Steps;
946 /// Describes why initialization failed.
948 /// Too many initializers provided for a reference.
949 FK_TooManyInitsForReference,
951 /// Reference initialized from a parenthesized initializer list.
952 FK_ParenthesizedListInitForReference,
954 /// Array must be initialized with an initializer list.
955 FK_ArrayNeedsInitList,
957 /// Array must be initialized with an initializer list or a
959 FK_ArrayNeedsInitListOrStringLiteral,
961 /// Array must be initialized with an initializer list or a
962 /// wide string literal.
963 FK_ArrayNeedsInitListOrWideStringLiteral,
965 /// Initializing a wide char array with narrow string literal.
966 FK_NarrowStringIntoWideCharArray,
968 /// Initializing char array with wide string literal.
969 FK_WideStringIntoCharArray,
971 /// Initializing wide char array with incompatible wide string
973 FK_IncompatWideStringIntoWideChar,
975 /// Initializing char8_t array with plain string literal.
976 FK_PlainStringIntoUTF8Char,
978 /// Initializing char array with UTF-8 string literal.
979 FK_UTF8StringIntoPlainChar,
981 /// Array type mismatch.
982 FK_ArrayTypeMismatch,
984 /// Non-constant array initializer
985 FK_NonConstantArrayInit,
987 /// Cannot resolve the address of an overloaded function.
988 FK_AddressOfOverloadFailed,
990 /// Overloading due to reference initialization failed.
991 FK_ReferenceInitOverloadFailed,
993 /// Non-const lvalue reference binding to a temporary.
994 FK_NonConstLValueReferenceBindingToTemporary,
996 /// Non-const lvalue reference binding to a bit-field.
997 FK_NonConstLValueReferenceBindingToBitfield,
999 /// Non-const lvalue reference binding to a vector element.
1000 FK_NonConstLValueReferenceBindingToVectorElement,
1002 /// Non-const lvalue reference binding to an lvalue of unrelated
1004 FK_NonConstLValueReferenceBindingToUnrelated,
1006 /// Rvalue reference binding to an lvalue.
1007 FK_RValueReferenceBindingToLValue,
1009 /// Reference binding drops qualifiers.
1010 FK_ReferenceInitDropsQualifiers,
1012 /// Reference with mismatching address space binding to temporary.
1013 FK_ReferenceAddrspaceMismatchTemporary,
1015 /// Reference binding failed.
1016 FK_ReferenceInitFailed,
1018 /// Implicit conversion failed.
1019 FK_ConversionFailed,
1021 /// Implicit conversion failed.
1022 FK_ConversionFromPropertyFailed,
1024 /// Too many initializers for scalar
1025 FK_TooManyInitsForScalar,
1027 /// Scalar initialized from a parenthesized initializer list.
1028 FK_ParenthesizedListInitForScalar,
1030 /// Reference initialization from an initializer list
1031 FK_ReferenceBindingToInitList,
1033 /// Initialization of some unused destination type with an
1034 /// initializer list.
1035 FK_InitListBadDestinationType,
1037 /// Overloading for a user-defined conversion failed.
1038 FK_UserConversionOverloadFailed,
1040 /// Overloading for initialization by constructor failed.
1041 FK_ConstructorOverloadFailed,
1043 /// Overloading for list-initialization by constructor failed.
1044 FK_ListConstructorOverloadFailed,
1046 /// Default-initialization of a 'const' object.
1047 FK_DefaultInitOfConst,
1049 /// Initialization of an incomplete type.
1052 /// Variable-length array must not have an initializer.
1053 FK_VariableLengthArrayHasInitializer,
1055 /// List initialization failed at some point.
1056 FK_ListInitializationFailed,
1058 /// Initializer has a placeholder type which cannot be
1059 /// resolved by initialization.
1062 /// Trying to take the address of a function that doesn't support
1063 /// having its address taken.
1064 FK_AddressOfUnaddressableFunction,
1066 /// List-copy-initialization chose an explicit constructor.
1067 FK_ExplicitConstructor,
1071 /// The reason why initialization failed.
1072 FailureKind Failure;
1074 /// The failed result of overload resolution.
1075 OverloadingResult FailedOverloadResult;
1077 /// The candidate set created when initialization failed.
1078 OverloadCandidateSet FailedCandidateSet;
1080 /// The incomplete type that caused a failure.
1081 QualType FailedIncompleteType;
1083 /// The fixit that needs to be applied to make this initialization
1085 std::string ZeroInitializationFixit;
1086 SourceLocation ZeroInitializationFixitLoc;
1089 /// Call for initializations are invalid but that would be valid
1090 /// zero initialzations if Fixit was applied.
1091 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
1092 ZeroInitializationFixit = Fixit;
1093 ZeroInitializationFixitLoc = L;
1097 /// Prints a follow-up note that highlights the location of
1098 /// the initialized entity, if it's remote.
1099 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
1102 /// Try to perform initialization of the given entity, creating a
1103 /// record of the steps required to perform the initialization.
1105 /// The generated initialization sequence will either contain enough
1106 /// information to diagnose
1108 /// \param S the semantic analysis object.
1110 /// \param Entity the entity being initialized.
1112 /// \param Kind the kind of initialization being performed.
1114 /// \param Args the argument(s) provided for initialization.
1116 /// \param TopLevelOfInitList true if we are initializing from an expression
1117 /// at the top level inside an initializer list. This disallows
1118 /// narrowing conversions in C++11 onwards.
1119 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
1121 InitializationSequence(Sema &S,
1122 const InitializedEntity &Entity,
1123 const InitializationKind &Kind,
1125 bool TopLevelOfInitList = false,
1126 bool TreatUnavailableAsInvalid = true);
1127 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
1128 const InitializationKind &Kind, MultiExprArg Args,
1129 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
1131 ~InitializationSequence();
1133 /// Perform the actual initialization of the given entity based on
1134 /// the computed initialization sequence.
1136 /// \param S the semantic analysis object.
1138 /// \param Entity the entity being initialized.
1140 /// \param Kind the kind of initialization being performed.
1142 /// \param Args the argument(s) provided for initialization, ownership of
1143 /// which is transferred into the routine.
1145 /// \param ResultType if non-NULL, will be set to the type of the
1146 /// initialized object, which is the type of the declaration in most
1147 /// cases. However, when the initialized object is a variable of
1148 /// incomplete array type and the initializer is an initializer
1149 /// list, this type will be set to the completed array type.
1151 /// \returns an expression that performs the actual object initialization, if
1152 /// the initialization is well-formed. Otherwise, emits diagnostics
1153 /// and returns an invalid expression.
1154 ExprResult Perform(Sema &S,
1155 const InitializedEntity &Entity,
1156 const InitializationKind &Kind,
1158 QualType *ResultType = nullptr);
1160 /// Diagnose an potentially-invalid initialization sequence.
1162 /// \returns true if the initialization sequence was ill-formed,
1163 /// false otherwise.
1164 bool Diagnose(Sema &S,
1165 const InitializedEntity &Entity,
1166 const InitializationKind &Kind,
1167 ArrayRef<Expr *> Args);
1169 /// Determine the kind of initialization sequence computed.
1170 enum SequenceKind getKind() const { return SequenceKind; }
1172 /// Set the kind of sequence computed.
1173 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
1175 /// Determine whether the initialization sequence is valid.
1176 explicit operator bool() const { return !Failed(); }
1178 /// Determine whether the initialization sequence is invalid.
1179 bool Failed() const { return SequenceKind == FailedSequence; }
1181 using step_iterator = SmallVectorImpl<Step>::const_iterator;
1183 step_iterator step_begin() const { return Steps.begin(); }
1184 step_iterator step_end() const { return Steps.end(); }
1186 using step_range = llvm::iterator_range<step_iterator>;
1188 step_range steps() const { return {step_begin(), step_end()}; }
1190 /// Determine whether this initialization is a direct reference
1191 /// binding (C++ [dcl.init.ref]).
1192 bool isDirectReferenceBinding() const;
1194 /// Determine whether this initialization failed due to an ambiguity.
1195 bool isAmbiguous() const;
1197 /// Determine whether this initialization is direct call to a
1199 bool isConstructorInitialization() const;
1201 /// Returns whether the last step in this initialization sequence is a
1202 /// narrowing conversion, defined by C++0x [dcl.init.list]p7.
1204 /// If this function returns true, *isInitializerConstant will be set to
1205 /// describe whether *Initializer was a constant expression. If
1206 /// *isInitializerConstant is set to true, *ConstantValue will be set to the
1207 /// evaluated value of *Initializer.
1208 bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
1209 bool *isInitializerConstant,
1210 APValue *ConstantValue) const;
1212 /// Add a new step in the initialization that resolves the address
1213 /// of an overloaded function to a specific function declaration.
1215 /// \param Function the function to which the overloaded function reference
1217 void AddAddressOverloadResolutionStep(FunctionDecl *Function,
1218 DeclAccessPair Found,
1219 bool HadMultipleCandidates);
1221 /// Add a new step in the initialization that performs a derived-to-
1224 /// \param BaseType the base type to which we will be casting.
1226 /// \param Category Indicates whether the result will be treated as an
1227 /// rvalue, an xvalue, or an lvalue.
1228 void AddDerivedToBaseCastStep(QualType BaseType,
1229 ExprValueKind Category);
1231 /// Add a new step binding a reference to an object.
1233 /// \param BindingTemporary True if we are binding a reference to a temporary
1234 /// object (thereby extending its lifetime); false if we are binding to an
1235 /// lvalue or an lvalue treated as an rvalue.
1236 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1238 /// Add a new step that makes an extraneous copy of the input
1239 /// to a temporary of the same class type.
1241 /// This extraneous copy only occurs during reference binding in
1242 /// C++98/03, where we are permitted (but not required) to introduce
1243 /// an extra copy. At a bare minimum, we must check that we could
1244 /// call the copy constructor, and produce a diagnostic if the copy
1245 /// constructor is inaccessible or no copy constructor matches.
1247 /// \param T The type of the temporary being created.
1248 void AddExtraneousCopyToTemporary(QualType T);
1250 /// Add a new step that makes a copy of the input to an object of
1251 /// the given type, as the final step in class copy-initialization.
1252 void AddFinalCopy(QualType T);
1254 /// Add a new step invoking a conversion function, which is either
1255 /// a constructor or a conversion function.
1256 void AddUserConversionStep(FunctionDecl *Function,
1257 DeclAccessPair FoundDecl,
1259 bool HadMultipleCandidates);
1261 /// Add a new step that performs a qualification conversion to the
1263 void AddQualificationConversionStep(QualType Ty,
1264 ExprValueKind Category);
1266 /// Add a new step that performs conversion from non-atomic to atomic
1268 void AddAtomicConversionStep(QualType Ty);
1270 /// Add a new step that applies an implicit conversion sequence.
1271 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
1272 QualType T, bool TopLevelOfInitList = false);
1274 /// Add a list-initialization step.
1275 void AddListInitializationStep(QualType T);
1277 /// Add a constructor-initialization step.
1279 /// \param FromInitList The constructor call is syntactically an initializer
1281 /// \param AsInitList The constructor is called as an init list constructor.
1282 void AddConstructorInitializationStep(DeclAccessPair FoundDecl,
1283 CXXConstructorDecl *Constructor,
1285 bool HadMultipleCandidates,
1286 bool FromInitList, bool AsInitList);
1288 /// Add a zero-initialization step.
1289 void AddZeroInitializationStep(QualType T);
1291 /// Add a C assignment step.
1293 // FIXME: It isn't clear whether this should ever be needed;
1294 // ideally, we would handle everything needed in C in the common
1295 // path. However, that isn't the case yet.
1296 void AddCAssignmentStep(QualType T);
1298 /// Add a string init step.
1299 void AddStringInitStep(QualType T);
1301 /// Add an Objective-C object conversion step, which is
1303 void AddObjCObjectConversionStep(QualType T);
1305 /// Add an array initialization loop step.
1306 void AddArrayInitLoopStep(QualType T, QualType EltTy);
1308 /// Add an array initialization step.
1309 void AddArrayInitStep(QualType T, bool IsGNUExtension);
1311 /// Add a parenthesized array initialization step.
1312 void AddParenthesizedArrayInitStep(QualType T);
1314 /// Add a step to pass an object by indirect copy-restore.
1315 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1317 /// Add a step to "produce" an Objective-C object (by
1319 void AddProduceObjCObjectStep(QualType T);
1321 /// Add a step to construct a std::initializer_list object from an
1322 /// initializer list.
1323 void AddStdInitializerListConstructionStep(QualType T);
1325 /// Add a step to initialize an OpenCL sampler from an integer
1327 void AddOCLSamplerInitStep(QualType T);
1329 /// Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.)
1330 /// from a zero constant.
1331 void AddOCLZeroOpaqueTypeStep(QualType T);
1333 /// Add a step to initialize by zero types defined in the
1334 /// cl_intel_device_side_avc_motion_estimation OpenCL extension
1335 void AddOCLIntelSubgroupAVCZeroInitStep(QualType T);
1337 /// Add steps to unwrap a initializer list for a reference around a
1338 /// single element and rewrap it at the end.
1339 void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
1341 /// Note that this initialization sequence failed.
1342 void SetFailed(FailureKind Failure) {
1343 SequenceKind = FailedSequence;
1344 this->Failure = Failure;
1345 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1346 "Incomplete type failure requires a type!");
1349 /// Note that this initialization sequence failed due to failed
1350 /// overload resolution.
1351 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1353 /// Retrieve a reference to the candidate set when overload
1354 /// resolution fails.
1355 OverloadCandidateSet &getFailedCandidateSet() {
1356 return FailedCandidateSet;
1359 /// Get the overloading result, for when the initialization
1360 /// sequence failed due to a bad overload.
1361 OverloadingResult getFailedOverloadResult() const {
1362 return FailedOverloadResult;
1365 /// Note that this initialization sequence failed due to an
1366 /// incomplete type.
1367 void setIncompleteTypeFailure(QualType IncompleteType) {
1368 FailedIncompleteType = IncompleteType;
1369 SetFailed(FK_Incomplete);
1372 /// Determine why initialization failed.
1373 FailureKind getFailureKind() const {
1374 assert(Failed() && "Not an initialization failure!");
1378 /// Dump a representation of this initialization sequence to
1379 /// the given stream, for debugging purposes.
1380 void dump(raw_ostream &OS) const;
1382 /// Dump a representation of this initialization sequence to
1383 /// standard error, for debugging purposes.
1387 } // namespace clang
1389 #endif // LLVM_CLANG_SEMA_INITIALIZATION_H