clang 22.0.0git
Initialization.h
Go to the documentation of this file.
1//===- Initialization.h - Semantic Analysis for Initializers ----*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides supporting data types for initialization of objects.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
14#define LLVM_CLANG_SEMA_INITIALIZATION_H
15
17#include "clang/AST/Attr.h"
18#include "clang/AST/Decl.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/Type.h"
24#include "clang/Basic/LLVM.h"
28#include "clang/Sema/Overload.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"
35#include <cassert>
36#include <cstdint>
37#include <string>
38
39namespace clang {
40
43class ObjCMethodDecl;
44class Sema;
45
46/// Describes an entity that is being initialized.
47class alignas(8) InitializedEntity {
48public:
49 /// Specifies the kind of entity being initialized.
51 /// The entity being initialized is a variable.
53
54 /// The entity being initialized is a function parameter.
56
57 /// The entity being initialized is a non-type template parameter.
59
60 /// The entity being initialized is the result of a function call.
62
63 /// The entity being initialized is the result of a statement expression.
65
66 /// The entity being initialized is an exception object that
67 /// is being thrown.
69
70 /// The entity being initialized is a non-static data member
71 /// subobject.
73
74 /// The entity being initialized is an element of an array.
76
77 /// The entity being initialized is an object (or array of
78 /// objects) allocated via new.
80
81 /// The entity being initialized is a temporary object.
83
84 /// The entity being initialized is a base member subobject.
86
87 /// The initialization is being done by a delegating constructor.
89
90 /// The entity being initialized is an element of a vector.
91 /// or vector.
93
94 /// The entity being initialized is an element of a matrix.
95 /// or matrix.
97
98 /// The entity being initialized is a field of block descriptor for
99 /// the copied-in c++ object.
101
102 /// The entity being initialized is a field of block descriptor for the
103 /// copied-in lambda object that's used in the lambda to block conversion.
105
106 /// The entity being initialized is the real or imaginary part of a
107 /// complex number.
109
110 /// The entity being initialized is the field that captures a
111 /// variable in a lambda.
113
114 /// The entity being initialized is the initializer for a compound
115 /// literal.
117
118 /// The entity being implicitly initialized back to the formal
119 /// result type.
121
122 /// The entity being initialized is a function parameter; function
123 /// is member of group of audited CF APIs.
125
126 /// The entity being initialized is a structured binding of a
127 /// decomposition declaration.
129
130 /// The entity being initialized is a non-static data member subobject of an
131 /// object initialized via parenthesized aggregate initialization.
133
134 // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
135 // enum as an index for its first %select. When modifying this list,
136 // that diagnostic text needs to be updated as well.
137 };
138
139private:
140 /// The kind of entity being initialized.
141 EntityKind Kind;
142
143 /// If non-NULL, the parent entity in which this
144 /// initialization occurs.
145 const InitializedEntity *Parent = nullptr;
146
147 /// The type of the object or reference being initialized.
149
150 /// The mangling number for the next reference temporary to be created.
151 mutable unsigned ManglingNumber = 0;
152
153 struct LN {
154 /// When Kind == EK_Result, EK_Exception, EK_New, the
155 /// location of the 'return', 'throw', or 'new' keyword,
156 /// respectively. When Kind == EK_Temporary, the location where
157 /// the temporary is being created.
158 SourceLocation Location;
159
160 /// Whether the entity being initialized may end up using the
161 /// named return value optimization (NRVO).
162 bool NRVO;
163 };
164
165 struct VD {
166 /// The VarDecl, FieldDecl, TemplateParmDecl, or BindingDecl being
167 /// initialized.
168 NamedDecl *VariableOrMember;
169
170 /// When Kind == EK_Member, whether this is an implicit member
171 /// initialization in a copy or move constructor. These can perform array
172 /// copies.
173 bool IsImplicitFieldInit;
174
175 /// When Kind == EK_Member, whether this is the initial initialization
176 /// check for a default member initializer.
177 bool IsDefaultMemberInit;
178 };
179
180 struct C {
181 /// The name of the variable being captured by an EK_LambdaCapture.
182 IdentifierInfo *VarID;
183
184 /// The source location at which the capture occurs.
185 SourceLocation Location;
186 };
187
188 union {
189 /// When Kind == EK_Variable, EK_Member, EK_Binding, or
190 /// EK_TemplateParameter, the variable, binding, or template parameter.
192
193 /// When Kind == EK_RelatedResult, the ObjectiveC method where
194 /// result type was implicitly changed to accommodate ARC semantics.
196
197 /// When Kind == EK_Parameter, the ParmVarDecl, with the
198 /// integer indicating whether the parameter is "consumed".
199 llvm::PointerIntPair<ParmVarDecl *, 1> Parameter;
200
201 /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
202 /// source information for the temporary.
204
205 struct LN LocAndNRVO;
206
207 /// When Kind == EK_Base, the base specifier that provides the
208 /// base class. The integer specifies whether the base is an inherited
209 /// virtual base.
210 llvm::PointerIntPair<const CXXBaseSpecifier *, 1> Base;
211
212 /// When Kind == EK_ArrayElement, EK_VectorElement, EK_MatrixElement,
213 /// or EK_ComplexElement, the index of the array or vector element being
214 /// initialized.
215 unsigned Index;
216
217 struct C Capture;
218 };
219
221
222 /// Create the initialization entity for a variable.
223 InitializedEntity(VarDecl *Var, EntityKind EK = EK_Variable)
224 : Kind(EK), Type(Var->getType()), Variable{Var, false, false} {}
225
226 /// Create the initialization entity for the result of a
227 /// function, throwing an object, performing an explicit cast, or
228 /// initializing a parameter for which there is no declaration.
229 InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
230 bool NRVO = false)
231 : Kind(Kind), Type(Type) {
232 new (&LocAndNRVO) LN;
233 LocAndNRVO.Location = Loc;
234 LocAndNRVO.NRVO = NRVO;
235 }
236
237 /// Create the initialization entity for a member subobject.
238 InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent,
239 bool Implicit, bool DefaultMemberInit,
240 bool IsParenAggInit = false)
241 : Kind(IsParenAggInit ? EK_ParenAggInitMember : EK_Member),
242 Parent(Parent), Type(Member->getType()),
243 Variable{Member, Implicit, DefaultMemberInit} {}
244
245 /// Create the initialization entity for an array element.
246 InitializedEntity(ASTContext &Context, unsigned Index,
247 const InitializedEntity &Parent);
248
249 /// Create the initialization entity for a lambda capture.
250 InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
251 : Kind(EK_LambdaCapture), Type(FieldType) {
252 new (&Capture) C;
253 Capture.VarID = VarID;
254 Capture.Location = Loc;
255 }
256
257public:
258 /// Create the initialization entity for a variable.
259 static InitializedEntity InitializeVariable(VarDecl *Var) {
260 return InitializedEntity(Var);
261 }
262
263 /// Create the initialization entity for a parameter.
264 static InitializedEntity InitializeParameter(ASTContext &Context,
265 ParmVarDecl *Parm) {
266 return InitializeParameter(Context, Parm, Parm->getType());
267 }
268
269 /// Create the initialization entity for a parameter, but use
270 /// another type.
271 static InitializedEntity
273 bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
274 Parm->hasAttr<NSConsumedAttr>());
275
276 InitializedEntity Entity;
277 Entity.Kind = EK_Parameter;
278 Entity.Type =
279 Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
280 Entity.Parent = nullptr;
281 Entity.Parameter = {Parm, Consumed};
282 return Entity;
283 }
284
285 /// Create the initialization entity for a parameter that is
286 /// only known by its type.
287 static InitializedEntity InitializeParameter(ASTContext &Context,
288 QualType Type,
289 bool Consumed) {
290 InitializedEntity Entity;
291 Entity.Kind = EK_Parameter;
292 Entity.Type = Context.getVariableArrayDecayedType(Type);
293 Entity.Parent = nullptr;
294 Entity.Parameter = {nullptr, Consumed};
295 return Entity;
296 }
297
298 /// Create the initialization entity for a template parameter.
299 static InitializedEntity InitializeTemplateParameter(QualType T,
300 NamedDecl *Param) {
301 InitializedEntity Entity;
302 Entity.Kind = EK_TemplateParameter;
303 Entity.Type = T;
304 Entity.Parent = nullptr;
305 Entity.Variable = {Param, false, false};
306 return Entity;
307 }
308
309 /// Create the initialization entity for the result of a function.
310 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
311 QualType Type) {
312 return InitializedEntity(EK_Result, ReturnLoc, Type);
313 }
314
315 static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc,
316 QualType Type) {
317 return InitializedEntity(EK_StmtExprResult, ReturnLoc, Type);
318 }
319
320 static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
321 QualType Type) {
322 return InitializedEntity(EK_BlockElement, BlockVarLoc, Type);
323 }
324
325 static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc,
326 QualType Type) {
327 return InitializedEntity(EK_LambdaToBlockConversionBlockElement,
328 BlockVarLoc, Type);
329 }
330
331 /// Create the initialization entity for an exception object.
332 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
333 QualType Type) {
334 return InitializedEntity(EK_Exception, ThrowLoc, Type);
335 }
336
337 /// Create the initialization entity for an object allocated via new.
338 static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
339 return InitializedEntity(EK_New, NewLoc, Type);
340 }
341
342 /// Create the initialization entity for a temporary.
343 static InitializedEntity InitializeTemporary(QualType Type) {
344 return InitializeTemporary(nullptr, Type);
345 }
346
347 /// Create the initialization entity for a temporary.
348 static InitializedEntity InitializeTemporary(ASTContext &Context,
350 QualType Type = TypeInfo->getType();
351 if (Context.getLangOpts().OpenCLCPlusPlus) {
352 assert(!Type.hasAddressSpace() && "Temporary already has address space!");
353 Type = Context.getAddrSpaceQualType(Type, LangAS::opencl_private);
354 }
355
356 return InitializeTemporary(TypeInfo, Type);
357 }
358
359 /// Create the initialization entity for a temporary.
360 static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo,
361 QualType Type) {
362 InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
363 Result.TypeInfo = TypeInfo;
364 return Result;
365 }
366
367 /// Create the initialization entity for a related result.
368 static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
369 QualType Type) {
370 InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
371 Result.MethodDecl = MD;
372 return Result;
373 }
374
375 /// Create the initialization entity for a base class subobject.
376 static InitializedEntity
378 bool IsInheritedVirtualBase,
379 const InitializedEntity *Parent = nullptr);
380
381 /// Create the initialization entity for a delegated constructor.
382 static InitializedEntity InitializeDelegation(QualType Type) {
383 return InitializedEntity(EK_Delegating, SourceLocation(), Type);
384 }
385
386 /// Create the initialization entity for a member subobject.
387 static InitializedEntity
389 const InitializedEntity *Parent = nullptr,
390 bool Implicit = false) {
391 return InitializedEntity(Member, Parent, Implicit, false);
392 }
393
394 /// Create the initialization entity for a member subobject.
395 static InitializedEntity
397 const InitializedEntity *Parent = nullptr,
398 bool Implicit = false) {
399 return InitializedEntity(Member->getAnonField(), Parent, Implicit, false);
400 }
401
402 /// Create the initialization entity for a member subobject initialized via
403 /// parenthesized aggregate init.
405 return InitializedEntity(Member, /*Parent=*/nullptr, /*Implicit=*/false,
406 /*DefaultMemberInit=*/false,
407 /*IsParenAggInit=*/true);
408 }
409
410 /// Create the initialization entity for a default member initializer.
411 static InitializedEntity
413 return InitializedEntity(Member, nullptr, false, true);
414 }
415
416 /// Create the initialization entity for an array element.
417 static InitializedEntity InitializeElement(ASTContext &Context,
418 unsigned Index,
419 const InitializedEntity &Parent) {
420 return InitializedEntity(Context, Index, Parent);
421 }
422
423 /// Create the initialization entity for a structured binding.
424 static InitializedEntity InitializeBinding(VarDecl *Binding) {
425 return InitializedEntity(Binding, EK_Binding);
426 }
427
428 /// Create the initialization entity for a lambda capture.
429 ///
430 /// \p VarID The name of the entity being captured, or nullptr for 'this'.
431 static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
432 QualType FieldType,
433 SourceLocation Loc) {
434 return InitializedEntity(VarID, FieldType, Loc);
435 }
436
437 /// Create the entity for a compound literal initializer.
438 static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
439 InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
440 TSI->getType());
441 Result.TypeInfo = TSI;
442 return Result;
443 }
444
445 /// Determine the kind of initialization.
446 EntityKind getKind() const { return Kind; }
447
448 /// Retrieve the parent of the entity being initialized, when
449 /// the initialization itself is occurring within the context of a
450 /// larger initialization.
451 const InitializedEntity *getParent() const { return Parent; }
452
453 /// Retrieve type being initialized.
454 QualType getType() const { return Type; }
455
456 /// Retrieve complete type-source information for the object being
457 /// constructed, if known.
459 if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
460 return TypeInfo;
461
462 return nullptr;
463 }
464
465 /// Retrieve the name of the entity being initialized.
466 DeclarationName getName() const;
467
468 /// Retrieve the variable, parameter, or field being
469 /// initialized.
470 ValueDecl *getDecl() const;
471
472 /// Retrieve the ObjectiveC method being initialized.
474
475 /// Determine whether this initialization allows the named return
476 /// value optimization, which also applies to thrown objects.
477 bool allowsNRVO() const;
478
479 bool isParameterKind() const {
480 return (getKind() == EK_Parameter ||
482 }
483
486 }
487
488 /// Determine whether this initialization consumes the
489 /// parameter.
490 bool isParameterConsumed() const {
491 assert(isParameterKind() && "Not a parameter");
492 return Parameter.getInt();
493 }
494
495 /// Retrieve the base specifier.
497 assert(getKind() == EK_Base && "Not a base specifier");
498 return Base.getPointer();
499 }
500
501 /// Return whether the base is an inherited virtual base.
503 assert(getKind() == EK_Base && "Not a base specifier");
504 return Base.getInt();
505 }
506
507 /// Determine whether this is an array new with an unknown bound.
509 return getKind() == EK_New && isa_and_nonnull<IncompleteArrayType>(
510 getType()->getAsArrayTypeUnsafe());
511 }
512
513 /// Is this the implicit initialization of a member of a class from
514 /// a defaulted constructor?
516 return getKind() == EK_Member && Variable.IsImplicitFieldInit;
517 }
518
519 /// Is this the default member initializer of a member (specified inside
520 /// the class definition)?
522 return getKind() == EK_Member && Variable.IsDefaultMemberInit;
523 }
524
525 /// Determine the location of the 'return' keyword when initializing
526 /// the result of a function call.
528 assert(getKind() == EK_Result && "No 'return' location!");
529 return LocAndNRVO.Location;
530 }
531
532 /// Determine the location of the 'throw' keyword when initializing
533 /// an exception object.
535 assert(getKind() == EK_Exception && "No 'throw' location!");
536 return LocAndNRVO.Location;
537 }
538
539 /// If this is an array, vector, or complex number element, get the
540 /// element's index.
541 unsigned getElementIndex() const {
542 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
544 return Index;
545 }
546
547 /// If this is already the initializer for an array or vector
548 /// element, sets the element index.
549 void setElementIndex(unsigned Index) {
550 assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
552 this->Index = Index;
553 }
554
555 /// For a lambda capture, return the capture's name.
556 StringRef getCapturedVarName() const {
557 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
558 return Capture.VarID ? Capture.VarID->getName() : "this";
559 }
560
561 /// Determine the location of the capture when initializing
562 /// field from a captured variable in a lambda.
564 assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
565 return Capture.Location;
566 }
567
571
572 unsigned allocateManglingNumber() const { return ++ManglingNumber; }
573
574 /// Dump a representation of the initialized entity to standard error,
575 /// for debugging purposes.
576 void dump() const;
577
578private:
579 unsigned dumpImpl(raw_ostream &OS) const;
580};
581
582/// Describes the kind of initialization being performed, along with
583/// location information for tokens related to the initialization (equal sign,
584/// parentheses).
585class InitializationKind {
586public:
587 /// The kind of initialization being performed.
588 enum InitKind {
589 /// Direct initialization
591
592 /// Direct list-initialization
594
595 /// Copy initialization
597
598 /// Default initialization
600
601 /// Value initialization
603 };
604
605private:
606 /// The context of the initialization.
607 enum InitContext {
608 /// Normal context
609 IC_Normal,
610
611 /// Normal context, but allows explicit conversion functions
612 IC_ExplicitConvs,
613
614 /// Implicit context (value initialization)
615 IC_Implicit,
616
617 /// Static cast context
618 IC_StaticCast,
619
620 /// C-style cast context
621 IC_CStyleCast,
622
623 /// Functional cast context
624 IC_FunctionalCast
625 };
626
627 /// The kind of initialization being performed.
628 InitKind Kind : 8;
629
630 /// The context of the initialization.
631 InitContext Context : 8;
632
633 /// The source locations involved in the initialization.
634 SourceLocation Locations[3];
635
636 InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
637 SourceLocation Loc2, SourceLocation Loc3)
638 : Kind(Kind), Context(Context) {
639 Locations[0] = Loc1;
640 Locations[1] = Loc2;
641 Locations[2] = Loc3;
642 }
643
644public:
645 /// Create a direct initialization.
646 static InitializationKind CreateDirect(SourceLocation InitLoc,
647 SourceLocation LParenLoc,
648 SourceLocation RParenLoc) {
649 return InitializationKind(IK_Direct, IC_Normal,
650 InitLoc, LParenLoc, RParenLoc);
651 }
652
653 static InitializationKind CreateDirectList(SourceLocation InitLoc) {
654 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, InitLoc,
655 InitLoc);
656 }
657
658 static InitializationKind CreateDirectList(SourceLocation InitLoc,
659 SourceLocation LBraceLoc,
660 SourceLocation RBraceLoc) {
661 return InitializationKind(IK_DirectList, IC_Normal, InitLoc, LBraceLoc,
662 RBraceLoc);
663 }
664
665 /// Create a direct initialization due to a cast that isn't a C-style
666 /// or functional cast.
667 static InitializationKind CreateCast(SourceRange TypeRange) {
668 return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
669 TypeRange.getBegin(), TypeRange.getEnd());
670 }
671
672 /// Create a direct initialization for a C-style cast.
673 static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
674 SourceRange TypeRange,
675 bool InitList) {
676 // C++ cast syntax doesn't permit init lists, but C compound literals are
677 // exactly that.
678 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
679 IC_CStyleCast, StartLoc, TypeRange.getBegin(),
680 TypeRange.getEnd());
681 }
682
683 /// Create a direct initialization for a functional cast.
684 static InitializationKind CreateFunctionalCast(SourceLocation StartLoc,
685 SourceRange ParenRange,
686 bool InitList) {
687 return InitializationKind(InitList ? IK_DirectList : IK_Direct,
688 IC_FunctionalCast, StartLoc,
689 ParenRange.getBegin(), ParenRange.getEnd());
690 }
691
692 /// Create a copy initialization.
693 static InitializationKind CreateCopy(SourceLocation InitLoc,
694 SourceLocation EqualLoc,
695 bool AllowExplicitConvs = false) {
696 return InitializationKind(IK_Copy,
697 AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
698 InitLoc, EqualLoc, EqualLoc);
699 }
700
701 /// Create a default initialization.
702 static InitializationKind CreateDefault(SourceLocation InitLoc) {
703 return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
704 }
705
706 /// Create a value initialization.
707 static InitializationKind CreateValue(SourceLocation InitLoc,
708 SourceLocation LParenLoc,
709 SourceLocation RParenLoc,
710 bool isImplicit = false) {
711 return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
712 InitLoc, LParenLoc, RParenLoc);
713 }
714
715 /// Create an initialization from an initializer (which, for direct
716 /// initialization from a parenthesized list, will be a ParenListExpr).
717 static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit,
718 Expr *Init) {
719 if (!Init) return CreateDefault(Loc);
720 if (!DirectInit)
721 return CreateCopy(Loc, Init->getBeginLoc());
723 return CreateDirectList(Loc, Init->getBeginLoc(), Init->getEndLoc());
724 return CreateDirect(Loc, Init->getBeginLoc(), Init->getEndLoc());
725 }
726
727 /// Determine the initialization kind.
729 return Kind;
730 }
731
732 /// Determine whether this initialization is an explicit cast.
733 bool isExplicitCast() const {
734 return Context >= IC_StaticCast;
735 }
736
737 /// Determine whether this initialization is a static cast.
738 bool isStaticCast() const { return Context == IC_StaticCast; }
739
740 /// Determine whether this initialization is a C-style cast.
742 return Context >= IC_CStyleCast;
743 }
744
745 /// Determine whether this is a C-style cast.
746 bool isCStyleCast() const {
747 return Context == IC_CStyleCast;
748 }
749
750 /// Determine whether this is a functional-style cast.
751 bool isFunctionalCast() const {
752 return Context == IC_FunctionalCast;
753 }
754
755 /// Determine whether this initialization is an implicit
756 /// value-initialization, e.g., as occurs during aggregate
757 /// initialization.
758 bool isImplicitValueInit() const { return Context == IC_Implicit; }
759
760 /// Retrieve the location at which initialization is occurring.
761 SourceLocation getLocation() const { return Locations[0]; }
762
763 /// Retrieve the source range that covers the initialization.
765 return SourceRange(Locations[0], Locations[2]);
766 }
767
768 /// Retrieve the location of the equal sign for copy initialization
769 /// (if present).
771 assert(Kind == IK_Copy && "Only copy initialization has an '='");
772 return Locations[1];
773 }
774
775 bool isCopyInit() const { return Kind == IK_Copy; }
776
777 /// Retrieve whether this initialization allows the use of explicit
778 /// constructors.
779 bool AllowExplicit() const { return !isCopyInit(); }
780
781 /// Retrieve whether this initialization allows the use of explicit
782 /// conversion functions when binding a reference. If the reference is the
783 /// first parameter in a copy or move constructor, such conversions are
784 /// permitted even though we are performing copy-initialization.
786 return !isCopyInit() || Context == IC_ExplicitConvs;
787 }
788
789 /// Determine whether this initialization has a source range containing the
790 /// locations of open and closing parentheses or braces.
791 bool hasParenOrBraceRange() const {
792 return Kind == IK_Direct || Kind == IK_Value || Kind == IK_DirectList;
793 }
794
795 /// Retrieve the source range containing the locations of the open
796 /// and closing parentheses or braces for value, direct, and direct list
797 /// initializations.
799 assert(hasParenOrBraceRange() && "Only direct, value, and direct-list "
800 "initialization have parentheses or "
801 "braces");
802 return SourceRange(Locations[1], Locations[2]);
803 }
804};
805
806/// Describes the sequence of initializations required to initialize
807/// a given object or reference with a set of arguments.
809public:
810 /// Describes the kind of initialization sequence computed.
812 /// A failed initialization sequence. The failure kind tells what
813 /// happened.
815
816 /// A dependent initialization, which could not be
817 /// type-checked due to the presence of dependent types or
818 /// dependently-typed expressions.
820
821 /// A normal sequence.
823 };
824
825 /// Describes the kind of a particular step in an initialization
826 /// sequence.
827 enum StepKind {
828 /// Resolve the address of an overloaded function to a specific
829 /// function declaration.
831
832 /// Perform a derived-to-base cast, producing an rvalue.
834
835 /// Perform a derived-to-base cast, producing an xvalue.
837
838 /// Perform a derived-to-base cast, producing an lvalue.
840
841 /// Reference binding to an lvalue.
843
844 /// Reference binding to a temporary.
846
847 /// An optional copy of a temporary object to another
848 /// temporary object, which is permitted (but not required) by
849 /// C++98/03 but not C++0x.
851
852 /// Direct-initialization from a reference-related object in the
853 /// final stage of class copy-initialization.
855
856 /// Perform a user-defined conversion, either via a conversion
857 /// function or via a constructor.
859
860 /// Perform a qualification conversion, producing a prvalue.
862
863 /// Perform a qualification conversion, producing an xvalue.
865
866 /// Perform a qualification conversion, producing an lvalue.
868
869 /// Perform a function reference conversion, see [dcl.init.ref]p4.
871
872 /// Perform a conversion adding _Atomic to a type.
874
875 /// Perform an implicit conversion sequence.
877
878 /// Perform an implicit conversion sequence without narrowing.
880
881 /// Perform list-initialization without a constructor.
883
884 /// Unwrap the single-element initializer list for a reference.
886
887 /// Rewrap the single-element initializer list for a reference.
889
890 /// Perform initialization via a constructor.
892
893 /// Perform initialization via a constructor, taking arguments from
894 /// a single InitListExpr.
896
897 /// Zero-initialize the object
899
900 /// C assignment
902
903 /// Initialization by string
905
906 /// An initialization that "converts" an Objective-C object
907 /// (not a point to an object) to another Objective-C object type.
909
910 /// Array indexing for initialization by elementwise copy.
912
913 /// Array initialization by elementwise copy.
915
916 /// Array initialization (from an array rvalue).
918
919 /// Array initialization (from an array rvalue) as a GNU extension.
921
922 /// Array initialization from a parenthesized initializer list.
923 /// This is a GNU C++ extension.
925
926 /// Pass an object by indirect copy-and-restore.
928
929 /// Pass an object by indirect restore.
931
932 /// Produce an Objective-C object pointer.
934
935 /// Construct a std::initializer_list from an initializer list.
937
938 /// Perform initialization via a constructor taking a single
939 /// std::initializer_list argument.
941
942 /// Initialize an OpenCL sampler from an integer.
944
945 /// Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero
947
948 /// Initialize an aggreagate with parenthesized list of values.
949 /// This is a C++20 feature.
951 };
952
953 /// A single step in the initialization sequence.
954 class Step {
955 public:
956 /// The kind of conversion or initialization step we are taking.
958
959 // The type that results from this initialization.
961
967
968 union {
969 /// When Kind == SK_ResolvedOverloadedFunction or Kind ==
970 /// SK_UserConversion, the function that the expression should be
971 /// resolved to or the conversion function to call, respectively.
972 /// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
973 /// the constructor to be called.
974 ///
975 /// Always a FunctionDecl, plus a Boolean flag telling if it was
976 /// selected from an overloaded set having size greater than 1.
977 /// For conversion decls, the naming class is the source type.
978 /// For construct decls, the naming class is the target type.
979 struct F Function;
980
981 /// When Kind = SK_ConversionSequence, the implicit conversion
982 /// sequence.
984
985 /// When Kind = SK_RewrapInitList, the syntactic form of the
986 /// wrapping list.
988 };
989
990 void Destroy();
991 };
992
993private:
994 /// The kind of initialization sequence computed.
996
997 /// Steps taken by this initialization.
999
1000public:
1001 /// Describes why initialization failed.
1003 /// Too many initializers provided for a reference.
1005
1006 /// Reference initialized from a parenthesized initializer list.
1008
1009 /// Array must be initialized with an initializer list.
1011
1012 /// Array must be initialized with an initializer list or a
1013 /// string literal.
1015
1016 /// Array must be initialized with an initializer list or a
1017 /// wide string literal.
1019
1020 /// Initializing a wide char array with narrow string literal.
1022
1023 /// Initializing char array with wide string literal.
1025
1026 /// Initializing wide char array with incompatible wide string
1027 /// literal.
1029
1030 /// Initializing char8_t array with plain string literal.
1032
1033 /// Initializing char array with UTF-8 string literal.
1035
1036 /// Array type mismatch.
1038
1039 /// Non-constant array initializer
1041
1042 /// Cannot resolve the address of an overloaded function.
1044
1045 /// Overloading due to reference initialization failed.
1047
1048 /// Non-const lvalue reference binding to a temporary.
1050
1051 /// Non-const lvalue reference binding to a bit-field.
1053
1054 /// Non-const lvalue reference binding to a vector element.
1056
1057 /// Non-const lvalue reference binding to a matrix element.
1059
1060 /// Non-const lvalue reference binding to an lvalue of unrelated
1061 /// type.
1063
1064 /// Rvalue reference binding to an lvalue.
1066
1067 /// Reference binding drops qualifiers.
1069
1070 /// Reference with mismatching address space binding to temporary.
1072
1073 /// Reference binding failed.
1075
1076 /// Implicit conversion failed.
1078
1079 /// Implicit conversion failed.
1081
1082 /// Too many initializers for scalar
1084
1085 /// Scalar initialized from a parenthesized initializer list.
1087
1088 /// Reference initialization from an initializer list
1090
1091 /// Initialization of some unused destination type with an
1092 /// initializer list.
1094
1095 /// Overloading for a user-defined conversion failed.
1097
1098 /// Overloading for initialization by constructor failed.
1100
1101 /// Overloading for list-initialization by constructor failed.
1103
1104 /// Default-initialization of a 'const' object.
1106
1107 /// Initialization of an incomplete type.
1109
1110 /// Variable-length array must not have an initializer.
1112
1113 /// List initialization failed at some point.
1115
1116 /// Initializer has a placeholder type which cannot be
1117 /// resolved by initialization.
1119
1120 /// Trying to take the address of a function that doesn't support
1121 /// having its address taken.
1123
1124 /// List-copy-initialization chose an explicit constructor.
1126
1127 /// Parenthesized list initialization failed at some point.
1128 /// This is a C++20 feature.
1130
1131 // A designated initializer was provided for a non-aggregate type.
1133
1134 /// HLSL intialization list flattening failed.
1136 };
1137
1138private:
1139 /// The reason why initialization failed.
1140 FailureKind Failure;
1141
1142 /// The failed result of overload resolution.
1143 OverloadingResult FailedOverloadResult;
1144
1145 /// The candidate set created when initialization failed.
1146 OverloadCandidateSet FailedCandidateSet;
1147
1148 /// The incomplete type that caused a failure.
1149 QualType FailedIncompleteType;
1150
1151 /// The fixit that needs to be applied to make this initialization
1152 /// succeed.
1153 std::string ZeroInitializationFixit;
1154 SourceLocation ZeroInitializationFixitLoc;
1155
1156public:
1157 /// Call for initializations are invalid but that would be valid
1158 /// zero initialzations if Fixit was applied.
1159 void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
1160 ZeroInitializationFixit = Fixit;
1161 ZeroInitializationFixitLoc = L;
1162 }
1163
1164private:
1165 /// Prints a follow-up note that highlights the location of
1166 /// the initialized entity, if it's remote.
1167 void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
1168
1169public:
1170 /// Try to perform initialization of the given entity, creating a
1171 /// record of the steps required to perform the initialization.
1172 ///
1173 /// The generated initialization sequence will either contain enough
1174 /// information to diagnose
1175 ///
1176 /// \param S the semantic analysis object.
1177 ///
1178 /// \param Entity the entity being initialized.
1179 ///
1180 /// \param Kind the kind of initialization being performed.
1181 ///
1182 /// \param Args the argument(s) provided for initialization.
1183 ///
1184 /// \param TopLevelOfInitList true if we are initializing from an expression
1185 /// at the top level inside an initializer list. This disallows
1186 /// narrowing conversions in C++11 onwards.
1187 /// \param TreatUnavailableAsInvalid true if we want to treat unavailable
1188 /// as invalid.
1190 const InitializedEntity &Entity,
1191 const InitializationKind &Kind,
1192 MultiExprArg Args,
1193 bool TopLevelOfInitList = false,
1194 bool TreatUnavailableAsInvalid = true);
1195 void InitializeFrom(Sema &S, const InitializedEntity &Entity,
1196 const InitializationKind &Kind, MultiExprArg Args,
1197 bool TopLevelOfInitList, bool TreatUnavailableAsInvalid);
1198
1200
1201 /// Perform the actual initialization of the given entity based on
1202 /// the computed initialization sequence.
1203 ///
1204 /// \param S the semantic analysis object.
1205 ///
1206 /// \param Entity the entity being initialized.
1207 ///
1208 /// \param Kind the kind of initialization being performed.
1209 ///
1210 /// \param Args the argument(s) provided for initialization, ownership of
1211 /// which is transferred into the routine.
1212 ///
1213 /// \param ResultType if non-NULL, will be set to the type of the
1214 /// initialized object, which is the type of the declaration in most
1215 /// cases. However, when the initialized object is a variable of
1216 /// incomplete array type and the initializer is an initializer
1217 /// list, this type will be set to the completed array type.
1218 ///
1219 /// \returns an expression that performs the actual object initialization, if
1220 /// the initialization is well-formed. Otherwise, emits diagnostics
1221 /// and returns an invalid expression.
1223 const InitializedEntity &Entity,
1224 const InitializationKind &Kind,
1225 MultiExprArg Args,
1226 QualType *ResultType = nullptr);
1227
1228 /// Diagnose an potentially-invalid initialization sequence.
1229 ///
1230 /// \returns true if the initialization sequence was ill-formed,
1231 /// false otherwise.
1232 bool Diagnose(Sema &S,
1233 const InitializedEntity &Entity,
1234 const InitializationKind &Kind,
1235 ArrayRef<Expr *> Args);
1236
1237 /// Determine the kind of initialization sequence computed.
1238 enum SequenceKind getKind() const { return SequenceKind; }
1239
1240 /// Set the kind of sequence computed.
1242
1243 /// Determine whether the initialization sequence is valid.
1244 explicit operator bool() const { return !Failed(); }
1245
1246 /// Determine whether the initialization sequence is invalid.
1247 bool Failed() const { return SequenceKind == FailedSequence; }
1248
1250
1251 step_iterator step_begin() const { return Steps.begin(); }
1252 step_iterator step_end() const { return Steps.end(); }
1253
1254 using step_range = llvm::iterator_range<step_iterator>;
1255
1256 step_range steps() const { return {step_begin(), step_end()}; }
1257
1258 /// Determine whether this initialization is a direct reference
1259 /// binding (C++ [dcl.init.ref]).
1260 bool isDirectReferenceBinding() const;
1261
1262 /// Determine whether this initialization failed due to an ambiguity.
1263 bool isAmbiguous() const;
1264
1265 /// Determine whether this initialization is direct call to a
1266 /// constructor.
1267 bool isConstructorInitialization() const;
1268
1269 /// Add a new step in the initialization that resolves the address
1270 /// of an overloaded function to a specific function declaration.
1271 ///
1272 /// \param Function the function to which the overloaded function reference
1273 /// resolves.
1276 bool HadMultipleCandidates);
1277
1278 /// Add a new step in the initialization that performs a derived-to-
1279 /// base cast.
1280 ///
1281 /// \param BaseType the base type to which we will be casting.
1282 ///
1283 /// \param Category Indicates whether the result will be treated as an
1284 /// rvalue, an xvalue, or an lvalue.
1285 void AddDerivedToBaseCastStep(QualType BaseType,
1286 ExprValueKind Category);
1287
1288 /// Add a new step binding a reference to an object.
1289 ///
1290 /// \param BindingTemporary True if we are binding a reference to a temporary
1291 /// object (thereby extending its lifetime); false if we are binding to an
1292 /// lvalue or an lvalue treated as an rvalue.
1293 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
1294
1295 /// Add a new step that makes an extraneous copy of the input
1296 /// to a temporary of the same class type.
1297 ///
1298 /// This extraneous copy only occurs during reference binding in
1299 /// C++98/03, where we are permitted (but not required) to introduce
1300 /// an extra copy. At a bare minimum, we must check that we could
1301 /// call the copy constructor, and produce a diagnostic if the copy
1302 /// constructor is inaccessible or no copy constructor matches.
1303 //
1304 /// \param T The type of the temporary being created.
1306
1307 /// Add a new step that makes a copy of the input to an object of
1308 /// the given type, as the final step in class copy-initialization.
1309 void AddFinalCopy(QualType T);
1310
1311 /// Add a new step invoking a conversion function, which is either
1312 /// a constructor or a conversion function.
1314 DeclAccessPair FoundDecl,
1315 QualType T,
1316 bool HadMultipleCandidates);
1317
1318 /// Add a new step that performs a qualification conversion to the
1319 /// given type.
1321 ExprValueKind Category);
1322
1323 /// Add a new step that performs a function reference conversion to the
1324 /// given type.
1326
1327 /// Add a new step that performs conversion from non-atomic to atomic
1328 /// type.
1330
1331 /// Add a new step that applies an implicit conversion sequence.
1333 QualType T, bool TopLevelOfInitList = false);
1334
1335 /// Add a list-initialization step.
1337
1338 /// Add a constructor-initialization step.
1339 ///
1340 /// \param FromInitList The constructor call is syntactically an initializer
1341 /// list.
1342 /// \param AsInitList The constructor is called as an init list constructor.
1345 QualType T,
1346 bool HadMultipleCandidates,
1347 bool FromInitList, bool AsInitList);
1348
1349 /// Add a zero-initialization step.
1351
1352 /// Add a C assignment step.
1353 //
1354 // FIXME: It isn't clear whether this should ever be needed;
1355 // ideally, we would handle everything needed in C in the common
1356 // path. However, that isn't the case yet.
1358
1359 /// Add a string init step.
1361
1362 /// Add an Objective-C object conversion step, which is
1363 /// always a no-op.
1365
1366 /// Add an array initialization loop step.
1368
1369 /// Add an array initialization step.
1370 void AddArrayInitStep(QualType T, bool IsGNUExtension);
1371
1372 /// Add a parenthesized array initialization step.
1374
1375 /// Add a step to pass an object by indirect copy-restore.
1376 void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
1377
1378 /// Add a step to "produce" an Objective-C object (by
1379 /// retaining it).
1381
1382 /// Add a step to construct a std::initializer_list object from an
1383 /// initializer list.
1385
1386 /// Add a step to initialize an OpenCL sampler from an integer
1387 /// constant.
1389
1390 /// Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.)
1391 /// from a zero constant.
1393
1395
1396 /// Only used when initializing structured bindings from an array with
1397 /// direct-list-initialization. Unwrap the initializer list to get the array
1398 /// for array copy.
1399 void AddUnwrapInitListInitStep(InitListExpr *Syntactic);
1400
1401 /// Add steps to unwrap a initializer list for a reference around a
1402 /// single element and rewrap it at the end.
1404
1405 /// Note that this initialization sequence failed.
1406 void SetFailed(FailureKind Failure) {
1408 this->Failure = Failure;
1409 assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
1410 "Incomplete type failure requires a type!");
1411 }
1412
1413 /// Note that this initialization sequence failed due to failed
1414 /// overload resolution.
1415 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
1416
1417 /// Retrieve a reference to the candidate set when overload
1418 /// resolution fails.
1420 return FailedCandidateSet;
1421 }
1422
1423 /// Get the overloading result, for when the initialization
1424 /// sequence failed due to a bad overload.
1426 return FailedOverloadResult;
1427 }
1428
1429 /// Note that this initialization sequence failed due to an
1430 /// incomplete type.
1431 void setIncompleteTypeFailure(QualType IncompleteType) {
1432 FailedIncompleteType = IncompleteType;
1434 }
1435
1436 /// Determine why initialization failed.
1438 assert(Failed() && "Not an initialization failure!");
1439 return Failure;
1440 }
1441
1442 /// Dump a representation of this initialization sequence to
1443 /// the given stream, for debugging purposes.
1444 void dump(raw_ostream &OS) const;
1445
1446 /// Dump a representation of this initialization sequence to
1447 /// standard error, for debugging purposes.
1448 void dump() const;
1449};
1450
1451} // namespace clang
1452
1453#endif // LLVM_CLANG_SEMA_INITIALIZATION_H
Defines the clang::ASTContext interface.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
A POD class for pairing a NamedDecl* with an access specifier.
bool hasAttr() const
Definition DeclBase.h:577
The name of a declaration.
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3160
Represents a function declaration or definition.
Definition Decl.h:2000
One of these records is kept for each identifier that is lexed.
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
Describes an C or C++ initializer list.
Definition Expr.h:5233
Describes the kind of initialization being performed, along with location information for tokens rela...
SourceLocation getLocation() const
Retrieve the location at which initialization is occurring.
static InitializationKind CreateCast(SourceRange TypeRange)
Create a direct initialization due to a cast that isn't a C-style or functional cast.
InitKind
The kind of initialization being performed.
@ IK_DirectList
Direct list-initialization.
@ IK_Value
Value initialization.
@ IK_Direct
Direct initialization.
@ IK_Copy
Copy initialization.
@ IK_Default
Default initialization.
SourceLocation getEqualLoc() const
Retrieve the location of the equal sign for copy initialization (if present).
bool isCStyleOrFunctionalCast() const
Determine whether this initialization is a C-style cast.
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
bool hasParenOrBraceRange() const
Determine whether this initialization has a source range containing the locations of open and closing...
bool isExplicitCast() const
Determine whether this initialization is an explicit cast.
bool isFunctionalCast() const
Determine whether this is a functional-style cast.
InitKind getKind() const
Determine the initialization kind.
static InitializationKind CreateFunctionalCast(SourceLocation StartLoc, SourceRange ParenRange, bool InitList)
Create a direct initialization for a functional cast.
bool AllowExplicit() const
Retrieve whether this initialization allows the use of explicit constructors.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
bool isImplicitValueInit() const
Determine whether this initialization is an implicit value-initialization, e.g., as occurs during agg...
bool isCStyleCast() const
Determine whether this is a C-style cast.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
SourceRange getParenOrBraceRange() const
Retrieve the source range containing the locations of the open and closing parentheses or braces for ...
bool allowExplicitConversionFunctionsInRefBinding() const
Retrieve whether this initialization allows the use of explicit conversion functions when binding a r...
static InitializationKind CreateDirectList(SourceLocation InitLoc, SourceLocation LBraceLoc, SourceLocation RBraceLoc)
bool isStaticCast() const
Determine whether this initialization is a static cast.
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
SourceRange getRange() const
Retrieve the source range that covers the initialization.
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
A single step in the initialization sequence.
StepKind Kind
The kind of conversion or initialization step we are taking.
InitListExpr * WrappingSyntacticList
When Kind = SK_RewrapInitList, the syntactic form of the wrapping list.
ImplicitConversionSequence * ICS
When Kind = SK_ConversionSequence, the implicit conversion sequence.
struct F Function
When Kind == SK_ResolvedOverloadedFunction or Kind == SK_UserConversion, the function that the expres...
step_iterator step_begin() const
void AddListInitializationStep(QualType T)
Add a list-initialization step.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
void AddStringInitStep(QualType T)
Add a string init step.
void AddStdInitializerListConstructionStep(QualType T)
Add a step to construct a std::initializer_list object from an initializer list.
void AddConstructorInitializationStep(DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, bool HadMultipleCandidates, bool FromInitList, bool AsInitList)
Add a constructor-initialization step.
StepKind
Describes the kind of a particular step in an initialization sequence.
@ SK_StdInitializerListConstructorCall
Perform initialization via a constructor taking a single std::initializer_list argument.
@ SK_AtomicConversion
Perform a conversion adding _Atomic to a type.
@ SK_ObjCObjectConversion
An initialization that "converts" an Objective-C object (not a point to an object) to another Objecti...
@ SK_GNUArrayInit
Array initialization (from an array rvalue) as a GNU extension.
@ SK_CastDerivedToBaseLValue
Perform a derived-to-base cast, producing an lvalue.
@ SK_ProduceObjCObject
Produce an Objective-C object pointer.
@ SK_FunctionReferenceConversion
Perform a function reference conversion, see [dcl.init.ref]p4.
@ SK_BindReference
Reference binding to an lvalue.
@ SK_ArrayLoopInit
Array initialization by elementwise copy.
@ SK_ConstructorInitialization
Perform initialization via a constructor.
@ SK_OCLSamplerInit
Initialize an OpenCL sampler from an integer.
@ SK_StringInit
Initialization by string.
@ SK_ZeroInitialization
Zero-initialize the object.
@ SK_CastDerivedToBaseXValue
Perform a derived-to-base cast, producing an xvalue.
@ SK_QualificationConversionXValue
Perform a qualification conversion, producing an xvalue.
@ SK_UserConversion
Perform a user-defined conversion, either via a conversion function or via a constructor.
@ SK_CastDerivedToBasePRValue
Perform a derived-to-base cast, producing an rvalue.
@ SK_BindReferenceToTemporary
Reference binding to a temporary.
@ SK_PassByIndirectRestore
Pass an object by indirect restore.
@ SK_ParenthesizedArrayInit
Array initialization from a parenthesized initializer list.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
@ SK_ArrayInit
Array initialization (from an array rvalue).
@ SK_ExtraneousCopyToTemporary
An optional copy of a temporary object to another temporary object, which is permitted (but not requi...
@ SK_ArrayLoopIndex
Array indexing for initialization by elementwise copy.
@ SK_ConversionSequenceNoNarrowing
Perform an implicit conversion sequence without narrowing.
@ SK_RewrapInitList
Rewrap the single-element initializer list for a reference.
@ SK_ConstructorInitializationFromList
Perform initialization via a constructor, taking arguments from a single InitListExpr.
@ SK_PassByIndirectCopyRestore
Pass an object by indirect copy-and-restore.
@ SK_ResolveAddressOfOverloadedFunction
Resolve the address of an overloaded function to a specific function declaration.
@ SK_UnwrapInitList
Unwrap the single-element initializer list for a reference.
@ SK_FinalCopy
Direct-initialization from a reference-related object in the final stage of class copy-initialization...
@ SK_QualificationConversionLValue
Perform a qualification conversion, producing an lvalue.
@ SK_StdInitializerList
Construct a std::initializer_list from an initializer list.
@ SK_QualificationConversionPRValue
Perform a qualification conversion, producing a prvalue.
@ SK_ConversionSequence
Perform an implicit conversion sequence.
@ SK_ListInitialization
Perform list-initialization without a constructor.
@ SK_OCLZeroOpaqueType
Initialize an opaque OpenCL type (event_t, queue_t, etc.) with zero.
void AddUserConversionStep(FunctionDecl *Function, DeclAccessPair FoundDecl, QualType T, bool HadMultipleCandidates)
Add a new step invoking a conversion function, which is either a constructor or a conversion function...
void SetZeroInitializationFixit(const std::string &Fixit, SourceLocation L)
Call for initializations are invalid but that would be valid zero initialzations if Fixit was applied...
llvm::iterator_range< step_iterator > step_range
InitializationSequence(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList=false, bool TreatUnavailableAsInvalid=true)
Try to perform initialization of the given entity, creating a record of the steps required to perform...
void AddQualificationConversionStep(QualType Ty, ExprValueKind Category)
Add a new step that performs a qualification conversion to the given type.
void AddFunctionReferenceConversionStep(QualType Ty)
Add a new step that performs a function reference conversion to the given type.
void AddDerivedToBaseCastStep(QualType BaseType, ExprValueKind Category)
Add a new step in the initialization that performs a derived-to- base cast.
FailureKind getFailureKind() const
Determine why initialization failed.
void InitializeFrom(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
void AddParenthesizedListInitStep(QualType T)
void SetFailed(FailureKind Failure)
Note that this initialization sequence failed.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
void AddUnwrapInitListInitStep(InitListExpr *Syntactic)
Only used when initializing structured bindings from an array with direct-list-initialization.
void AddOCLZeroOpaqueTypeStep(QualType T)
Add a step to initialzie an OpenCL opaque type (event_t, queue_t, etc.) from a zero constant.
void AddFinalCopy(QualType T)
Add a new step that makes a copy of the input to an object of the given type, as the final step in cl...
OverloadingResult getFailedOverloadResult() const
Get the overloading result, for when the initialization sequence failed due to a bad overload.
void setSequenceKind(enum SequenceKind SK)
Set the kind of sequence computed.
void AddObjCObjectConversionStep(QualType T)
Add an Objective-C object conversion step, which is always a no-op.
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result)
Note that this initialization sequence failed due to failed overload resolution.
step_iterator step_end() const
void AddParenthesizedArrayInitStep(QualType T)
Add a parenthesized array initialization step.
void AddExtraneousCopyToTemporary(QualType T)
Add a new step that makes an extraneous copy of the input to a temporary of the same class type.
void setIncompleteTypeFailure(QualType IncompleteType)
Note that this initialization sequence failed due to an incomplete type.
void AddOCLSamplerInitStep(QualType T)
Add a step to initialize an OpenCL sampler from an integer constant.
void AddCAssignmentStep(QualType T)
Add a C assignment step.
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy)
Add a step to pass an object by indirect copy-restore.
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic)
Add steps to unwrap a initializer list for a reference around a single element and rewrap it at the e...
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
bool Failed() const
Determine whether the initialization sequence is invalid.
void AddAtomicConversionStep(QualType Ty)
Add a new step that performs conversion from non-atomic to atomic type.
void dump() const
Dump a representation of this initialization sequence to standard error, for debugging purposes.
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS, QualType T, bool TopLevelOfInitList=false)
Add a new step that applies an implicit conversion sequence.
void AddZeroInitializationStep(QualType T)
Add a zero-initialization step.
void AddProduceObjCObjectStep(QualType T)
Add a step to "produce" an Objective-C object (by retaining it).
enum SequenceKind getKind() const
Determine the kind of initialization sequence computed.
SequenceKind
Describes the kind of initialization sequence computed.
@ NormalSequence
A normal sequence.
@ FailedSequence
A failed initialization sequence.
@ DependentSequence
A dependent initialization, which could not be type-checked due to the presence of dependent types or...
void AddReferenceBindingStep(QualType T, bool BindingTemporary)
Add a new step binding a reference to an object.
FailureKind
Describes why initialization failed.
@ FK_UserConversionOverloadFailed
Overloading for a user-defined conversion failed.
@ FK_NarrowStringIntoWideCharArray
Initializing a wide char array with narrow string literal.
@ FK_ArrayTypeMismatch
Array type mismatch.
@ FK_ParenthesizedListInitForReference
Reference initialized from a parenthesized initializer list.
@ FK_NonConstLValueReferenceBindingToVectorElement
Non-const lvalue reference binding to a vector element.
@ FK_ReferenceInitDropsQualifiers
Reference binding drops qualifiers.
@ FK_InitListBadDestinationType
Initialization of some unused destination type with an initializer list.
@ FK_ConversionFromPropertyFailed
Implicit conversion failed.
@ FK_NonConstLValueReferenceBindingToUnrelated
Non-const lvalue reference binding to an lvalue of unrelated type.
@ FK_ListConstructorOverloadFailed
Overloading for list-initialization by constructor failed.
@ FK_ReferenceInitFailed
Reference binding failed.
@ FK_ArrayNeedsInitList
Array must be initialized with an initializer list.
@ FK_PlainStringIntoUTF8Char
Initializing char8_t array with plain string literal.
@ FK_NonConstantArrayInit
Non-constant array initializer.
@ FK_NonConstLValueReferenceBindingToTemporary
Non-const lvalue reference binding to a temporary.
@ FK_ConversionFailed
Implicit conversion failed.
@ FK_ArrayNeedsInitListOrStringLiteral
Array must be initialized with an initializer list or a string literal.
@ FK_ParenthesizedListInitForScalar
Scalar initialized from a parenthesized initializer list.
@ FK_HLSLInitListFlatteningFailed
HLSL intialization list flattening failed.
@ FK_PlaceholderType
Initializer has a placeholder type which cannot be resolved by initialization.
@ FK_IncompatWideStringIntoWideChar
Initializing wide char array with incompatible wide string literal.
@ FK_NonConstLValueReferenceBindingToMatrixElement
Non-const lvalue reference binding to a matrix element.
@ FK_TooManyInitsForReference
Too many initializers provided for a reference.
@ FK_NonConstLValueReferenceBindingToBitfield
Non-const lvalue reference binding to a bit-field.
@ FK_ReferenceAddrspaceMismatchTemporary
Reference with mismatching address space binding to temporary.
@ FK_ListInitializationFailed
List initialization failed at some point.
@ FK_TooManyInitsForScalar
Too many initializers for scalar.
@ FK_AddressOfOverloadFailed
Cannot resolve the address of an overloaded function.
@ FK_VariableLengthArrayHasInitializer
Variable-length array must not have an initializer.
@ FK_ArrayNeedsInitListOrWideStringLiteral
Array must be initialized with an initializer list or a wide string literal.
@ FK_RValueReferenceBindingToLValue
Rvalue reference binding to an lvalue.
@ FK_Incomplete
Initialization of an incomplete type.
@ FK_WideStringIntoCharArray
Initializing char array with wide string literal.
@ FK_ExplicitConstructor
List-copy-initialization chose an explicit constructor.
@ FK_ReferenceInitOverloadFailed
Overloading due to reference initialization failed.
@ FK_ConstructorOverloadFailed
Overloading for initialization by constructor failed.
@ FK_ReferenceBindingToInitList
Reference initialization from an initializer list.
@ FK_DefaultInitOfConst
Default-initialization of a 'const' object.
@ FK_ParenthesizedListInitFailed
Parenthesized list initialization failed at some point.
@ FK_AddressOfUnaddressableFunction
Trying to take the address of a function that doesn't support having its address taken.
@ FK_UTF8StringIntoPlainChar
Initializing char array with UTF-8 string literal.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
void AddArrayInitLoopStep(QualType T, QualType EltTy)
Add an array initialization loop step.
void AddAddressOverloadResolutionStep(FunctionDecl *Function, DeclAccessPair Found, bool HadMultipleCandidates)
Add a new step in the initialization that resolves the address of an overloaded function to a specifi...
void AddArrayInitStep(QualType T, bool IsGNUExtension)
Add an array initialization step.
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
SmallVectorImpl< Step >::const_iterator step_iterator
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
Describes an entity that is being initialized.
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
static InitializedEntity InitializeResult(SourceLocation ReturnLoc, QualType Type)
Create the initialization entity for the result of a function.
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
VD Variable
When Kind == EK_Variable, EK_Member, EK_Binding, or EK_TemplateParameter, the variable,...
static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, QualType Type)
Create the initialization entity for a related result.
EntityKind getKind() const
Determine the kind of initialization.
DeclarationName getName() const
Retrieve the name of the entity being initialized.
static InitializedEntity InitializeException(SourceLocation ThrowLoc, QualType Type)
Create the initialization entity for an exception object.
unsigned allocateManglingNumber() const
QualType getType() const
Retrieve type being initialized.
static InitializedEntity InitializeTemporary(ASTContext &Context, TypeSourceInfo *TypeInfo)
Create the initialization entity for a temporary.
ValueDecl * getDecl() const
Retrieve the variable, parameter, or field being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, QualType Type, bool Consumed)
Create the initialization entity for a parameter that is only known by its type.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
bool isImplicitMemberInitializer() const
Is this the implicit initialization of a member of a class from a defaulted constructor?
const InitializedEntity * getParent() const
Retrieve the parent of the entity being initialized, when the initialization itself is occurring with...
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isParameterConsumed() const
Determine whether this initialization consumes the parameter.
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm, QualType Type)
Create the initialization entity for a parameter, but use another type.
TypeSourceInfo * TypeInfo
When Kind == EK_Temporary or EK_CompoundLiteralInit, the type source information for the temporary.
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
unsigned getElementIndex() const
If this is an array, vector, or complex number element, get the element's index.
bool isInheritedVirtualBase() const
Return whether the base is an inherited virtual base.
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type)
void setElementIndex(unsigned Index)
If this is already the initializer for an array or vector element, sets the element index.
SourceLocation getCaptureLoc() const
Determine the location of the capture when initializing field from a captured variable in a lambda.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
bool isParamOrTemplateParamKind() const
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type)
Create the initialization entity for an object allocated via new.
llvm::PointerIntPair< const CXXBaseSpecifier *, 1 > Base
When Kind == EK_Base, the base specifier that provides the base class.
static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo, QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
bool allowsNRVO() const
Determine whether this initialization allows the named return value optimization, which also applies ...
void dump() const
Dump a representation of the initialized entity to standard error, for debugging purposes.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
EntityKind
Specifies the kind of entity being initialized.
@ EK_Variable
The entity being initialized is a variable.
@ EK_Temporary
The entity being initialized is a temporary object.
@ EK_Binding
The entity being initialized is a structured binding of a decomposition declaration.
@ EK_BlockElement
The entity being initialized is a field of block descriptor for the copied-in c++ object.
@ EK_MatrixElement
The entity being initialized is an element of a matrix.
@ EK_Parameter_CF_Audited
The entity being initialized is a function parameter; function is member of group of audited CF APIs.
@ EK_LambdaToBlockConversionBlockElement
The entity being initialized is a field of block descriptor for the copied-in lambda object that's us...
@ EK_Member
The entity being initialized is a non-static data member subobject.
@ EK_Base
The entity being initialized is a base member subobject.
@ EK_Result
The entity being initialized is the result of a function call.
@ EK_TemplateParameter
The entity being initialized is a non-type template parameter.
@ EK_StmtExprResult
The entity being initialized is the result of a statement expression.
@ EK_ParenAggInitMember
The entity being initialized is a non-static data member subobject of an object initialized via paren...
@ EK_VectorElement
The entity being initialized is an element of a vector.
@ EK_New
The entity being initialized is an object (or array of objects) allocated via new.
@ EK_CompoundLiteralInit
The entity being initialized is the initializer for a compound literal.
@ EK_Parameter
The entity being initialized is a function parameter.
@ EK_Delegating
The initialization is being done by a delegating constructor.
@ EK_ComplexElement
The entity being initialized is the real or imaginary part of a complex number.
@ EK_ArrayElement
The entity being initialized is an element of an array.
@ EK_LambdaCapture
The entity being initialized is the field that captures a variable in a lambda.
@ EK_Exception
The entity being initialized is an exception object that is being thrown.
@ EK_RelatedResult
The entity being implicitly initialized back to the formal result type.
StringRef getCapturedVarName() const
For a lambda capture, return the capture's name.
static InitializedEntity InitializeMemberFromParenAggInit(FieldDecl *Member)
Create the initialization entity for a member subobject initialized via parenthesized aggregate init.
SourceLocation getThrowLoc() const
Determine the location of the 'throw' keyword when initializing an exception object.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
unsigned Index
When Kind == EK_ArrayElement, EK_VectorElement, EK_MatrixElement, or EK_ComplexElement,...
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static InitializedEntity InitializeMember(IndirectFieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
bool isVariableLengthArrayNew() const
Determine whether this is an array new with an unknown bound.
ObjCMethodDecl * MethodDecl
When Kind == EK_RelatedResult, the ObjectiveC method where result type was implicitly changed to acco...
bool isDefaultMemberInitializer() const
Is this the default member initializer of a member (specified inside the class definition)?
llvm::PointerIntPair< ParmVarDecl *, 1 > Parameter
When Kind == EK_Parameter, the ParmVarDecl, with the integer indicating whether the parameter is "con...
const CXXBaseSpecifier * getBaseSpecifier() const
Retrieve the base specifier.
SourceLocation getReturnLoc() const
Determine the location of the 'return' keyword when initializing the result of a function call.
TypeSourceInfo * getTypeSourceInfo() const
Retrieve complete type-source information for the object being constructed, if known.
ObjCMethodDecl * getMethodDecl() const
Retrieve the ObjectiveC method being initialized.
This represents a decl that may have a name.
Definition Decl.h:274
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
Represents a parameter to a function.
Definition Decl.h:1790
A (possibly-)qualified type.
Definition TypeBase.h:937
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
A container of type source information.
Definition TypeBase.h:8249
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8260
The base class of the type hierarchy.
Definition TypeBase.h:1833
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
#define bool
Definition gpuintrin.h:32
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Implicit
An implicit conversion.
Definition Sema.h:438
#define false
Definition stdbool.h:26