1 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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 implements semantic analysis for initializers.
11 //===----------------------------------------------------------------------===//
13 #include "CheckExprLifetime.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/IgnoreExpr.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/Designator.h"
25 #include "clang/Sema/EnterExpressionEvaluationContext.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Ownership.h"
29 #include "clang/Sema/SemaObjC.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/FoldingSet.h"
32 #include "llvm/ADT/PointerIntPair.h"
33 #include "llvm/ADT/STLForwardCompat.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
39 using namespace clang
;
41 //===----------------------------------------------------------------------===//
42 // Sema Initialization Checking
43 //===----------------------------------------------------------------------===//
45 /// Check whether T is compatible with a wide character type (wchar_t,
46 /// char16_t or char32_t).
47 static bool IsWideCharCompatible(QualType T
, ASTContext
&Context
) {
48 if (Context
.typesAreCompatible(Context
.getWideCharType(), T
))
50 if (Context
.getLangOpts().CPlusPlus
|| Context
.getLangOpts().C11
) {
51 return Context
.typesAreCompatible(Context
.Char16Ty
, T
) ||
52 Context
.typesAreCompatible(Context
.Char32Ty
, T
);
57 enum StringInitFailureKind
{
59 SIF_NarrowStringIntoWideChar
,
60 SIF_WideStringIntoChar
,
61 SIF_IncompatWideStringIntoWideChar
,
62 SIF_UTF8StringIntoPlainChar
,
63 SIF_PlainStringIntoUTF8Char
,
67 /// Check whether the array of type AT can be initialized by the Init
68 /// expression by means of string initialization. Returns SIF_None if so,
69 /// otherwise returns a StringInitFailureKind that describes why the
70 /// initialization would not work.
71 static StringInitFailureKind
IsStringInit(Expr
*Init
, const ArrayType
*AT
,
72 ASTContext
&Context
) {
73 if (!isa
<ConstantArrayType
>(AT
) && !isa
<IncompleteArrayType
>(AT
))
76 // See if this is a string literal or @encode.
77 Init
= Init
->IgnoreParens();
79 // Handle @encode, which is a narrow string.
80 if (isa
<ObjCEncodeExpr
>(Init
) && AT
->getElementType()->isCharType())
83 // Otherwise we can only handle string literals.
84 StringLiteral
*SL
= dyn_cast
<StringLiteral
>(Init
);
88 const QualType ElemTy
=
89 Context
.getCanonicalType(AT
->getElementType()).getUnqualifiedType();
91 auto IsCharOrUnsignedChar
= [](const QualType
&T
) {
92 const BuiltinType
*BT
= dyn_cast
<BuiltinType
>(T
.getTypePtr());
93 return BT
&& BT
->isCharType() && BT
->getKind() != BuiltinType::SChar
;
96 switch (SL
->getKind()) {
97 case StringLiteralKind::UTF8
:
98 // char8_t array can be initialized with a UTF-8 string.
99 // - C++20 [dcl.init.string] (DR)
100 // Additionally, an array of char or unsigned char may be initialized
101 // by a UTF-8 string literal.
102 if (ElemTy
->isChar8Type() ||
103 (Context
.getLangOpts().Char8
&&
104 IsCharOrUnsignedChar(ElemTy
.getCanonicalType())))
107 case StringLiteralKind::Ordinary
:
108 // char array can be initialized with a narrow string.
109 // Only allow char x[] = "foo"; not char x[] = L"foo";
110 if (ElemTy
->isCharType())
111 return (SL
->getKind() == StringLiteralKind::UTF8
&&
112 Context
.getLangOpts().Char8
)
113 ? SIF_UTF8StringIntoPlainChar
115 if (ElemTy
->isChar8Type())
116 return SIF_PlainStringIntoUTF8Char
;
117 if (IsWideCharCompatible(ElemTy
, Context
))
118 return SIF_NarrowStringIntoWideChar
;
120 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
121 // "An array with element type compatible with a qualified or unqualified
122 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
123 // string literal with the corresponding encoding prefix (L, u, or U,
124 // respectively), optionally enclosed in braces.
125 case StringLiteralKind::UTF16
:
126 if (Context
.typesAreCompatible(Context
.Char16Ty
, ElemTy
))
128 if (ElemTy
->isCharType() || ElemTy
->isChar8Type())
129 return SIF_WideStringIntoChar
;
130 if (IsWideCharCompatible(ElemTy
, Context
))
131 return SIF_IncompatWideStringIntoWideChar
;
133 case StringLiteralKind::UTF32
:
134 if (Context
.typesAreCompatible(Context
.Char32Ty
, ElemTy
))
136 if (ElemTy
->isCharType() || ElemTy
->isChar8Type())
137 return SIF_WideStringIntoChar
;
138 if (IsWideCharCompatible(ElemTy
, Context
))
139 return SIF_IncompatWideStringIntoWideChar
;
141 case StringLiteralKind::Wide
:
142 if (Context
.typesAreCompatible(Context
.getWideCharType(), ElemTy
))
144 if (ElemTy
->isCharType() || ElemTy
->isChar8Type())
145 return SIF_WideStringIntoChar
;
146 if (IsWideCharCompatible(ElemTy
, Context
))
147 return SIF_IncompatWideStringIntoWideChar
;
149 case StringLiteralKind::Unevaluated
:
150 assert(false && "Unevaluated string literal in initialization");
154 llvm_unreachable("missed a StringLiteral kind?");
157 static StringInitFailureKind
IsStringInit(Expr
*init
, QualType declType
,
158 ASTContext
&Context
) {
159 const ArrayType
*arrayType
= Context
.getAsArrayType(declType
);
162 return IsStringInit(init
, arrayType
, Context
);
165 bool Sema::IsStringInit(Expr
*Init
, const ArrayType
*AT
) {
166 return ::IsStringInit(Init
, AT
, Context
) == SIF_None
;
169 /// Update the type of a string literal, including any surrounding parentheses,
170 /// to match the type of the object which it is initializing.
171 static void updateStringLiteralType(Expr
*E
, QualType Ty
) {
174 E
->setValueKind(VK_PRValue
);
175 if (isa
<StringLiteral
>(E
) || isa
<ObjCEncodeExpr
>(E
))
177 E
= IgnoreParensSingleStep(E
);
181 /// Fix a compound literal initializing an array so it's correctly marked
183 static void updateGNUCompoundLiteralRValue(Expr
*E
) {
185 E
->setValueKind(VK_PRValue
);
186 if (isa
<CompoundLiteralExpr
>(E
))
188 E
= IgnoreParensSingleStep(E
);
192 static bool initializingConstexprVariable(const InitializedEntity
&Entity
) {
193 Decl
*D
= Entity
.getDecl();
194 const InitializedEntity
*Parent
= &Entity
;
197 D
= Parent
->getDecl();
198 Parent
= Parent
->getParent();
201 if (const auto *VD
= dyn_cast_if_present
<VarDecl
>(D
); VD
&& VD
->isConstexpr())
207 static void CheckC23ConstexprInitStringLiteral(const StringLiteral
*SE
,
208 Sema
&SemaRef
, QualType
&TT
);
210 static void CheckStringInit(Expr
*Str
, QualType
&DeclT
, const ArrayType
*AT
,
211 Sema
&S
, bool CheckC23ConstexprInit
= false) {
212 // Get the length of the string as parsed.
213 auto *ConstantArrayTy
=
214 cast
<ConstantArrayType
>(Str
->getType()->getAsArrayTypeUnsafe());
215 uint64_t StrLength
= ConstantArrayTy
->getZExtSize();
217 if (CheckC23ConstexprInit
)
218 if (const StringLiteral
*SL
= dyn_cast
<StringLiteral
>(Str
->IgnoreParens()))
219 CheckC23ConstexprInitStringLiteral(SL
, S
, DeclT
);
221 if (const IncompleteArrayType
*IAT
= dyn_cast
<IncompleteArrayType
>(AT
)) {
222 // C99 6.7.8p14. We have an array of character type with unknown size
223 // being initialized to a string literal.
224 llvm::APInt
ConstVal(32, StrLength
);
225 // Return a new array type (C99 6.7.8p22).
226 DeclT
= S
.Context
.getConstantArrayType(
227 IAT
->getElementType(), ConstVal
, nullptr, ArraySizeModifier::Normal
, 0);
228 updateStringLiteralType(Str
, DeclT
);
232 const ConstantArrayType
*CAT
= cast
<ConstantArrayType
>(AT
);
234 // We have an array of character type with known size. However,
235 // the size may be smaller or larger than the string we are initializing.
236 // FIXME: Avoid truncation for 64-bit length strings.
237 if (S
.getLangOpts().CPlusPlus
) {
238 if (StringLiteral
*SL
= dyn_cast
<StringLiteral
>(Str
->IgnoreParens())) {
239 // For Pascal strings it's OK to strip off the terminating null character,
240 // so the example below is valid:
242 // unsigned char a[2] = "\pa";
247 // [dcl.init.string]p2
248 if (StrLength
> CAT
->getZExtSize())
249 S
.Diag(Str
->getBeginLoc(),
250 diag::err_initializer_string_for_char_array_too_long
)
251 << CAT
->getZExtSize() << StrLength
<< Str
->getSourceRange();
254 if (StrLength
- 1 > CAT
->getZExtSize())
255 S
.Diag(Str
->getBeginLoc(),
256 diag::ext_initializer_string_for_char_array_too_long
)
257 << Str
->getSourceRange();
260 // Set the type to the actual size that we are initializing. If we have
262 // char x[1] = "foo";
263 // then this will set the string literal's type to char[1].
264 updateStringLiteralType(Str
, DeclT
);
267 //===----------------------------------------------------------------------===//
268 // Semantic checking for initializer lists.
269 //===----------------------------------------------------------------------===//
273 /// Semantic checking for initializer lists.
275 /// The InitListChecker class contains a set of routines that each
276 /// handle the initialization of a certain kind of entity, e.g.,
277 /// arrays, vectors, struct/union types, scalars, etc. The
278 /// InitListChecker itself performs a recursive walk of the subobject
279 /// structure of the type to be initialized, while stepping through
280 /// the initializer list one element at a time. The IList and Index
281 /// parameters to each of the Check* routines contain the active
282 /// (syntactic) initializer list and the index into that initializer
283 /// list that represents the current initializer. Each routine is
284 /// responsible for moving that Index forward as it consumes elements.
286 /// Each Check* routine also has a StructuredList/StructuredIndex
287 /// arguments, which contains the current "structured" (semantic)
288 /// initializer list and the index into that initializer list where we
289 /// are copying initializers as we map them over to the semantic
290 /// list. Once we have completed our recursive walk of the subobject
291 /// structure, we will have constructed a full semantic initializer
294 /// C99 designators cause changes in the initializer list traversal,
295 /// because they make the initialization "jump" into a specific
296 /// subobject and then continue the initialization from that
297 /// point. CheckDesignatedInitializer() recursively steps into the
298 /// designated subobject and manages backing out the recursion to
299 /// initialize the subobjects after the one designated.
301 /// If an initializer list contains any designators, we build a placeholder
302 /// structured list even in 'verify only' mode, so that we can track which
303 /// elements need 'empty' initializtion.
304 class InitListChecker
{
306 bool hadError
= false;
307 bool VerifyOnly
; // No diagnostics.
308 bool TreatUnavailableAsInvalid
; // Used only in VerifyOnly mode.
309 bool InOverloadResolution
;
310 InitListExpr
*FullyStructuredList
= nullptr;
311 NoInitExpr
*DummyExpr
= nullptr;
312 SmallVectorImpl
<QualType
> *AggrDeductionCandidateParamTypes
= nullptr;
313 EmbedExpr
*CurEmbed
= nullptr; // Save current embed we're processing.
314 unsigned CurEmbedIndex
= 0;
316 NoInitExpr
*getDummyInit() {
318 DummyExpr
= new (SemaRef
.Context
) NoInitExpr(SemaRef
.Context
.VoidTy
);
322 void CheckImplicitInitList(const InitializedEntity
&Entity
,
323 InitListExpr
*ParentIList
, QualType T
,
324 unsigned &Index
, InitListExpr
*StructuredList
,
325 unsigned &StructuredIndex
);
326 void CheckExplicitInitList(const InitializedEntity
&Entity
,
327 InitListExpr
*IList
, QualType
&T
,
328 InitListExpr
*StructuredList
,
329 bool TopLevelObject
= false);
330 void CheckListElementTypes(const InitializedEntity
&Entity
,
331 InitListExpr
*IList
, QualType
&DeclType
,
332 bool SubobjectIsDesignatorContext
,
334 InitListExpr
*StructuredList
,
335 unsigned &StructuredIndex
,
336 bool TopLevelObject
= false);
337 void CheckSubElementType(const InitializedEntity
&Entity
,
338 InitListExpr
*IList
, QualType ElemType
,
340 InitListExpr
*StructuredList
,
341 unsigned &StructuredIndex
,
342 bool DirectlyDesignated
= false);
343 void CheckComplexType(const InitializedEntity
&Entity
,
344 InitListExpr
*IList
, QualType DeclType
,
346 InitListExpr
*StructuredList
,
347 unsigned &StructuredIndex
);
348 void CheckScalarType(const InitializedEntity
&Entity
,
349 InitListExpr
*IList
, QualType DeclType
,
351 InitListExpr
*StructuredList
,
352 unsigned &StructuredIndex
);
353 void CheckReferenceType(const InitializedEntity
&Entity
,
354 InitListExpr
*IList
, QualType DeclType
,
356 InitListExpr
*StructuredList
,
357 unsigned &StructuredIndex
);
358 void CheckVectorType(const InitializedEntity
&Entity
,
359 InitListExpr
*IList
, QualType DeclType
, unsigned &Index
,
360 InitListExpr
*StructuredList
,
361 unsigned &StructuredIndex
);
362 void CheckStructUnionTypes(const InitializedEntity
&Entity
,
363 InitListExpr
*IList
, QualType DeclType
,
364 CXXRecordDecl::base_class_const_range Bases
,
365 RecordDecl::field_iterator Field
,
366 bool SubobjectIsDesignatorContext
, unsigned &Index
,
367 InitListExpr
*StructuredList
,
368 unsigned &StructuredIndex
,
369 bool TopLevelObject
= false);
370 void CheckArrayType(const InitializedEntity
&Entity
,
371 InitListExpr
*IList
, QualType
&DeclType
,
372 llvm::APSInt elementIndex
,
373 bool SubobjectIsDesignatorContext
, unsigned &Index
,
374 InitListExpr
*StructuredList
,
375 unsigned &StructuredIndex
);
376 bool CheckDesignatedInitializer(const InitializedEntity
&Entity
,
377 InitListExpr
*IList
, DesignatedInitExpr
*DIE
,
379 QualType
&CurrentObjectType
,
380 RecordDecl::field_iterator
*NextField
,
381 llvm::APSInt
*NextElementIndex
,
383 InitListExpr
*StructuredList
,
384 unsigned &StructuredIndex
,
385 bool FinishSubobjectInit
,
386 bool TopLevelObject
);
387 InitListExpr
*getStructuredSubobjectInit(InitListExpr
*IList
, unsigned Index
,
388 QualType CurrentObjectType
,
389 InitListExpr
*StructuredList
,
390 unsigned StructuredIndex
,
391 SourceRange InitRange
,
392 bool IsFullyOverwritten
= false);
393 void UpdateStructuredListElement(InitListExpr
*StructuredList
,
394 unsigned &StructuredIndex
,
396 InitListExpr
*createInitListExpr(QualType CurrentObjectType
,
397 SourceRange InitRange
,
398 unsigned ExpectedNumInits
);
399 int numArrayElements(QualType DeclType
);
400 int numStructUnionElements(QualType DeclType
);
401 static RecordDecl
*getRecordDecl(QualType DeclType
);
403 ExprResult
PerformEmptyInit(SourceLocation Loc
,
404 const InitializedEntity
&Entity
);
406 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
407 void diagnoseInitOverride(Expr
*OldInit
, SourceRange NewInitRange
,
408 bool UnionOverride
= false,
409 bool FullyOverwritten
= true) {
410 // Overriding an initializer via a designator is valid with C99 designated
411 // initializers, but ill-formed with C++20 designated initializers.
413 SemaRef
.getLangOpts().CPlusPlus
414 ? (UnionOverride
? diag::ext_initializer_union_overrides
415 : diag::ext_initializer_overrides
)
416 : diag::warn_initializer_overrides
;
418 if (InOverloadResolution
&& SemaRef
.getLangOpts().CPlusPlus
) {
419 // In overload resolution, we have to strictly enforce the rules, and so
420 // don't allow any overriding of prior initializers. This matters for a
423 // union U { int a, b; };
424 // struct S { int a, b; };
427 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
428 // consistency, we disallow all overriding of prior initializers in
429 // overload resolution, not only overriding of union members.
431 } else if (OldInit
->getType().isDestructedType() && !FullyOverwritten
) {
432 // If we'll be keeping around the old initializer but overwriting part of
433 // the object it initialized, and that object is not trivially
434 // destructible, this can leak. Don't allow that, not even as an
437 // FIXME: It might be reasonable to allow this in cases where the part of
438 // the initializer that we're overriding has trivial destruction.
439 DiagID
= diag::err_initializer_overrides_destructed
;
440 } else if (!OldInit
->getSourceRange().isValid()) {
441 // We need to check on source range validity because the previous
442 // initializer does not have to be an explicit initializer. e.g.,
444 // struct P { int a, b; };
445 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
447 // There is an overwrite taking place because the first braced initializer
448 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
450 // Such overwrites are harmless, so we don't diagnose them. (Note that in
451 // C++, this cannot be reached unless we've already seen and diagnosed a
452 // different conformance issue, such as a mixture of designated and
453 // non-designated initializers or a multi-level designator.)
458 SemaRef
.Diag(NewInitRange
.getBegin(), DiagID
)
459 << NewInitRange
<< FullyOverwritten
<< OldInit
->getType();
460 SemaRef
.Diag(OldInit
->getBeginLoc(), diag::note_previous_initializer
)
461 << (OldInit
->HasSideEffects(SemaRef
.Context
) && FullyOverwritten
)
462 << OldInit
->getSourceRange();
466 // Explanation on the "FillWithNoInit" mode:
468 // Assume we have the following definitions (Case#1):
469 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
470 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
472 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
473 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
475 // But if we have (Case#2):
476 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
478 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
479 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
481 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
482 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
483 // initializers but with special "NoInitExpr" place holders, which tells the
484 // CodeGen not to generate any initializers for these parts.
485 void FillInEmptyInitForBase(unsigned Init
, const CXXBaseSpecifier
&Base
,
486 const InitializedEntity
&ParentEntity
,
487 InitListExpr
*ILE
, bool &RequiresSecondPass
,
488 bool FillWithNoInit
);
489 void FillInEmptyInitForField(unsigned Init
, FieldDecl
*Field
,
490 const InitializedEntity
&ParentEntity
,
491 InitListExpr
*ILE
, bool &RequiresSecondPass
,
492 bool FillWithNoInit
= false);
493 void FillInEmptyInitializations(const InitializedEntity
&Entity
,
494 InitListExpr
*ILE
, bool &RequiresSecondPass
,
495 InitListExpr
*OuterILE
, unsigned OuterIndex
,
496 bool FillWithNoInit
= false);
497 bool CheckFlexibleArrayInit(const InitializedEntity
&Entity
,
498 Expr
*InitExpr
, FieldDecl
*Field
,
499 bool TopLevelObject
);
500 void CheckEmptyInitializable(const InitializedEntity
&Entity
,
503 Expr
*HandleEmbed(EmbedExpr
*Embed
, const InitializedEntity
&Entity
) {
504 Expr
*Result
= nullptr;
505 // Undrestand which part of embed we'd like to reference.
510 // Reference just one if we're initializing a single scalar.
511 uint64_t ElsCount
= 1;
512 // Otherwise try to fill whole array with embed data.
513 if (Entity
.getKind() == InitializedEntity::EK_ArrayElement
) {
515 SemaRef
.Context
.getAsArrayType(Entity
.getParent()->getType());
516 assert(AType
&& "expected array type when initializing array");
517 ElsCount
= Embed
->getDataElementCount();
518 if (const auto *CAType
= dyn_cast
<ConstantArrayType
>(AType
))
519 ElsCount
= std::min(CAType
->getSize().getZExtValue(),
520 ElsCount
- CurEmbedIndex
);
521 if (ElsCount
== Embed
->getDataElementCount()) {
528 Result
= new (SemaRef
.Context
)
529 EmbedExpr(SemaRef
.Context
, Embed
->getLocation(), Embed
->getData(),
530 CurEmbedIndex
, ElsCount
);
531 CurEmbedIndex
+= ElsCount
;
532 if (CurEmbedIndex
>= Embed
->getDataElementCount()) {
541 Sema
&S
, const InitializedEntity
&Entity
, InitListExpr
*IL
, QualType
&T
,
542 bool VerifyOnly
, bool TreatUnavailableAsInvalid
,
543 bool InOverloadResolution
= false,
544 SmallVectorImpl
<QualType
> *AggrDeductionCandidateParamTypes
= nullptr);
545 InitListChecker(Sema
&S
, const InitializedEntity
&Entity
, InitListExpr
*IL
,
547 SmallVectorImpl
<QualType
> &AggrDeductionCandidateParamTypes
)
548 : InitListChecker(S
, Entity
, IL
, T
, /*VerifyOnly=*/true,
549 /*TreatUnavailableAsInvalid=*/false,
550 /*InOverloadResolution=*/false,
551 &AggrDeductionCandidateParamTypes
) {}
553 bool HadError() { return hadError
; }
555 // Retrieves the fully-structured initializer list used for
556 // semantic analysis and code generation.
557 InitListExpr
*getFullyStructuredList() const { return FullyStructuredList
; }
560 } // end anonymous namespace
562 ExprResult
InitListChecker::PerformEmptyInit(SourceLocation Loc
,
563 const InitializedEntity
&Entity
) {
564 InitializationKind Kind
= InitializationKind::CreateValue(Loc
, Loc
, Loc
,
566 MultiExprArg SubInit
;
568 InitListExpr
DummyInitList(SemaRef
.Context
, Loc
, {}, Loc
);
570 // C++ [dcl.init.aggr]p7:
571 // If there are fewer initializer-clauses in the list than there are
572 // members in the aggregate, then each member not explicitly initialized
574 bool EmptyInitList
= SemaRef
.getLangOpts().CPlusPlus11
&&
575 Entity
.getType()->getBaseElementTypeUnsafe()->isRecordType();
578 // shall be initialized [...] from an empty initializer list.
580 // We apply the resolution of this DR to C++11 but not C++98, since C++98
581 // does not have useful semantics for initialization from an init list.
582 // We treat this as copy-initialization, because aggregate initialization
583 // always performs copy-initialization on its elements.
585 // Only do this if we're initializing a class type, to avoid filling in
586 // the initializer list where possible.
587 InitExpr
= VerifyOnly
? &DummyInitList
588 : new (SemaRef
.Context
)
589 InitListExpr(SemaRef
.Context
, Loc
, {}, Loc
);
590 InitExpr
->setType(SemaRef
.Context
.VoidTy
);
592 Kind
= InitializationKind::CreateCopy(Loc
, Loc
);
595 // shall be value-initialized.
598 InitializationSequence
InitSeq(SemaRef
, Entity
, Kind
, SubInit
);
599 // libstdc++4.6 marks the vector default constructor as explicit in
600 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
601 // stlport does so too. Look for std::__debug for libstdc++, and for
602 // std:: for stlport. This is effectively a compiler-side implementation of
604 if (!InitSeq
&& EmptyInitList
&& InitSeq
.getFailureKind() ==
605 InitializationSequence::FK_ExplicitConstructor
) {
606 OverloadCandidateSet::iterator Best
;
607 OverloadingResult O
=
608 InitSeq
.getFailedCandidateSet()
609 .BestViableFunction(SemaRef
, Kind
.getLocation(), Best
);
611 assert(O
== OR_Success
&& "Inconsistent overload resolution");
612 CXXConstructorDecl
*CtorDecl
= cast
<CXXConstructorDecl
>(Best
->Function
);
613 CXXRecordDecl
*R
= CtorDecl
->getParent();
615 if (CtorDecl
->getMinRequiredArguments() == 0 &&
616 CtorDecl
->isExplicit() && R
->getDeclName() &&
617 SemaRef
.SourceMgr
.isInSystemHeader(CtorDecl
->getLocation())) {
618 bool IsInStd
= false;
619 for (NamespaceDecl
*ND
= dyn_cast
<NamespaceDecl
>(R
->getDeclContext());
620 ND
&& !IsInStd
; ND
= dyn_cast
<NamespaceDecl
>(ND
->getParent())) {
621 if (SemaRef
.getStdNamespace()->InEnclosingNamespaceSetOf(ND
))
625 if (IsInStd
&& llvm::StringSwitch
<bool>(R
->getName())
626 .Cases("basic_string", "deque", "forward_list", true)
627 .Cases("list", "map", "multimap", "multiset", true)
628 .Cases("priority_queue", "queue", "set", "stack", true)
629 .Cases("unordered_map", "unordered_set", "vector", true)
631 InitSeq
.InitializeFrom(
633 InitializationKind::CreateValue(Loc
, Loc
, Loc
, true),
634 MultiExprArg(), /*TopLevelOfInitList=*/false,
635 TreatUnavailableAsInvalid
);
636 // Emit a warning for this. System header warnings aren't shown
637 // by default, but people working on system headers should see it.
639 SemaRef
.Diag(CtorDecl
->getLocation(),
640 diag::warn_invalid_initializer_from_system_header
);
641 if (Entity
.getKind() == InitializedEntity::EK_Member
)
642 SemaRef
.Diag(Entity
.getDecl()->getLocation(),
643 diag::note_used_in_initialization_here
);
644 else if (Entity
.getKind() == InitializedEntity::EK_ArrayElement
)
645 SemaRef
.Diag(Loc
, diag::note_used_in_initialization_here
);
652 InitSeq
.Diagnose(SemaRef
, Entity
, Kind
, SubInit
);
653 if (Entity
.getKind() == InitializedEntity::EK_Member
)
654 SemaRef
.Diag(Entity
.getDecl()->getLocation(),
655 diag::note_in_omitted_aggregate_initializer
)
656 << /*field*/1 << Entity
.getDecl();
657 else if (Entity
.getKind() == InitializedEntity::EK_ArrayElement
) {
658 bool IsTrailingArrayNewMember
=
659 Entity
.getParent() &&
660 Entity
.getParent()->isVariableLengthArrayNew();
661 SemaRef
.Diag(Loc
, diag::note_in_omitted_aggregate_initializer
)
662 << (IsTrailingArrayNewMember
? 2 : /*array element*/0)
663 << Entity
.getElementIndex();
670 return VerifyOnly
? ExprResult()
671 : InitSeq
.Perform(SemaRef
, Entity
, Kind
, SubInit
);
674 void InitListChecker::CheckEmptyInitializable(const InitializedEntity
&Entity
,
675 SourceLocation Loc
) {
676 // If we're building a fully-structured list, we'll check this at the end
677 // once we know which elements are actually initialized. Otherwise, we know
678 // that there are no designators so we can just check now.
679 if (FullyStructuredList
)
681 PerformEmptyInit(Loc
, Entity
);
684 void InitListChecker::FillInEmptyInitForBase(
685 unsigned Init
, const CXXBaseSpecifier
&Base
,
686 const InitializedEntity
&ParentEntity
, InitListExpr
*ILE
,
687 bool &RequiresSecondPass
, bool FillWithNoInit
) {
688 InitializedEntity BaseEntity
= InitializedEntity::InitializeBase(
689 SemaRef
.Context
, &Base
, false, &ParentEntity
);
691 if (Init
>= ILE
->getNumInits() || !ILE
->getInit(Init
)) {
692 ExprResult BaseInit
= FillWithNoInit
693 ? new (SemaRef
.Context
) NoInitExpr(Base
.getType())
694 : PerformEmptyInit(ILE
->getEndLoc(), BaseEntity
);
695 if (BaseInit
.isInvalid()) {
701 assert(Init
< ILE
->getNumInits() && "should have been expanded");
702 ILE
->setInit(Init
, BaseInit
.getAs
<Expr
>());
704 } else if (InitListExpr
*InnerILE
=
705 dyn_cast
<InitListExpr
>(ILE
->getInit(Init
))) {
706 FillInEmptyInitializations(BaseEntity
, InnerILE
, RequiresSecondPass
,
707 ILE
, Init
, FillWithNoInit
);
708 } else if (DesignatedInitUpdateExpr
*InnerDIUE
=
709 dyn_cast
<DesignatedInitUpdateExpr
>(ILE
->getInit(Init
))) {
710 FillInEmptyInitializations(BaseEntity
, InnerDIUE
->getUpdater(),
711 RequiresSecondPass
, ILE
, Init
,
712 /*FillWithNoInit =*/true);
716 void InitListChecker::FillInEmptyInitForField(unsigned Init
, FieldDecl
*Field
,
717 const InitializedEntity
&ParentEntity
,
719 bool &RequiresSecondPass
,
720 bool FillWithNoInit
) {
721 SourceLocation Loc
= ILE
->getEndLoc();
722 unsigned NumInits
= ILE
->getNumInits();
723 InitializedEntity MemberEntity
724 = InitializedEntity::InitializeMember(Field
, &ParentEntity
);
726 if (Init
>= NumInits
|| !ILE
->getInit(Init
)) {
727 if (const RecordType
*RType
= ILE
->getType()->getAs
<RecordType
>())
728 if (!RType
->getDecl()->isUnion())
729 assert((Init
< NumInits
|| VerifyOnly
) &&
730 "This ILE should have been expanded");
732 if (FillWithNoInit
) {
733 assert(!VerifyOnly
&& "should not fill with no-init in verify-only mode");
734 Expr
*Filler
= new (SemaRef
.Context
) NoInitExpr(Field
->getType());
736 ILE
->setInit(Init
, Filler
);
738 ILE
->updateInit(SemaRef
.Context
, Init
, Filler
);
741 // C++1y [dcl.init.aggr]p7:
742 // If there are fewer initializer-clauses in the list than there are
743 // members in the aggregate, then each member not explicitly initialized
744 // shall be initialized from its brace-or-equal-initializer [...]
745 if (Field
->hasInClassInitializer()) {
750 // Enter a default initializer rebuild context, then we can support
751 // lifetime extension of temporary created by aggregate initialization
752 // using a default member initializer.
753 // CWG1815 (https://wg21.link/CWG1815).
754 EnterExpressionEvaluationContext
RebuildDefaultInit(
755 SemaRef
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
756 SemaRef
.currentEvaluationContext().RebuildDefaultArgOrDefaultInit
=
758 SemaRef
.currentEvaluationContext().DelayedDefaultInitializationContext
=
759 SemaRef
.parentEvaluationContext()
760 .DelayedDefaultInitializationContext
;
761 SemaRef
.currentEvaluationContext().InLifetimeExtendingContext
=
762 SemaRef
.parentEvaluationContext().InLifetimeExtendingContext
;
763 DIE
= SemaRef
.BuildCXXDefaultInitExpr(Loc
, Field
);
765 if (DIE
.isInvalid()) {
769 SemaRef
.checkInitializerLifetime(MemberEntity
, DIE
.get());
771 ILE
->setInit(Init
, DIE
.get());
773 ILE
->updateInit(SemaRef
.Context
, Init
, DIE
.get());
774 RequiresSecondPass
= true;
779 if (Field
->getType()->isReferenceType()) {
781 // C++ [dcl.init.aggr]p9:
782 // If an incomplete or empty initializer-list leaves a
783 // member of reference type uninitialized, the program is
785 SemaRef
.Diag(Loc
, diag::err_init_reference_member_uninitialized
)
787 << (ILE
->isSyntacticForm() ? ILE
: ILE
->getSyntacticForm())
789 SemaRef
.Diag(Field
->getLocation(), diag::note_uninit_reference_member
);
795 ExprResult MemberInit
= PerformEmptyInit(Loc
, MemberEntity
);
796 if (MemberInit
.isInvalid()) {
801 if (hadError
|| VerifyOnly
) {
803 } else if (Init
< NumInits
) {
804 ILE
->setInit(Init
, MemberInit
.getAs
<Expr
>());
805 } else if (!isa
<ImplicitValueInitExpr
>(MemberInit
.get())) {
806 // Empty initialization requires a constructor call, so
807 // extend the initializer list to include the constructor
808 // call and make a note that we'll need to take another pass
809 // through the initializer list.
810 ILE
->updateInit(SemaRef
.Context
, Init
, MemberInit
.getAs
<Expr
>());
811 RequiresSecondPass
= true;
813 } else if (InitListExpr
*InnerILE
814 = dyn_cast
<InitListExpr
>(ILE
->getInit(Init
))) {
815 FillInEmptyInitializations(MemberEntity
, InnerILE
,
816 RequiresSecondPass
, ILE
, Init
, FillWithNoInit
);
817 } else if (DesignatedInitUpdateExpr
*InnerDIUE
=
818 dyn_cast
<DesignatedInitUpdateExpr
>(ILE
->getInit(Init
))) {
819 FillInEmptyInitializations(MemberEntity
, InnerDIUE
->getUpdater(),
820 RequiresSecondPass
, ILE
, Init
,
821 /*FillWithNoInit =*/true);
825 /// Recursively replaces NULL values within the given initializer list
826 /// with expressions that perform value-initialization of the
827 /// appropriate type, and finish off the InitListExpr formation.
829 InitListChecker::FillInEmptyInitializations(const InitializedEntity
&Entity
,
831 bool &RequiresSecondPass
,
832 InitListExpr
*OuterILE
,
834 bool FillWithNoInit
) {
835 assert((ILE
->getType() != SemaRef
.Context
.VoidTy
) &&
836 "Should not have void type");
838 // We don't need to do any checks when just filling NoInitExprs; that can't
840 if (FillWithNoInit
&& VerifyOnly
)
843 // If this is a nested initializer list, we might have changed its contents
844 // (and therefore some of its properties, such as instantiation-dependence)
845 // while filling it in. Inform the outer initializer list so that its state
846 // can be updated to match.
847 // FIXME: We should fully build the inner initializers before constructing
848 // the outer InitListExpr instead of mutating AST nodes after they have
849 // been used as subexpressions of other nodes.
850 struct UpdateOuterILEWithUpdatedInit
{
853 ~UpdateOuterILEWithUpdatedInit() {
855 Outer
->setInit(OuterIndex
, Outer
->getInit(OuterIndex
));
857 } UpdateOuterRAII
= {OuterILE
, OuterIndex
};
859 // A transparent ILE is not performing aggregate initialization and should
861 if (ILE
->isTransparent())
864 if (const RecordType
*RType
= ILE
->getType()->getAs
<RecordType
>()) {
865 const RecordDecl
*RDecl
= RType
->getDecl();
866 if (RDecl
->isUnion() && ILE
->getInitializedFieldInUnion()) {
867 FillInEmptyInitForField(0, ILE
->getInitializedFieldInUnion(), Entity
, ILE
,
868 RequiresSecondPass
, FillWithNoInit
);
870 assert((!RDecl
->isUnion() || !isa
<CXXRecordDecl
>(RDecl
) ||
871 !cast
<CXXRecordDecl
>(RDecl
)->hasInClassInitializer()) &&
872 "We should have computed initialized fields already");
873 // The fields beyond ILE->getNumInits() are default initialized, so in
874 // order to leave them uninitialized, the ILE is expanded and the extra
875 // fields are then filled with NoInitExpr.
876 unsigned NumElems
= numStructUnionElements(ILE
->getType());
877 if (!RDecl
->isUnion() && RDecl
->hasFlexibleArrayMember())
879 if (!VerifyOnly
&& ILE
->getNumInits() < NumElems
)
880 ILE
->resizeInits(SemaRef
.Context
, NumElems
);
884 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RDecl
)) {
885 for (auto &Base
: CXXRD
->bases()) {
889 FillInEmptyInitForBase(Init
, Base
, Entity
, ILE
, RequiresSecondPass
,
895 for (auto *Field
: RDecl
->fields()) {
896 if (Field
->isUnnamedBitField())
902 FillInEmptyInitForField(Init
, Field
, Entity
, ILE
, RequiresSecondPass
,
909 // Only look at the first initialization of a union.
910 if (RDecl
->isUnion())
918 QualType ElementType
;
920 InitializedEntity ElementEntity
= Entity
;
921 unsigned NumInits
= ILE
->getNumInits();
922 uint64_t NumElements
= NumInits
;
923 if (const ArrayType
*AType
= SemaRef
.Context
.getAsArrayType(ILE
->getType())) {
924 ElementType
= AType
->getElementType();
925 if (const auto *CAType
= dyn_cast
<ConstantArrayType
>(AType
))
926 NumElements
= CAType
->getZExtSize();
927 // For an array new with an unknown bound, ask for one additional element
928 // in order to populate the array filler.
929 if (Entity
.isVariableLengthArrayNew())
931 ElementEntity
= InitializedEntity::InitializeElement(SemaRef
.Context
,
933 } else if (const VectorType
*VType
= ILE
->getType()->getAs
<VectorType
>()) {
934 ElementType
= VType
->getElementType();
935 NumElements
= VType
->getNumElements();
936 ElementEntity
= InitializedEntity::InitializeElement(SemaRef
.Context
,
939 ElementType
= ILE
->getType();
941 bool SkipEmptyInitChecks
= false;
942 for (uint64_t Init
= 0; Init
!= NumElements
; ++Init
) {
946 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
||
947 ElementEntity
.getKind() == InitializedEntity::EK_VectorElement
)
948 ElementEntity
.setElementIndex(Init
);
950 if (Init
>= NumInits
&& (ILE
->hasArrayFiller() || SkipEmptyInitChecks
))
953 Expr
*InitExpr
= (Init
< NumInits
? ILE
->getInit(Init
) : nullptr);
954 if (!InitExpr
&& Init
< NumInits
&& ILE
->hasArrayFiller())
955 ILE
->setInit(Init
, ILE
->getArrayFiller());
956 else if (!InitExpr
&& !ILE
->hasArrayFiller()) {
957 // In VerifyOnly mode, there's no point performing empty initialization
959 if (SkipEmptyInitChecks
)
962 Expr
*Filler
= nullptr;
965 Filler
= new (SemaRef
.Context
) NoInitExpr(ElementType
);
967 ExprResult ElementInit
=
968 PerformEmptyInit(ILE
->getEndLoc(), ElementEntity
);
969 if (ElementInit
.isInvalid()) {
974 Filler
= ElementInit
.getAs
<Expr
>();
979 } else if (VerifyOnly
) {
980 SkipEmptyInitChecks
= true;
981 } else if (Init
< NumInits
) {
982 // For arrays, just set the expression used for value-initialization
983 // of the "holes" in the array.
984 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
)
985 ILE
->setArrayFiller(Filler
);
987 ILE
->setInit(Init
, Filler
);
989 // For arrays, just set the expression used for value-initialization
990 // of the rest of elements and exit.
991 if (ElementEntity
.getKind() == InitializedEntity::EK_ArrayElement
) {
992 ILE
->setArrayFiller(Filler
);
996 if (!isa
<ImplicitValueInitExpr
>(Filler
) && !isa
<NoInitExpr
>(Filler
)) {
997 // Empty initialization requires a constructor call, so
998 // extend the initializer list to include the constructor
999 // call and make a note that we'll need to take another pass
1000 // through the initializer list.
1001 ILE
->updateInit(SemaRef
.Context
, Init
, Filler
);
1002 RequiresSecondPass
= true;
1005 } else if (InitListExpr
*InnerILE
1006 = dyn_cast_or_null
<InitListExpr
>(InitExpr
)) {
1007 FillInEmptyInitializations(ElementEntity
, InnerILE
, RequiresSecondPass
,
1008 ILE
, Init
, FillWithNoInit
);
1009 } else if (DesignatedInitUpdateExpr
*InnerDIUE
=
1010 dyn_cast_or_null
<DesignatedInitUpdateExpr
>(InitExpr
)) {
1011 FillInEmptyInitializations(ElementEntity
, InnerDIUE
->getUpdater(),
1012 RequiresSecondPass
, ILE
, Init
,
1013 /*FillWithNoInit =*/true);
1018 static bool hasAnyDesignatedInits(const InitListExpr
*IL
) {
1019 for (const Stmt
*Init
: *IL
)
1020 if (isa_and_nonnull
<DesignatedInitExpr
>(Init
))
1025 InitListChecker::InitListChecker(
1026 Sema
&S
, const InitializedEntity
&Entity
, InitListExpr
*IL
, QualType
&T
,
1027 bool VerifyOnly
, bool TreatUnavailableAsInvalid
, bool InOverloadResolution
,
1028 SmallVectorImpl
<QualType
> *AggrDeductionCandidateParamTypes
)
1029 : SemaRef(S
), VerifyOnly(VerifyOnly
),
1030 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid
),
1031 InOverloadResolution(InOverloadResolution
),
1032 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes
) {
1033 if (!VerifyOnly
|| hasAnyDesignatedInits(IL
)) {
1034 FullyStructuredList
=
1035 createInitListExpr(T
, IL
->getSourceRange(), IL
->getNumInits());
1037 // FIXME: Check that IL isn't already the semantic form of some other
1038 // InitListExpr. If it is, we'd create a broken AST.
1040 FullyStructuredList
->setSyntacticForm(IL
);
1043 CheckExplicitInitList(Entity
, IL
, T
, FullyStructuredList
,
1044 /*TopLevelObject=*/true);
1046 if (!hadError
&& !AggrDeductionCandidateParamTypes
&& FullyStructuredList
) {
1047 bool RequiresSecondPass
= false;
1048 FillInEmptyInitializations(Entity
, FullyStructuredList
, RequiresSecondPass
,
1049 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1050 if (RequiresSecondPass
&& !hadError
)
1051 FillInEmptyInitializations(Entity
, FullyStructuredList
,
1052 RequiresSecondPass
, nullptr, 0);
1054 if (hadError
&& FullyStructuredList
)
1055 FullyStructuredList
->markError();
1058 int InitListChecker::numArrayElements(QualType DeclType
) {
1059 // FIXME: use a proper constant
1060 int maxElements
= 0x7FFFFFFF;
1061 if (const ConstantArrayType
*CAT
=
1062 SemaRef
.Context
.getAsConstantArrayType(DeclType
)) {
1063 maxElements
= static_cast<int>(CAT
->getZExtSize());
1068 int InitListChecker::numStructUnionElements(QualType DeclType
) {
1069 RecordDecl
*structDecl
= DeclType
->castAs
<RecordType
>()->getDecl();
1070 int InitializableMembers
= 0;
1071 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(structDecl
))
1072 InitializableMembers
+= CXXRD
->getNumBases();
1073 for (const auto *Field
: structDecl
->fields())
1074 if (!Field
->isUnnamedBitField())
1075 ++InitializableMembers
;
1077 if (structDecl
->isUnion())
1078 return std::min(InitializableMembers
, 1);
1079 return InitializableMembers
- structDecl
->hasFlexibleArrayMember();
1082 RecordDecl
*InitListChecker::getRecordDecl(QualType DeclType
) {
1083 if (const auto *RT
= DeclType
->getAs
<RecordType
>())
1084 return RT
->getDecl();
1085 if (const auto *Inject
= DeclType
->getAs
<InjectedClassNameType
>())
1086 return Inject
->getDecl();
1090 /// Determine whether Entity is an entity for which it is idiomatic to elide
1091 /// the braces in aggregate initialization.
1092 static bool isIdiomaticBraceElisionEntity(const InitializedEntity
&Entity
) {
1093 // Recursive initialization of the one and only field within an aggregate
1094 // class is considered idiomatic. This case arises in particular for
1095 // initialization of std::array, where the C++ standard suggests the idiom of
1097 // std::array<T, N> arr = {1, 2, 3};
1099 // (where std::array is an aggregate struct containing a single array field.
1101 if (!Entity
.getParent())
1104 // Allows elide brace initialization for aggregates with empty base.
1105 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
1107 Entity
.getParent()->getType()->castAs
<RecordType
>()->getDecl();
1108 CXXRecordDecl
*CXXRD
= cast
<CXXRecordDecl
>(ParentRD
);
1109 return CXXRD
->getNumBases() == 1 && CXXRD
->field_empty();
1112 // Allow brace elision if the only subobject is a field.
1113 if (Entity
.getKind() == InitializedEntity::EK_Member
) {
1115 Entity
.getParent()->getType()->castAs
<RecordType
>()->getDecl();
1116 if (CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(ParentRD
)) {
1117 if (CXXRD
->getNumBases()) {
1121 auto FieldIt
= ParentRD
->field_begin();
1122 assert(FieldIt
!= ParentRD
->field_end() &&
1123 "no fields but have initializer for member?");
1124 return ++FieldIt
== ParentRD
->field_end();
1130 /// Check whether the range of the initializer \p ParentIList from element
1131 /// \p Index onwards can be used to initialize an object of type \p T. Update
1132 /// \p Index to indicate how many elements of the list were consumed.
1134 /// This also fills in \p StructuredList, from element \p StructuredIndex
1135 /// onwards, with the fully-braced, desugared form of the initialization.
1136 void InitListChecker::CheckImplicitInitList(const InitializedEntity
&Entity
,
1137 InitListExpr
*ParentIList
,
1138 QualType T
, unsigned &Index
,
1139 InitListExpr
*StructuredList
,
1140 unsigned &StructuredIndex
) {
1141 int maxElements
= 0;
1143 if (T
->isArrayType())
1144 maxElements
= numArrayElements(T
);
1145 else if (T
->isRecordType())
1146 maxElements
= numStructUnionElements(T
);
1147 else if (T
->isVectorType())
1148 maxElements
= T
->castAs
<VectorType
>()->getNumElements();
1150 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1152 if (maxElements
== 0) {
1154 SemaRef
.Diag(ParentIList
->getInit(Index
)->getBeginLoc(),
1155 diag::err_implicit_empty_initializer
);
1161 // Build a structured initializer list corresponding to this subobject.
1162 InitListExpr
*StructuredSubobjectInitList
= getStructuredSubobjectInit(
1163 ParentIList
, Index
, T
, StructuredList
, StructuredIndex
,
1164 SourceRange(ParentIList
->getInit(Index
)->getBeginLoc(),
1165 ParentIList
->getSourceRange().getEnd()));
1166 unsigned StructuredSubobjectInitIndex
= 0;
1168 // Check the element types and build the structural subobject.
1169 unsigned StartIndex
= Index
;
1170 CheckListElementTypes(Entity
, ParentIList
, T
,
1171 /*SubobjectIsDesignatorContext=*/false, Index
,
1172 StructuredSubobjectInitList
,
1173 StructuredSubobjectInitIndex
);
1175 if (StructuredSubobjectInitList
) {
1176 StructuredSubobjectInitList
->setType(T
);
1178 unsigned EndIndex
= (Index
== StartIndex
? StartIndex
: Index
- 1);
1179 // Update the structured sub-object initializer so that it's ending
1180 // range corresponds with the end of the last initializer it used.
1181 if (EndIndex
< ParentIList
->getNumInits() &&
1182 ParentIList
->getInit(EndIndex
)) {
1183 SourceLocation EndLoc
1184 = ParentIList
->getInit(EndIndex
)->getSourceRange().getEnd();
1185 StructuredSubobjectInitList
->setRBraceLoc(EndLoc
);
1188 // Complain about missing braces.
1189 if (!VerifyOnly
&& (T
->isArrayType() || T
->isRecordType()) &&
1190 !ParentIList
->isIdiomaticZeroInitializer(SemaRef
.getLangOpts()) &&
1191 !isIdiomaticBraceElisionEntity(Entity
)) {
1192 SemaRef
.Diag(StructuredSubobjectInitList
->getBeginLoc(),
1193 diag::warn_missing_braces
)
1194 << StructuredSubobjectInitList
->getSourceRange()
1195 << FixItHint::CreateInsertion(
1196 StructuredSubobjectInitList
->getBeginLoc(), "{")
1197 << FixItHint::CreateInsertion(
1198 SemaRef
.getLocForEndOfToken(
1199 StructuredSubobjectInitList
->getEndLoc()),
1203 // Warn if this type won't be an aggregate in future versions of C++.
1204 auto *CXXRD
= T
->getAsCXXRecordDecl();
1205 if (!VerifyOnly
&& CXXRD
&& CXXRD
->hasUserDeclaredConstructor()) {
1206 SemaRef
.Diag(StructuredSubobjectInitList
->getBeginLoc(),
1207 diag::warn_cxx20_compat_aggregate_init_with_ctors
)
1208 << StructuredSubobjectInitList
->getSourceRange() << T
;
1213 /// Warn that \p Entity was of scalar type and was initialized by a
1214 /// single-element braced initializer list.
1215 static void warnBracedScalarInit(Sema
&S
, const InitializedEntity
&Entity
,
1216 SourceRange Braces
) {
1217 // Don't warn during template instantiation. If the initialization was
1218 // non-dependent, we warned during the initial parse; otherwise, the
1219 // type might not be scalar in some uses of the template.
1220 if (S
.inTemplateInstantiation())
1223 unsigned DiagID
= 0;
1225 switch (Entity
.getKind()) {
1226 case InitializedEntity::EK_VectorElement
:
1227 case InitializedEntity::EK_ComplexElement
:
1228 case InitializedEntity::EK_ArrayElement
:
1229 case InitializedEntity::EK_Parameter
:
1230 case InitializedEntity::EK_Parameter_CF_Audited
:
1231 case InitializedEntity::EK_TemplateParameter
:
1232 case InitializedEntity::EK_Result
:
1233 case InitializedEntity::EK_ParenAggInitMember
:
1234 // Extra braces here are suspicious.
1235 DiagID
= diag::warn_braces_around_init
;
1238 case InitializedEntity::EK_Member
:
1239 // Warn on aggregate initialization but not on ctor init list or
1240 // default member initializer.
1241 if (Entity
.getParent())
1242 DiagID
= diag::warn_braces_around_init
;
1245 case InitializedEntity::EK_Variable
:
1246 case InitializedEntity::EK_LambdaCapture
:
1247 // No warning, might be direct-list-initialization.
1248 // FIXME: Should we warn for copy-list-initialization in these cases?
1251 case InitializedEntity::EK_New
:
1252 case InitializedEntity::EK_Temporary
:
1253 case InitializedEntity::EK_CompoundLiteralInit
:
1254 // No warning, braces are part of the syntax of the underlying construct.
1257 case InitializedEntity::EK_RelatedResult
:
1258 // No warning, we already warned when initializing the result.
1261 case InitializedEntity::EK_Exception
:
1262 case InitializedEntity::EK_Base
:
1263 case InitializedEntity::EK_Delegating
:
1264 case InitializedEntity::EK_BlockElement
:
1265 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
1266 case InitializedEntity::EK_Binding
:
1267 case InitializedEntity::EK_StmtExprResult
:
1268 llvm_unreachable("unexpected braced scalar init");
1272 S
.Diag(Braces
.getBegin(), DiagID
)
1273 << Entity
.getType()->isSizelessBuiltinType() << Braces
1274 << FixItHint::CreateRemoval(Braces
.getBegin())
1275 << FixItHint::CreateRemoval(Braces
.getEnd());
1279 /// Check whether the initializer \p IList (that was written with explicit
1280 /// braces) can be used to initialize an object of type \p T.
1282 /// This also fills in \p StructuredList with the fully-braced, desugared
1283 /// form of the initialization.
1284 void InitListChecker::CheckExplicitInitList(const InitializedEntity
&Entity
,
1285 InitListExpr
*IList
, QualType
&T
,
1286 InitListExpr
*StructuredList
,
1287 bool TopLevelObject
) {
1288 unsigned Index
= 0, StructuredIndex
= 0;
1289 CheckListElementTypes(Entity
, IList
, T
, /*SubobjectIsDesignatorContext=*/true,
1290 Index
, StructuredList
, StructuredIndex
, TopLevelObject
);
1291 if (StructuredList
) {
1292 QualType ExprTy
= T
;
1293 if (!ExprTy
->isArrayType())
1294 ExprTy
= ExprTy
.getNonLValueExprType(SemaRef
.Context
);
1296 IList
->setType(ExprTy
);
1297 StructuredList
->setType(ExprTy
);
1302 // Don't complain for incomplete types, since we'll get an error elsewhere.
1303 if (Index
< IList
->getNumInits() && !T
->isIncompleteType()) {
1304 // We have leftover initializers
1305 bool ExtraInitsIsError
= SemaRef
.getLangOpts().CPlusPlus
||
1306 (SemaRef
.getLangOpts().OpenCL
&& T
->isVectorType());
1307 hadError
= ExtraInitsIsError
;
1310 } else if (StructuredIndex
== 1 &&
1311 IsStringInit(StructuredList
->getInit(0), T
, SemaRef
.Context
) ==
1315 ? diag::err_excess_initializers_in_char_array_initializer
1316 : diag::ext_excess_initializers_in_char_array_initializer
;
1317 SemaRef
.Diag(IList
->getInit(Index
)->getBeginLoc(), DK
)
1318 << IList
->getInit(Index
)->getSourceRange();
1319 } else if (T
->isSizelessBuiltinType()) {
1320 unsigned DK
= ExtraInitsIsError
1321 ? diag::err_excess_initializers_for_sizeless_type
1322 : diag::ext_excess_initializers_for_sizeless_type
;
1323 SemaRef
.Diag(IList
->getInit(Index
)->getBeginLoc(), DK
)
1324 << T
<< IList
->getInit(Index
)->getSourceRange();
1326 int initKind
= T
->isArrayType() ? 0 :
1327 T
->isVectorType() ? 1 :
1328 T
->isScalarType() ? 2 :
1329 T
->isUnionType() ? 3 :
1332 unsigned DK
= ExtraInitsIsError
? diag::err_excess_initializers
1333 : diag::ext_excess_initializers
;
1334 SemaRef
.Diag(IList
->getInit(Index
)->getBeginLoc(), DK
)
1335 << initKind
<< IList
->getInit(Index
)->getSourceRange();
1340 if (T
->isScalarType() && IList
->getNumInits() == 1 &&
1341 !isa
<InitListExpr
>(IList
->getInit(0)))
1342 warnBracedScalarInit(SemaRef
, Entity
, IList
->getSourceRange());
1344 // Warn if this is a class type that won't be an aggregate in future
1346 auto *CXXRD
= T
->getAsCXXRecordDecl();
1347 if (CXXRD
&& CXXRD
->hasUserDeclaredConstructor()) {
1348 // Don't warn if there's an equivalent default constructor that would be
1350 bool HasEquivCtor
= false;
1351 if (IList
->getNumInits() == 0) {
1352 auto *CD
= SemaRef
.LookupDefaultConstructor(CXXRD
);
1353 HasEquivCtor
= CD
&& !CD
->isDeleted();
1356 if (!HasEquivCtor
) {
1357 SemaRef
.Diag(IList
->getBeginLoc(),
1358 diag::warn_cxx20_compat_aggregate_init_with_ctors
)
1359 << IList
->getSourceRange() << T
;
1365 void InitListChecker::CheckListElementTypes(const InitializedEntity
&Entity
,
1366 InitListExpr
*IList
,
1368 bool SubobjectIsDesignatorContext
,
1370 InitListExpr
*StructuredList
,
1371 unsigned &StructuredIndex
,
1372 bool TopLevelObject
) {
1373 if (DeclType
->isAnyComplexType() && SubobjectIsDesignatorContext
) {
1374 // Explicitly braced initializer for complex type can be real+imaginary
1376 CheckComplexType(Entity
, IList
, DeclType
, Index
,
1377 StructuredList
, StructuredIndex
);
1378 } else if (DeclType
->isScalarType()) {
1379 CheckScalarType(Entity
, IList
, DeclType
, Index
,
1380 StructuredList
, StructuredIndex
);
1381 } else if (DeclType
->isVectorType()) {
1382 CheckVectorType(Entity
, IList
, DeclType
, Index
,
1383 StructuredList
, StructuredIndex
);
1384 } else if (const RecordDecl
*RD
= getRecordDecl(DeclType
)) {
1386 CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1387 CXXRecordDecl::base_class_const_iterator());
1388 if (DeclType
->isRecordType()) {
1389 assert(DeclType
->isAggregateType() &&
1390 "non-aggregate records should be handed in CheckSubElementType");
1391 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
1392 Bases
= CXXRD
->bases();
1394 Bases
= cast
<CXXRecordDecl
>(RD
)->bases();
1396 CheckStructUnionTypes(Entity
, IList
, DeclType
, Bases
, RD
->field_begin(),
1397 SubobjectIsDesignatorContext
, Index
, StructuredList
,
1398 StructuredIndex
, TopLevelObject
);
1399 } else if (DeclType
->isArrayType()) {
1401 SemaRef
.Context
.getTypeSize(SemaRef
.Context
.getSizeType()),
1403 CheckArrayType(Entity
, IList
, DeclType
, Zero
,
1404 SubobjectIsDesignatorContext
, Index
,
1405 StructuredList
, StructuredIndex
);
1406 } else if (DeclType
->isVoidType() || DeclType
->isFunctionType()) {
1407 // This type is invalid, issue a diagnostic.
1410 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_illegal_initializer_type
)
1413 } else if (DeclType
->isReferenceType()) {
1414 CheckReferenceType(Entity
, IList
, DeclType
, Index
,
1415 StructuredList
, StructuredIndex
);
1416 } else if (DeclType
->isObjCObjectType()) {
1418 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_init_objc_class
) << DeclType
;
1420 } else if (DeclType
->isOCLIntelSubgroupAVCType() ||
1421 DeclType
->isSizelessBuiltinType()) {
1422 // Checks for scalar type are sufficient for these types too.
1423 CheckScalarType(Entity
, IList
, DeclType
, Index
, StructuredList
,
1425 } else if (DeclType
->isDependentType()) {
1426 // C++ [over.match.class.deduct]p1.5:
1427 // brace elision is not considered for any aggregate element that has a
1428 // dependent non-array type or an array type with a value-dependent bound
1430 assert(AggrDeductionCandidateParamTypes
);
1431 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1434 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_illegal_initializer_type
)
1440 void InitListChecker::CheckSubElementType(const InitializedEntity
&Entity
,
1441 InitListExpr
*IList
,
1444 InitListExpr
*StructuredList
,
1445 unsigned &StructuredIndex
,
1446 bool DirectlyDesignated
) {
1447 Expr
*expr
= IList
->getInit(Index
);
1449 if (ElemType
->isReferenceType())
1450 return CheckReferenceType(Entity
, IList
, ElemType
, Index
,
1451 StructuredList
, StructuredIndex
);
1453 if (InitListExpr
*SubInitList
= dyn_cast
<InitListExpr
>(expr
)) {
1454 if (SubInitList
->getNumInits() == 1 &&
1455 IsStringInit(SubInitList
->getInit(0), ElemType
, SemaRef
.Context
) ==
1457 // FIXME: It would be more faithful and no less correct to include an
1458 // InitListExpr in the semantic form of the initializer list in this case.
1459 expr
= SubInitList
->getInit(0);
1461 // Nested aggregate initialization and C++ initialization are handled later.
1462 } else if (isa
<ImplicitValueInitExpr
>(expr
)) {
1463 // This happens during template instantiation when we see an InitListExpr
1464 // that we've already checked once.
1465 assert(SemaRef
.Context
.hasSameType(expr
->getType(), ElemType
) &&
1466 "found implicit initialization for the wrong type");
1467 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
1472 if (SemaRef
.getLangOpts().CPlusPlus
|| isa
<InitListExpr
>(expr
)) {
1473 // C++ [dcl.init.aggr]p2:
1474 // Each member is copy-initialized from the corresponding
1475 // initializer-clause.
1477 // FIXME: Better EqualLoc?
1478 InitializationKind Kind
=
1479 InitializationKind::CreateCopy(expr
->getBeginLoc(), SourceLocation());
1481 // Vector elements can be initialized from other vectors in which case
1482 // we need initialization entity with a type of a vector (and not a vector
1483 // element!) initializing multiple vector elements.
1485 (ElemType
->isExtVectorType() && !Entity
.getType()->isExtVectorType())
1486 ? InitializedEntity::InitializeTemporary(ElemType
)
1489 if (TmpEntity
.getType()->isDependentType()) {
1490 // C++ [over.match.class.deduct]p1.5:
1491 // brace elision is not considered for any aggregate element that has a
1492 // dependent non-array type or an array type with a value-dependent
1494 assert(AggrDeductionCandidateParamTypes
);
1496 // In the presence of a braced-init-list within the initializer, we should
1497 // not perform brace-elision, even if brace elision would otherwise be
1498 // applicable. For example, given:
1500 // template <class T> struct Foo {
1504 // Foo t = {{1, 2}};
1506 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1508 if (isa
<InitListExpr
, DesignatedInitExpr
>(expr
) ||
1509 !isa_and_present
<ConstantArrayType
>(
1510 SemaRef
.Context
.getAsArrayType(ElemType
))) {
1512 AggrDeductionCandidateParamTypes
->push_back(ElemType
);
1516 InitializationSequence
Seq(SemaRef
, TmpEntity
, Kind
, expr
,
1517 /*TopLevelOfInitList*/ true);
1518 // C++14 [dcl.init.aggr]p13:
1519 // If the assignment-expression can initialize a member, the member is
1520 // initialized. Otherwise [...] brace elision is assumed
1522 // Brace elision is never performed if the element is not an
1523 // assignment-expression.
1524 if (Seq
|| isa
<InitListExpr
>(expr
)) {
1525 if (auto *Embed
= dyn_cast
<EmbedExpr
>(expr
)) {
1526 expr
= HandleEmbed(Embed
, Entity
);
1529 ExprResult Result
= Seq
.Perform(SemaRef
, TmpEntity
, Kind
, expr
);
1530 if (Result
.isInvalid())
1533 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1534 Result
.getAs
<Expr
>());
1537 } else if (StructuredList
) {
1538 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1543 if (AggrDeductionCandidateParamTypes
)
1544 AggrDeductionCandidateParamTypes
->push_back(ElemType
);
1549 // Fall through for subaggregate initialization
1550 } else if (ElemType
->isScalarType() || ElemType
->isAtomicType()) {
1551 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1552 return CheckScalarType(Entity
, IList
, ElemType
, Index
,
1553 StructuredList
, StructuredIndex
);
1554 } else if (const ArrayType
*arrayType
=
1555 SemaRef
.Context
.getAsArrayType(ElemType
)) {
1556 // arrayType can be incomplete if we're initializing a flexible
1557 // array member. There's nothing we can do with the completed
1558 // type here, though.
1560 if (IsStringInit(expr
, arrayType
, SemaRef
.Context
) == SIF_None
) {
1561 // FIXME: Should we do this checking in verify-only mode?
1563 CheckStringInit(expr
, ElemType
, arrayType
, SemaRef
,
1564 SemaRef
.getLangOpts().C23
&&
1565 initializingConstexprVariable(Entity
));
1567 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
1572 // Fall through for subaggregate initialization.
1575 assert((ElemType
->isRecordType() || ElemType
->isVectorType() ||
1576 ElemType
->isOpenCLSpecificType()) && "Unexpected type");
1580 // The initializer for a structure or union object that has
1581 // automatic storage duration shall be either an initializer
1582 // list as described below, or a single expression that has
1583 // compatible structure or union type. In the latter case, the
1584 // initial value of the object, including unnamed members, is
1585 // that of the expression.
1586 ExprResult ExprRes
= expr
;
1587 if (SemaRef
.CheckSingleAssignmentConstraints(
1588 ElemType
, ExprRes
, !VerifyOnly
) != Sema::Incompatible
) {
1589 if (ExprRes
.isInvalid())
1592 ExprRes
= SemaRef
.DefaultFunctionArrayLvalueConversion(ExprRes
.get());
1593 if (ExprRes
.isInvalid())
1596 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
1597 ExprRes
.getAs
<Expr
>());
1602 // Fall through for subaggregate initialization
1605 // C++ [dcl.init.aggr]p12:
1607 // [...] Otherwise, if the member is itself a non-empty
1608 // subaggregate, brace elision is assumed and the initializer is
1609 // considered for the initialization of the first member of
1610 // the subaggregate.
1611 // OpenCL vector initializer is handled elsewhere.
1612 if ((!SemaRef
.getLangOpts().OpenCL
&& ElemType
->isVectorType()) ||
1613 ElemType
->isAggregateType()) {
1614 CheckImplicitInitList(Entity
, IList
, ElemType
, Index
, StructuredList
,
1618 // In C++20, brace elision is not permitted for a designated initializer.
1619 if (DirectlyDesignated
&& SemaRef
.getLangOpts().CPlusPlus
&& !hadError
) {
1620 if (InOverloadResolution
)
1623 SemaRef
.Diag(expr
->getBeginLoc(),
1624 diag::ext_designated_init_brace_elision
)
1625 << expr
->getSourceRange()
1626 << FixItHint::CreateInsertion(expr
->getBeginLoc(), "{")
1627 << FixItHint::CreateInsertion(
1628 SemaRef
.getLocForEndOfToken(expr
->getEndLoc()), "}");
1633 // We cannot initialize this element, so let PerformCopyInitialization
1634 // produce the appropriate diagnostic. We already checked that this
1635 // initialization will fail.
1637 SemaRef
.PerformCopyInitialization(Entity
, SourceLocation(), expr
,
1638 /*TopLevelOfInitList=*/true);
1640 assert(Copy
.isInvalid() &&
1641 "expected non-aggregate initialization to fail");
1649 void InitListChecker::CheckComplexType(const InitializedEntity
&Entity
,
1650 InitListExpr
*IList
, QualType DeclType
,
1652 InitListExpr
*StructuredList
,
1653 unsigned &StructuredIndex
) {
1654 assert(Index
== 0 && "Index in explicit init list must be zero");
1656 // As an extension, clang supports complex initializers, which initialize
1657 // a complex number component-wise. When an explicit initializer list for
1658 // a complex number contains two initializers, this extension kicks in:
1659 // it expects the initializer list to contain two elements convertible to
1660 // the element type of the complex type. The first element initializes
1661 // the real part, and the second element intitializes the imaginary part.
1663 if (IList
->getNumInits() < 2)
1664 return CheckScalarType(Entity
, IList
, DeclType
, Index
, StructuredList
,
1667 // This is an extension in C. (The builtin _Complex type does not exist
1668 // in the C++ standard.)
1669 if (!SemaRef
.getLangOpts().CPlusPlus
&& !VerifyOnly
)
1670 SemaRef
.Diag(IList
->getBeginLoc(), diag::ext_complex_component_init
)
1671 << IList
->getSourceRange();
1673 // Initialize the complex number.
1674 QualType elementType
= DeclType
->castAs
<ComplexType
>()->getElementType();
1675 InitializedEntity ElementEntity
=
1676 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1678 for (unsigned i
= 0; i
< 2; ++i
) {
1679 ElementEntity
.setElementIndex(Index
);
1680 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1681 StructuredList
, StructuredIndex
);
1685 void InitListChecker::CheckScalarType(const InitializedEntity
&Entity
,
1686 InitListExpr
*IList
, QualType DeclType
,
1688 InitListExpr
*StructuredList
,
1689 unsigned &StructuredIndex
) {
1690 if (Index
>= IList
->getNumInits()) {
1692 if (SemaRef
.getLangOpts().CPlusPlus
) {
1693 if (DeclType
->isSizelessBuiltinType())
1694 SemaRef
.Diag(IList
->getBeginLoc(),
1695 SemaRef
.getLangOpts().CPlusPlus11
1696 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1697 : diag::err_empty_sizeless_initializer
)
1698 << DeclType
<< IList
->getSourceRange();
1700 SemaRef
.Diag(IList
->getBeginLoc(),
1701 SemaRef
.getLangOpts().CPlusPlus11
1702 ? diag::warn_cxx98_compat_empty_scalar_initializer
1703 : diag::err_empty_scalar_initializer
)
1704 << IList
->getSourceRange();
1708 SemaRef
.getLangOpts().CPlusPlus
&& !SemaRef
.getLangOpts().CPlusPlus11
;
1714 Expr
*expr
= IList
->getInit(Index
);
1715 if (InitListExpr
*SubIList
= dyn_cast
<InitListExpr
>(expr
)) {
1716 // FIXME: This is invalid, and accepting it causes overload resolution
1717 // to pick the wrong overload in some corner cases.
1719 SemaRef
.Diag(SubIList
->getBeginLoc(), diag::ext_many_braces_around_init
)
1720 << DeclType
->isSizelessBuiltinType() << SubIList
->getSourceRange();
1722 CheckScalarType(Entity
, SubIList
, DeclType
, Index
, StructuredList
,
1725 } else if (isa
<DesignatedInitExpr
>(expr
)) {
1727 SemaRef
.Diag(expr
->getBeginLoc(),
1728 diag::err_designator_for_scalar_or_sizeless_init
)
1729 << DeclType
->isSizelessBuiltinType() << DeclType
1730 << expr
->getSourceRange();
1735 } else if (auto *Embed
= dyn_cast
<EmbedExpr
>(expr
)) {
1736 expr
= HandleEmbed(Embed
, Entity
);
1741 if (SemaRef
.CanPerformCopyInitialization(Entity
, expr
))
1742 Result
= getDummyInit();
1744 Result
= ExprError();
1747 SemaRef
.PerformCopyInitialization(Entity
, expr
->getBeginLoc(), expr
,
1748 /*TopLevelOfInitList=*/true);
1751 Expr
*ResultExpr
= nullptr;
1753 if (Result
.isInvalid())
1754 hadError
= true; // types weren't compatible.
1756 ResultExpr
= Result
.getAs
<Expr
>();
1758 if (ResultExpr
!= expr
&& !VerifyOnly
&& !CurEmbed
) {
1759 // The type was promoted, update initializer list.
1760 // FIXME: Why are we updating the syntactic init list?
1761 IList
->setInit(Index
, ResultExpr
);
1765 UpdateStructuredListElement(StructuredList
, StructuredIndex
, ResultExpr
);
1768 if (AggrDeductionCandidateParamTypes
)
1769 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1772 void InitListChecker::CheckReferenceType(const InitializedEntity
&Entity
,
1773 InitListExpr
*IList
, QualType DeclType
,
1775 InitListExpr
*StructuredList
,
1776 unsigned &StructuredIndex
) {
1777 if (Index
>= IList
->getNumInits()) {
1778 // FIXME: It would be wonderful if we could point at the actual member. In
1779 // general, it would be useful to pass location information down the stack,
1780 // so that we know the location (or decl) of the "current object" being
1783 SemaRef
.Diag(IList
->getBeginLoc(),
1784 diag::err_init_reference_member_uninitialized
)
1785 << DeclType
<< IList
->getSourceRange();
1792 Expr
*expr
= IList
->getInit(Index
);
1793 if (isa
<InitListExpr
>(expr
) && !SemaRef
.getLangOpts().CPlusPlus11
) {
1795 SemaRef
.Diag(IList
->getBeginLoc(), diag::err_init_non_aggr_init_list
)
1796 << DeclType
<< IList
->getSourceRange();
1805 if (SemaRef
.CanPerformCopyInitialization(Entity
,expr
))
1806 Result
= getDummyInit();
1808 Result
= ExprError();
1811 SemaRef
.PerformCopyInitialization(Entity
, expr
->getBeginLoc(), expr
,
1812 /*TopLevelOfInitList=*/true);
1815 if (Result
.isInvalid())
1818 expr
= Result
.getAs
<Expr
>();
1819 // FIXME: Why are we updating the syntactic init list?
1820 if (!VerifyOnly
&& expr
)
1821 IList
->setInit(Index
, expr
);
1823 UpdateStructuredListElement(StructuredList
, StructuredIndex
, expr
);
1825 if (AggrDeductionCandidateParamTypes
)
1826 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
1829 void InitListChecker::CheckVectorType(const InitializedEntity
&Entity
,
1830 InitListExpr
*IList
, QualType DeclType
,
1832 InitListExpr
*StructuredList
,
1833 unsigned &StructuredIndex
) {
1834 const VectorType
*VT
= DeclType
->castAs
<VectorType
>();
1835 unsigned maxElements
= VT
->getNumElements();
1836 unsigned numEltsInit
= 0;
1837 QualType elementType
= VT
->getElementType();
1839 if (Index
>= IList
->getNumInits()) {
1840 // Make sure the element type can be value-initialized.
1841 CheckEmptyInitializable(
1842 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
),
1843 IList
->getEndLoc());
1847 if (!SemaRef
.getLangOpts().OpenCL
&& !SemaRef
.getLangOpts().HLSL
) {
1848 // If the initializing element is a vector, try to copy-initialize
1849 // instead of breaking it apart (which is doomed to failure anyway).
1850 Expr
*Init
= IList
->getInit(Index
);
1851 if (!isa
<InitListExpr
>(Init
) && Init
->getType()->isVectorType()) {
1854 if (SemaRef
.CanPerformCopyInitialization(Entity
, Init
))
1855 Result
= getDummyInit();
1857 Result
= ExprError();
1860 SemaRef
.PerformCopyInitialization(Entity
, Init
->getBeginLoc(), Init
,
1861 /*TopLevelOfInitList=*/true);
1864 Expr
*ResultExpr
= nullptr;
1865 if (Result
.isInvalid())
1866 hadError
= true; // types weren't compatible.
1868 ResultExpr
= Result
.getAs
<Expr
>();
1870 if (ResultExpr
!= Init
&& !VerifyOnly
) {
1871 // The type was promoted, update initializer list.
1872 // FIXME: Why are we updating the syntactic init list?
1873 IList
->setInit(Index
, ResultExpr
);
1876 UpdateStructuredListElement(StructuredList
, StructuredIndex
, ResultExpr
);
1878 if (AggrDeductionCandidateParamTypes
)
1879 AggrDeductionCandidateParamTypes
->push_back(elementType
);
1883 InitializedEntity ElementEntity
=
1884 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1886 for (unsigned i
= 0; i
< maxElements
; ++i
, ++numEltsInit
) {
1887 // Don't attempt to go past the end of the init list
1888 if (Index
>= IList
->getNumInits()) {
1889 CheckEmptyInitializable(ElementEntity
, IList
->getEndLoc());
1893 ElementEntity
.setElementIndex(Index
);
1894 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1895 StructuredList
, StructuredIndex
);
1901 bool isBigEndian
= SemaRef
.Context
.getTargetInfo().isBigEndian();
1902 const VectorType
*T
= Entity
.getType()->castAs
<VectorType
>();
1903 if (isBigEndian
&& (T
->getVectorKind() == VectorKind::Neon
||
1904 T
->getVectorKind() == VectorKind::NeonPoly
)) {
1905 // The ability to use vector initializer lists is a GNU vector extension
1906 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1907 // endian machines it works fine, however on big endian machines it
1908 // exhibits surprising behaviour:
1910 // uint32x2_t x = {42, 64};
1911 // return vget_lane_u32(x, 0); // Will return 64.
1913 // Because of this, explicitly call out that it is non-portable.
1915 SemaRef
.Diag(IList
->getBeginLoc(),
1916 diag::warn_neon_vector_initializer_non_portable
);
1918 const char *typeCode
;
1919 unsigned typeSize
= SemaRef
.Context
.getTypeSize(elementType
);
1921 if (elementType
->isFloatingType())
1923 else if (elementType
->isSignedIntegerType())
1925 else if (elementType
->isUnsignedIntegerType())
1928 llvm_unreachable("Invalid element type!");
1930 SemaRef
.Diag(IList
->getBeginLoc(),
1931 SemaRef
.Context
.getTypeSize(VT
) > 64
1932 ? diag::note_neon_vector_initializer_non_portable_q
1933 : diag::note_neon_vector_initializer_non_portable
)
1934 << typeCode
<< typeSize
;
1940 InitializedEntity ElementEntity
=
1941 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
1943 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1944 for (unsigned i
= 0; i
< maxElements
; ++i
) {
1945 // Don't attempt to go past the end of the init list
1946 if (Index
>= IList
->getNumInits())
1949 ElementEntity
.setElementIndex(Index
);
1951 QualType IType
= IList
->getInit(Index
)->getType();
1952 if (!IType
->isVectorType()) {
1953 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
1954 StructuredList
, StructuredIndex
);
1958 const VectorType
*IVT
= IType
->castAs
<VectorType
>();
1959 unsigned numIElts
= IVT
->getNumElements();
1961 if (IType
->isExtVectorType())
1962 VecType
= SemaRef
.Context
.getExtVectorType(elementType
, numIElts
);
1964 VecType
= SemaRef
.Context
.getVectorType(elementType
, numIElts
,
1965 IVT
->getVectorKind());
1966 CheckSubElementType(ElementEntity
, IList
, VecType
, Index
,
1967 StructuredList
, StructuredIndex
);
1968 numEltsInit
+= numIElts
;
1972 // OpenCL and HLSL require all elements to be initialized.
1973 if (numEltsInit
!= maxElements
) {
1975 SemaRef
.Diag(IList
->getBeginLoc(),
1976 diag::err_vector_incorrect_num_elements
)
1977 << (numEltsInit
< maxElements
) << maxElements
<< numEltsInit
1978 << /*initialization*/ 0;
1983 /// Check if the type of a class element has an accessible destructor, and marks
1984 /// it referenced. Returns true if we shouldn't form a reference to the
1987 /// Aggregate initialization requires a class element's destructor be
1988 /// accessible per 11.6.1 [dcl.init.aggr]:
1990 /// The destructor for each element of class type is potentially invoked
1991 /// (15.4 [class.dtor]) from the context where the aggregate initialization
1993 static bool checkDestructorReference(QualType ElementType
, SourceLocation Loc
,
1995 auto *CXXRD
= ElementType
->getAsCXXRecordDecl();
1999 CXXDestructorDecl
*Destructor
= SemaRef
.LookupDestructor(CXXRD
);
2003 SemaRef
.CheckDestructorAccess(Loc
, Destructor
,
2004 SemaRef
.PDiag(diag::err_access_dtor_temp
)
2006 SemaRef
.MarkFunctionReferenced(Loc
, Destructor
);
2007 return SemaRef
.DiagnoseUseOfDecl(Destructor
, Loc
);
2011 canInitializeArrayWithEmbedDataString(ArrayRef
<Expr
*> ExprList
,
2012 const InitializedEntity
&Entity
,
2013 ASTContext
&Context
) {
2014 QualType InitType
= Entity
.getType();
2015 const InitializedEntity
*Parent
= &Entity
;
2018 InitType
= Parent
->getType();
2019 Parent
= Parent
->getParent();
2022 // Only one initializer, it's an embed and the types match;
2024 ExprList
.size() == 1
2025 ? dyn_cast_if_present
<EmbedExpr
>(ExprList
[0]->IgnoreParens())
2030 if (InitType
->isArrayType()) {
2031 const ArrayType
*InitArrayType
= InitType
->getAsArrayTypeUnsafe();
2032 QualType InitElementTy
= InitArrayType
->getElementType();
2033 QualType EmbedExprElementTy
= EE
->getDataStringLiteral()->getType();
2034 const bool TypesMatch
=
2035 Context
.typesAreCompatible(InitElementTy
, EmbedExprElementTy
) ||
2036 (InitElementTy
->isCharType() && EmbedExprElementTy
->isCharType());
2043 void InitListChecker::CheckArrayType(const InitializedEntity
&Entity
,
2044 InitListExpr
*IList
, QualType
&DeclType
,
2045 llvm::APSInt elementIndex
,
2046 bool SubobjectIsDesignatorContext
,
2048 InitListExpr
*StructuredList
,
2049 unsigned &StructuredIndex
) {
2050 const ArrayType
*arrayType
= SemaRef
.Context
.getAsArrayType(DeclType
);
2053 if (checkDestructorReference(arrayType
->getElementType(),
2054 IList
->getEndLoc(), SemaRef
)) {
2060 if (canInitializeArrayWithEmbedDataString(IList
->inits(), Entity
,
2062 EmbedExpr
*Embed
= cast
<EmbedExpr
>(IList
->inits()[0]);
2063 IList
->setInit(0, Embed
->getDataStringLiteral());
2066 // Check for the special-case of initializing an array with a string.
2067 if (Index
< IList
->getNumInits()) {
2068 if (IsStringInit(IList
->getInit(Index
), arrayType
, SemaRef
.Context
) ==
2070 // We place the string literal directly into the resulting
2071 // initializer list. This is the only place where the structure
2072 // of the structured initializer list doesn't match exactly,
2073 // because doing so would involve allocating one character
2074 // constant for each string.
2075 // FIXME: Should we do these checks in verify-only mode too?
2077 CheckStringInit(IList
->getInit(Index
), DeclType
, arrayType
, SemaRef
,
2078 SemaRef
.getLangOpts().C23
&&
2079 initializingConstexprVariable(Entity
));
2080 if (StructuredList
) {
2081 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
2082 IList
->getInit(Index
));
2083 StructuredList
->resizeInits(SemaRef
.Context
, StructuredIndex
);
2086 if (AggrDeductionCandidateParamTypes
)
2087 AggrDeductionCandidateParamTypes
->push_back(DeclType
);
2091 if (const VariableArrayType
*VAT
= dyn_cast
<VariableArrayType
>(arrayType
)) {
2092 // Check for VLAs; in standard C it would be possible to check this
2093 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2094 // them in all sorts of strange places).
2095 bool HasErr
= IList
->getNumInits() != 0 || SemaRef
.getLangOpts().CPlusPlus
;
2097 // C23 6.7.10p4: An entity of variable length array type shall not be
2098 // initialized except by an empty initializer.
2100 // The C extension warnings are issued from ParseBraceInitializer() and
2101 // do not need to be issued here. However, we continue to issue an error
2102 // in the case there are initializers or we are compiling C++. We allow
2103 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2104 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2105 // FIXME: should we allow this construct in C++ when it makes sense to do
2108 SemaRef
.Diag(VAT
->getSizeExpr()->getBeginLoc(),
2109 diag::err_variable_object_no_init
)
2110 << VAT
->getSizeExpr()->getSourceRange();
2118 // We might know the maximum number of elements in advance.
2119 llvm::APSInt
maxElements(elementIndex
.getBitWidth(),
2120 elementIndex
.isUnsigned());
2121 bool maxElementsKnown
= false;
2122 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(arrayType
)) {
2123 maxElements
= CAT
->getSize();
2124 elementIndex
= elementIndex
.extOrTrunc(maxElements
.getBitWidth());
2125 elementIndex
.setIsUnsigned(maxElements
.isUnsigned());
2126 maxElementsKnown
= true;
2129 QualType elementType
= arrayType
->getElementType();
2130 while (Index
< IList
->getNumInits()) {
2131 Expr
*Init
= IList
->getInit(Index
);
2132 if (DesignatedInitExpr
*DIE
= dyn_cast
<DesignatedInitExpr
>(Init
)) {
2133 // If we're not the subobject that matches up with the '{' for
2134 // the designator, we shouldn't be handling the
2135 // designator. Return immediately.
2136 if (!SubobjectIsDesignatorContext
)
2139 // Handle this designated initializer. elementIndex will be
2140 // updated to be the next array element we'll initialize.
2141 if (CheckDesignatedInitializer(Entity
, IList
, DIE
, 0,
2142 DeclType
, nullptr, &elementIndex
, Index
,
2143 StructuredList
, StructuredIndex
, true,
2149 if (elementIndex
.getBitWidth() > maxElements
.getBitWidth())
2150 maxElements
= maxElements
.extend(elementIndex
.getBitWidth());
2151 else if (elementIndex
.getBitWidth() < maxElements
.getBitWidth())
2152 elementIndex
= elementIndex
.extend(maxElements
.getBitWidth());
2153 elementIndex
.setIsUnsigned(maxElements
.isUnsigned());
2155 // If the array is of incomplete type, keep track of the number of
2156 // elements in the initializer.
2157 if (!maxElementsKnown
&& elementIndex
> maxElements
)
2158 maxElements
= elementIndex
;
2163 // If we know the maximum number of elements, and we've already
2164 // hit it, stop consuming elements in the initializer list.
2165 if (maxElementsKnown
&& elementIndex
== maxElements
)
2168 InitializedEntity ElementEntity
= InitializedEntity::InitializeElement(
2169 SemaRef
.Context
, StructuredIndex
, Entity
);
2171 unsigned EmbedElementIndexBeforeInit
= CurEmbedIndex
;
2172 // Check this element.
2173 CheckSubElementType(ElementEntity
, IList
, elementType
, Index
,
2174 StructuredList
, StructuredIndex
);
2176 if ((CurEmbed
|| isa
<EmbedExpr
>(Init
)) && elementType
->isScalarType()) {
2179 elementIndex
+ CurEmbedIndex
- EmbedElementIndexBeforeInit
- 1;
2181 auto Embed
= cast
<EmbedExpr
>(Init
);
2182 elementIndex
= elementIndex
+ Embed
->getDataElementCount() -
2183 EmbedElementIndexBeforeInit
- 1;
2187 // If the array is of incomplete type, keep track of the number of
2188 // elements in the initializer.
2189 if (!maxElementsKnown
&& elementIndex
> maxElements
)
2190 maxElements
= elementIndex
;
2192 if (!hadError
&& DeclType
->isIncompleteArrayType() && !VerifyOnly
) {
2193 // If this is an incomplete array type, the actual type needs to
2194 // be calculated here.
2195 llvm::APSInt
Zero(maxElements
.getBitWidth(), maxElements
.isUnsigned());
2196 if (maxElements
== Zero
&& !Entity
.isVariableLengthArrayNew()) {
2197 // Sizing an array implicitly to zero is not allowed by ISO C,
2198 // but is supported by GNU.
2199 SemaRef
.Diag(IList
->getBeginLoc(), diag::ext_typecheck_zero_array_size
);
2202 DeclType
= SemaRef
.Context
.getConstantArrayType(
2203 elementType
, maxElements
, nullptr, ArraySizeModifier::Normal
, 0);
2206 // If there are any members of the array that get value-initialized, check
2207 // that is possible. That happens if we know the bound and don't have
2208 // enough elements, or if we're performing an array new with an unknown
2210 if ((maxElementsKnown
&& elementIndex
< maxElements
) ||
2211 Entity
.isVariableLengthArrayNew())
2212 CheckEmptyInitializable(
2213 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
),
2214 IList
->getEndLoc());
2218 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity
&Entity
,
2221 bool TopLevelObject
) {
2222 // Handle GNU flexible array initializers.
2223 unsigned FlexArrayDiag
;
2224 if (isa
<InitListExpr
>(InitExpr
) &&
2225 cast
<InitListExpr
>(InitExpr
)->getNumInits() == 0) {
2226 // Empty flexible array init always allowed as an extension
2227 FlexArrayDiag
= diag::ext_flexible_array_init
;
2228 } else if (!TopLevelObject
) {
2229 // Disallow flexible array init on non-top-level object
2230 FlexArrayDiag
= diag::err_flexible_array_init
;
2231 } else if (Entity
.getKind() != InitializedEntity::EK_Variable
) {
2232 // Disallow flexible array init on anything which is not a variable.
2233 FlexArrayDiag
= diag::err_flexible_array_init
;
2234 } else if (cast
<VarDecl
>(Entity
.getDecl())->hasLocalStorage()) {
2235 // Disallow flexible array init on local variables.
2236 FlexArrayDiag
= diag::err_flexible_array_init
;
2238 // Allow other cases.
2239 FlexArrayDiag
= diag::ext_flexible_array_init
;
2243 SemaRef
.Diag(InitExpr
->getBeginLoc(), FlexArrayDiag
)
2244 << InitExpr
->getBeginLoc();
2245 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
2249 return FlexArrayDiag
!= diag::ext_flexible_array_init
;
2252 static bool isInitializedStructuredList(const InitListExpr
*StructuredList
) {
2253 return StructuredList
&& StructuredList
->getNumInits() == 1U;
2256 void InitListChecker::CheckStructUnionTypes(
2257 const InitializedEntity
&Entity
, InitListExpr
*IList
, QualType DeclType
,
2258 CXXRecordDecl::base_class_const_range Bases
, RecordDecl::field_iterator Field
,
2259 bool SubobjectIsDesignatorContext
, unsigned &Index
,
2260 InitListExpr
*StructuredList
, unsigned &StructuredIndex
,
2261 bool TopLevelObject
) {
2262 const RecordDecl
*RD
= getRecordDecl(DeclType
);
2264 // If the record is invalid, some of it's members are invalid. To avoid
2265 // confusion, we forgo checking the initializer for the entire record.
2266 if (RD
->isInvalidDecl()) {
2267 // Assume it was supposed to consume a single initializer.
2273 if (RD
->isUnion() && IList
->getNumInits() == 0) {
2275 for (FieldDecl
*FD
: RD
->fields()) {
2276 QualType ET
= SemaRef
.Context
.getBaseElementType(FD
->getType());
2277 if (checkDestructorReference(ET
, IList
->getEndLoc(), SemaRef
)) {
2283 // If there's a default initializer, use it.
2284 if (isa
<CXXRecordDecl
>(RD
) &&
2285 cast
<CXXRecordDecl
>(RD
)->hasInClassInitializer()) {
2286 if (!StructuredList
)
2288 for (RecordDecl::field_iterator FieldEnd
= RD
->field_end();
2289 Field
!= FieldEnd
; ++Field
) {
2290 if (Field
->hasInClassInitializer() ||
2291 (Field
->isAnonymousStructOrUnion() &&
2292 Field
->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
2293 StructuredList
->setInitializedFieldInUnion(*Field
);
2294 // FIXME: Actually build a CXXDefaultInitExpr?
2298 llvm_unreachable("Couldn't find in-class initializer");
2301 // Value-initialize the first member of the union that isn't an unnamed
2303 for (RecordDecl::field_iterator FieldEnd
= RD
->field_end();
2304 Field
!= FieldEnd
; ++Field
) {
2305 if (!Field
->isUnnamedBitField()) {
2306 CheckEmptyInitializable(
2307 InitializedEntity::InitializeMember(*Field
, &Entity
),
2308 IList
->getEndLoc());
2310 StructuredList
->setInitializedFieldInUnion(*Field
);
2317 bool InitializedSomething
= false;
2319 // If we have any base classes, they are initialized prior to the fields.
2320 for (auto I
= Bases
.begin(), E
= Bases
.end(); I
!= E
; ++I
) {
2322 Expr
*Init
= Index
< IList
->getNumInits() ? IList
->getInit(Index
) : nullptr;
2324 // Designated inits always initialize fields, so if we see one, all
2325 // remaining base classes have no explicit initializer.
2326 if (isa_and_nonnull
<DesignatedInitExpr
>(Init
))
2329 // C++ [over.match.class.deduct]p1.6:
2330 // each non-trailing aggregate element that is a pack expansion is assumed
2331 // to correspond to no elements of the initializer list, and (1.7) a
2332 // trailing aggregate element that is a pack expansion is assumed to
2333 // correspond to all remaining elements of the initializer list (if any).
2335 // C++ [over.match.class.deduct]p1.9:
2336 // ... except that additional parameter packs of the form P_j... are
2337 // inserted into the parameter list in their original aggregate element
2338 // position corresponding to each non-trailing aggregate element of
2339 // type P_j that was skipped because it was a parameter pack, and the
2340 // trailing sequence of parameters corresponding to a trailing
2341 // aggregate element that is a pack expansion (if any) is replaced
2342 // by a single parameter of the form T_n....
2343 if (AggrDeductionCandidateParamTypes
&& Base
.isPackExpansion()) {
2344 AggrDeductionCandidateParamTypes
->push_back(
2345 SemaRef
.Context
.getPackExpansionType(Base
.getType(), std::nullopt
));
2347 // Trailing pack expansion
2348 if (I
+ 1 == E
&& RD
->field_empty()) {
2349 if (Index
< IList
->getNumInits())
2350 Index
= IList
->getNumInits();
2357 SourceLocation InitLoc
= Init
? Init
->getBeginLoc() : IList
->getEndLoc();
2358 InitializedEntity BaseEntity
= InitializedEntity::InitializeBase(
2359 SemaRef
.Context
, &Base
, false, &Entity
);
2361 CheckSubElementType(BaseEntity
, IList
, Base
.getType(), Index
,
2362 StructuredList
, StructuredIndex
);
2363 InitializedSomething
= true;
2365 CheckEmptyInitializable(BaseEntity
, InitLoc
);
2369 if (checkDestructorReference(Base
.getType(), InitLoc
, SemaRef
)) {
2375 // If structDecl is a forward declaration, this loop won't do
2376 // anything except look at designated initializers; That's okay,
2377 // because an error should get printed out elsewhere. It might be
2378 // worthwhile to skip over the rest of the initializer, though.
2379 RecordDecl::field_iterator FieldEnd
= RD
->field_end();
2380 size_t NumRecordDecls
= llvm::count_if(RD
->decls(), [&](const Decl
*D
) {
2381 return isa
<FieldDecl
>(D
) || isa
<RecordDecl
>(D
);
2383 bool HasDesignatedInit
= false;
2385 llvm::SmallPtrSet
<FieldDecl
*, 4> InitializedFields
;
2387 while (Index
< IList
->getNumInits()) {
2388 Expr
*Init
= IList
->getInit(Index
);
2389 SourceLocation InitLoc
= Init
->getBeginLoc();
2391 if (DesignatedInitExpr
*DIE
= dyn_cast
<DesignatedInitExpr
>(Init
)) {
2392 // If we're not the subobject that matches up with the '{' for
2393 // the designator, we shouldn't be handling the
2394 // designator. Return immediately.
2395 if (!SubobjectIsDesignatorContext
)
2398 HasDesignatedInit
= true;
2400 // Handle this designated initializer. Field will be updated to
2401 // the next field that we'll be initializing.
2402 bool DesignatedInitFailed
= CheckDesignatedInitializer(
2403 Entity
, IList
, DIE
, 0, DeclType
, &Field
, nullptr, Index
,
2404 StructuredList
, StructuredIndex
, true, TopLevelObject
);
2405 if (DesignatedInitFailed
)
2408 // Find the field named by the designated initializer.
2409 DesignatedInitExpr::Designator
*D
= DIE
->getDesignator(0);
2410 if (!VerifyOnly
&& D
->isFieldDesignator()) {
2411 FieldDecl
*F
= D
->getFieldDecl();
2412 InitializedFields
.insert(F
);
2413 if (!DesignatedInitFailed
) {
2414 QualType ET
= SemaRef
.Context
.getBaseElementType(F
->getType());
2415 if (checkDestructorReference(ET
, InitLoc
, SemaRef
)) {
2422 InitializedSomething
= true;
2426 // Check if this is an initializer of forms:
2428 // struct foo f = {};
2429 // struct foo g = {0};
2431 // These are okay for randomized structures. [C99 6.7.8p19]
2433 // Also, if there is only one element in the structure, we allow something
2434 // like this, because it's really not randomized in the traditional sense.
2436 // struct foo h = {bar};
2437 auto IsZeroInitializer
= [&](const Expr
*I
) {
2438 if (IList
->getNumInits() == 1) {
2439 if (NumRecordDecls
== 1)
2441 if (const auto *IL
= dyn_cast
<IntegerLiteral
>(I
))
2442 return IL
->getValue().isZero();
2447 // Don't allow non-designated initializers on randomized structures.
2448 if (RD
->isRandomized() && !IsZeroInitializer(Init
)) {
2450 SemaRef
.Diag(InitLoc
, diag::err_non_designated_init_used
);
2455 if (Field
== FieldEnd
) {
2456 // We've run out of fields. We're done.
2460 // We've already initialized a member of a union. We can stop entirely.
2461 if (InitializedSomething
&& RD
->isUnion())
2464 // Stop if we've hit a flexible array member.
2465 if (Field
->getType()->isIncompleteArrayType())
2468 if (Field
->isUnnamedBitField()) {
2469 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2474 // Make sure we can use this declaration.
2477 InvalidUse
= !SemaRef
.CanUseDecl(*Field
, TreatUnavailableAsInvalid
);
2479 InvalidUse
= SemaRef
.DiagnoseUseOfDecl(
2480 *Field
, IList
->getInit(Index
)->getBeginLoc());
2489 QualType ET
= SemaRef
.Context
.getBaseElementType(Field
->getType());
2490 if (checkDestructorReference(ET
, InitLoc
, SemaRef
)) {
2496 InitializedEntity MemberEntity
=
2497 InitializedEntity::InitializeMember(*Field
, &Entity
);
2498 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
2499 StructuredList
, StructuredIndex
);
2500 InitializedSomething
= true;
2501 InitializedFields
.insert(*Field
);
2502 if (RD
->isUnion() && isInitializedStructuredList(StructuredList
)) {
2503 // Initialize the first field within the union.
2504 StructuredList
->setInitializedFieldInUnion(*Field
);
2510 // Emit warnings for missing struct field initializers.
2511 // This check is disabled for designated initializers in C.
2512 // This matches gcc behaviour.
2513 bool IsCDesignatedInitializer
=
2514 HasDesignatedInit
&& !SemaRef
.getLangOpts().CPlusPlus
;
2515 if (!VerifyOnly
&& InitializedSomething
&& !RD
->isUnion() &&
2516 !IList
->isIdiomaticZeroInitializer(SemaRef
.getLangOpts()) &&
2517 !IsCDesignatedInitializer
) {
2518 // It is possible we have one or more unnamed bitfields remaining.
2519 // Find first (if any) named field and emit warning.
2520 for (RecordDecl::field_iterator it
= HasDesignatedInit
? RD
->field_begin()
2522 end
= RD
->field_end();
2524 if (HasDesignatedInit
&& InitializedFields
.count(*it
))
2527 if (!it
->isUnnamedBitField() && !it
->hasInClassInitializer() &&
2528 !it
->getType()->isIncompleteArrayType()) {
2529 auto Diag
= HasDesignatedInit
2530 ? diag::warn_missing_designated_field_initializers
2531 : diag::warn_missing_field_initializers
;
2532 SemaRef
.Diag(IList
->getSourceRange().getEnd(), Diag
) << *it
;
2538 // Check that any remaining fields can be value-initialized if we're not
2539 // building a structured list. (If we are, we'll check this later.)
2540 if (!StructuredList
&& Field
!= FieldEnd
&& !RD
->isUnion() &&
2541 !Field
->getType()->isIncompleteArrayType()) {
2542 for (; Field
!= FieldEnd
&& !hadError
; ++Field
) {
2543 if (!Field
->isUnnamedBitField() && !Field
->hasInClassInitializer())
2544 CheckEmptyInitializable(
2545 InitializedEntity::InitializeMember(*Field
, &Entity
),
2546 IList
->getEndLoc());
2550 // Check that the types of the remaining fields have accessible destructors.
2552 // If the initializer expression has a designated initializer, check the
2553 // elements for which a designated initializer is not provided too.
2554 RecordDecl::field_iterator I
= HasDesignatedInit
? RD
->field_begin()
2556 for (RecordDecl::field_iterator E
= RD
->field_end(); I
!= E
; ++I
) {
2557 QualType ET
= SemaRef
.Context
.getBaseElementType(I
->getType());
2558 if (checkDestructorReference(ET
, IList
->getEndLoc(), SemaRef
)) {
2565 if (Field
== FieldEnd
|| !Field
->getType()->isIncompleteArrayType() ||
2566 Index
>= IList
->getNumInits())
2569 if (CheckFlexibleArrayInit(Entity
, IList
->getInit(Index
), *Field
,
2576 InitializedEntity MemberEntity
=
2577 InitializedEntity::InitializeMember(*Field
, &Entity
);
2579 if (isa
<InitListExpr
>(IList
->getInit(Index
)) ||
2580 AggrDeductionCandidateParamTypes
)
2581 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
2582 StructuredList
, StructuredIndex
);
2584 CheckImplicitInitList(MemberEntity
, IList
, Field
->getType(), Index
,
2585 StructuredList
, StructuredIndex
);
2587 if (RD
->isUnion() && isInitializedStructuredList(StructuredList
)) {
2588 // Initialize the first field within the union.
2589 StructuredList
->setInitializedFieldInUnion(*Field
);
2593 /// Expand a field designator that refers to a member of an
2594 /// anonymous struct or union into a series of field designators that
2595 /// refers to the field within the appropriate subobject.
2597 static void ExpandAnonymousFieldDesignator(Sema
&SemaRef
,
2598 DesignatedInitExpr
*DIE
,
2600 IndirectFieldDecl
*IndirectField
) {
2601 typedef DesignatedInitExpr::Designator Designator
;
2603 // Build the replacement designators.
2604 SmallVector
<Designator
, 4> Replacements
;
2605 for (IndirectFieldDecl::chain_iterator PI
= IndirectField
->chain_begin(),
2606 PE
= IndirectField
->chain_end(); PI
!= PE
; ++PI
) {
2608 Replacements
.push_back(Designator::CreateFieldDesignator(
2609 (IdentifierInfo
*)nullptr, DIE
->getDesignator(DesigIdx
)->getDotLoc(),
2610 DIE
->getDesignator(DesigIdx
)->getFieldLoc()));
2612 Replacements
.push_back(Designator::CreateFieldDesignator(
2613 (IdentifierInfo
*)nullptr, SourceLocation(), SourceLocation()));
2614 assert(isa
<FieldDecl
>(*PI
));
2615 Replacements
.back().setFieldDecl(cast
<FieldDecl
>(*PI
));
2618 // Expand the current designator into the set of replacement
2619 // designators, so we have a full subobject path down to where the
2620 // member of the anonymous struct/union is actually stored.
2621 DIE
->ExpandDesignator(SemaRef
.Context
, DesigIdx
, &Replacements
[0],
2622 &Replacements
[0] + Replacements
.size());
2625 static DesignatedInitExpr
*CloneDesignatedInitExpr(Sema
&SemaRef
,
2626 DesignatedInitExpr
*DIE
) {
2627 unsigned NumIndexExprs
= DIE
->getNumSubExprs() - 1;
2628 SmallVector
<Expr
*, 4> IndexExprs(NumIndexExprs
);
2629 for (unsigned I
= 0; I
< NumIndexExprs
; ++I
)
2630 IndexExprs
[I
] = DIE
->getSubExpr(I
+ 1);
2631 return DesignatedInitExpr::Create(SemaRef
.Context
, DIE
->designators(),
2633 DIE
->getEqualOrColonLoc(),
2634 DIE
->usesGNUSyntax(), DIE
->getInit());
2639 // Callback to only accept typo corrections that are for field members of
2640 // the given struct or union.
2641 class FieldInitializerValidatorCCC final
: public CorrectionCandidateCallback
{
2643 explicit FieldInitializerValidatorCCC(const RecordDecl
*RD
)
2646 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
2647 FieldDecl
*FD
= candidate
.getCorrectionDeclAs
<FieldDecl
>();
2648 return FD
&& FD
->getDeclContext()->getRedeclContext()->Equals(Record
);
2651 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
2652 return std::make_unique
<FieldInitializerValidatorCCC
>(*this);
2656 const RecordDecl
*Record
;
2659 } // end anonymous namespace
2661 /// Check the well-formedness of a C99 designated initializer.
2663 /// Determines whether the designated initializer @p DIE, which
2664 /// resides at the given @p Index within the initializer list @p
2665 /// IList, is well-formed for a current object of type @p DeclType
2666 /// (C99 6.7.8). The actual subobject that this designator refers to
2667 /// within the current subobject is returned in either
2668 /// @p NextField or @p NextElementIndex (whichever is appropriate).
2670 /// @param IList The initializer list in which this designated
2671 /// initializer occurs.
2673 /// @param DIE The designated initializer expression.
2675 /// @param DesigIdx The index of the current designator.
2677 /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2678 /// into which the designation in @p DIE should refer.
2680 /// @param NextField If non-NULL and the first designator in @p DIE is
2681 /// a field, this will be set to the field declaration corresponding
2682 /// to the field named by the designator. On input, this is expected to be
2683 /// the next field that would be initialized in the absence of designation,
2684 /// if the complete object being initialized is a struct.
2686 /// @param NextElementIndex If non-NULL and the first designator in @p
2687 /// DIE is an array designator or GNU array-range designator, this
2688 /// will be set to the last index initialized by this designator.
2690 /// @param Index Index into @p IList where the designated initializer
2693 /// @param StructuredList The initializer list expression that
2694 /// describes all of the subobject initializers in the order they'll
2695 /// actually be initialized.
2697 /// @returns true if there was an error, false otherwise.
2699 InitListChecker::CheckDesignatedInitializer(const InitializedEntity
&Entity
,
2700 InitListExpr
*IList
,
2701 DesignatedInitExpr
*DIE
,
2703 QualType
&CurrentObjectType
,
2704 RecordDecl::field_iterator
*NextField
,
2705 llvm::APSInt
*NextElementIndex
,
2707 InitListExpr
*StructuredList
,
2708 unsigned &StructuredIndex
,
2709 bool FinishSubobjectInit
,
2710 bool TopLevelObject
) {
2711 if (DesigIdx
== DIE
->size()) {
2712 // C++20 designated initialization can result in direct-list-initialization
2713 // of the designated subobject. This is the only way that we can end up
2714 // performing direct initialization as part of aggregate initialization, so
2715 // it needs special handling.
2716 if (DIE
->isDirectInit()) {
2717 Expr
*Init
= DIE
->getInit();
2718 assert(isa
<InitListExpr
>(Init
) &&
2719 "designator result in direct non-list initialization?");
2720 InitializationKind Kind
= InitializationKind::CreateDirectList(
2721 DIE
->getBeginLoc(), Init
->getBeginLoc(), Init
->getEndLoc());
2722 InitializationSequence
Seq(SemaRef
, Entity
, Kind
, Init
,
2723 /*TopLevelOfInitList*/ true);
2724 if (StructuredList
) {
2725 ExprResult Result
= VerifyOnly
2727 : Seq
.Perform(SemaRef
, Entity
, Kind
, Init
);
2728 UpdateStructuredListElement(StructuredList
, StructuredIndex
,
2732 if (AggrDeductionCandidateParamTypes
)
2733 AggrDeductionCandidateParamTypes
->push_back(CurrentObjectType
);
2737 // Check the actual initialization for the designated object type.
2738 bool prevHadError
= hadError
;
2740 // Temporarily remove the designator expression from the
2741 // initializer list that the child calls see, so that we don't try
2742 // to re-process the designator.
2743 unsigned OldIndex
= Index
;
2744 IList
->setInit(OldIndex
, DIE
->getInit());
2746 CheckSubElementType(Entity
, IList
, CurrentObjectType
, Index
, StructuredList
,
2747 StructuredIndex
, /*DirectlyDesignated=*/true);
2749 // Restore the designated initializer expression in the syntactic
2750 // form of the initializer list.
2751 if (IList
->getInit(OldIndex
) != DIE
->getInit())
2752 DIE
->setInit(IList
->getInit(OldIndex
));
2753 IList
->setInit(OldIndex
, DIE
);
2755 return hadError
&& !prevHadError
;
2758 DesignatedInitExpr::Designator
*D
= DIE
->getDesignator(DesigIdx
);
2759 bool IsFirstDesignator
= (DesigIdx
== 0);
2760 if (IsFirstDesignator
? FullyStructuredList
: StructuredList
) {
2761 // Determine the structural initializer list that corresponds to the
2762 // current subobject.
2763 if (IsFirstDesignator
)
2764 StructuredList
= FullyStructuredList
;
2766 Expr
*ExistingInit
= StructuredIndex
< StructuredList
->getNumInits() ?
2767 StructuredList
->getInit(StructuredIndex
) : nullptr;
2768 if (!ExistingInit
&& StructuredList
->hasArrayFiller())
2769 ExistingInit
= StructuredList
->getArrayFiller();
2772 StructuredList
= getStructuredSubobjectInit(
2773 IList
, Index
, CurrentObjectType
, StructuredList
, StructuredIndex
,
2774 SourceRange(D
->getBeginLoc(), DIE
->getEndLoc()));
2775 else if (InitListExpr
*Result
= dyn_cast
<InitListExpr
>(ExistingInit
))
2776 StructuredList
= Result
;
2778 // We are creating an initializer list that initializes the
2779 // subobjects of the current object, but there was already an
2780 // initialization that completely initialized the current
2781 // subobject, e.g., by a compound literal:
2783 // struct X { int a, b; };
2784 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2786 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2787 // designated initializer re-initializes only its current object
2789 diagnoseInitOverride(ExistingInit
,
2790 SourceRange(D
->getBeginLoc(), DIE
->getEndLoc()),
2791 /*UnionOverride=*/false,
2792 /*FullyOverwritten=*/false);
2795 if (DesignatedInitUpdateExpr
*E
=
2796 dyn_cast
<DesignatedInitUpdateExpr
>(ExistingInit
))
2797 StructuredList
= E
->getUpdater();
2799 DesignatedInitUpdateExpr
*DIUE
= new (SemaRef
.Context
)
2800 DesignatedInitUpdateExpr(SemaRef
.Context
, D
->getBeginLoc(),
2801 ExistingInit
, DIE
->getEndLoc());
2802 StructuredList
->updateInit(SemaRef
.Context
, StructuredIndex
, DIUE
);
2803 StructuredList
= DIUE
->getUpdater();
2806 // We don't need to track the structured representation of a
2807 // designated init update of an already-fully-initialized object in
2808 // verify-only mode. The only reason we would need the structure is
2809 // to determine where the uninitialized "holes" are, and in this
2810 // case, we know there aren't any and we can't introduce any.
2811 StructuredList
= nullptr;
2817 if (D
->isFieldDesignator()) {
2820 // If a designator has the form
2824 // then the current object (defined below) shall have
2825 // structure or union type and the identifier shall be the
2826 // name of a member of that type.
2827 RecordDecl
*RD
= getRecordDecl(CurrentObjectType
);
2829 SourceLocation Loc
= D
->getDotLoc();
2830 if (Loc
.isInvalid())
2831 Loc
= D
->getFieldLoc();
2833 SemaRef
.Diag(Loc
, diag::err_field_designator_non_aggr
)
2834 << SemaRef
.getLangOpts().CPlusPlus
<< CurrentObjectType
;
2839 FieldDecl
*KnownField
= D
->getFieldDecl();
2841 const IdentifierInfo
*FieldName
= D
->getFieldName();
2842 ValueDecl
*VD
= SemaRef
.tryLookupUnambiguousFieldDecl(RD
, FieldName
);
2843 if (auto *FD
= dyn_cast_if_present
<FieldDecl
>(VD
)) {
2845 } else if (auto *IFD
= dyn_cast_if_present
<IndirectFieldDecl
>(VD
)) {
2846 // In verify mode, don't modify the original.
2848 DIE
= CloneDesignatedInitExpr(SemaRef
, DIE
);
2849 ExpandAnonymousFieldDesignator(SemaRef
, DIE
, DesigIdx
, IFD
);
2850 D
= DIE
->getDesignator(DesigIdx
);
2851 KnownField
= cast
<FieldDecl
>(*IFD
->chain_begin());
2856 return true; // No typo correction when just trying this out.
2859 // We found a placeholder variable
2860 if (SemaRef
.DiagRedefinedPlaceholderFieldDecl(DIE
->getBeginLoc(), RD
,
2865 // Name lookup found something, but it wasn't a field.
2866 if (DeclContextLookupResult Lookup
= RD
->lookup(FieldName
);
2868 SemaRef
.Diag(D
->getFieldLoc(), diag::err_field_designator_nonfield
)
2870 SemaRef
.Diag(Lookup
.front()->getLocation(),
2871 diag::note_field_designator_found
);
2876 // Name lookup didn't find anything.
2877 // Determine whether this was a typo for another field name.
2878 FieldInitializerValidatorCCC
CCC(RD
);
2879 if (TypoCorrection Corrected
= SemaRef
.CorrectTypo(
2880 DeclarationNameInfo(FieldName
, D
->getFieldLoc()),
2881 Sema::LookupMemberName
, /*Scope=*/nullptr, /*SS=*/nullptr, CCC
,
2882 Sema::CTK_ErrorRecovery
, RD
)) {
2883 SemaRef
.diagnoseTypo(
2885 SemaRef
.PDiag(diag::err_field_designator_unknown_suggest
)
2886 << FieldName
<< CurrentObjectType
);
2887 KnownField
= Corrected
.getCorrectionDeclAs
<FieldDecl
>();
2890 // Typo correction didn't find anything.
2891 SourceLocation Loc
= D
->getFieldLoc();
2893 // The loc can be invalid with a "null" designator (i.e. an anonymous
2894 // union/struct). Do our best to approximate the location.
2895 if (Loc
.isInvalid())
2896 Loc
= IList
->getBeginLoc();
2898 SemaRef
.Diag(Loc
, diag::err_field_designator_unknown
)
2899 << FieldName
<< CurrentObjectType
<< DIE
->getSourceRange();
2906 unsigned NumBases
= 0;
2907 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
2908 NumBases
= CXXRD
->getNumBases();
2910 unsigned FieldIndex
= NumBases
;
2912 for (auto *FI
: RD
->fields()) {
2913 if (FI
->isUnnamedBitField())
2915 if (declaresSameEntity(KnownField
, FI
)) {
2922 RecordDecl::field_iterator Field
=
2923 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField
));
2925 // All of the fields of a union are located at the same place in
2926 // the initializer list.
2927 if (RD
->isUnion()) {
2929 if (StructuredList
) {
2930 FieldDecl
*CurrentField
= StructuredList
->getInitializedFieldInUnion();
2931 if (CurrentField
&& !declaresSameEntity(CurrentField
, *Field
)) {
2932 assert(StructuredList
->getNumInits() == 1
2933 && "A union should never have more than one initializer!");
2935 Expr
*ExistingInit
= StructuredList
->getInit(0);
2937 // We're about to throw away an initializer, emit warning.
2938 diagnoseInitOverride(
2939 ExistingInit
, SourceRange(D
->getBeginLoc(), DIE
->getEndLoc()),
2940 /*UnionOverride=*/true,
2941 /*FullyOverwritten=*/SemaRef
.getLangOpts().CPlusPlus
? false
2945 // remove existing initializer
2946 StructuredList
->resizeInits(SemaRef
.Context
, 0);
2947 StructuredList
->setInitializedFieldInUnion(nullptr);
2950 StructuredList
->setInitializedFieldInUnion(*Field
);
2954 // Make sure we can use this declaration.
2957 InvalidUse
= !SemaRef
.CanUseDecl(*Field
, TreatUnavailableAsInvalid
);
2959 InvalidUse
= SemaRef
.DiagnoseUseOfDecl(*Field
, D
->getFieldLoc());
2965 // C++20 [dcl.init.list]p3:
2966 // The ordered identifiers in the designators of the designated-
2967 // initializer-list shall form a subsequence of the ordered identifiers
2968 // in the direct non-static data members of T.
2970 // Note that this is not a condition on forming the aggregate
2971 // initialization, only on actually performing initialization,
2972 // so it is not checked in VerifyOnly mode.
2974 // FIXME: This is the only reordering diagnostic we produce, and it only
2975 // catches cases where we have a top-level field designator that jumps
2976 // backwards. This is the only such case that is reachable in an
2977 // otherwise-valid C++20 program, so is the only case that's required for
2978 // conformance, but for consistency, we should diagnose all the other
2979 // cases where a designator takes us backwards too.
2980 if (IsFirstDesignator
&& !VerifyOnly
&& SemaRef
.getLangOpts().CPlusPlus
&&
2982 (*NextField
== RD
->field_end() ||
2983 (*NextField
)->getFieldIndex() > Field
->getFieldIndex() + 1)) {
2984 // Find the field that we just initialized.
2985 FieldDecl
*PrevField
= nullptr;
2986 for (auto FI
= RD
->field_begin(); FI
!= RD
->field_end(); ++FI
) {
2987 if (FI
->isUnnamedBitField())
2989 if (*NextField
!= RD
->field_end() &&
2990 declaresSameEntity(*FI
, **NextField
))
2996 PrevField
->getFieldIndex() > KnownField
->getFieldIndex()) {
2997 SemaRef
.Diag(DIE
->getInit()->getBeginLoc(),
2998 diag::ext_designated_init_reordered
)
2999 << KnownField
<< PrevField
<< DIE
->getSourceRange();
3001 unsigned OldIndex
= StructuredIndex
- 1;
3002 if (StructuredList
&& OldIndex
<= StructuredList
->getNumInits()) {
3003 if (Expr
*PrevInit
= StructuredList
->getInit(OldIndex
)) {
3004 SemaRef
.Diag(PrevInit
->getBeginLoc(),
3005 diag::note_previous_field_init
)
3006 << PrevField
<< PrevInit
->getSourceRange();
3013 // Update the designator with the field declaration.
3015 D
->setFieldDecl(*Field
);
3017 // Make sure that our non-designated initializer list has space
3018 // for a subobject corresponding to this field.
3019 if (StructuredList
&& FieldIndex
>= StructuredList
->getNumInits())
3020 StructuredList
->resizeInits(SemaRef
.Context
, FieldIndex
+ 1);
3022 // This designator names a flexible array member.
3023 if (Field
->getType()->isIncompleteArrayType()) {
3024 bool Invalid
= false;
3025 if ((DesigIdx
+ 1) != DIE
->size()) {
3026 // We can't designate an object within the flexible array
3027 // member (because GCC doesn't allow it).
3029 DesignatedInitExpr::Designator
*NextD
3030 = DIE
->getDesignator(DesigIdx
+ 1);
3031 SemaRef
.Diag(NextD
->getBeginLoc(),
3032 diag::err_designator_into_flexible_array_member
)
3033 << SourceRange(NextD
->getBeginLoc(), DIE
->getEndLoc());
3034 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
3040 if (!hadError
&& !isa
<InitListExpr
>(DIE
->getInit()) &&
3041 !isa
<StringLiteral
>(DIE
->getInit())) {
3042 // The initializer is not an initializer list.
3044 SemaRef
.Diag(DIE
->getInit()->getBeginLoc(),
3045 diag::err_flexible_array_init_needs_braces
)
3046 << DIE
->getInit()->getSourceRange();
3047 SemaRef
.Diag(Field
->getLocation(), diag::note_flexible_array_member
)
3053 // Check GNU flexible array initializer.
3054 if (!Invalid
&& CheckFlexibleArrayInit(Entity
, DIE
->getInit(), *Field
,
3063 // Initialize the array.
3064 bool prevHadError
= hadError
;
3065 unsigned newStructuredIndex
= FieldIndex
;
3066 unsigned OldIndex
= Index
;
3067 IList
->setInit(Index
, DIE
->getInit());
3069 InitializedEntity MemberEntity
=
3070 InitializedEntity::InitializeMember(*Field
, &Entity
);
3071 CheckSubElementType(MemberEntity
, IList
, Field
->getType(), Index
,
3072 StructuredList
, newStructuredIndex
);
3074 IList
->setInit(OldIndex
, DIE
);
3075 if (hadError
&& !prevHadError
) {
3080 StructuredIndex
= FieldIndex
;
3084 // Recurse to check later designated subobjects.
3085 QualType FieldType
= Field
->getType();
3086 unsigned newStructuredIndex
= FieldIndex
;
3088 InitializedEntity MemberEntity
=
3089 InitializedEntity::InitializeMember(*Field
, &Entity
);
3090 if (CheckDesignatedInitializer(MemberEntity
, IList
, DIE
, DesigIdx
+ 1,
3091 FieldType
, nullptr, nullptr, Index
,
3092 StructuredList
, newStructuredIndex
,
3093 FinishSubobjectInit
, false))
3097 // Find the position of the next field to be initialized in this
3102 // If this the first designator, our caller will continue checking
3103 // the rest of this struct/class/union subobject.
3104 if (IsFirstDesignator
) {
3105 if (Field
!= RD
->field_end() && Field
->isUnnamedBitField())
3111 StructuredIndex
= FieldIndex
;
3115 if (!FinishSubobjectInit
)
3118 // We've already initialized something in the union; we're done.
3122 // Check the remaining fields within this class/struct/union subobject.
3123 bool prevHadError
= hadError
;
3126 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
3127 CXXRecordDecl::base_class_iterator());
3128 CheckStructUnionTypes(Entity
, IList
, CurrentObjectType
, NoBases
, Field
,
3129 false, Index
, StructuredList
, FieldIndex
);
3130 return hadError
&& !prevHadError
;
3135 // If a designator has the form
3137 // [ constant-expression ]
3139 // then the current object (defined below) shall have array
3140 // type and the expression shall be an integer constant
3141 // expression. If the array is of unknown size, any
3142 // nonnegative value is valid.
3144 // Additionally, cope with the GNU extension that permits
3145 // designators of the form
3147 // [ constant-expression ... constant-expression ]
3148 const ArrayType
*AT
= SemaRef
.Context
.getAsArrayType(CurrentObjectType
);
3151 SemaRef
.Diag(D
->getLBracketLoc(), diag::err_array_designator_non_array
)
3152 << CurrentObjectType
;
3157 Expr
*IndexExpr
= nullptr;
3158 llvm::APSInt DesignatedStartIndex
, DesignatedEndIndex
;
3159 if (D
->isArrayDesignator()) {
3160 IndexExpr
= DIE
->getArrayIndex(*D
);
3161 DesignatedStartIndex
= IndexExpr
->EvaluateKnownConstInt(SemaRef
.Context
);
3162 DesignatedEndIndex
= DesignatedStartIndex
;
3164 assert(D
->isArrayRangeDesignator() && "Need array-range designator");
3166 DesignatedStartIndex
=
3167 DIE
->getArrayRangeStart(*D
)->EvaluateKnownConstInt(SemaRef
.Context
);
3168 DesignatedEndIndex
=
3169 DIE
->getArrayRangeEnd(*D
)->EvaluateKnownConstInt(SemaRef
.Context
);
3170 IndexExpr
= DIE
->getArrayRangeEnd(*D
);
3172 // Codegen can't handle evaluating array range designators that have side
3173 // effects, because we replicate the AST value for each initialized element.
3174 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3175 // elements with something that has a side effect, so codegen can emit an
3176 // "error unsupported" error instead of miscompiling the app.
3177 if (DesignatedStartIndex
.getZExtValue()!=DesignatedEndIndex
.getZExtValue()&&
3178 DIE
->getInit()->HasSideEffects(SemaRef
.Context
) && !VerifyOnly
)
3179 FullyStructuredList
->sawArrayRangeDesignator();
3182 if (isa
<ConstantArrayType
>(AT
)) {
3183 llvm::APSInt
MaxElements(cast
<ConstantArrayType
>(AT
)->getSize(), false);
3184 DesignatedStartIndex
3185 = DesignatedStartIndex
.extOrTrunc(MaxElements
.getBitWidth());
3186 DesignatedStartIndex
.setIsUnsigned(MaxElements
.isUnsigned());
3188 = DesignatedEndIndex
.extOrTrunc(MaxElements
.getBitWidth());
3189 DesignatedEndIndex
.setIsUnsigned(MaxElements
.isUnsigned());
3190 if (DesignatedEndIndex
>= MaxElements
) {
3192 SemaRef
.Diag(IndexExpr
->getBeginLoc(),
3193 diag::err_array_designator_too_large
)
3194 << toString(DesignatedEndIndex
, 10) << toString(MaxElements
, 10)
3195 << IndexExpr
->getSourceRange();
3200 unsigned DesignatedIndexBitWidth
=
3201 ConstantArrayType::getMaxSizeBits(SemaRef
.Context
);
3202 DesignatedStartIndex
=
3203 DesignatedStartIndex
.extOrTrunc(DesignatedIndexBitWidth
);
3204 DesignatedEndIndex
=
3205 DesignatedEndIndex
.extOrTrunc(DesignatedIndexBitWidth
);
3206 DesignatedStartIndex
.setIsUnsigned(true);
3207 DesignatedEndIndex
.setIsUnsigned(true);
3210 bool IsStringLiteralInitUpdate
=
3211 StructuredList
&& StructuredList
->isStringLiteralInit();
3212 if (IsStringLiteralInitUpdate
&& VerifyOnly
) {
3213 // We're just verifying an update to a string literal init. We don't need
3214 // to split the string up into individual characters to do that.
3215 StructuredList
= nullptr;
3216 } else if (IsStringLiteralInitUpdate
) {
3217 // We're modifying a string literal init; we have to decompose the string
3218 // so we can modify the individual characters.
3219 ASTContext
&Context
= SemaRef
.Context
;
3220 Expr
*SubExpr
= StructuredList
->getInit(0)->IgnoreParenImpCasts();
3222 // Compute the character type
3223 QualType CharTy
= AT
->getElementType();
3225 // Compute the type of the integer literals.
3226 QualType PromotedCharTy
= CharTy
;
3227 if (Context
.isPromotableIntegerType(CharTy
))
3228 PromotedCharTy
= Context
.getPromotedIntegerType(CharTy
);
3229 unsigned PromotedCharTyWidth
= Context
.getTypeSize(PromotedCharTy
);
3231 if (StringLiteral
*SL
= dyn_cast
<StringLiteral
>(SubExpr
)) {
3232 // Get the length of the string.
3233 uint64_t StrLen
= SL
->getLength();
3234 if (cast
<ConstantArrayType
>(AT
)->getSize().ult(StrLen
))
3235 StrLen
= cast
<ConstantArrayType
>(AT
)->getZExtSize();
3236 StructuredList
->resizeInits(Context
, StrLen
);
3238 // Build a literal for each character in the string, and put them into
3240 for (unsigned i
= 0, e
= StrLen
; i
!= e
; ++i
) {
3241 llvm::APInt
CodeUnit(PromotedCharTyWidth
, SL
->getCodeUnit(i
));
3242 Expr
*Init
= new (Context
) IntegerLiteral(
3243 Context
, CodeUnit
, PromotedCharTy
, SubExpr
->getExprLoc());
3244 if (CharTy
!= PromotedCharTy
)
3245 Init
= ImplicitCastExpr::Create(Context
, CharTy
, CK_IntegralCast
,
3246 Init
, nullptr, VK_PRValue
,
3247 FPOptionsOverride());
3248 StructuredList
->updateInit(Context
, i
, Init
);
3251 ObjCEncodeExpr
*E
= cast
<ObjCEncodeExpr
>(SubExpr
);
3253 Context
.getObjCEncodingForType(E
->getEncodedType(), Str
);
3255 // Get the length of the string.
3256 uint64_t StrLen
= Str
.size();
3257 if (cast
<ConstantArrayType
>(AT
)->getSize().ult(StrLen
))
3258 StrLen
= cast
<ConstantArrayType
>(AT
)->getZExtSize();
3259 StructuredList
->resizeInits(Context
, StrLen
);
3261 // Build a literal for each character in the string, and put them into
3263 for (unsigned i
= 0, e
= StrLen
; i
!= e
; ++i
) {
3264 llvm::APInt
CodeUnit(PromotedCharTyWidth
, Str
[i
]);
3265 Expr
*Init
= new (Context
) IntegerLiteral(
3266 Context
, CodeUnit
, PromotedCharTy
, SubExpr
->getExprLoc());
3267 if (CharTy
!= PromotedCharTy
)
3268 Init
= ImplicitCastExpr::Create(Context
, CharTy
, CK_IntegralCast
,
3269 Init
, nullptr, VK_PRValue
,
3270 FPOptionsOverride());
3271 StructuredList
->updateInit(Context
, i
, Init
);
3276 // Make sure that our non-designated initializer list has space
3277 // for a subobject corresponding to this array element.
3278 if (StructuredList
&&
3279 DesignatedEndIndex
.getZExtValue() >= StructuredList
->getNumInits())
3280 StructuredList
->resizeInits(SemaRef
.Context
,
3281 DesignatedEndIndex
.getZExtValue() + 1);
3283 // Repeatedly perform subobject initializations in the range
3284 // [DesignatedStartIndex, DesignatedEndIndex].
3286 // Move to the next designator
3287 unsigned ElementIndex
= DesignatedStartIndex
.getZExtValue();
3288 unsigned OldIndex
= Index
;
3290 InitializedEntity ElementEntity
=
3291 InitializedEntity::InitializeElement(SemaRef
.Context
, 0, Entity
);
3293 while (DesignatedStartIndex
<= DesignatedEndIndex
) {
3294 // Recurse to check later designated subobjects.
3295 QualType ElementType
= AT
->getElementType();
3298 ElementEntity
.setElementIndex(ElementIndex
);
3299 if (CheckDesignatedInitializer(
3300 ElementEntity
, IList
, DIE
, DesigIdx
+ 1, ElementType
, nullptr,
3301 nullptr, Index
, StructuredList
, ElementIndex
,
3302 FinishSubobjectInit
&& (DesignatedStartIndex
== DesignatedEndIndex
),
3306 // Move to the next index in the array that we'll be initializing.
3307 ++DesignatedStartIndex
;
3308 ElementIndex
= DesignatedStartIndex
.getZExtValue();
3311 // If this the first designator, our caller will continue checking
3312 // the rest of this array subobject.
3313 if (IsFirstDesignator
) {
3314 if (NextElementIndex
)
3315 *NextElementIndex
= DesignatedStartIndex
;
3316 StructuredIndex
= ElementIndex
;
3320 if (!FinishSubobjectInit
)
3323 // Check the remaining elements within this array subobject.
3324 bool prevHadError
= hadError
;
3325 CheckArrayType(Entity
, IList
, CurrentObjectType
, DesignatedStartIndex
,
3326 /*SubobjectIsDesignatorContext=*/false, Index
,
3327 StructuredList
, ElementIndex
);
3328 return hadError
&& !prevHadError
;
3331 // Get the structured initializer list for a subobject of type
3332 // @p CurrentObjectType.
3334 InitListChecker::getStructuredSubobjectInit(InitListExpr
*IList
, unsigned Index
,
3335 QualType CurrentObjectType
,
3336 InitListExpr
*StructuredList
,
3337 unsigned StructuredIndex
,
3338 SourceRange InitRange
,
3339 bool IsFullyOverwritten
) {
3340 if (!StructuredList
)
3343 Expr
*ExistingInit
= nullptr;
3344 if (StructuredIndex
< StructuredList
->getNumInits())
3345 ExistingInit
= StructuredList
->getInit(StructuredIndex
);
3347 if (InitListExpr
*Result
= dyn_cast_or_null
<InitListExpr
>(ExistingInit
))
3348 // There might have already been initializers for subobjects of the current
3349 // object, but a subsequent initializer list will overwrite the entirety
3350 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3352 // struct P { char x[6]; };
3353 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3355 // The first designated initializer is ignored, and l.x is just "f".
3356 if (!IsFullyOverwritten
)
3360 // We are creating an initializer list that initializes the
3361 // subobjects of the current object, but there was already an
3362 // initialization that completely initialized the current
3365 // struct X { int a, b; };
3366 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3368 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3369 // designated initializer overwrites the [0].b initializer
3370 // from the prior initialization.
3372 // When the existing initializer is an expression rather than an
3373 // initializer list, we cannot decompose and update it in this way.
3376 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3378 // This case is handled by CheckDesignatedInitializer.
3379 diagnoseInitOverride(ExistingInit
, InitRange
);
3382 unsigned ExpectedNumInits
= 0;
3383 if (Index
< IList
->getNumInits()) {
3384 if (auto *Init
= dyn_cast_or_null
<InitListExpr
>(IList
->getInit(Index
)))
3385 ExpectedNumInits
= Init
->getNumInits();
3387 ExpectedNumInits
= IList
->getNumInits() - Index
;
3390 InitListExpr
*Result
=
3391 createInitListExpr(CurrentObjectType
, InitRange
, ExpectedNumInits
);
3393 // Link this new initializer list into the structured initializer
3395 StructuredList
->updateInit(SemaRef
.Context
, StructuredIndex
, Result
);
3400 InitListChecker::createInitListExpr(QualType CurrentObjectType
,
3401 SourceRange InitRange
,
3402 unsigned ExpectedNumInits
) {
3403 InitListExpr
*Result
= new (SemaRef
.Context
) InitListExpr(
3404 SemaRef
.Context
, InitRange
.getBegin(), {}, InitRange
.getEnd());
3406 QualType ResultType
= CurrentObjectType
;
3407 if (!ResultType
->isArrayType())
3408 ResultType
= ResultType
.getNonLValueExprType(SemaRef
.Context
);
3409 Result
->setType(ResultType
);
3411 // Pre-allocate storage for the structured initializer list.
3412 unsigned NumElements
= 0;
3414 if (const ArrayType
*AType
3415 = SemaRef
.Context
.getAsArrayType(CurrentObjectType
)) {
3416 if (const ConstantArrayType
*CAType
= dyn_cast
<ConstantArrayType
>(AType
)) {
3417 NumElements
= CAType
->getZExtSize();
3418 // Simple heuristic so that we don't allocate a very large
3419 // initializer with many empty entries at the end.
3420 if (NumElements
> ExpectedNumInits
)
3423 } else if (const VectorType
*VType
= CurrentObjectType
->getAs
<VectorType
>()) {
3424 NumElements
= VType
->getNumElements();
3425 } else if (CurrentObjectType
->isRecordType()) {
3426 NumElements
= numStructUnionElements(CurrentObjectType
);
3427 } else if (CurrentObjectType
->isDependentType()) {
3431 Result
->reserveInits(SemaRef
.Context
, NumElements
);
3436 /// Update the initializer at index @p StructuredIndex within the
3437 /// structured initializer list to the value @p expr.
3438 void InitListChecker::UpdateStructuredListElement(InitListExpr
*StructuredList
,
3439 unsigned &StructuredIndex
,
3441 // No structured initializer list to update
3442 if (!StructuredList
)
3445 if (Expr
*PrevInit
= StructuredList
->updateInit(SemaRef
.Context
,
3446 StructuredIndex
, expr
)) {
3447 // This initializer overwrites a previous initializer.
3448 // No need to diagnose when `expr` is nullptr because a more relevant
3449 // diagnostic has already been issued and this diagnostic is potentially
3452 diagnoseInitOverride(PrevInit
, expr
->getSourceRange());
3458 bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3459 const InitializedEntity
&Entity
, InitListExpr
*From
) {
3460 QualType Type
= Entity
.getType();
3461 InitListChecker
Check(*this, Entity
, From
, Type
, /*VerifyOnly=*/true,
3462 /*TreatUnavailableAsInvalid=*/false,
3463 /*InOverloadResolution=*/true);
3464 return !Check
.HadError();
3467 /// Check that the given Index expression is a valid array designator
3468 /// value. This is essentially just a wrapper around
3469 /// VerifyIntegerConstantExpression that also checks for negative values
3470 /// and produces a reasonable diagnostic if there is a
3471 /// failure. Returns the index expression, possibly with an implicit cast
3472 /// added, on success. If everything went okay, Value will receive the
3473 /// value of the constant expression.
3475 CheckArrayDesignatorExpr(Sema
&S
, Expr
*Index
, llvm::APSInt
&Value
) {
3476 SourceLocation Loc
= Index
->getBeginLoc();
3478 // Make sure this is an integer constant expression.
3480 S
.VerifyIntegerConstantExpression(Index
, &Value
, Sema::AllowFold
);
3481 if (Result
.isInvalid())
3484 if (Value
.isSigned() && Value
.isNegative())
3485 return S
.Diag(Loc
, diag::err_array_designator_negative
)
3486 << toString(Value
, 10) << Index
->getSourceRange();
3488 Value
.setIsUnsigned(true);
3492 ExprResult
Sema::ActOnDesignatedInitializer(Designation
&Desig
,
3493 SourceLocation EqualOrColonLoc
,
3496 typedef DesignatedInitExpr::Designator ASTDesignator
;
3498 bool Invalid
= false;
3499 SmallVector
<ASTDesignator
, 32> Designators
;
3500 SmallVector
<Expr
*, 32> InitExpressions
;
3502 // Build designators and check array designator expressions.
3503 for (unsigned Idx
= 0; Idx
< Desig
.getNumDesignators(); ++Idx
) {
3504 const Designator
&D
= Desig
.getDesignator(Idx
);
3506 if (D
.isFieldDesignator()) {
3507 Designators
.push_back(ASTDesignator::CreateFieldDesignator(
3508 D
.getFieldDecl(), D
.getDotLoc(), D
.getFieldLoc()));
3509 } else if (D
.isArrayDesignator()) {
3510 Expr
*Index
= static_cast<Expr
*>(D
.getArrayIndex());
3511 llvm::APSInt IndexValue
;
3512 if (!Index
->isTypeDependent() && !Index
->isValueDependent())
3513 Index
= CheckArrayDesignatorExpr(*this, Index
, IndexValue
).get();
3517 Designators
.push_back(ASTDesignator::CreateArrayDesignator(
3518 InitExpressions
.size(), D
.getLBracketLoc(), D
.getRBracketLoc()));
3519 InitExpressions
.push_back(Index
);
3521 } else if (D
.isArrayRangeDesignator()) {
3522 Expr
*StartIndex
= static_cast<Expr
*>(D
.getArrayRangeStart());
3523 Expr
*EndIndex
= static_cast<Expr
*>(D
.getArrayRangeEnd());
3524 llvm::APSInt StartValue
;
3525 llvm::APSInt EndValue
;
3526 bool StartDependent
= StartIndex
->isTypeDependent() ||
3527 StartIndex
->isValueDependent();
3528 bool EndDependent
= EndIndex
->isTypeDependent() ||
3529 EndIndex
->isValueDependent();
3530 if (!StartDependent
)
3532 CheckArrayDesignatorExpr(*this, StartIndex
, StartValue
).get();
3534 EndIndex
= CheckArrayDesignatorExpr(*this, EndIndex
, EndValue
).get();
3536 if (!StartIndex
|| !EndIndex
)
3539 // Make sure we're comparing values with the same bit width.
3540 if (StartDependent
|| EndDependent
) {
3541 // Nothing to compute.
3542 } else if (StartValue
.getBitWidth() > EndValue
.getBitWidth())
3543 EndValue
= EndValue
.extend(StartValue
.getBitWidth());
3544 else if (StartValue
.getBitWidth() < EndValue
.getBitWidth())
3545 StartValue
= StartValue
.extend(EndValue
.getBitWidth());
3547 if (!StartDependent
&& !EndDependent
&& EndValue
< StartValue
) {
3548 Diag(D
.getEllipsisLoc(), diag::err_array_designator_empty_range
)
3549 << toString(StartValue
, 10) << toString(EndValue
, 10)
3550 << StartIndex
->getSourceRange() << EndIndex
->getSourceRange();
3553 Designators
.push_back(ASTDesignator::CreateArrayRangeDesignator(
3554 InitExpressions
.size(), D
.getLBracketLoc(), D
.getEllipsisLoc(),
3555 D
.getRBracketLoc()));
3556 InitExpressions
.push_back(StartIndex
);
3557 InitExpressions
.push_back(EndIndex
);
3563 if (Invalid
|| Init
.isInvalid())
3566 return DesignatedInitExpr::Create(Context
, Designators
, InitExpressions
,
3567 EqualOrColonLoc
, GNUSyntax
,
3568 Init
.getAs
<Expr
>());
3571 //===----------------------------------------------------------------------===//
3572 // Initialization entity
3573 //===----------------------------------------------------------------------===//
3575 InitializedEntity::InitializedEntity(ASTContext
&Context
, unsigned Index
,
3576 const InitializedEntity
&Parent
)
3577 : Parent(&Parent
), Index(Index
)
3579 if (const ArrayType
*AT
= Context
.getAsArrayType(Parent
.getType())) {
3580 Kind
= EK_ArrayElement
;
3581 Type
= AT
->getElementType();
3582 } else if (const VectorType
*VT
= Parent
.getType()->getAs
<VectorType
>()) {
3583 Kind
= EK_VectorElement
;
3584 Type
= VT
->getElementType();
3586 const ComplexType
*CT
= Parent
.getType()->getAs
<ComplexType
>();
3587 assert(CT
&& "Unexpected type");
3588 Kind
= EK_ComplexElement
;
3589 Type
= CT
->getElementType();
3594 InitializedEntity::InitializeBase(ASTContext
&Context
,
3595 const CXXBaseSpecifier
*Base
,
3596 bool IsInheritedVirtualBase
,
3597 const InitializedEntity
*Parent
) {
3598 InitializedEntity Result
;
3599 Result
.Kind
= EK_Base
;
3600 Result
.Parent
= Parent
;
3601 Result
.Base
= {Base
, IsInheritedVirtualBase
};
3602 Result
.Type
= Base
->getType();
3606 DeclarationName
InitializedEntity::getName() const {
3607 switch (getKind()) {
3609 case EK_Parameter_CF_Audited
: {
3610 ParmVarDecl
*D
= Parameter
.getPointer();
3611 return (D
? D
->getDeclName() : DeclarationName());
3616 case EK_ParenAggInitMember
:
3618 case EK_TemplateParameter
:
3619 return Variable
.VariableOrMember
->getDeclName();
3621 case EK_LambdaCapture
:
3622 return DeclarationName(Capture
.VarID
);
3625 case EK_StmtExprResult
:
3631 case EK_ArrayElement
:
3632 case EK_VectorElement
:
3633 case EK_ComplexElement
:
3634 case EK_BlockElement
:
3635 case EK_LambdaToBlockConversionBlockElement
:
3636 case EK_CompoundLiteralInit
:
3637 case EK_RelatedResult
:
3638 return DeclarationName();
3641 llvm_unreachable("Invalid EntityKind!");
3644 ValueDecl
*InitializedEntity::getDecl() const {
3645 switch (getKind()) {
3648 case EK_ParenAggInitMember
:
3650 case EK_TemplateParameter
:
3651 return Variable
.VariableOrMember
;
3654 case EK_Parameter_CF_Audited
:
3655 return Parameter
.getPointer();
3658 case EK_StmtExprResult
:
3664 case EK_ArrayElement
:
3665 case EK_VectorElement
:
3666 case EK_ComplexElement
:
3667 case EK_BlockElement
:
3668 case EK_LambdaToBlockConversionBlockElement
:
3669 case EK_LambdaCapture
:
3670 case EK_CompoundLiteralInit
:
3671 case EK_RelatedResult
:
3675 llvm_unreachable("Invalid EntityKind!");
3678 bool InitializedEntity::allowsNRVO() const {
3679 switch (getKind()) {
3682 return LocAndNRVO
.NRVO
;
3684 case EK_StmtExprResult
:
3687 case EK_Parameter_CF_Audited
:
3688 case EK_TemplateParameter
:
3690 case EK_ParenAggInitMember
:
3694 case EK_CompoundLiteralInit
:
3697 case EK_ArrayElement
:
3698 case EK_VectorElement
:
3699 case EK_ComplexElement
:
3700 case EK_BlockElement
:
3701 case EK_LambdaToBlockConversionBlockElement
:
3702 case EK_LambdaCapture
:
3703 case EK_RelatedResult
:
3710 unsigned InitializedEntity::dumpImpl(raw_ostream
&OS
) const {
3711 assert(getParent() != this);
3712 unsigned Depth
= getParent() ? getParent()->dumpImpl(OS
) : 0;
3713 for (unsigned I
= 0; I
!= Depth
; ++I
)
3716 switch (getKind()) {
3717 case EK_Variable
: OS
<< "Variable"; break;
3718 case EK_Parameter
: OS
<< "Parameter"; break;
3719 case EK_Parameter_CF_Audited
: OS
<< "CF audited function Parameter";
3721 case EK_TemplateParameter
: OS
<< "TemplateParameter"; break;
3722 case EK_Result
: OS
<< "Result"; break;
3723 case EK_StmtExprResult
: OS
<< "StmtExprResult"; break;
3724 case EK_Exception
: OS
<< "Exception"; break;
3726 case EK_ParenAggInitMember
:
3729 case EK_Binding
: OS
<< "Binding"; break;
3730 case EK_New
: OS
<< "New"; break;
3731 case EK_Temporary
: OS
<< "Temporary"; break;
3732 case EK_CompoundLiteralInit
: OS
<< "CompoundLiteral";break;
3733 case EK_RelatedResult
: OS
<< "RelatedResult"; break;
3734 case EK_Base
: OS
<< "Base"; break;
3735 case EK_Delegating
: OS
<< "Delegating"; break;
3736 case EK_ArrayElement
: OS
<< "ArrayElement " << Index
; break;
3737 case EK_VectorElement
: OS
<< "VectorElement " << Index
; break;
3738 case EK_ComplexElement
: OS
<< "ComplexElement " << Index
; break;
3739 case EK_BlockElement
: OS
<< "Block"; break;
3740 case EK_LambdaToBlockConversionBlockElement
:
3741 OS
<< "Block (lambda)";
3743 case EK_LambdaCapture
:
3744 OS
<< "LambdaCapture ";
3745 OS
<< DeclarationName(Capture
.VarID
);
3749 if (auto *D
= getDecl()) {
3751 D
->printQualifiedName(OS
);
3754 OS
<< " '" << getType() << "'\n";
3759 LLVM_DUMP_METHOD
void InitializedEntity::dump() const {
3760 dumpImpl(llvm::errs());
3763 //===----------------------------------------------------------------------===//
3764 // Initialization sequence
3765 //===----------------------------------------------------------------------===//
3767 void InitializationSequence::Step::Destroy() {
3769 case SK_ResolveAddressOfOverloadedFunction
:
3770 case SK_CastDerivedToBasePRValue
:
3771 case SK_CastDerivedToBaseXValue
:
3772 case SK_CastDerivedToBaseLValue
:
3773 case SK_BindReference
:
3774 case SK_BindReferenceToTemporary
:
3776 case SK_ExtraneousCopyToTemporary
:
3777 case SK_UserConversion
:
3778 case SK_QualificationConversionPRValue
:
3779 case SK_QualificationConversionXValue
:
3780 case SK_QualificationConversionLValue
:
3781 case SK_FunctionReferenceConversion
:
3782 case SK_AtomicConversion
:
3783 case SK_ListInitialization
:
3784 case SK_UnwrapInitList
:
3785 case SK_RewrapInitList
:
3786 case SK_ConstructorInitialization
:
3787 case SK_ConstructorInitializationFromList
:
3788 case SK_ZeroInitialization
:
3789 case SK_CAssignment
:
3791 case SK_ObjCObjectConversion
:
3792 case SK_ArrayLoopIndex
:
3793 case SK_ArrayLoopInit
:
3795 case SK_GNUArrayInit
:
3796 case SK_ParenthesizedArrayInit
:
3797 case SK_PassByIndirectCopyRestore
:
3798 case SK_PassByIndirectRestore
:
3799 case SK_ProduceObjCObject
:
3800 case SK_StdInitializerList
:
3801 case SK_StdInitializerListConstructorCall
:
3802 case SK_OCLSamplerInit
:
3803 case SK_OCLZeroOpaqueType
:
3804 case SK_ParenthesizedListInit
:
3807 case SK_ConversionSequence
:
3808 case SK_ConversionSequenceNoNarrowing
:
3813 bool InitializationSequence::isDirectReferenceBinding() const {
3814 // There can be some lvalue adjustments after the SK_BindReference step.
3815 for (const Step
&S
: llvm::reverse(Steps
)) {
3816 if (S
.Kind
== SK_BindReference
)
3818 if (S
.Kind
== SK_BindReferenceToTemporary
)
3824 bool InitializationSequence::isAmbiguous() const {
3828 switch (getFailureKind()) {
3829 case FK_TooManyInitsForReference
:
3830 case FK_ParenthesizedListInitForReference
:
3831 case FK_ArrayNeedsInitList
:
3832 case FK_ArrayNeedsInitListOrStringLiteral
:
3833 case FK_ArrayNeedsInitListOrWideStringLiteral
:
3834 case FK_NarrowStringIntoWideCharArray
:
3835 case FK_WideStringIntoCharArray
:
3836 case FK_IncompatWideStringIntoWideChar
:
3837 case FK_PlainStringIntoUTF8Char
:
3838 case FK_UTF8StringIntoPlainChar
:
3839 case FK_AddressOfOverloadFailed
: // FIXME: Could do better
3840 case FK_NonConstLValueReferenceBindingToTemporary
:
3841 case FK_NonConstLValueReferenceBindingToBitfield
:
3842 case FK_NonConstLValueReferenceBindingToVectorElement
:
3843 case FK_NonConstLValueReferenceBindingToMatrixElement
:
3844 case FK_NonConstLValueReferenceBindingToUnrelated
:
3845 case FK_RValueReferenceBindingToLValue
:
3846 case FK_ReferenceAddrspaceMismatchTemporary
:
3847 case FK_ReferenceInitDropsQualifiers
:
3848 case FK_ReferenceInitFailed
:
3849 case FK_ConversionFailed
:
3850 case FK_ConversionFromPropertyFailed
:
3851 case FK_TooManyInitsForScalar
:
3852 case FK_ParenthesizedListInitForScalar
:
3853 case FK_ReferenceBindingToInitList
:
3854 case FK_InitListBadDestinationType
:
3855 case FK_DefaultInitOfConst
:
3857 case FK_ArrayTypeMismatch
:
3858 case FK_NonConstantArrayInit
:
3859 case FK_ListInitializationFailed
:
3860 case FK_VariableLengthArrayHasInitializer
:
3861 case FK_PlaceholderType
:
3862 case FK_ExplicitConstructor
:
3863 case FK_AddressOfUnaddressableFunction
:
3864 case FK_ParenthesizedListInitFailed
:
3865 case FK_DesignatedInitForNonAggregate
:
3868 case FK_ReferenceInitOverloadFailed
:
3869 case FK_UserConversionOverloadFailed
:
3870 case FK_ConstructorOverloadFailed
:
3871 case FK_ListConstructorOverloadFailed
:
3872 return FailedOverloadResult
== OR_Ambiguous
;
3875 llvm_unreachable("Invalid EntityKind!");
3878 bool InitializationSequence::isConstructorInitialization() const {
3879 return !Steps
.empty() && Steps
.back().Kind
== SK_ConstructorInitialization
;
3883 InitializationSequence
3884 ::AddAddressOverloadResolutionStep(FunctionDecl
*Function
,
3885 DeclAccessPair Found
,
3886 bool HadMultipleCandidates
) {
3888 S
.Kind
= SK_ResolveAddressOfOverloadedFunction
;
3889 S
.Type
= Function
->getType();
3890 S
.Function
.HadMultipleCandidates
= HadMultipleCandidates
;
3891 S
.Function
.Function
= Function
;
3892 S
.Function
.FoundDecl
= Found
;
3896 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType
,
3901 S
.Kind
= SK_CastDerivedToBasePRValue
;
3903 case VK_XValue
: S
.Kind
= SK_CastDerivedToBaseXValue
; break;
3904 case VK_LValue
: S
.Kind
= SK_CastDerivedToBaseLValue
; break;
3910 void InitializationSequence::AddReferenceBindingStep(QualType T
,
3911 bool BindingTemporary
) {
3913 S
.Kind
= BindingTemporary
? SK_BindReferenceToTemporary
: SK_BindReference
;
3918 void InitializationSequence::AddFinalCopy(QualType T
) {
3920 S
.Kind
= SK_FinalCopy
;
3925 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T
) {
3927 S
.Kind
= SK_ExtraneousCopyToTemporary
;
3933 InitializationSequence::AddUserConversionStep(FunctionDecl
*Function
,
3934 DeclAccessPair FoundDecl
,
3936 bool HadMultipleCandidates
) {
3938 S
.Kind
= SK_UserConversion
;
3940 S
.Function
.HadMultipleCandidates
= HadMultipleCandidates
;
3941 S
.Function
.Function
= Function
;
3942 S
.Function
.FoundDecl
= FoundDecl
;
3946 void InitializationSequence::AddQualificationConversionStep(QualType Ty
,
3949 S
.Kind
= SK_QualificationConversionPRValue
; // work around a gcc warning
3952 S
.Kind
= SK_QualificationConversionPRValue
;
3955 S
.Kind
= SK_QualificationConversionXValue
;
3958 S
.Kind
= SK_QualificationConversionLValue
;
3965 void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty
) {
3967 S
.Kind
= SK_FunctionReferenceConversion
;
3972 void InitializationSequence::AddAtomicConversionStep(QualType Ty
) {
3974 S
.Kind
= SK_AtomicConversion
;
3979 void InitializationSequence::AddConversionSequenceStep(
3980 const ImplicitConversionSequence
&ICS
, QualType T
,
3981 bool TopLevelOfInitList
) {
3983 S
.Kind
= TopLevelOfInitList
? SK_ConversionSequenceNoNarrowing
3984 : SK_ConversionSequence
;
3986 S
.ICS
= new ImplicitConversionSequence(ICS
);
3990 void InitializationSequence::AddListInitializationStep(QualType T
) {
3992 S
.Kind
= SK_ListInitialization
;
3997 void InitializationSequence::AddConstructorInitializationStep(
3998 DeclAccessPair FoundDecl
, CXXConstructorDecl
*Constructor
, QualType T
,
3999 bool HadMultipleCandidates
, bool FromInitList
, bool AsInitList
) {
4001 S
.Kind
= FromInitList
? AsInitList
? SK_StdInitializerListConstructorCall
4002 : SK_ConstructorInitializationFromList
4003 : SK_ConstructorInitialization
;
4005 S
.Function
.HadMultipleCandidates
= HadMultipleCandidates
;
4006 S
.Function
.Function
= Constructor
;
4007 S
.Function
.FoundDecl
= FoundDecl
;
4011 void InitializationSequence::AddZeroInitializationStep(QualType T
) {
4013 S
.Kind
= SK_ZeroInitialization
;
4018 void InitializationSequence::AddCAssignmentStep(QualType T
) {
4020 S
.Kind
= SK_CAssignment
;
4025 void InitializationSequence::AddStringInitStep(QualType T
) {
4027 S
.Kind
= SK_StringInit
;
4032 void InitializationSequence::AddObjCObjectConversionStep(QualType T
) {
4034 S
.Kind
= SK_ObjCObjectConversion
;
4039 void InitializationSequence::AddArrayInitStep(QualType T
, bool IsGNUExtension
) {
4041 S
.Kind
= IsGNUExtension
? SK_GNUArrayInit
: SK_ArrayInit
;
4046 void InitializationSequence::AddArrayInitLoopStep(QualType T
, QualType EltT
) {
4048 S
.Kind
= SK_ArrayLoopIndex
;
4050 Steps
.insert(Steps
.begin(), S
);
4052 S
.Kind
= SK_ArrayLoopInit
;
4057 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T
) {
4059 S
.Kind
= SK_ParenthesizedArrayInit
;
4064 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type
,
4067 s
.Kind
= (shouldCopy
? SK_PassByIndirectCopyRestore
4068 : SK_PassByIndirectRestore
);
4073 void InitializationSequence::AddProduceObjCObjectStep(QualType T
) {
4075 S
.Kind
= SK_ProduceObjCObject
;
4080 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T
) {
4082 S
.Kind
= SK_StdInitializerList
;
4087 void InitializationSequence::AddOCLSamplerInitStep(QualType T
) {
4089 S
.Kind
= SK_OCLSamplerInit
;
4094 void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T
) {
4096 S
.Kind
= SK_OCLZeroOpaqueType
;
4101 void InitializationSequence::AddParenthesizedListInitStep(QualType T
) {
4103 S
.Kind
= SK_ParenthesizedListInit
;
4108 void InitializationSequence::AddUnwrapInitListInitStep(
4109 InitListExpr
*Syntactic
) {
4110 assert(Syntactic
->getNumInits() == 1 &&
4111 "Can only unwrap trivial init lists.");
4113 S
.Kind
= SK_UnwrapInitList
;
4114 S
.Type
= Syntactic
->getInit(0)->getType();
4115 Steps
.insert(Steps
.begin(), S
);
4118 void InitializationSequence::RewrapReferenceInitList(QualType T
,
4119 InitListExpr
*Syntactic
) {
4120 assert(Syntactic
->getNumInits() == 1 &&
4121 "Can only rewrap trivial init lists.");
4123 S
.Kind
= SK_UnwrapInitList
;
4124 S
.Type
= Syntactic
->getInit(0)->getType();
4125 Steps
.insert(Steps
.begin(), S
);
4127 S
.Kind
= SK_RewrapInitList
;
4129 S
.WrappingSyntacticList
= Syntactic
;
4133 void InitializationSequence::SetOverloadFailure(FailureKind Failure
,
4134 OverloadingResult Result
) {
4135 setSequenceKind(FailedSequence
);
4136 this->Failure
= Failure
;
4137 this->FailedOverloadResult
= Result
;
4140 //===----------------------------------------------------------------------===//
4141 // Attempt initialization
4142 //===----------------------------------------------------------------------===//
4144 /// Tries to add a zero initializer. Returns true if that worked.
4146 maybeRecoverWithZeroInitialization(Sema
&S
, InitializationSequence
&Sequence
,
4147 const InitializedEntity
&Entity
) {
4148 if (Entity
.getKind() != InitializedEntity::EK_Variable
)
4151 VarDecl
*VD
= cast
<VarDecl
>(Entity
.getDecl());
4152 if (VD
->getInit() || VD
->getEndLoc().isMacroID())
4155 QualType VariableTy
= VD
->getType().getCanonicalType();
4156 SourceLocation Loc
= S
.getLocForEndOfToken(VD
->getEndLoc());
4157 std::string Init
= S
.getFixItZeroInitializerForType(VariableTy
, Loc
);
4158 if (!Init
.empty()) {
4159 Sequence
.AddZeroInitializationStep(Entity
.getType());
4160 Sequence
.SetZeroInitializationFixit(Init
, Loc
);
4166 static void MaybeProduceObjCObject(Sema
&S
,
4167 InitializationSequence
&Sequence
,
4168 const InitializedEntity
&Entity
) {
4169 if (!S
.getLangOpts().ObjCAutoRefCount
) return;
4171 /// When initializing a parameter, produce the value if it's marked
4172 /// __attribute__((ns_consumed)).
4173 if (Entity
.isParameterKind()) {
4174 if (!Entity
.isParameterConsumed())
4177 assert(Entity
.getType()->isObjCRetainableType() &&
4178 "consuming an object of unretainable type?");
4179 Sequence
.AddProduceObjCObjectStep(Entity
.getType());
4181 /// When initializing a return value, if the return type is a
4182 /// retainable type, then returns need to immediately retain the
4183 /// object. If an autorelease is required, it will be done at the
4185 } else if (Entity
.getKind() == InitializedEntity::EK_Result
||
4186 Entity
.getKind() == InitializedEntity::EK_StmtExprResult
) {
4187 if (!Entity
.getType()->isObjCRetainableType())
4190 Sequence
.AddProduceObjCObjectStep(Entity
.getType());
4194 /// Initialize an array from another array
4195 static void TryArrayCopy(Sema
&S
, const InitializationKind
&Kind
,
4196 const InitializedEntity
&Entity
, Expr
*Initializer
,
4197 QualType DestType
, InitializationSequence
&Sequence
,
4198 bool TreatUnavailableAsInvalid
) {
4199 // If source is a prvalue, use it directly.
4200 if (Initializer
->isPRValue()) {
4201 Sequence
.AddArrayInitStep(DestType
, /*IsGNUExtension*/ false);
4205 // Emit element-at-a-time copy loop.
4206 InitializedEntity Element
=
4207 InitializedEntity::InitializeElement(S
.Context
, 0, Entity
);
4209 S
.Context
.getAsArrayType(Initializer
->getType())->getElementType();
4210 OpaqueValueExpr
OVE(Initializer
->getExprLoc(), InitEltT
,
4211 Initializer
->getValueKind(),
4212 Initializer
->getObjectKind());
4213 Expr
*OVEAsExpr
= &OVE
;
4214 Sequence
.InitializeFrom(S
, Element
, Kind
, OVEAsExpr
,
4215 /*TopLevelOfInitList*/ false,
4216 TreatUnavailableAsInvalid
);
4218 Sequence
.AddArrayInitLoopStep(Entity
.getType(), InitEltT
);
4221 static void TryListInitialization(Sema
&S
,
4222 const InitializedEntity
&Entity
,
4223 const InitializationKind
&Kind
,
4224 InitListExpr
*InitList
,
4225 InitializationSequence
&Sequence
,
4226 bool TreatUnavailableAsInvalid
);
4228 /// When initializing from init list via constructor, handle
4229 /// initialization of an object of type std::initializer_list<T>.
4231 /// \return true if we have handled initialization of an object of type
4232 /// std::initializer_list<T>, false otherwise.
4233 static bool TryInitializerListConstruction(Sema
&S
,
4236 InitializationSequence
&Sequence
,
4237 bool TreatUnavailableAsInvalid
) {
4239 if (!S
.isStdInitializerList(DestType
, &E
))
4242 if (!S
.isCompleteType(List
->getExprLoc(), E
)) {
4243 Sequence
.setIncompleteTypeFailure(E
);
4247 // Try initializing a temporary array from the init list.
4248 QualType ArrayType
= S
.Context
.getConstantArrayType(
4250 llvm::APInt(S
.Context
.getTypeSize(S
.Context
.getSizeType()),
4251 List
->getNumInits()),
4252 nullptr, clang::ArraySizeModifier::Normal
, 0);
4253 InitializedEntity HiddenArray
=
4254 InitializedEntity::InitializeTemporary(ArrayType
);
4255 InitializationKind Kind
= InitializationKind::CreateDirectList(
4256 List
->getExprLoc(), List
->getBeginLoc(), List
->getEndLoc());
4257 TryListInitialization(S
, HiddenArray
, Kind
, List
, Sequence
,
4258 TreatUnavailableAsInvalid
);
4260 Sequence
.AddStdInitializerListConstructionStep(DestType
);
4264 /// Determine if the constructor has the signature of a copy or move
4265 /// constructor for the type T of the class in which it was found. That is,
4266 /// determine if its first parameter is of type T or reference to (possibly
4267 /// cv-qualified) T.
4268 static bool hasCopyOrMoveCtorParam(ASTContext
&Ctx
,
4269 const ConstructorInfo
&Info
) {
4270 if (Info
.Constructor
->getNumParams() == 0)
4274 Info
.Constructor
->getParamDecl(0)->getType().getNonReferenceType();
4276 Ctx
.getRecordType(cast
<CXXRecordDecl
>(Info
.FoundDecl
->getDeclContext()));
4278 return Ctx
.hasSameUnqualifiedType(ParmT
, ClassT
);
4281 static OverloadingResult
ResolveConstructorOverload(
4282 Sema
&S
, SourceLocation DeclLoc
, MultiExprArg Args
,
4283 OverloadCandidateSet
&CandidateSet
, QualType DestType
,
4284 DeclContext::lookup_result Ctors
, OverloadCandidateSet::iterator
&Best
,
4285 bool CopyInitializing
, bool AllowExplicit
, bool OnlyListConstructors
,
4286 bool IsListInit
, bool RequireActualConstructor
,
4287 bool SecondStepOfCopyInit
= false) {
4288 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByConstructor
);
4289 CandidateSet
.setDestAS(DestType
.getQualifiers().getAddressSpace());
4291 for (NamedDecl
*D
: Ctors
) {
4292 auto Info
= getConstructorInfo(D
);
4293 if (!Info
.Constructor
|| Info
.Constructor
->isInvalidDecl())
4296 if (OnlyListConstructors
&& !S
.isInitListConstructor(Info
.Constructor
))
4299 // C++11 [over.best.ics]p4:
4300 // ... and the constructor or user-defined conversion function is a
4302 // - 13.3.1.3, when the argument is the temporary in the second step
4303 // of a class copy-initialization, or
4304 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4305 // - the second phase of 13.3.1.7 when the initializer list has exactly
4306 // one element that is itself an initializer list, and the target is
4307 // the first parameter of a constructor of class X, and the conversion
4308 // is to X or reference to (possibly cv-qualified X),
4309 // user-defined conversion sequences are not considered.
4310 bool SuppressUserConversions
=
4311 SecondStepOfCopyInit
||
4312 (IsListInit
&& Args
.size() == 1 && isa
<InitListExpr
>(Args
[0]) &&
4313 hasCopyOrMoveCtorParam(S
.Context
, Info
));
4315 if (Info
.ConstructorTmpl
)
4316 S
.AddTemplateOverloadCandidate(
4317 Info
.ConstructorTmpl
, Info
.FoundDecl
,
4318 /*ExplicitArgs*/ nullptr, Args
, CandidateSet
, SuppressUserConversions
,
4319 /*PartialOverloading=*/false, AllowExplicit
);
4321 // C++ [over.match.copy]p1:
4322 // - When initializing a temporary to be bound to the first parameter
4323 // of a constructor [for type T] that takes a reference to possibly
4324 // cv-qualified T as its first argument, called with a single
4325 // argument in the context of direct-initialization, explicit
4326 // conversion functions are also considered.
4327 // FIXME: What if a constructor template instantiates to such a signature?
4328 bool AllowExplicitConv
= AllowExplicit
&& !CopyInitializing
&&
4330 hasCopyOrMoveCtorParam(S
.Context
, Info
);
4331 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
, Args
,
4332 CandidateSet
, SuppressUserConversions
,
4333 /*PartialOverloading=*/false, AllowExplicit
,
4338 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4340 // When initializing an object of class type T by constructor
4341 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4342 // from a single expression of class type U, conversion functions of
4343 // U that convert to the non-reference type cv T are candidates.
4344 // Explicit conversion functions are only candidates during
4345 // direct-initialization.
4347 // Note: SecondStepOfCopyInit is only ever true in this case when
4348 // evaluating whether to produce a C++98 compatibility warning.
4349 if (S
.getLangOpts().CPlusPlus17
&& Args
.size() == 1 &&
4350 !RequireActualConstructor
&& !SecondStepOfCopyInit
) {
4351 Expr
*Initializer
= Args
[0];
4352 auto *SourceRD
= Initializer
->getType()->getAsCXXRecordDecl();
4353 if (SourceRD
&& S
.isCompleteType(DeclLoc
, Initializer
->getType())) {
4354 const auto &Conversions
= SourceRD
->getVisibleConversionFunctions();
4355 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
4357 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
4358 D
= D
->getUnderlyingDecl();
4360 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
4361 CXXConversionDecl
*Conv
;
4363 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
4365 Conv
= cast
<CXXConversionDecl
>(D
);
4368 S
.AddTemplateConversionCandidate(
4369 ConvTemplate
, I
.getPair(), ActingDC
, Initializer
, DestType
,
4370 CandidateSet
, AllowExplicit
, AllowExplicit
,
4371 /*AllowResultConversion*/ false);
4373 S
.AddConversionCandidate(Conv
, I
.getPair(), ActingDC
, Initializer
,
4374 DestType
, CandidateSet
, AllowExplicit
,
4376 /*AllowResultConversion*/ false);
4381 // Perform overload resolution and return the result.
4382 return CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
);
4385 /// Attempt initialization by constructor (C++ [dcl.init]), which
4386 /// enumerates the constructors of the initialized entity and performs overload
4387 /// resolution to select the best.
4388 /// \param DestType The destination class type.
4389 /// \param DestArrayType The destination type, which is either DestType or
4390 /// a (possibly multidimensional) array of DestType.
4391 /// \param IsListInit Is this list-initialization?
4392 /// \param IsInitListCopy Is this non-list-initialization resulting from a
4393 /// list-initialization from {x} where x is the same
4394 /// aggregate type as the entity?
4395 static void TryConstructorInitialization(Sema
&S
,
4396 const InitializedEntity
&Entity
,
4397 const InitializationKind
&Kind
,
4398 MultiExprArg Args
, QualType DestType
,
4399 QualType DestArrayType
,
4400 InitializationSequence
&Sequence
,
4401 bool IsListInit
= false,
4402 bool IsInitListCopy
= false) {
4403 assert(((!IsListInit
&& !IsInitListCopy
) ||
4404 (Args
.size() == 1 && isa
<InitListExpr
>(Args
[0]))) &&
4405 "IsListInit/IsInitListCopy must come with a single initializer list "
4408 (IsListInit
|| IsInitListCopy
) ? cast
<InitListExpr
>(Args
[0]) : nullptr;
4409 MultiExprArg UnwrappedArgs
=
4410 ILE
? MultiExprArg(ILE
->getInits(), ILE
->getNumInits()) : Args
;
4412 // The type we're constructing needs to be complete.
4413 if (!S
.isCompleteType(Kind
.getLocation(), DestType
)) {
4414 Sequence
.setIncompleteTypeFailure(DestType
);
4418 bool RequireActualConstructor
=
4419 !(Entity
.getKind() != InitializedEntity::EK_Base
&&
4420 Entity
.getKind() != InitializedEntity::EK_Delegating
&&
4422 InitializedEntity::EK_LambdaToBlockConversionBlockElement
);
4424 bool CopyElisionPossible
= false;
4425 auto ElideConstructor
= [&] {
4426 // Convert qualifications if necessary.
4427 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
4429 Sequence
.RewrapReferenceInitList(DestType
, ILE
);
4432 // C++17 [dcl.init]p17:
4433 // - If the initializer expression is a prvalue and the cv-unqualified
4434 // version of the source type is the same class as the class of the
4435 // destination, the initializer expression is used to initialize the
4436 // destination object.
4437 // Per DR (no number yet), this does not apply when initializing a base
4438 // class or delegating to another constructor from a mem-initializer.
4439 // ObjC++: Lambda captured by the block in the lambda to block conversion
4440 // should avoid copy elision.
4441 if (S
.getLangOpts().CPlusPlus17
&& !RequireActualConstructor
&&
4442 UnwrappedArgs
.size() == 1 && UnwrappedArgs
[0]->isPRValue() &&
4443 S
.Context
.hasSameUnqualifiedType(UnwrappedArgs
[0]->getType(), DestType
)) {
4444 if (ILE
&& !DestType
->isAggregateType()) {
4445 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4446 // Make this an elision if this won't call an initializer-list
4447 // constructor. (Always on an aggregate type or check constructors first.)
4449 // This effectively makes our resolution as follows. The parts in angle
4450 // brackets are additions.
4451 // C++17 [over.match.list]p(1.2):
4452 // - If no viable initializer-list constructor is found <and the
4453 // initializer list does not consist of exactly a single element with
4454 // the same cv-unqualified class type as T>, [...]
4455 // C++17 [dcl.init.list]p(3.6):
4456 // - Otherwise, if T is a class type, constructors are considered. The
4457 // applicable constructors are enumerated and the best one is chosen
4458 // through overload resolution. <If no constructor is found and the
4459 // initializer list consists of exactly a single element with the same
4460 // cv-unqualified class type as T, the object is initialized from that
4461 // element (by copy-initialization for copy-list-initialization, or by
4462 // direct-initialization for direct-list-initialization). Otherwise, >
4463 // if a narrowing conversion [...]
4464 assert(!IsInitListCopy
&&
4465 "IsInitListCopy only possible with aggregate types");
4466 CopyElisionPossible
= true;
4473 const RecordType
*DestRecordType
= DestType
->getAs
<RecordType
>();
4474 assert(DestRecordType
&& "Constructor initialization requires record type");
4475 CXXRecordDecl
*DestRecordDecl
4476 = cast
<CXXRecordDecl
>(DestRecordType
->getDecl());
4478 // Build the candidate set directly in the initialization sequence
4479 // structure, so that it will persist if we fail.
4480 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
4482 // Determine whether we are allowed to call explicit constructors or
4483 // explicit conversion operators.
4484 bool AllowExplicit
= Kind
.AllowExplicit() || IsListInit
;
4485 bool CopyInitialization
= Kind
.getKind() == InitializationKind::IK_Copy
;
4487 // - Otherwise, if T is a class type, constructors are considered. The
4488 // applicable constructors are enumerated, and the best one is chosen
4489 // through overload resolution.
4490 DeclContext::lookup_result Ctors
= S
.LookupConstructors(DestRecordDecl
);
4492 OverloadingResult Result
= OR_No_Viable_Function
;
4493 OverloadCandidateSet::iterator Best
;
4494 bool AsInitializerList
= false;
4496 // C++11 [over.match.list]p1, per DR1467:
4497 // When objects of non-aggregate type T are list-initialized, such that
4498 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4499 // according to the rules in this section, overload resolution selects
4500 // the constructor in two phases:
4502 // - Initially, the candidate functions are the initializer-list
4503 // constructors of the class T and the argument list consists of the
4504 // initializer list as a single argument.
4506 AsInitializerList
= true;
4508 // If the initializer list has no elements and T has a default constructor,
4509 // the first phase is omitted.
4510 if (!(UnwrappedArgs
.empty() && S
.LookupDefaultConstructor(DestRecordDecl
)))
4511 Result
= ResolveConstructorOverload(
4512 S
, Kind
.getLocation(), Args
, CandidateSet
, DestType
, Ctors
, Best
,
4513 CopyInitialization
, AllowExplicit
,
4514 /*OnlyListConstructors=*/true, IsListInit
, RequireActualConstructor
);
4516 if (CopyElisionPossible
&& Result
== OR_No_Viable_Function
) {
4517 // No initializer list candidate
4523 // C++11 [over.match.list]p1:
4524 // - If no viable initializer-list constructor is found, overload resolution
4525 // is performed again, where the candidate functions are all the
4526 // constructors of the class T and the argument list consists of the
4527 // elements of the initializer list.
4528 if (Result
== OR_No_Viable_Function
) {
4529 AsInitializerList
= false;
4530 Result
= ResolveConstructorOverload(
4531 S
, Kind
.getLocation(), UnwrappedArgs
, CandidateSet
, DestType
, Ctors
,
4532 Best
, CopyInitialization
, AllowExplicit
,
4533 /*OnlyListConstructors=*/false, IsListInit
, RequireActualConstructor
);
4536 Sequence
.SetOverloadFailure(
4537 IsListInit
? InitializationSequence::FK_ListConstructorOverloadFailed
4538 : InitializationSequence::FK_ConstructorOverloadFailed
,
4541 if (Result
!= OR_Deleted
)
4545 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
4547 // In C++17, ResolveConstructorOverload can select a conversion function
4548 // instead of a constructor.
4549 if (auto *CD
= dyn_cast
<CXXConversionDecl
>(Best
->Function
)) {
4550 // Add the user-defined conversion step that calls the conversion function.
4551 QualType ConvType
= CD
->getConversionType();
4552 assert(S
.Context
.hasSameUnqualifiedType(ConvType
, DestType
) &&
4553 "should not have selected this conversion function");
4554 Sequence
.AddUserConversionStep(CD
, Best
->FoundDecl
, ConvType
,
4555 HadMultipleCandidates
);
4556 if (!S
.Context
.hasSameType(ConvType
, DestType
))
4557 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
4559 Sequence
.RewrapReferenceInitList(Entity
.getType(), ILE
);
4563 CXXConstructorDecl
*CtorDecl
= cast
<CXXConstructorDecl
>(Best
->Function
);
4564 if (Result
!= OR_Deleted
) {
4565 // C++11 [dcl.init]p6:
4566 // If a program calls for the default initialization of an object
4567 // of a const-qualified type T, T shall be a class type with a
4568 // user-provided default constructor.
4569 // C++ core issue 253 proposal:
4570 // If the implicit default constructor initializes all subobjects, no
4571 // initializer should be required.
4572 // The 253 proposal is for example needed to process libstdc++ headers
4574 if (Kind
.getKind() == InitializationKind::IK_Default
&&
4575 Entity
.getType().isConstQualified()) {
4576 if (!CtorDecl
->getParent()->allowConstDefaultInit()) {
4577 if (!maybeRecoverWithZeroInitialization(S
, Sequence
, Entity
))
4578 Sequence
.SetFailed(InitializationSequence::FK_DefaultInitOfConst
);
4583 // C++11 [over.match.list]p1:
4584 // In copy-list-initialization, if an explicit constructor is chosen, the
4585 // initializer is ill-formed.
4586 if (IsListInit
&& !Kind
.AllowExplicit() && CtorDecl
->isExplicit()) {
4587 Sequence
.SetFailed(InitializationSequence::FK_ExplicitConstructor
);
4592 // [class.copy.elision]p3:
4593 // In some copy-initialization contexts, a two-stage overload resolution
4595 // If the first overload resolution selects a deleted function, we also
4596 // need the initialization sequence to decide whether to perform the second
4597 // overload resolution.
4598 // For deleted functions in other contexts, there is no need to get the
4599 // initialization sequence.
4600 if (Result
== OR_Deleted
&& Kind
.getKind() != InitializationKind::IK_Copy
)
4603 // Add the constructor initialization step. Any cv-qualification conversion is
4604 // subsumed by the initialization.
4605 Sequence
.AddConstructorInitializationStep(
4606 Best
->FoundDecl
, CtorDecl
, DestArrayType
, HadMultipleCandidates
,
4607 IsListInit
| IsInitListCopy
, AsInitializerList
);
4611 ResolveOverloadedFunctionForReferenceBinding(Sema
&S
,
4613 QualType
&SourceType
,
4614 QualType
&UnqualifiedSourceType
,
4615 QualType UnqualifiedTargetType
,
4616 InitializationSequence
&Sequence
) {
4617 if (S
.Context
.getCanonicalType(UnqualifiedSourceType
) ==
4618 S
.Context
.OverloadTy
) {
4619 DeclAccessPair Found
;
4620 bool HadMultipleCandidates
= false;
4621 if (FunctionDecl
*Fn
4622 = S
.ResolveAddressOfOverloadedFunction(Initializer
,
4623 UnqualifiedTargetType
,
4625 &HadMultipleCandidates
)) {
4626 Sequence
.AddAddressOverloadResolutionStep(Fn
, Found
,
4627 HadMultipleCandidates
);
4628 SourceType
= Fn
->getType();
4629 UnqualifiedSourceType
= SourceType
.getUnqualifiedType();
4630 } else if (!UnqualifiedTargetType
->isRecordType()) {
4631 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
4638 static void TryReferenceInitializationCore(Sema
&S
,
4639 const InitializedEntity
&Entity
,
4640 const InitializationKind
&Kind
,
4642 QualType cv1T1
, QualType T1
,
4644 QualType cv2T2
, QualType T2
,
4646 InitializationSequence
&Sequence
,
4647 bool TopLevelOfInitList
);
4649 static void TryValueInitialization(Sema
&S
,
4650 const InitializedEntity
&Entity
,
4651 const InitializationKind
&Kind
,
4652 InitializationSequence
&Sequence
,
4653 InitListExpr
*InitList
= nullptr);
4655 /// Attempt list initialization of a reference.
4656 static void TryReferenceListInitialization(Sema
&S
,
4657 const InitializedEntity
&Entity
,
4658 const InitializationKind
&Kind
,
4659 InitListExpr
*InitList
,
4660 InitializationSequence
&Sequence
,
4661 bool TreatUnavailableAsInvalid
) {
4662 // First, catch C++03 where this isn't possible.
4663 if (!S
.getLangOpts().CPlusPlus11
) {
4664 Sequence
.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList
);
4667 // Can't reference initialize a compound literal.
4668 if (Entity
.getKind() == InitializedEntity::EK_CompoundLiteralInit
) {
4669 Sequence
.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList
);
4673 QualType DestType
= Entity
.getType();
4674 QualType cv1T1
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
4676 QualType T1
= S
.Context
.getUnqualifiedArrayType(cv1T1
, T1Quals
);
4678 // Reference initialization via an initializer list works thus:
4679 // If the initializer list consists of a single element that is
4680 // reference-related to the referenced type, bind directly to that element
4681 // (possibly creating temporaries).
4682 // Otherwise, initialize a temporary with the initializer list and
4684 if (InitList
->getNumInits() == 1) {
4685 Expr
*Initializer
= InitList
->getInit(0);
4686 QualType cv2T2
= S
.getCompletedType(Initializer
);
4688 QualType T2
= S
.Context
.getUnqualifiedArrayType(cv2T2
, T2Quals
);
4690 // If this fails, creating a temporary wouldn't work either.
4691 if (ResolveOverloadedFunctionForReferenceBinding(S
, Initializer
, cv2T2
, T2
,
4695 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
4696 Sema::ReferenceCompareResult RefRelationship
4697 = S
.CompareReferenceRelationship(DeclLoc
, cv1T1
, cv2T2
);
4698 if (RefRelationship
>= Sema::Ref_Related
) {
4699 // Try to bind the reference here.
4700 TryReferenceInitializationCore(S
, Entity
, Kind
, Initializer
, cv1T1
, T1
,
4701 T1Quals
, cv2T2
, T2
, T2Quals
, Sequence
,
4702 /*TopLevelOfInitList=*/true);
4704 Sequence
.RewrapReferenceInitList(cv1T1
, InitList
);
4708 // Update the initializer if we've resolved an overloaded function.
4709 if (Sequence
.step_begin() != Sequence
.step_end())
4710 Sequence
.RewrapReferenceInitList(cv1T1
, InitList
);
4712 // Perform address space compatibility check.
4713 QualType cv1T1IgnoreAS
= cv1T1
;
4714 if (T1Quals
.hasAddressSpace()) {
4716 (void)S
.Context
.getUnqualifiedArrayType(InitList
->getType(), T2Quals
);
4717 if (!T1Quals
.isAddressSpaceSupersetOf(T2Quals
, S
.getASTContext())) {
4719 InitializationSequence::FK_ReferenceInitDropsQualifiers
);
4722 // Ignore address space of reference type at this point and perform address
4723 // space conversion after the reference binding step.
4725 S
.Context
.getQualifiedType(T1
, T1Quals
.withoutAddressSpace());
4727 // Not reference-related. Create a temporary and bind to that.
4728 InitializedEntity TempEntity
=
4729 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS
);
4731 TryListInitialization(S
, TempEntity
, Kind
, InitList
, Sequence
,
4732 TreatUnavailableAsInvalid
);
4734 if (DestType
->isRValueReferenceType() ||
4735 (T1Quals
.hasConst() && !T1Quals
.hasVolatile())) {
4736 if (S
.getLangOpts().CPlusPlus20
&&
4737 isa
<IncompleteArrayType
>(T1
->getUnqualifiedDesugaredType()) &&
4738 DestType
->isRValueReferenceType()) {
4739 // C++20 [dcl.init.list]p3.10:
4740 // List-initialization of an object or reference of type T is defined as
4742 // ..., unless T is “reference to array of unknown bound of U”, in which
4743 // case the type of the prvalue is the type of x in the declaration U
4744 // x[] H, where H is the initializer list.
4745 Sequence
.AddQualificationConversionStep(cv1T1
, clang::VK_PRValue
);
4747 Sequence
.AddReferenceBindingStep(cv1T1IgnoreAS
,
4748 /*BindingTemporary=*/true);
4749 if (T1Quals
.hasAddressSpace())
4750 Sequence
.AddQualificationConversionStep(
4751 cv1T1
, DestType
->isRValueReferenceType() ? VK_XValue
: VK_LValue
);
4754 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary
);
4758 /// Attempt list initialization (C++0x [dcl.init.list])
4759 static void TryListInitialization(Sema
&S
,
4760 const InitializedEntity
&Entity
,
4761 const InitializationKind
&Kind
,
4762 InitListExpr
*InitList
,
4763 InitializationSequence
&Sequence
,
4764 bool TreatUnavailableAsInvalid
) {
4765 QualType DestType
= Entity
.getType();
4767 // C++ doesn't allow scalar initialization with more than one argument.
4768 // But C99 complex numbers are scalars and it makes sense there.
4769 if (S
.getLangOpts().CPlusPlus
&& DestType
->isScalarType() &&
4770 !DestType
->isAnyComplexType() && InitList
->getNumInits() > 1) {
4771 Sequence
.SetFailed(InitializationSequence::FK_TooManyInitsForScalar
);
4774 if (DestType
->isReferenceType()) {
4775 TryReferenceListInitialization(S
, Entity
, Kind
, InitList
, Sequence
,
4776 TreatUnavailableAsInvalid
);
4780 if (DestType
->isRecordType() &&
4781 !S
.isCompleteType(InitList
->getBeginLoc(), DestType
)) {
4782 Sequence
.setIncompleteTypeFailure(DestType
);
4786 // C++20 [dcl.init.list]p3:
4787 // - If the braced-init-list contains a designated-initializer-list, T shall
4788 // be an aggregate class. [...] Aggregate initialization is performed.
4790 // We allow arrays here too in order to support array designators.
4792 // FIXME: This check should precede the handling of reference initialization.
4793 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4794 // as a tentative DR resolution.
4795 bool IsDesignatedInit
= InitList
->hasDesignatedInit();
4796 if (!DestType
->isAggregateType() && IsDesignatedInit
) {
4798 InitializationSequence::FK_DesignatedInitForNonAggregate
);
4802 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4803 // - If T is an aggregate class and the initializer list has a single element
4804 // of type cv U, where U is T or a class derived from T, the object is
4805 // initialized from that element (by copy-initialization for
4806 // copy-list-initialization, or by direct-initialization for
4807 // direct-list-initialization).
4808 // - Otherwise, if T is a character array and the initializer list has a
4809 // single element that is an appropriately-typed string literal
4810 // (8.5.2 [dcl.init.string]), initialization is performed as described
4812 // - Otherwise, if T is an aggregate, [...] (continue below).
4813 if (S
.getLangOpts().CPlusPlus11
&& InitList
->getNumInits() == 1 &&
4814 !IsDesignatedInit
) {
4815 if (DestType
->isRecordType() && DestType
->isAggregateType()) {
4816 QualType InitType
= InitList
->getInit(0)->getType();
4817 if (S
.Context
.hasSameUnqualifiedType(InitType
, DestType
) ||
4818 S
.IsDerivedFrom(InitList
->getBeginLoc(), InitType
, DestType
)) {
4819 Expr
*InitListAsExpr
= InitList
;
4820 TryConstructorInitialization(S
, Entity
, Kind
, InitListAsExpr
, DestType
,
4822 /*InitListSyntax*/false,
4823 /*IsInitListCopy*/true);
4827 if (const ArrayType
*DestAT
= S
.Context
.getAsArrayType(DestType
)) {
4828 Expr
*SubInit
[1] = {InitList
->getInit(0)};
4830 // C++17 [dcl.struct.bind]p1:
4831 // ... If the assignment-expression in the initializer has array type A
4832 // and no ref-qualifier is present, e has type cv A and each element is
4833 // copy-initialized or direct-initialized from the corresponding element
4834 // of the assignment-expression as specified by the form of the
4837 // This is a special case not following list-initialization.
4838 if (isa
<ConstantArrayType
>(DestAT
) &&
4839 Entity
.getKind() == InitializedEntity::EK_Variable
&&
4840 isa
<DecompositionDecl
>(Entity
.getDecl())) {
4842 S
.Context
.hasSameUnqualifiedType(SubInit
[0]->getType(), DestType
) &&
4843 "Deduced to other type?");
4845 InitializationKind::CreateCopy(Kind
.getLocation(),
4846 InitList
->getLBraceLoc()),
4847 Entity
, SubInit
[0], DestType
, Sequence
,
4848 TreatUnavailableAsInvalid
);
4850 Sequence
.AddUnwrapInitListInitStep(InitList
);
4854 if (!isa
<VariableArrayType
>(DestAT
) &&
4855 IsStringInit(SubInit
[0], DestAT
, S
.Context
) == SIF_None
) {
4856 InitializationKind SubKind
=
4857 Kind
.getKind() == InitializationKind::IK_DirectList
4858 ? InitializationKind::CreateDirect(Kind
.getLocation(),
4859 InitList
->getLBraceLoc(),
4860 InitList
->getRBraceLoc())
4862 Sequence
.InitializeFrom(S
, Entity
, SubKind
, SubInit
,
4863 /*TopLevelOfInitList*/ true,
4864 TreatUnavailableAsInvalid
);
4866 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4867 // the element is not an appropriately-typed string literal, in which
4868 // case we should proceed as in C++11 (below).
4870 Sequence
.RewrapReferenceInitList(Entity
.getType(), InitList
);
4877 // C++11 [dcl.init.list]p3:
4878 // - If T is an aggregate, aggregate initialization is performed.
4879 if ((DestType
->isRecordType() && !DestType
->isAggregateType()) ||
4880 (S
.getLangOpts().CPlusPlus11
&&
4881 S
.isStdInitializerList(DestType
, nullptr) && !IsDesignatedInit
)) {
4882 if (S
.getLangOpts().CPlusPlus11
) {
4883 // - Otherwise, if the initializer list has no elements and T is a
4884 // class type with a default constructor, the object is
4885 // value-initialized.
4886 if (InitList
->getNumInits() == 0) {
4887 CXXRecordDecl
*RD
= DestType
->getAsCXXRecordDecl();
4888 if (S
.LookupDefaultConstructor(RD
)) {
4889 TryValueInitialization(S
, Entity
, Kind
, Sequence
, InitList
);
4894 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4895 // an initializer_list object constructed [...]
4896 if (TryInitializerListConstruction(S
, InitList
, DestType
, Sequence
,
4897 TreatUnavailableAsInvalid
))
4900 // - Otherwise, if T is a class type, constructors are considered.
4901 Expr
*InitListAsExpr
= InitList
;
4902 TryConstructorInitialization(S
, Entity
, Kind
, InitListAsExpr
, DestType
,
4903 DestType
, Sequence
, /*InitListSyntax*/true);
4905 Sequence
.SetFailed(InitializationSequence::FK_InitListBadDestinationType
);
4909 if (S
.getLangOpts().CPlusPlus
&& !DestType
->isAggregateType() &&
4910 InitList
->getNumInits() == 1) {
4911 Expr
*E
= InitList
->getInit(0);
4913 // - Otherwise, if T is an enumeration with a fixed underlying type,
4914 // the initializer-list has a single element v, and the initialization
4915 // is direct-list-initialization, the object is initialized with the
4916 // value T(v); if a narrowing conversion is required to convert v to
4917 // the underlying type of T, the program is ill-formed.
4918 auto *ET
= DestType
->getAs
<EnumType
>();
4919 if (S
.getLangOpts().CPlusPlus17
&&
4920 Kind
.getKind() == InitializationKind::IK_DirectList
&&
4921 ET
&& ET
->getDecl()->isFixed() &&
4922 !S
.Context
.hasSameUnqualifiedType(E
->getType(), DestType
) &&
4923 (E
->getType()->isIntegralOrUnscopedEnumerationType() ||
4924 E
->getType()->isFloatingType())) {
4925 // There are two ways that T(v) can work when T is an enumeration type.
4926 // If there is either an implicit conversion sequence from v to T or
4927 // a conversion function that can convert from v to T, then we use that.
4928 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4929 // type, it is converted to the enumeration type via its underlying type.
4930 // There is no overlap possible between these two cases (except when the
4931 // source value is already of the destination type), and the first
4932 // case is handled by the general case for single-element lists below.
4933 ImplicitConversionSequence ICS
;
4935 ICS
.Standard
.setAsIdentityConversion();
4936 if (!E
->isPRValue())
4937 ICS
.Standard
.First
= ICK_Lvalue_To_Rvalue
;
4938 // If E is of a floating-point type, then the conversion is ill-formed
4939 // due to narrowing, but go through the motions in order to produce the
4940 // right diagnostic.
4941 ICS
.Standard
.Second
= E
->getType()->isFloatingType()
4942 ? ICK_Floating_Integral
4943 : ICK_Integral_Conversion
;
4944 ICS
.Standard
.setFromType(E
->getType());
4945 ICS
.Standard
.setToType(0, E
->getType());
4946 ICS
.Standard
.setToType(1, DestType
);
4947 ICS
.Standard
.setToType(2, DestType
);
4948 Sequence
.AddConversionSequenceStep(ICS
, ICS
.Standard
.getToType(2),
4949 /*TopLevelOfInitList*/true);
4950 Sequence
.RewrapReferenceInitList(Entity
.getType(), InitList
);
4954 // - Otherwise, if the initializer list has a single element of type E
4955 // [...references are handled above...], the object or reference is
4956 // initialized from that element (by copy-initialization for
4957 // copy-list-initialization, or by direct-initialization for
4958 // direct-list-initialization); if a narrowing conversion is required
4959 // to convert the element to T, the program is ill-formed.
4961 // Per core-24034, this is direct-initialization if we were performing
4962 // direct-list-initialization and copy-initialization otherwise.
4963 // We can't use InitListChecker for this, because it always performs
4964 // copy-initialization. This only matters if we might use an 'explicit'
4965 // conversion operator, or for the special case conversion of nullptr_t to
4966 // bool, so we only need to handle those cases.
4968 // FIXME: Why not do this in all cases?
4969 Expr
*Init
= InitList
->getInit(0);
4970 if (Init
->getType()->isRecordType() ||
4971 (Init
->getType()->isNullPtrType() && DestType
->isBooleanType())) {
4972 InitializationKind SubKind
=
4973 Kind
.getKind() == InitializationKind::IK_DirectList
4974 ? InitializationKind::CreateDirect(Kind
.getLocation(),
4975 InitList
->getLBraceLoc(),
4976 InitList
->getRBraceLoc())
4978 Expr
*SubInit
[1] = { Init
};
4979 Sequence
.InitializeFrom(S
, Entity
, SubKind
, SubInit
,
4980 /*TopLevelOfInitList*/true,
4981 TreatUnavailableAsInvalid
);
4983 Sequence
.RewrapReferenceInitList(Entity
.getType(), InitList
);
4988 InitListChecker
CheckInitList(S
, Entity
, InitList
,
4989 DestType
, /*VerifyOnly=*/true, TreatUnavailableAsInvalid
);
4990 if (CheckInitList
.HadError()) {
4991 Sequence
.SetFailed(InitializationSequence::FK_ListInitializationFailed
);
4995 // Add the list initialization step with the built init list.
4996 Sequence
.AddListInitializationStep(DestType
);
4999 /// Try a reference initialization that involves calling a conversion
5001 static OverloadingResult
TryRefInitWithConversionFunction(
5002 Sema
&S
, const InitializedEntity
&Entity
, const InitializationKind
&Kind
,
5003 Expr
*Initializer
, bool AllowRValues
, bool IsLValueRef
,
5004 InitializationSequence
&Sequence
) {
5005 QualType DestType
= Entity
.getType();
5006 QualType cv1T1
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
5007 QualType T1
= cv1T1
.getUnqualifiedType();
5008 QualType cv2T2
= Initializer
->getType();
5009 QualType T2
= cv2T2
.getUnqualifiedType();
5011 assert(!S
.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1
, T2
) &&
5012 "Must have incompatible references when binding via conversion");
5014 // Build the candidate set directly in the initialization sequence
5015 // structure, so that it will persist if we fail.
5016 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
5017 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
5019 // Determine whether we are allowed to call explicit conversion operators.
5020 // Note that none of [over.match.copy], [over.match.conv], nor
5021 // [over.match.ref] permit an explicit constructor to be chosen when
5022 // initializing a reference, not even for direct-initialization.
5023 bool AllowExplicitCtors
= false;
5024 bool AllowExplicitConvs
= Kind
.allowExplicitConversionFunctionsInRefBinding();
5026 const RecordType
*T1RecordType
= nullptr;
5027 if (AllowRValues
&& (T1RecordType
= T1
->getAs
<RecordType
>()) &&
5028 S
.isCompleteType(Kind
.getLocation(), T1
)) {
5029 // The type we're converting to is a class type. Enumerate its constructors
5030 // to see if there is a suitable conversion.
5031 CXXRecordDecl
*T1RecordDecl
= cast
<CXXRecordDecl
>(T1RecordType
->getDecl());
5033 for (NamedDecl
*D
: S
.LookupConstructors(T1RecordDecl
)) {
5034 auto Info
= getConstructorInfo(D
);
5035 if (!Info
.Constructor
)
5038 if (!Info
.Constructor
->isInvalidDecl() &&
5039 Info
.Constructor
->isConvertingConstructor(/*AllowExplicit*/true)) {
5040 if (Info
.ConstructorTmpl
)
5041 S
.AddTemplateOverloadCandidate(
5042 Info
.ConstructorTmpl
, Info
.FoundDecl
,
5043 /*ExplicitArgs*/ nullptr, Initializer
, CandidateSet
,
5044 /*SuppressUserConversions=*/true,
5045 /*PartialOverloading*/ false, AllowExplicitCtors
);
5047 S
.AddOverloadCandidate(
5048 Info
.Constructor
, Info
.FoundDecl
, Initializer
, CandidateSet
,
5049 /*SuppressUserConversions=*/true,
5050 /*PartialOverloading*/ false, AllowExplicitCtors
);
5054 if (T1RecordType
&& T1RecordType
->getDecl()->isInvalidDecl())
5055 return OR_No_Viable_Function
;
5057 const RecordType
*T2RecordType
= nullptr;
5058 if ((T2RecordType
= T2
->getAs
<RecordType
>()) &&
5059 S
.isCompleteType(Kind
.getLocation(), T2
)) {
5060 // The type we're converting from is a class type, enumerate its conversion
5062 CXXRecordDecl
*T2RecordDecl
= cast
<CXXRecordDecl
>(T2RecordType
->getDecl());
5064 const auto &Conversions
= T2RecordDecl
->getVisibleConversionFunctions();
5065 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
5067 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
5068 if (isa
<UsingShadowDecl
>(D
))
5069 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
5071 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
5072 CXXConversionDecl
*Conv
;
5074 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
5076 Conv
= cast
<CXXConversionDecl
>(D
);
5078 // If the conversion function doesn't return a reference type,
5079 // it can't be considered for this conversion unless we're allowed to
5080 // consider rvalues.
5081 // FIXME: Do we need to make sure that we only consider conversion
5082 // candidates with reference-compatible results? That might be needed to
5084 if ((AllowRValues
||
5085 Conv
->getConversionType()->isLValueReferenceType())) {
5087 S
.AddTemplateConversionCandidate(
5088 ConvTemplate
, I
.getPair(), ActingDC
, Initializer
, DestType
,
5090 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs
);
5092 S
.AddConversionCandidate(
5093 Conv
, I
.getPair(), ActingDC
, Initializer
, DestType
, CandidateSet
,
5094 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs
);
5098 if (T2RecordType
&& T2RecordType
->getDecl()->isInvalidDecl())
5099 return OR_No_Viable_Function
;
5101 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
5103 // Perform overload resolution. If it fails, return the failed result.
5104 OverloadCandidateSet::iterator Best
;
5105 if (OverloadingResult Result
5106 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
))
5109 FunctionDecl
*Function
= Best
->Function
;
5110 // This is the overload that will be used for this initialization step if we
5111 // use this initialization. Mark it as referenced.
5112 Function
->setReferenced();
5114 // Compute the returned type and value kind of the conversion.
5116 if (isa
<CXXConversionDecl
>(Function
))
5117 cv3T3
= Function
->getReturnType();
5121 ExprValueKind VK
= VK_PRValue
;
5122 if (cv3T3
->isLValueReferenceType())
5124 else if (const auto *RRef
= cv3T3
->getAs
<RValueReferenceType
>())
5125 VK
= RRef
->getPointeeType()->isFunctionType() ? VK_LValue
: VK_XValue
;
5126 cv3T3
= cv3T3
.getNonLValueExprType(S
.Context
);
5128 // Add the user-defined conversion step.
5129 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
5130 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, cv3T3
,
5131 HadMultipleCandidates
);
5133 // Determine whether we'll need to perform derived-to-base adjustments or
5134 // other conversions.
5135 Sema::ReferenceConversions RefConv
;
5136 Sema::ReferenceCompareResult NewRefRelationship
=
5137 S
.CompareReferenceRelationship(DeclLoc
, T1
, cv3T3
, &RefConv
);
5139 // Add the final conversion sequence, if necessary.
5140 if (NewRefRelationship
== Sema::Ref_Incompatible
) {
5141 assert(!isa
<CXXConstructorDecl
>(Function
) &&
5142 "should not have conversion after constructor");
5144 ImplicitConversionSequence ICS
;
5146 ICS
.Standard
= Best
->FinalConversion
;
5147 Sequence
.AddConversionSequenceStep(ICS
, ICS
.Standard
.getToType(2));
5149 // Every implicit conversion results in a prvalue, except for a glvalue
5150 // derived-to-base conversion, which we handle below.
5151 cv3T3
= ICS
.Standard
.getToType(2);
5155 // If the converted initializer is a prvalue, its type T4 is adjusted to
5156 // type "cv1 T4" and the temporary materialization conversion is applied.
5158 // We adjust the cv-qualifications to match the reference regardless of
5159 // whether we have a prvalue so that the AST records the change. In this
5160 // case, T4 is "cv3 T3".
5161 QualType cv1T4
= S
.Context
.getQualifiedType(cv3T3
, cv1T1
.getQualifiers());
5162 if (cv1T4
.getQualifiers() != cv3T3
.getQualifiers())
5163 Sequence
.AddQualificationConversionStep(cv1T4
, VK
);
5164 Sequence
.AddReferenceBindingStep(cv1T4
, VK
== VK_PRValue
);
5165 VK
= IsLValueRef
? VK_LValue
: VK_XValue
;
5167 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5168 Sequence
.AddDerivedToBaseCastStep(cv1T1
, VK
);
5169 else if (RefConv
& Sema::ReferenceConversions::ObjC
)
5170 Sequence
.AddObjCObjectConversionStep(cv1T1
);
5171 else if (RefConv
& Sema::ReferenceConversions::Function
)
5172 Sequence
.AddFunctionReferenceConversionStep(cv1T1
);
5173 else if (RefConv
& Sema::ReferenceConversions::Qualification
) {
5174 if (!S
.Context
.hasSameType(cv1T4
, cv1T1
))
5175 Sequence
.AddQualificationConversionStep(cv1T1
, VK
);
5181 static void CheckCXX98CompatAccessibleCopy(Sema
&S
,
5182 const InitializedEntity
&Entity
,
5185 /// Attempt reference initialization (C++0x [dcl.init.ref])
5186 static void TryReferenceInitialization(Sema
&S
, const InitializedEntity
&Entity
,
5187 const InitializationKind
&Kind
,
5189 InitializationSequence
&Sequence
,
5190 bool TopLevelOfInitList
) {
5191 QualType DestType
= Entity
.getType();
5192 QualType cv1T1
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
5194 QualType T1
= S
.Context
.getUnqualifiedArrayType(cv1T1
, T1Quals
);
5195 QualType cv2T2
= S
.getCompletedType(Initializer
);
5197 QualType T2
= S
.Context
.getUnqualifiedArrayType(cv2T2
, T2Quals
);
5199 // If the initializer is the address of an overloaded function, try
5200 // to resolve the overloaded function. If all goes well, T2 is the
5201 // type of the resulting function.
5202 if (ResolveOverloadedFunctionForReferenceBinding(S
, Initializer
, cv2T2
, T2
,
5206 // Delegate everything else to a subfunction.
5207 TryReferenceInitializationCore(S
, Entity
, Kind
, Initializer
, cv1T1
, T1
,
5208 T1Quals
, cv2T2
, T2
, T2Quals
, Sequence
,
5209 TopLevelOfInitList
);
5212 /// Determine whether an expression is a non-referenceable glvalue (one to
5213 /// which a reference can never bind). Attempting to bind a reference to
5214 /// such a glvalue will always create a temporary.
5215 static bool isNonReferenceableGLValue(Expr
*E
) {
5216 return E
->refersToBitField() || E
->refersToVectorElement() ||
5217 E
->refersToMatrixElement();
5220 /// Reference initialization without resolving overloaded functions.
5222 /// We also can get here in C if we call a builtin which is declared as
5223 /// a function with a parameter of reference type (such as __builtin_va_end()).
5224 static void TryReferenceInitializationCore(Sema
&S
,
5225 const InitializedEntity
&Entity
,
5226 const InitializationKind
&Kind
,
5228 QualType cv1T1
, QualType T1
,
5230 QualType cv2T2
, QualType T2
,
5232 InitializationSequence
&Sequence
,
5233 bool TopLevelOfInitList
) {
5234 QualType DestType
= Entity
.getType();
5235 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
5237 // Compute some basic properties of the types and the initializer.
5238 bool isLValueRef
= DestType
->isLValueReferenceType();
5239 bool isRValueRef
= !isLValueRef
;
5240 Expr::Classification InitCategory
= Initializer
->Classify(S
.Context
);
5242 Sema::ReferenceConversions RefConv
;
5243 Sema::ReferenceCompareResult RefRelationship
=
5244 S
.CompareReferenceRelationship(DeclLoc
, cv1T1
, cv2T2
, &RefConv
);
5246 // C++0x [dcl.init.ref]p5:
5247 // A reference to type "cv1 T1" is initialized by an expression of type
5248 // "cv2 T2" as follows:
5250 // - If the reference is an lvalue reference and the initializer
5252 // Note the analogous bullet points for rvalue refs to functions. Because
5253 // there are no function rvalues in C++, rvalue refs to functions are treated
5254 // like lvalue refs.
5255 OverloadingResult ConvOvlResult
= OR_Success
;
5256 bool T1Function
= T1
->isFunctionType();
5257 if (isLValueRef
|| T1Function
) {
5258 if (InitCategory
.isLValue() && !isNonReferenceableGLValue(Initializer
) &&
5259 (RefRelationship
== Sema::Ref_Compatible
||
5260 (Kind
.isCStyleOrFunctionalCast() &&
5261 RefRelationship
== Sema::Ref_Related
))) {
5262 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5263 // reference-compatible with "cv2 T2," or
5264 if (RefConv
& (Sema::ReferenceConversions::DerivedToBase
|
5265 Sema::ReferenceConversions::ObjC
)) {
5266 // If we're converting the pointee, add any qualifiers first;
5267 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5268 if (RefConv
& (Sema::ReferenceConversions::Qualification
))
5269 Sequence
.AddQualificationConversionStep(
5270 S
.Context
.getQualifiedType(T2
, T1Quals
),
5271 Initializer
->getValueKind());
5272 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5273 Sequence
.AddDerivedToBaseCastStep(cv1T1
, VK_LValue
);
5275 Sequence
.AddObjCObjectConversionStep(cv1T1
);
5276 } else if (RefConv
& Sema::ReferenceConversions::Qualification
) {
5277 // Perform a (possibly multi-level) qualification conversion.
5278 Sequence
.AddQualificationConversionStep(cv1T1
,
5279 Initializer
->getValueKind());
5280 } else if (RefConv
& Sema::ReferenceConversions::Function
) {
5281 Sequence
.AddFunctionReferenceConversionStep(cv1T1
);
5284 // We only create a temporary here when binding a reference to a
5285 // bit-field or vector element. Those cases are't supposed to be
5286 // handled by this bullet, but the outcome is the same either way.
5287 Sequence
.AddReferenceBindingStep(cv1T1
, false);
5291 // - has a class type (i.e., T2 is a class type), where T1 is not
5292 // reference-related to T2, and can be implicitly converted to an
5293 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5294 // with "cv3 T3" (this conversion is selected by enumerating the
5295 // applicable conversion functions (13.3.1.6) and choosing the best
5296 // one through overload resolution (13.3)),
5297 // If we have an rvalue ref to function type here, the rhs must be
5298 // an rvalue. DR1287 removed the "implicitly" here.
5299 if (RefRelationship
== Sema::Ref_Incompatible
&& T2
->isRecordType() &&
5300 (isLValueRef
|| InitCategory
.isRValue())) {
5301 if (S
.getLangOpts().CPlusPlus
) {
5302 // Try conversion functions only for C++.
5303 ConvOvlResult
= TryRefInitWithConversionFunction(
5304 S
, Entity
, Kind
, Initializer
, /*AllowRValues*/ isRValueRef
,
5305 /*IsLValueRef*/ isLValueRef
, Sequence
);
5306 if (ConvOvlResult
== OR_Success
)
5308 if (ConvOvlResult
!= OR_No_Viable_Function
)
5309 Sequence
.SetOverloadFailure(
5310 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5313 ConvOvlResult
= OR_No_Viable_Function
;
5318 // - Otherwise, the reference shall be an lvalue reference to a
5319 // non-volatile const type (i.e., cv1 shall be const), or the reference
5320 // shall be an rvalue reference.
5321 // For address spaces, we interpret this to mean that an addr space
5322 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5324 !(T1Quals
.hasConst() && !T1Quals
.hasVolatile() &&
5325 T1Quals
.isAddressSpaceSupersetOf(T2Quals
, S
.getASTContext()))) {
5326 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
)
5327 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
5328 else if (ConvOvlResult
&& !Sequence
.getFailedCandidateSet().empty())
5329 Sequence
.SetOverloadFailure(
5330 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5332 else if (!InitCategory
.isLValue())
5334 T1Quals
.isAddressSpaceSupersetOf(T2Quals
, S
.getASTContext())
5335 ? InitializationSequence::
5336 FK_NonConstLValueReferenceBindingToTemporary
5337 : InitializationSequence::FK_ReferenceInitDropsQualifiers
);
5339 InitializationSequence::FailureKind FK
;
5340 switch (RefRelationship
) {
5341 case Sema::Ref_Compatible
:
5342 if (Initializer
->refersToBitField())
5343 FK
= InitializationSequence::
5344 FK_NonConstLValueReferenceBindingToBitfield
;
5345 else if (Initializer
->refersToVectorElement())
5346 FK
= InitializationSequence::
5347 FK_NonConstLValueReferenceBindingToVectorElement
;
5348 else if (Initializer
->refersToMatrixElement())
5349 FK
= InitializationSequence::
5350 FK_NonConstLValueReferenceBindingToMatrixElement
;
5352 llvm_unreachable("unexpected kind of compatible initializer");
5354 case Sema::Ref_Related
:
5355 FK
= InitializationSequence::FK_ReferenceInitDropsQualifiers
;
5357 case Sema::Ref_Incompatible
:
5358 FK
= InitializationSequence::
5359 FK_NonConstLValueReferenceBindingToUnrelated
;
5362 Sequence
.SetFailed(FK
);
5367 // - If the initializer expression
5369 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5370 // [1z] rvalue (but not a bit-field) or
5371 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5373 // Note: functions are handled above and below rather than here...
5375 (RefRelationship
== Sema::Ref_Compatible
||
5376 (Kind
.isCStyleOrFunctionalCast() &&
5377 RefRelationship
== Sema::Ref_Related
)) &&
5378 ((InitCategory
.isXValue() && !isNonReferenceableGLValue(Initializer
)) ||
5379 (InitCategory
.isPRValue() &&
5380 (S
.getLangOpts().CPlusPlus17
|| T2
->isRecordType() ||
5381 T2
->isArrayType())))) {
5382 ExprValueKind ValueKind
= InitCategory
.isXValue() ? VK_XValue
: VK_PRValue
;
5383 if (InitCategory
.isPRValue() && T2
->isRecordType()) {
5384 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5385 // compiler the freedom to perform a copy here or bind to the
5386 // object, while C++0x requires that we bind directly to the
5387 // object. Hence, we always bind to the object without making an
5388 // extra copy. However, in C++03 requires that we check for the
5389 // presence of a suitable copy constructor:
5391 // The constructor that would be used to make the copy shall
5392 // be callable whether or not the copy is actually done.
5393 if (!S
.getLangOpts().CPlusPlus11
&& !S
.getLangOpts().MicrosoftExt
)
5394 Sequence
.AddExtraneousCopyToTemporary(cv2T2
);
5395 else if (S
.getLangOpts().CPlusPlus11
)
5396 CheckCXX98CompatAccessibleCopy(S
, Entity
, Initializer
);
5399 // C++1z [dcl.init.ref]/5.2.1.2:
5400 // If the converted initializer is a prvalue, its type T4 is adjusted
5401 // to type "cv1 T4" and the temporary materialization conversion is
5403 // Postpone address space conversions to after the temporary materialization
5404 // conversion to allow creating temporaries in the alloca address space.
5405 auto T1QualsIgnoreAS
= T1Quals
;
5406 auto T2QualsIgnoreAS
= T2Quals
;
5407 if (T1Quals
.getAddressSpace() != T2Quals
.getAddressSpace()) {
5408 T1QualsIgnoreAS
.removeAddressSpace();
5409 T2QualsIgnoreAS
.removeAddressSpace();
5411 QualType cv1T4
= S
.Context
.getQualifiedType(cv2T2
, T1QualsIgnoreAS
);
5412 if (T1QualsIgnoreAS
!= T2QualsIgnoreAS
)
5413 Sequence
.AddQualificationConversionStep(cv1T4
, ValueKind
);
5414 Sequence
.AddReferenceBindingStep(cv1T4
, ValueKind
== VK_PRValue
);
5415 ValueKind
= isLValueRef
? VK_LValue
: VK_XValue
;
5416 // Add addr space conversion if required.
5417 if (T1Quals
.getAddressSpace() != T2Quals
.getAddressSpace()) {
5418 auto T4Quals
= cv1T4
.getQualifiers();
5419 T4Quals
.addAddressSpace(T1Quals
.getAddressSpace());
5420 QualType cv1T4WithAS
= S
.Context
.getQualifiedType(T2
, T4Quals
);
5421 Sequence
.AddQualificationConversionStep(cv1T4WithAS
, ValueKind
);
5422 cv1T4
= cv1T4WithAS
;
5425 // In any case, the reference is bound to the resulting glvalue (or to
5426 // an appropriate base class subobject).
5427 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5428 Sequence
.AddDerivedToBaseCastStep(cv1T1
, ValueKind
);
5429 else if (RefConv
& Sema::ReferenceConversions::ObjC
)
5430 Sequence
.AddObjCObjectConversionStep(cv1T1
);
5431 else if (RefConv
& Sema::ReferenceConversions::Qualification
) {
5432 if (!S
.Context
.hasSameType(cv1T4
, cv1T1
))
5433 Sequence
.AddQualificationConversionStep(cv1T1
, ValueKind
);
5438 // - has a class type (i.e., T2 is a class type), where T1 is not
5439 // reference-related to T2, and can be implicitly converted to an
5440 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5441 // where "cv1 T1" is reference-compatible with "cv3 T3",
5443 // DR1287 removes the "implicitly" here.
5444 if (T2
->isRecordType()) {
5445 if (RefRelationship
== Sema::Ref_Incompatible
) {
5446 ConvOvlResult
= TryRefInitWithConversionFunction(
5447 S
, Entity
, Kind
, Initializer
, /*AllowRValues*/ true,
5448 /*IsLValueRef*/ isLValueRef
, Sequence
);
5450 Sequence
.SetOverloadFailure(
5451 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5457 if (RefRelationship
== Sema::Ref_Compatible
&&
5458 isRValueRef
&& InitCategory
.isLValue()) {
5460 InitializationSequence::FK_RValueReferenceBindingToLValue
);
5464 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers
);
5468 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5469 // from the initializer expression using the rules for a non-reference
5470 // copy-initialization (8.5). The reference is then bound to the
5473 // Ignore address space of reference type at this point and perform address
5474 // space conversion after the reference binding step.
5475 QualType cv1T1IgnoreAS
=
5476 T1Quals
.hasAddressSpace()
5477 ? S
.Context
.getQualifiedType(T1
, T1Quals
.withoutAddressSpace())
5480 InitializedEntity TempEntity
=
5481 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS
);
5483 // FIXME: Why do we use an implicit conversion here rather than trying
5484 // copy-initialization?
5485 ImplicitConversionSequence ICS
5486 = S
.TryImplicitConversion(Initializer
, TempEntity
.getType(),
5487 /*SuppressUserConversions=*/false,
5488 Sema::AllowedExplicit::None
,
5489 /*FIXME:InOverloadResolution=*/false,
5490 /*CStyle=*/Kind
.isCStyleOrFunctionalCast(),
5491 /*AllowObjCWritebackConversion=*/false);
5494 // FIXME: Use the conversion function set stored in ICS to turn
5495 // this into an overloading ambiguity diagnostic. However, we need
5496 // to keep that set as an OverloadCandidateSet rather than as some
5497 // other kind of set.
5498 if (ConvOvlResult
&& !Sequence
.getFailedCandidateSet().empty())
5499 Sequence
.SetOverloadFailure(
5500 InitializationSequence::FK_ReferenceInitOverloadFailed
,
5502 else if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
)
5503 Sequence
.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
5505 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitFailed
);
5508 Sequence
.AddConversionSequenceStep(ICS
, TempEntity
.getType(),
5509 TopLevelOfInitList
);
5512 // [...] If T1 is reference-related to T2, cv1 must be the
5513 // same cv-qualification as, or greater cv-qualification
5514 // than, cv2; otherwise, the program is ill-formed.
5515 unsigned T1CVRQuals
= T1Quals
.getCVRQualifiers();
5516 unsigned T2CVRQuals
= T2Quals
.getCVRQualifiers();
5517 if (RefRelationship
== Sema::Ref_Related
&&
5518 ((T1CVRQuals
| T2CVRQuals
) != T1CVRQuals
||
5519 !T1Quals
.isAddressSpaceSupersetOf(T2Quals
, S
.getASTContext()))) {
5520 Sequence
.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers
);
5524 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5525 // reference, the initializer expression shall not be an lvalue.
5526 if (RefRelationship
>= Sema::Ref_Related
&& !isLValueRef
&&
5527 InitCategory
.isLValue()) {
5529 InitializationSequence::FK_RValueReferenceBindingToLValue
);
5533 Sequence
.AddReferenceBindingStep(cv1T1IgnoreAS
, /*BindingTemporary=*/true);
5535 if (T1Quals
.hasAddressSpace()) {
5536 if (!Qualifiers::isAddressSpaceSupersetOf(
5537 T1Quals
.getAddressSpace(), LangAS::Default
, S
.getASTContext())) {
5539 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary
);
5542 Sequence
.AddQualificationConversionStep(cv1T1
, isLValueRef
? VK_LValue
5547 /// Attempt character array initialization from a string literal
5548 /// (C++ [dcl.init.string], C99 6.7.8).
5549 static void TryStringLiteralInitialization(Sema
&S
,
5550 const InitializedEntity
&Entity
,
5551 const InitializationKind
&Kind
,
5553 InitializationSequence
&Sequence
) {
5554 Sequence
.AddStringInitStep(Entity
.getType());
5557 /// Attempt value initialization (C++ [dcl.init]p7).
5558 static void TryValueInitialization(Sema
&S
,
5559 const InitializedEntity
&Entity
,
5560 const InitializationKind
&Kind
,
5561 InitializationSequence
&Sequence
,
5562 InitListExpr
*InitList
) {
5563 assert((!InitList
|| InitList
->getNumInits() == 0) &&
5564 "Shouldn't use value-init for non-empty init lists");
5566 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5568 // To value-initialize an object of type T means:
5569 QualType T
= Entity
.getType();
5570 assert(!T
->isVoidType() && "Cannot value-init void");
5572 // -- if T is an array type, then each element is value-initialized;
5573 T
= S
.Context
.getBaseElementType(T
);
5575 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
5576 if (CXXRecordDecl
*ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl())) {
5577 bool NeedZeroInitialization
= true;
5579 // -- if T is a class type (clause 9) with a user-declared constructor
5580 // (12.1), then the default constructor for T is called (and the
5581 // initialization is ill-formed if T has no accessible default
5584 // -- if T is a class type (clause 9) with either no default constructor
5585 // (12.1 [class.ctor]) or a default constructor that is user-provided
5586 // or deleted, then the object is default-initialized;
5588 // Note that the C++11 rule is the same as the C++98 rule if there are no
5589 // defaulted or deleted constructors, so we just use it unconditionally.
5590 CXXConstructorDecl
*CD
= S
.LookupDefaultConstructor(ClassDecl
);
5591 if (!CD
|| !CD
->getCanonicalDecl()->isDefaulted() || CD
->isDeleted())
5592 NeedZeroInitialization
= false;
5594 // -- if T is a (possibly cv-qualified) non-union class type without a
5595 // user-provided or deleted default constructor, then the object is
5596 // zero-initialized and, if T has a non-trivial default constructor,
5597 // default-initialized;
5598 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5599 // constructor' part was removed by DR1507.
5600 if (NeedZeroInitialization
)
5601 Sequence
.AddZeroInitializationStep(Entity
.getType());
5604 // -- if T is a non-union class type without a user-declared constructor,
5605 // then every non-static data member and base class component of T is
5606 // value-initialized;
5607 // [...] A program that calls for [...] value-initialization of an
5608 // entity of reference type is ill-formed.
5610 // C++11 doesn't need this handling, because value-initialization does not
5611 // occur recursively there, and the implicit default constructor is
5612 // defined as deleted in the problematic cases.
5613 if (!S
.getLangOpts().CPlusPlus11
&&
5614 ClassDecl
->hasUninitializedReferenceMember()) {
5615 Sequence
.SetFailed(InitializationSequence::FK_TooManyInitsForReference
);
5619 // If this is list-value-initialization, pass the empty init list on when
5620 // building the constructor call. This affects the semantics of a few
5621 // things (such as whether an explicit default constructor can be called).
5622 Expr
*InitListAsExpr
= InitList
;
5623 MultiExprArg
Args(&InitListAsExpr
, InitList
? 1 : 0);
5624 bool InitListSyntax
= InitList
;
5626 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5627 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5628 return TryConstructorInitialization(
5629 S
, Entity
, Kind
, Args
, T
, Entity
.getType(), Sequence
, InitListSyntax
);
5633 Sequence
.AddZeroInitializationStep(Entity
.getType());
5636 /// Attempt default initialization (C++ [dcl.init]p6).
5637 static void TryDefaultInitialization(Sema
&S
,
5638 const InitializedEntity
&Entity
,
5639 const InitializationKind
&Kind
,
5640 InitializationSequence
&Sequence
) {
5641 assert(Kind
.getKind() == InitializationKind::IK_Default
);
5643 // C++ [dcl.init]p6:
5644 // To default-initialize an object of type T means:
5645 // - if T is an array type, each element is default-initialized;
5646 QualType DestType
= S
.Context
.getBaseElementType(Entity
.getType());
5648 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5649 // constructor for T is called (and the initialization is ill-formed if
5650 // T has no accessible default constructor);
5651 if (DestType
->isRecordType() && S
.getLangOpts().CPlusPlus
) {
5652 TryConstructorInitialization(S
, Entity
, Kind
, {}, DestType
,
5653 Entity
.getType(), Sequence
);
5657 // - otherwise, no initialization is performed.
5659 // If a program calls for the default initialization of an object of
5660 // a const-qualified type T, T shall be a class type with a user-provided
5661 // default constructor.
5662 if (DestType
.isConstQualified() && S
.getLangOpts().CPlusPlus
) {
5663 if (!maybeRecoverWithZeroInitialization(S
, Sequence
, Entity
))
5664 Sequence
.SetFailed(InitializationSequence::FK_DefaultInitOfConst
);
5668 // If the destination type has a lifetime property, zero-initialize it.
5669 if (DestType
.getQualifiers().hasObjCLifetime()) {
5670 Sequence
.AddZeroInitializationStep(Entity
.getType());
5675 static void TryOrBuildParenListInitialization(
5676 Sema
&S
, const InitializedEntity
&Entity
, const InitializationKind
&Kind
,
5677 ArrayRef
<Expr
*> Args
, InitializationSequence
&Sequence
, bool VerifyOnly
,
5678 ExprResult
*Result
= nullptr) {
5679 unsigned EntityIndexToProcess
= 0;
5680 SmallVector
<Expr
*, 4> InitExprs
;
5681 QualType ResultType
;
5682 Expr
*ArrayFiller
= nullptr;
5683 FieldDecl
*InitializedFieldInUnion
= nullptr;
5685 auto HandleInitializedEntity
= [&](const InitializedEntity
&SubEntity
,
5686 const InitializationKind
&SubKind
,
5687 Expr
*Arg
, Expr
**InitExpr
= nullptr) {
5688 InitializationSequence IS
= InitializationSequence(
5689 S
, SubEntity
, SubKind
,
5690 Arg
? MultiExprArg(Arg
) : MutableArrayRef
<Expr
*>());
5694 IS
.Diagnose(S
, SubEntity
, SubKind
,
5695 Arg
? ArrayRef(Arg
) : ArrayRef
<Expr
*>());
5698 InitializationSequence::FK_ParenthesizedListInitFailed
);
5705 ER
= IS
.Perform(S
, SubEntity
, SubKind
,
5706 Arg
? MultiExprArg(Arg
) : MutableArrayRef
<Expr
*>());
5712 *InitExpr
= ER
.get();
5714 InitExprs
.push_back(ER
.get());
5719 if (const ArrayType
*AT
=
5720 S
.getASTContext().getAsArrayType(Entity
.getType())) {
5721 SmallVector
<InitializedEntity
, 4> ElementEntities
;
5722 uint64_t ArrayLength
;
5723 // C++ [dcl.init]p16.5
5724 // if the destination type is an array, the object is initialized as
5725 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5726 // the destination type is an array of unknown bound, it is defined as
5727 // having k elements.
5728 if (const ConstantArrayType
*CAT
=
5729 S
.getASTContext().getAsConstantArrayType(Entity
.getType())) {
5730 ArrayLength
= CAT
->getZExtSize();
5731 ResultType
= Entity
.getType();
5732 } else if (const VariableArrayType
*VAT
=
5733 S
.getASTContext().getAsVariableArrayType(Entity
.getType())) {
5734 // Braced-initialization of variable array types is not allowed, even if
5735 // the size is greater than or equal to the number of args, so we don't
5736 // allow them to be initialized via parenthesized aggregate initialization
5738 const Expr
*SE
= VAT
->getSizeExpr();
5739 S
.Diag(SE
->getBeginLoc(), diag::err_variable_object_no_init
)
5740 << SE
->getSourceRange();
5743 assert(Entity
.getType()->isIncompleteArrayType());
5744 ArrayLength
= Args
.size();
5746 EntityIndexToProcess
= ArrayLength
;
5748 // ...the ith array element is copy-initialized with xi for each
5750 for (Expr
*E
: Args
) {
5751 InitializedEntity SubEntity
= InitializedEntity::InitializeElement(
5752 S
.getASTContext(), EntityIndexToProcess
, Entity
);
5753 InitializationKind SubKind
= InitializationKind::CreateForInit(
5754 E
->getExprLoc(), /*isDirectInit=*/false, E
);
5755 if (!HandleInitializedEntity(SubEntity
, SubKind
, E
))
5758 // ...and value-initialized for each k < i <= n;
5759 if (ArrayLength
> Args
.size() || Entity
.isVariableLengthArrayNew()) {
5760 InitializedEntity SubEntity
= InitializedEntity::InitializeElement(
5761 S
.getASTContext(), Args
.size(), Entity
);
5762 InitializationKind SubKind
= InitializationKind::CreateValue(
5763 Kind
.getLocation(), Kind
.getLocation(), Kind
.getLocation(), true);
5764 if (!HandleInitializedEntity(SubEntity
, SubKind
, nullptr, &ArrayFiller
))
5768 if (ResultType
.isNull()) {
5769 ResultType
= S
.Context
.getConstantArrayType(
5770 AT
->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength
),
5771 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal
, 0);
5773 } else if (auto *RT
= Entity
.getType()->getAs
<RecordType
>()) {
5774 bool IsUnion
= RT
->isUnionType();
5775 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
5776 if (RD
->isInvalidDecl()) {
5777 // Exit early to avoid confusion when processing members.
5778 // We do the same for braced list initialization in
5779 // `CheckStructUnionTypes`.
5781 clang::InitializationSequence::FK_ParenthesizedListInitFailed
);
5786 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
5787 InitializedEntity SubEntity
= InitializedEntity::InitializeBase(
5788 S
.getASTContext(), &Base
, false, &Entity
);
5789 if (EntityIndexToProcess
< Args
.size()) {
5790 // C++ [dcl.init]p16.6.2.2.
5791 // ...the object is initialized is follows. Let e1, ..., en be the
5792 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5793 // the elements of the expression-list...The element ei is
5794 // copy-initialized with xi for 1 <= i <= k.
5795 Expr
*E
= Args
[EntityIndexToProcess
];
5796 InitializationKind SubKind
= InitializationKind::CreateForInit(
5797 E
->getExprLoc(), /*isDirectInit=*/false, E
);
5798 if (!HandleInitializedEntity(SubEntity
, SubKind
, E
))
5801 // We've processed all of the args, but there are still base classes
5802 // that have to be initialized.
5803 // C++ [dcl.init]p17.6.2.2
5804 // The remaining elements...otherwise are value initialzed
5805 InitializationKind SubKind
= InitializationKind::CreateValue(
5806 Kind
.getLocation(), Kind
.getLocation(), Kind
.getLocation(),
5807 /*IsImplicit=*/true);
5808 if (!HandleInitializedEntity(SubEntity
, SubKind
, nullptr))
5811 EntityIndexToProcess
++;
5815 for (FieldDecl
*FD
: RD
->fields()) {
5816 // Unnamed bitfields should not be initialized at all, either with an arg
5818 if (FD
->isUnnamedBitField())
5821 InitializedEntity SubEntity
=
5822 InitializedEntity::InitializeMemberFromParenAggInit(FD
);
5824 if (EntityIndexToProcess
< Args
.size()) {
5825 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5826 Expr
*E
= Args
[EntityIndexToProcess
];
5828 // Incomplete array types indicate flexible array members. Do not allow
5829 // paren list initializations of structs with these members, as GCC
5831 if (FD
->getType()->isIncompleteArrayType()) {
5833 S
.Diag(E
->getBeginLoc(), diag::err_flexible_array_init
)
5834 << SourceRange(E
->getBeginLoc(), E
->getEndLoc());
5835 S
.Diag(FD
->getLocation(), diag::note_flexible_array_member
) << FD
;
5838 InitializationSequence::FK_ParenthesizedListInitFailed
);
5842 InitializationKind SubKind
= InitializationKind::CreateForInit(
5843 E
->getExprLoc(), /*isDirectInit=*/false, E
);
5844 if (!HandleInitializedEntity(SubEntity
, SubKind
, E
))
5847 // Unions should have only one initializer expression, so we bail out
5848 // after processing the first field. If there are more initializers then
5849 // it will be caught when we later check whether EntityIndexToProcess is
5850 // less than Args.size();
5852 InitializedFieldInUnion
= FD
;
5853 EntityIndexToProcess
= 1;
5857 // We've processed all of the args, but there are still members that
5858 // have to be initialized.
5859 if (FD
->hasInClassInitializer()) {
5861 // C++ [dcl.init]p16.6.2.2
5862 // The remaining elements are initialized with their default
5863 // member initializers, if any
5864 ExprResult DIE
= S
.BuildCXXDefaultInitExpr(
5865 Kind
.getParenOrBraceRange().getEnd(), FD
);
5866 if (DIE
.isInvalid())
5868 S
.checkInitializerLifetime(SubEntity
, DIE
.get());
5869 InitExprs
.push_back(DIE
.get());
5872 // C++ [dcl.init]p17.6.2.2
5873 // The remaining elements...otherwise are value initialzed
5874 if (FD
->getType()->isReferenceType()) {
5876 InitializationSequence::FK_ParenthesizedListInitFailed
);
5878 SourceRange SR
= Kind
.getParenOrBraceRange();
5879 S
.Diag(SR
.getEnd(), diag::err_init_reference_member_uninitialized
)
5880 << FD
->getType() << SR
;
5881 S
.Diag(FD
->getLocation(), diag::note_uninit_reference_member
);
5885 InitializationKind SubKind
= InitializationKind::CreateValue(
5886 Kind
.getLocation(), Kind
.getLocation(), Kind
.getLocation(), true);
5887 if (!HandleInitializedEntity(SubEntity
, SubKind
, nullptr))
5891 EntityIndexToProcess
++;
5893 ResultType
= Entity
.getType();
5896 // Not all of the args have been processed, so there must've been more args
5897 // than were required to initialize the element.
5898 if (EntityIndexToProcess
< Args
.size()) {
5899 Sequence
.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed
);
5901 QualType T
= Entity
.getType();
5902 int InitKind
= T
->isArrayType() ? 0 : T
->isUnionType() ? 3 : 4;
5903 SourceRange
ExcessInitSR(Args
[EntityIndexToProcess
]->getBeginLoc(),
5904 Args
.back()->getEndLoc());
5905 S
.Diag(Kind
.getLocation(), diag::err_excess_initializers
)
5906 << InitKind
<< ExcessInitSR
;
5912 Sequence
.setSequenceKind(InitializationSequence::NormalSequence
);
5913 Sequence
.AddParenthesizedListInitStep(Entity
.getType());
5914 } else if (Result
) {
5915 SourceRange SR
= Kind
.getParenOrBraceRange();
5916 auto *CPLIE
= CXXParenListInitExpr::Create(
5917 S
.getASTContext(), InitExprs
, ResultType
, Args
.size(),
5918 Kind
.getLocation(), SR
.getBegin(), SR
.getEnd());
5920 CPLIE
->setArrayFiller(ArrayFiller
);
5921 if (InitializedFieldInUnion
)
5922 CPLIE
->setInitializedFieldInUnion(InitializedFieldInUnion
);
5924 S
.Diag(Kind
.getLocation(),
5925 diag::warn_cxx17_compat_aggregate_init_paren_list
)
5926 << Kind
.getLocation() << SR
<< ResultType
;
5930 /// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5931 /// which enumerates all conversion functions and performs overload resolution
5932 /// to select the best.
5933 static void TryUserDefinedConversion(Sema
&S
,
5935 const InitializationKind
&Kind
,
5937 InitializationSequence
&Sequence
,
5938 bool TopLevelOfInitList
) {
5939 assert(!DestType
->isReferenceType() && "References are handled elsewhere");
5940 QualType SourceType
= Initializer
->getType();
5941 assert((DestType
->isRecordType() || SourceType
->isRecordType()) &&
5942 "Must have a class type to perform a user-defined conversion");
5944 // Build the candidate set directly in the initialization sequence
5945 // structure, so that it will persist if we fail.
5946 OverloadCandidateSet
&CandidateSet
= Sequence
.getFailedCandidateSet();
5947 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
5948 CandidateSet
.setDestAS(DestType
.getQualifiers().getAddressSpace());
5950 // Determine whether we are allowed to call explicit constructors or
5951 // explicit conversion operators.
5952 bool AllowExplicit
= Kind
.AllowExplicit();
5954 if (const RecordType
*DestRecordType
= DestType
->getAs
<RecordType
>()) {
5955 // The type we're converting to is a class type. Enumerate its constructors
5956 // to see if there is a suitable conversion.
5957 CXXRecordDecl
*DestRecordDecl
5958 = cast
<CXXRecordDecl
>(DestRecordType
->getDecl());
5960 // Try to complete the type we're converting to.
5961 if (S
.isCompleteType(Kind
.getLocation(), DestType
)) {
5962 for (NamedDecl
*D
: S
.LookupConstructors(DestRecordDecl
)) {
5963 auto Info
= getConstructorInfo(D
);
5964 if (!Info
.Constructor
)
5967 if (!Info
.Constructor
->isInvalidDecl() &&
5968 Info
.Constructor
->isConvertingConstructor(/*AllowExplicit*/true)) {
5969 if (Info
.ConstructorTmpl
)
5970 S
.AddTemplateOverloadCandidate(
5971 Info
.ConstructorTmpl
, Info
.FoundDecl
,
5972 /*ExplicitArgs*/ nullptr, Initializer
, CandidateSet
,
5973 /*SuppressUserConversions=*/true,
5974 /*PartialOverloading*/ false, AllowExplicit
);
5976 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
,
5977 Initializer
, CandidateSet
,
5978 /*SuppressUserConversions=*/true,
5979 /*PartialOverloading*/ false, AllowExplicit
);
5985 SourceLocation DeclLoc
= Initializer
->getBeginLoc();
5987 if (const RecordType
*SourceRecordType
= SourceType
->getAs
<RecordType
>()) {
5988 // The type we're converting from is a class type, enumerate its conversion
5991 // We can only enumerate the conversion functions for a complete type; if
5992 // the type isn't complete, simply skip this step.
5993 if (S
.isCompleteType(DeclLoc
, SourceType
)) {
5994 CXXRecordDecl
*SourceRecordDecl
5995 = cast
<CXXRecordDecl
>(SourceRecordType
->getDecl());
5997 const auto &Conversions
=
5998 SourceRecordDecl
->getVisibleConversionFunctions();
5999 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
6001 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
6002 if (isa
<UsingShadowDecl
>(D
))
6003 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
6005 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
6006 CXXConversionDecl
*Conv
;
6008 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
6010 Conv
= cast
<CXXConversionDecl
>(D
);
6013 S
.AddTemplateConversionCandidate(
6014 ConvTemplate
, I
.getPair(), ActingDC
, Initializer
, DestType
,
6015 CandidateSet
, AllowExplicit
, AllowExplicit
);
6017 S
.AddConversionCandidate(Conv
, I
.getPair(), ActingDC
, Initializer
,
6018 DestType
, CandidateSet
, AllowExplicit
,
6024 // Perform overload resolution. If it fails, return the failed result.
6025 OverloadCandidateSet::iterator Best
;
6026 if (OverloadingResult Result
6027 = CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
)) {
6028 Sequence
.SetOverloadFailure(
6029 InitializationSequence::FK_UserConversionOverloadFailed
, Result
);
6031 // [class.copy.elision]p3:
6032 // In some copy-initialization contexts, a two-stage overload resolution
6034 // If the first overload resolution selects a deleted function, we also
6035 // need the initialization sequence to decide whether to perform the second
6036 // overload resolution.
6037 if (!(Result
== OR_Deleted
&&
6038 Kind
.getKind() == InitializationKind::IK_Copy
))
6042 FunctionDecl
*Function
= Best
->Function
;
6043 Function
->setReferenced();
6044 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
6046 if (isa
<CXXConstructorDecl
>(Function
)) {
6047 // Add the user-defined conversion step. Any cv-qualification conversion is
6048 // subsumed by the initialization. Per DR5, the created temporary is of the
6049 // cv-unqualified type of the destination.
6050 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
,
6051 DestType
.getUnqualifiedType(),
6052 HadMultipleCandidates
);
6054 // C++14 and before:
6055 // - if the function is a constructor, the call initializes a temporary
6056 // of the cv-unqualified version of the destination type. The [...]
6057 // temporary [...] is then used to direct-initialize, according to the
6058 // rules above, the object that is the destination of the
6059 // copy-initialization.
6060 // Note that this just performs a simple object copy from the temporary.
6063 // - if the function is a constructor, the call is a prvalue of the
6064 // cv-unqualified version of the destination type whose return object
6065 // is initialized by the constructor. The call is used to
6066 // direct-initialize, according to the rules above, the object that
6067 // is the destination of the copy-initialization.
6068 // Therefore we need to do nothing further.
6070 // FIXME: Mark this copy as extraneous.
6071 if (!S
.getLangOpts().CPlusPlus17
)
6072 Sequence
.AddFinalCopy(DestType
);
6073 else if (DestType
.hasQualifiers())
6074 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
6078 // Add the user-defined conversion step that calls the conversion function.
6079 QualType ConvType
= Function
->getCallResultType();
6080 Sequence
.AddUserConversionStep(Function
, Best
->FoundDecl
, ConvType
,
6081 HadMultipleCandidates
);
6083 if (ConvType
->getAs
<RecordType
>()) {
6084 // The call is used to direct-initialize [...] the object that is the
6085 // destination of the copy-initialization.
6087 // In C++17, this does not call a constructor if we enter /17.6.1:
6088 // - If the initializer expression is a prvalue and the cv-unqualified
6089 // version of the source type is the same as the class of the
6090 // destination [... do not make an extra copy]
6092 // FIXME: Mark this copy as extraneous.
6093 if (!S
.getLangOpts().CPlusPlus17
||
6094 Function
->getReturnType()->isReferenceType() ||
6095 !S
.Context
.hasSameUnqualifiedType(ConvType
, DestType
))
6096 Sequence
.AddFinalCopy(DestType
);
6097 else if (!S
.Context
.hasSameType(ConvType
, DestType
))
6098 Sequence
.AddQualificationConversionStep(DestType
, VK_PRValue
);
6102 // If the conversion following the call to the conversion function
6103 // is interesting, add it as a separate step.
6104 if (Best
->FinalConversion
.First
|| Best
->FinalConversion
.Second
||
6105 Best
->FinalConversion
.Third
) {
6106 ImplicitConversionSequence ICS
;
6108 ICS
.Standard
= Best
->FinalConversion
;
6109 Sequence
.AddConversionSequenceStep(ICS
, DestType
, TopLevelOfInitList
);
6113 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
6114 /// a function with a pointer return type contains a 'return false;' statement.
6115 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
6116 /// code using that header.
6118 /// Work around this by treating 'return false;' as zero-initializing the result
6119 /// if it's used in a pointer-returning function in a system header.
6120 static bool isLibstdcxxPointerReturnFalseHack(Sema
&S
,
6121 const InitializedEntity
&Entity
,
6123 return S
.getLangOpts().CPlusPlus11
&&
6124 Entity
.getKind() == InitializedEntity::EK_Result
&&
6125 Entity
.getType()->isPointerType() &&
6126 isa
<CXXBoolLiteralExpr
>(Init
) &&
6127 !cast
<CXXBoolLiteralExpr
>(Init
)->getValue() &&
6128 S
.getSourceManager().isInSystemHeader(Init
->getExprLoc());
6131 /// The non-zero enum values here are indexes into diagnostic alternatives.
6132 enum InvalidICRKind
{ IIK_okay
, IIK_nonlocal
, IIK_nonscalar
};
6134 /// Determines whether this expression is an acceptable ICR source.
6135 static InvalidICRKind
isInvalidICRSource(ASTContext
&C
, Expr
*e
,
6136 bool isAddressOf
, bool &isWeakAccess
) {
6138 e
= e
->IgnoreParens();
6140 // Skip address-of nodes.
6141 if (UnaryOperator
*op
= dyn_cast
<UnaryOperator
>(e
)) {
6142 if (op
->getOpcode() == UO_AddrOf
)
6143 return isInvalidICRSource(C
, op
->getSubExpr(), /*addressof*/ true,
6146 // Skip certain casts.
6147 } else if (CastExpr
*ce
= dyn_cast
<CastExpr
>(e
)) {
6148 switch (ce
->getCastKind()) {
6151 case CK_LValueBitCast
:
6153 return isInvalidICRSource(C
, ce
->getSubExpr(), isAddressOf
, isWeakAccess
);
6155 case CK_ArrayToPointerDecay
:
6156 return IIK_nonscalar
;
6158 case CK_NullToPointer
:
6165 // If we have a declaration reference, it had better be a local variable.
6166 } else if (isa
<DeclRefExpr
>(e
)) {
6167 // set isWeakAccess to true, to mean that there will be an implicit
6168 // load which requires a cleanup.
6169 if (e
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
)
6170 isWeakAccess
= true;
6172 if (!isAddressOf
) return IIK_nonlocal
;
6174 VarDecl
*var
= dyn_cast
<VarDecl
>(cast
<DeclRefExpr
>(e
)->getDecl());
6175 if (!var
) return IIK_nonlocal
;
6177 return (var
->hasLocalStorage() ? IIK_okay
: IIK_nonlocal
);
6179 // If we have a conditional operator, check both sides.
6180 } else if (ConditionalOperator
*cond
= dyn_cast
<ConditionalOperator
>(e
)) {
6181 if (InvalidICRKind iik
= isInvalidICRSource(C
, cond
->getLHS(), isAddressOf
,
6185 return isInvalidICRSource(C
, cond
->getRHS(), isAddressOf
, isWeakAccess
);
6187 // These are never scalar.
6188 } else if (isa
<ArraySubscriptExpr
>(e
)) {
6189 return IIK_nonscalar
;
6191 // Otherwise, it needs to be a null pointer constant.
6193 return (e
->isNullPointerConstant(C
, Expr::NPC_ValueDependentIsNull
)
6194 ? IIK_okay
: IIK_nonlocal
);
6197 return IIK_nonlocal
;
6200 /// Check whether the given expression is a valid operand for an
6201 /// indirect copy/restore.
6202 static void checkIndirectCopyRestoreSource(Sema
&S
, Expr
*src
) {
6203 assert(src
->isPRValue());
6204 bool isWeakAccess
= false;
6205 InvalidICRKind iik
= isInvalidICRSource(S
.Context
, src
, false, isWeakAccess
);
6206 // If isWeakAccess to true, there will be an implicit
6207 // load which requires a cleanup.
6208 if (S
.getLangOpts().ObjCAutoRefCount
&& isWeakAccess
)
6209 S
.Cleanup
.setExprNeedsCleanups(true);
6211 if (iik
== IIK_okay
) return;
6213 S
.Diag(src
->getExprLoc(), diag::err_arc_nonlocal_writeback
)
6214 << ((unsigned) iik
- 1) // shift index into diagnostic explanations
6215 << src
->getSourceRange();
6218 /// Determine whether we have compatible array types for the
6219 /// purposes of GNU by-copy array initialization.
6220 static bool hasCompatibleArrayTypes(ASTContext
&Context
, const ArrayType
*Dest
,
6221 const ArrayType
*Source
) {
6222 // If the source and destination array types are equivalent, we're
6224 if (Context
.hasSameType(QualType(Dest
, 0), QualType(Source
, 0)))
6227 // Make sure that the element types are the same.
6228 if (!Context
.hasSameType(Dest
->getElementType(), Source
->getElementType()))
6231 // The only mismatch we allow is when the destination is an
6232 // incomplete array type and the source is a constant array type.
6233 return Source
->isConstantArrayType() && Dest
->isIncompleteArrayType();
6236 static bool tryObjCWritebackConversion(Sema
&S
,
6237 InitializationSequence
&Sequence
,
6238 const InitializedEntity
&Entity
,
6239 Expr
*Initializer
) {
6240 bool ArrayDecay
= false;
6241 QualType ArgType
= Initializer
->getType();
6242 QualType ArgPointee
;
6243 if (const ArrayType
*ArgArrayType
= S
.Context
.getAsArrayType(ArgType
)) {
6245 ArgPointee
= ArgArrayType
->getElementType();
6246 ArgType
= S
.Context
.getPointerType(ArgPointee
);
6249 // Handle write-back conversion.
6250 QualType ConvertedArgType
;
6251 if (!S
.ObjC().isObjCWritebackConversion(ArgType
, Entity
.getType(),
6255 // We should copy unless we're passing to an argument explicitly
6257 bool ShouldCopy
= true;
6258 if (ParmVarDecl
*param
= cast_or_null
<ParmVarDecl
>(Entity
.getDecl()))
6259 ShouldCopy
= (param
->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out
);
6261 // Do we need an lvalue conversion?
6262 if (ArrayDecay
|| Initializer
->isGLValue()) {
6263 ImplicitConversionSequence ICS
;
6265 ICS
.Standard
.setAsIdentityConversion();
6267 QualType ResultType
;
6269 ICS
.Standard
.First
= ICK_Array_To_Pointer
;
6270 ResultType
= S
.Context
.getPointerType(ArgPointee
);
6272 ICS
.Standard
.First
= ICK_Lvalue_To_Rvalue
;
6273 ResultType
= Initializer
->getType().getNonLValueExprType(S
.Context
);
6276 Sequence
.AddConversionSequenceStep(ICS
, ResultType
);
6279 Sequence
.AddPassByIndirectCopyRestoreStep(Entity
.getType(), ShouldCopy
);
6283 static bool TryOCLSamplerInitialization(Sema
&S
,
6284 InitializationSequence
&Sequence
,
6286 Expr
*Initializer
) {
6287 if (!S
.getLangOpts().OpenCL
|| !DestType
->isSamplerT() ||
6288 (!Initializer
->isIntegerConstantExpr(S
.Context
) &&
6289 !Initializer
->getType()->isSamplerT()))
6292 Sequence
.AddOCLSamplerInitStep(DestType
);
6296 static bool IsZeroInitializer(Expr
*Initializer
, Sema
&S
) {
6297 return Initializer
->isIntegerConstantExpr(S
.getASTContext()) &&
6298 (Initializer
->EvaluateKnownConstInt(S
.getASTContext()) == 0);
6301 static bool TryOCLZeroOpaqueTypeInitialization(Sema
&S
,
6302 InitializationSequence
&Sequence
,
6304 Expr
*Initializer
) {
6305 if (!S
.getLangOpts().OpenCL
)
6309 // OpenCL 1.2 spec, s6.12.10
6311 // The event argument can also be used to associate the
6312 // async_work_group_copy with a previous async copy allowing
6313 // an event to be shared by multiple async copies; otherwise
6314 // event should be zero.
6316 if (DestType
->isEventT() || DestType
->isQueueT()) {
6317 if (!IsZeroInitializer(Initializer
, S
))
6320 Sequence
.AddOCLZeroOpaqueTypeStep(DestType
);
6324 // We should allow zero initialization for all types defined in the
6325 // cl_intel_device_side_avc_motion_estimation extension, except
6326 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6327 if (S
.getOpenCLOptions().isAvailableOption(
6328 "cl_intel_device_side_avc_motion_estimation", S
.getLangOpts()) &&
6329 DestType
->isOCLIntelSubgroupAVCType()) {
6330 if (DestType
->isOCLIntelSubgroupAVCMcePayloadType() ||
6331 DestType
->isOCLIntelSubgroupAVCMceResultType())
6333 if (!IsZeroInitializer(Initializer
, S
))
6336 Sequence
.AddOCLZeroOpaqueTypeStep(DestType
);
6343 InitializationSequence::InitializationSequence(
6344 Sema
&S
, const InitializedEntity
&Entity
, const InitializationKind
&Kind
,
6345 MultiExprArg Args
, bool TopLevelOfInitList
, bool TreatUnavailableAsInvalid
)
6346 : FailedOverloadResult(OR_Success
),
6347 FailedCandidateSet(Kind
.getLocation(), OverloadCandidateSet::CSK_Normal
) {
6348 InitializeFrom(S
, Entity
, Kind
, Args
, TopLevelOfInitList
,
6349 TreatUnavailableAsInvalid
);
6352 /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6353 /// address of that function, this returns true. Otherwise, it returns false.
6354 static bool isExprAnUnaddressableFunction(Sema
&S
, const Expr
*E
) {
6355 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
);
6356 if (!DRE
|| !isa
<FunctionDecl
>(DRE
->getDecl()))
6359 return !S
.checkAddressOfFunctionIsAvailable(
6360 cast
<FunctionDecl
>(DRE
->getDecl()));
6363 /// Determine whether we can perform an elementwise array copy for this kind
6365 static bool canPerformArrayCopy(const InitializedEntity
&Entity
) {
6366 switch (Entity
.getKind()) {
6367 case InitializedEntity::EK_LambdaCapture
:
6368 // C++ [expr.prim.lambda]p24:
6369 // For array members, the array elements are direct-initialized in
6370 // increasing subscript order.
6373 case InitializedEntity::EK_Variable
:
6374 // C++ [dcl.decomp]p1:
6375 // [...] each element is copy-initialized or direct-initialized from the
6376 // corresponding element of the assignment-expression [...]
6377 return isa
<DecompositionDecl
>(Entity
.getDecl());
6379 case InitializedEntity::EK_Member
:
6380 // C++ [class.copy.ctor]p14:
6381 // - if the member is an array, each element is direct-initialized with
6382 // the corresponding subobject of x
6383 return Entity
.isImplicitMemberInitializer();
6385 case InitializedEntity::EK_ArrayElement
:
6386 // All the above cases are intended to apply recursively, even though none
6387 // of them actually say that.
6388 if (auto *E
= Entity
.getParent())
6389 return canPerformArrayCopy(*E
);
6399 void InitializationSequence::InitializeFrom(Sema
&S
,
6400 const InitializedEntity
&Entity
,
6401 const InitializationKind
&Kind
,
6403 bool TopLevelOfInitList
,
6404 bool TreatUnavailableAsInvalid
) {
6405 ASTContext
&Context
= S
.Context
;
6407 // Eliminate non-overload placeholder types in the arguments. We
6408 // need to do this before checking whether types are dependent
6409 // because lowering a pseudo-object expression might well give us
6410 // something of dependent type.
6411 for (unsigned I
= 0, E
= Args
.size(); I
!= E
; ++I
)
6412 if (Args
[I
]->getType()->isNonOverloadPlaceholderType()) {
6413 // FIXME: should we be doing this here?
6414 ExprResult result
= S
.CheckPlaceholderExpr(Args
[I
]);
6415 if (result
.isInvalid()) {
6416 SetFailed(FK_PlaceholderType
);
6419 Args
[I
] = result
.get();
6422 // C++0x [dcl.init]p16:
6423 // The semantics of initializers are as follows. The destination type is
6424 // the type of the object or reference being initialized and the source
6425 // type is the type of the initializer expression. The source type is not
6426 // defined when the initializer is a braced-init-list or when it is a
6427 // parenthesized list of expressions.
6428 QualType DestType
= Entity
.getType();
6430 if (DestType
->isDependentType() ||
6431 Expr::hasAnyTypeDependentArguments(Args
)) {
6432 SequenceKind
= DependentSequence
;
6436 // Almost everything is a normal sequence.
6437 setSequenceKind(NormalSequence
);
6439 QualType SourceType
;
6440 Expr
*Initializer
= nullptr;
6441 if (Args
.size() == 1) {
6442 Initializer
= Args
[0];
6443 if (S
.getLangOpts().ObjC
) {
6444 if (S
.ObjC().CheckObjCBridgeRelatedConversions(
6445 Initializer
->getBeginLoc(), DestType
, Initializer
->getType(),
6447 S
.ObjC().CheckConversionToObjCLiteral(DestType
, Initializer
))
6448 Args
[0] = Initializer
;
6450 if (!isa
<InitListExpr
>(Initializer
))
6451 SourceType
= Initializer
->getType();
6454 // - If the initializer is a (non-parenthesized) braced-init-list, the
6455 // object is list-initialized (8.5.4).
6456 if (Kind
.getKind() != InitializationKind::IK_Direct
) {
6457 if (InitListExpr
*InitList
= dyn_cast_or_null
<InitListExpr
>(Initializer
)) {
6458 TryListInitialization(S
, Entity
, Kind
, InitList
, *this,
6459 TreatUnavailableAsInvalid
);
6464 // - If the destination type is a reference type, see 8.5.3.
6465 if (DestType
->isReferenceType()) {
6466 // C++0x [dcl.init.ref]p1:
6467 // A variable declared to be a T& or T&&, that is, "reference to type T"
6468 // (8.3.2), shall be initialized by an object, or function, of type T or
6469 // by an object that can be converted into a T.
6470 // (Therefore, multiple arguments are not permitted.)
6471 if (Args
.size() != 1)
6472 SetFailed(FK_TooManyInitsForReference
);
6473 // C++17 [dcl.init.ref]p5:
6474 // A reference [...] is initialized by an expression [...] as follows:
6475 // If the initializer is not an expression, presumably we should reject,
6476 // but the standard fails to actually say so.
6477 else if (isa
<InitListExpr
>(Args
[0]))
6478 SetFailed(FK_ParenthesizedListInitForReference
);
6480 TryReferenceInitialization(S
, Entity
, Kind
, Args
[0], *this,
6481 TopLevelOfInitList
);
6485 // - If the initializer is (), the object is value-initialized.
6486 if (Kind
.getKind() == InitializationKind::IK_Value
||
6487 (Kind
.getKind() == InitializationKind::IK_Direct
&& Args
.empty())) {
6488 TryValueInitialization(S
, Entity
, Kind
, *this);
6492 // Handle default initialization.
6493 if (Kind
.getKind() == InitializationKind::IK_Default
) {
6494 TryDefaultInitialization(S
, Entity
, Kind
, *this);
6498 // - If the destination type is an array of characters, an array of
6499 // char16_t, an array of char32_t, or an array of wchar_t, and the
6500 // initializer is a string literal, see 8.5.2.
6501 // - Otherwise, if the destination type is an array, the program is
6503 // - Except in HLSL, where non-decaying array parameters behave like
6504 // non-array types for initialization.
6505 if (DestType
->isArrayType() && !DestType
->isArrayParameterType()) {
6506 const ArrayType
*DestAT
= Context
.getAsArrayType(DestType
);
6507 if (Initializer
&& isa
<VariableArrayType
>(DestAT
)) {
6508 SetFailed(FK_VariableLengthArrayHasInitializer
);
6513 switch (IsStringInit(Initializer
, DestAT
, Context
)) {
6515 TryStringLiteralInitialization(S
, Entity
, Kind
, Initializer
, *this);
6517 case SIF_NarrowStringIntoWideChar
:
6518 SetFailed(FK_NarrowStringIntoWideCharArray
);
6520 case SIF_WideStringIntoChar
:
6521 SetFailed(FK_WideStringIntoCharArray
);
6523 case SIF_IncompatWideStringIntoWideChar
:
6524 SetFailed(FK_IncompatWideStringIntoWideChar
);
6526 case SIF_PlainStringIntoUTF8Char
:
6527 SetFailed(FK_PlainStringIntoUTF8Char
);
6529 case SIF_UTF8StringIntoPlainChar
:
6530 SetFailed(FK_UTF8StringIntoPlainChar
);
6537 // Some kinds of initialization permit an array to be initialized from
6538 // another array of the same type, and perform elementwise initialization.
6539 if (Initializer
&& isa
<ConstantArrayType
>(DestAT
) &&
6540 S
.Context
.hasSameUnqualifiedType(Initializer
->getType(),
6541 Entity
.getType()) &&
6542 canPerformArrayCopy(Entity
)) {
6543 TryArrayCopy(S
, Kind
, Entity
, Initializer
, DestType
, *this,
6544 TreatUnavailableAsInvalid
);
6548 // Note: as an GNU C extension, we allow initialization of an
6549 // array from a compound literal that creates an array of the same
6550 // type, so long as the initializer has no side effects.
6551 if (!S
.getLangOpts().CPlusPlus
&& Initializer
&&
6552 isa
<CompoundLiteralExpr
>(Initializer
->IgnoreParens()) &&
6553 Initializer
->getType()->isArrayType()) {
6554 const ArrayType
*SourceAT
6555 = Context
.getAsArrayType(Initializer
->getType());
6556 if (!hasCompatibleArrayTypes(S
.Context
, DestAT
, SourceAT
))
6557 SetFailed(FK_ArrayTypeMismatch
);
6558 else if (Initializer
->HasSideEffects(S
.Context
))
6559 SetFailed(FK_NonConstantArrayInit
);
6561 AddArrayInitStep(DestType
, /*IsGNUExtension*/true);
6564 // Note: as a GNU C++ extension, we allow list-initialization of a
6565 // class member of array type from a parenthesized initializer list.
6566 else if (S
.getLangOpts().CPlusPlus
&&
6567 Entity
.getKind() == InitializedEntity::EK_Member
&&
6568 isa_and_nonnull
<InitListExpr
>(Initializer
)) {
6569 TryListInitialization(S
, Entity
, Kind
, cast
<InitListExpr
>(Initializer
),
6570 *this, TreatUnavailableAsInvalid
);
6571 AddParenthesizedArrayInitStep(DestType
);
6572 } else if (S
.getLangOpts().CPlusPlus20
&& !TopLevelOfInitList
&&
6573 Kind
.getKind() == InitializationKind::IK_Direct
)
6574 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
6575 /*VerifyOnly=*/true);
6576 else if (DestAT
->getElementType()->isCharType())
6577 SetFailed(FK_ArrayNeedsInitListOrStringLiteral
);
6578 else if (IsWideCharCompatible(DestAT
->getElementType(), Context
))
6579 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral
);
6581 SetFailed(FK_ArrayNeedsInitList
);
6586 // Determine whether we should consider writeback conversions for
6588 bool allowObjCWritebackConversion
= S
.getLangOpts().ObjCAutoRefCount
&&
6589 Entity
.isParameterKind();
6591 if (TryOCLSamplerInitialization(S
, *this, DestType
, Initializer
))
6594 // We're at the end of the line for C: it's either a write-back conversion
6595 // or it's a C assignment. There's no need to check anything else.
6596 if (!S
.getLangOpts().CPlusPlus
) {
6597 assert(Initializer
&& "Initializer must be non-null");
6598 // If allowed, check whether this is an Objective-C writeback conversion.
6599 if (allowObjCWritebackConversion
&&
6600 tryObjCWritebackConversion(S
, *this, Entity
, Initializer
)) {
6604 if (TryOCLZeroOpaqueTypeInitialization(S
, *this, DestType
, Initializer
))
6607 // Handle initialization in C
6608 AddCAssignmentStep(DestType
);
6609 MaybeProduceObjCObject(S
, *this, Entity
);
6613 assert(S
.getLangOpts().CPlusPlus
);
6615 // - If the destination type is a (possibly cv-qualified) class type:
6616 if (DestType
->isRecordType()) {
6617 // - If the initialization is direct-initialization, or if it is
6618 // copy-initialization where the cv-unqualified version of the
6619 // source type is the same class as, or a derived class of, the
6620 // class of the destination, constructors are considered. [...]
6621 if (Kind
.getKind() == InitializationKind::IK_Direct
||
6622 (Kind
.getKind() == InitializationKind::IK_Copy
&&
6623 (Context
.hasSameUnqualifiedType(SourceType
, DestType
) ||
6624 (Initializer
&& S
.IsDerivedFrom(Initializer
->getBeginLoc(),
6625 SourceType
, DestType
))))) {
6626 TryConstructorInitialization(S
, Entity
, Kind
, Args
, DestType
, DestType
,
6629 // We fall back to the "no matching constructor" path if the
6630 // failed candidate set has functions other than the three default
6631 // constructors. For example, conversion function.
6632 if (const auto *RD
=
6633 dyn_cast
<CXXRecordDecl
>(DestType
->getAs
<RecordType
>()->getDecl());
6634 // In general, we should call isCompleteType for RD to check its
6635 // completeness, we don't call it here as it was already called in the
6636 // above TryConstructorInitialization.
6637 S
.getLangOpts().CPlusPlus20
&& RD
&& RD
->hasDefinition() &&
6638 RD
->isAggregate() && Failed() &&
6639 getFailureKind() == FK_ConstructorOverloadFailed
) {
6640 // Do not attempt paren list initialization if overload resolution
6641 // resolves to a deleted function .
6643 // We may reach this condition if we have a union wrapping a class with
6644 // a non-trivial copy or move constructor and we call one of those two
6645 // constructors. The union is an aggregate, but the matched constructor
6646 // is implicitly deleted, so we need to prevent aggregate initialization
6647 // (otherwise, it'll attempt aggregate initialization by initializing
6648 // the first element with a reference to the union).
6649 OverloadCandidateSet::iterator Best
;
6650 OverloadingResult OR
= getFailedCandidateSet().BestViableFunction(
6651 S
, Kind
.getLocation(), Best
);
6652 if (OR
!= OverloadingResult::OR_Deleted
) {
6653 // C++20 [dcl.init] 17.6.2.2:
6654 // - Otherwise, if no constructor is viable, the destination type is
6656 // aggregate class, and the initializer is a parenthesized
6658 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
6659 /*VerifyOnly=*/true);
6663 // - Otherwise (i.e., for the remaining copy-initialization cases),
6664 // user-defined conversion sequences that can convert from the
6665 // source type to the destination type or (when a conversion
6666 // function is used) to a derived class thereof are enumerated as
6667 // described in 13.3.1.4, and the best one is chosen through
6668 // overload resolution (13.3).
6669 assert(Initializer
&& "Initializer must be non-null");
6670 TryUserDefinedConversion(S
, DestType
, Kind
, Initializer
, *this,
6671 TopLevelOfInitList
);
6676 assert(Args
.size() >= 1 && "Zero-argument case handled above");
6678 // For HLSL ext vector types we allow list initialization behavior for C++
6679 // constructor syntax. This is accomplished by converting initialization
6680 // arguments an InitListExpr late.
6681 if (S
.getLangOpts().HLSL
&& Args
.size() > 1 && DestType
->isExtVectorType() &&
6682 (SourceType
.isNull() ||
6683 !Context
.hasSameUnqualifiedType(SourceType
, DestType
))) {
6685 llvm::SmallVector
<Expr
*> InitArgs
;
6686 for (auto *Arg
: Args
) {
6687 if (Arg
->getType()->isExtVectorType()) {
6688 const auto *VTy
= Arg
->getType()->castAs
<ExtVectorType
>();
6689 unsigned Elm
= VTy
->getNumElements();
6690 for (unsigned Idx
= 0; Idx
< Elm
; ++Idx
) {
6691 InitArgs
.emplace_back(new (Context
) ArraySubscriptExpr(
6693 IntegerLiteral::Create(
6694 Context
, llvm::APInt(Context
.getIntWidth(Context
.IntTy
), Idx
),
6695 Context
.IntTy
, SourceLocation()),
6696 VTy
->getElementType(), Arg
->getValueKind(), Arg
->getObjectKind(),
6700 InitArgs
.emplace_back(Arg
);
6702 InitListExpr
*ILE
= new (Context
) InitListExpr(
6703 S
.getASTContext(), SourceLocation(), InitArgs
, SourceLocation());
6705 AddListInitializationStep(DestType
);
6709 // The remaining cases all need a source type.
6710 if (Args
.size() > 1) {
6711 SetFailed(FK_TooManyInitsForScalar
);
6713 } else if (isa
<InitListExpr
>(Args
[0])) {
6714 SetFailed(FK_ParenthesizedListInitForScalar
);
6718 // - Otherwise, if the source type is a (possibly cv-qualified) class
6719 // type, conversion functions are considered.
6720 if (!SourceType
.isNull() && SourceType
->isRecordType()) {
6721 assert(Initializer
&& "Initializer must be non-null");
6722 // For a conversion to _Atomic(T) from either T or a class type derived
6723 // from T, initialize the T object then convert to _Atomic type.
6724 bool NeedAtomicConversion
= false;
6725 if (const AtomicType
*Atomic
= DestType
->getAs
<AtomicType
>()) {
6726 if (Context
.hasSameUnqualifiedType(SourceType
, Atomic
->getValueType()) ||
6727 S
.IsDerivedFrom(Initializer
->getBeginLoc(), SourceType
,
6728 Atomic
->getValueType())) {
6729 DestType
= Atomic
->getValueType();
6730 NeedAtomicConversion
= true;
6734 TryUserDefinedConversion(S
, DestType
, Kind
, Initializer
, *this,
6735 TopLevelOfInitList
);
6736 MaybeProduceObjCObject(S
, *this, Entity
);
6737 if (!Failed() && NeedAtomicConversion
)
6738 AddAtomicConversionStep(Entity
.getType());
6742 // - Otherwise, if the initialization is direct-initialization, the source
6743 // type is std::nullptr_t, and the destination type is bool, the initial
6744 // value of the object being initialized is false.
6745 if (!SourceType
.isNull() && SourceType
->isNullPtrType() &&
6746 DestType
->isBooleanType() &&
6747 Kind
.getKind() == InitializationKind::IK_Direct
) {
6748 AddConversionSequenceStep(
6749 ImplicitConversionSequence::getNullptrToBool(SourceType
, DestType
,
6750 Initializer
->isGLValue()),
6755 // - Otherwise, the initial value of the object being initialized is the
6756 // (possibly converted) value of the initializer expression. Standard
6757 // conversions (Clause 4) will be used, if necessary, to convert the
6758 // initializer expression to the cv-unqualified version of the
6759 // destination type; no user-defined conversions are considered.
6761 ImplicitConversionSequence ICS
6762 = S
.TryImplicitConversion(Initializer
, DestType
,
6763 /*SuppressUserConversions*/true,
6764 Sema::AllowedExplicit::None
,
6765 /*InOverloadResolution*/ false,
6766 /*CStyle=*/Kind
.isCStyleOrFunctionalCast(),
6767 allowObjCWritebackConversion
);
6769 if (ICS
.isStandard() &&
6770 ICS
.Standard
.Second
== ICK_Writeback_Conversion
) {
6771 // Objective-C ARC writeback conversion.
6773 // We should copy unless we're passing to an argument explicitly
6775 bool ShouldCopy
= true;
6776 if (ParmVarDecl
*Param
= cast_or_null
<ParmVarDecl
>(Entity
.getDecl()))
6777 ShouldCopy
= (Param
->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out
);
6779 // If there was an lvalue adjustment, add it as a separate conversion.
6780 if (ICS
.Standard
.First
== ICK_Array_To_Pointer
||
6781 ICS
.Standard
.First
== ICK_Lvalue_To_Rvalue
) {
6782 ImplicitConversionSequence LvalueICS
;
6783 LvalueICS
.setStandard();
6784 LvalueICS
.Standard
.setAsIdentityConversion();
6785 LvalueICS
.Standard
.setAllToTypes(ICS
.Standard
.getToType(0));
6786 LvalueICS
.Standard
.First
= ICS
.Standard
.First
;
6787 AddConversionSequenceStep(LvalueICS
, ICS
.Standard
.getToType(0));
6790 AddPassByIndirectCopyRestoreStep(DestType
, ShouldCopy
);
6791 } else if (ICS
.isBad()) {
6792 if (isLibstdcxxPointerReturnFalseHack(S
, Entity
, Initializer
))
6793 AddZeroInitializationStep(Entity
.getType());
6794 else if (DeclAccessPair Found
;
6795 Initializer
->getType() == Context
.OverloadTy
&&
6796 !S
.ResolveAddressOfOverloadedFunction(Initializer
, DestType
,
6797 /*Complain=*/false, Found
))
6798 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed
);
6799 else if (Initializer
->getType()->isFunctionType() &&
6800 isExprAnUnaddressableFunction(S
, Initializer
))
6801 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction
);
6803 SetFailed(InitializationSequence::FK_ConversionFailed
);
6805 AddConversionSequenceStep(ICS
, DestType
, TopLevelOfInitList
);
6807 MaybeProduceObjCObject(S
, *this, Entity
);
6811 InitializationSequence::~InitializationSequence() {
6812 for (auto &S
: Steps
)
6816 //===----------------------------------------------------------------------===//
6817 // Perform initialization
6818 //===----------------------------------------------------------------------===//
6819 static AssignmentAction
getAssignmentAction(const InitializedEntity
&Entity
,
6820 bool Diagnose
= false) {
6821 switch(Entity
.getKind()) {
6822 case InitializedEntity::EK_Variable
:
6823 case InitializedEntity::EK_New
:
6824 case InitializedEntity::EK_Exception
:
6825 case InitializedEntity::EK_Base
:
6826 case InitializedEntity::EK_Delegating
:
6827 return AssignmentAction::Initializing
;
6829 case InitializedEntity::EK_Parameter
:
6830 if (Entity
.getDecl() &&
6831 isa
<ObjCMethodDecl
>(Entity
.getDecl()->getDeclContext()))
6832 return AssignmentAction::Sending
;
6834 return AssignmentAction::Passing
;
6836 case InitializedEntity::EK_Parameter_CF_Audited
:
6837 if (Entity
.getDecl() &&
6838 isa
<ObjCMethodDecl
>(Entity
.getDecl()->getDeclContext()))
6839 return AssignmentAction::Sending
;
6841 return !Diagnose
? AssignmentAction::Passing
6842 : AssignmentAction::Passing_CFAudited
;
6844 case InitializedEntity::EK_Result
:
6845 case InitializedEntity::EK_StmtExprResult
: // FIXME: Not quite right.
6846 return AssignmentAction::Returning
;
6848 case InitializedEntity::EK_Temporary
:
6849 case InitializedEntity::EK_RelatedResult
:
6850 // FIXME: Can we tell apart casting vs. converting?
6851 return AssignmentAction::Casting
;
6853 case InitializedEntity::EK_TemplateParameter
:
6854 // This is really initialization, but refer to it as conversion for
6855 // consistency with CheckConvertedConstantExpression.
6856 return AssignmentAction::Converting
;
6858 case InitializedEntity::EK_Member
:
6859 case InitializedEntity::EK_ParenAggInitMember
:
6860 case InitializedEntity::EK_Binding
:
6861 case InitializedEntity::EK_ArrayElement
:
6862 case InitializedEntity::EK_VectorElement
:
6863 case InitializedEntity::EK_ComplexElement
:
6864 case InitializedEntity::EK_BlockElement
:
6865 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6866 case InitializedEntity::EK_LambdaCapture
:
6867 case InitializedEntity::EK_CompoundLiteralInit
:
6868 return AssignmentAction::Initializing
;
6871 llvm_unreachable("Invalid EntityKind!");
6874 /// Whether we should bind a created object as a temporary when
6875 /// initializing the given entity.
6876 static bool shouldBindAsTemporary(const InitializedEntity
&Entity
) {
6877 switch (Entity
.getKind()) {
6878 case InitializedEntity::EK_ArrayElement
:
6879 case InitializedEntity::EK_Member
:
6880 case InitializedEntity::EK_ParenAggInitMember
:
6881 case InitializedEntity::EK_Result
:
6882 case InitializedEntity::EK_StmtExprResult
:
6883 case InitializedEntity::EK_New
:
6884 case InitializedEntity::EK_Variable
:
6885 case InitializedEntity::EK_Base
:
6886 case InitializedEntity::EK_Delegating
:
6887 case InitializedEntity::EK_VectorElement
:
6888 case InitializedEntity::EK_ComplexElement
:
6889 case InitializedEntity::EK_Exception
:
6890 case InitializedEntity::EK_BlockElement
:
6891 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6892 case InitializedEntity::EK_LambdaCapture
:
6893 case InitializedEntity::EK_CompoundLiteralInit
:
6894 case InitializedEntity::EK_TemplateParameter
:
6897 case InitializedEntity::EK_Parameter
:
6898 case InitializedEntity::EK_Parameter_CF_Audited
:
6899 case InitializedEntity::EK_Temporary
:
6900 case InitializedEntity::EK_RelatedResult
:
6901 case InitializedEntity::EK_Binding
:
6905 llvm_unreachable("missed an InitializedEntity kind?");
6908 /// Whether the given entity, when initialized with an object
6909 /// created for that initialization, requires destruction.
6910 static bool shouldDestroyEntity(const InitializedEntity
&Entity
) {
6911 switch (Entity
.getKind()) {
6912 case InitializedEntity::EK_Result
:
6913 case InitializedEntity::EK_StmtExprResult
:
6914 case InitializedEntity::EK_New
:
6915 case InitializedEntity::EK_Base
:
6916 case InitializedEntity::EK_Delegating
:
6917 case InitializedEntity::EK_VectorElement
:
6918 case InitializedEntity::EK_ComplexElement
:
6919 case InitializedEntity::EK_BlockElement
:
6920 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6921 case InitializedEntity::EK_LambdaCapture
:
6924 case InitializedEntity::EK_Member
:
6925 case InitializedEntity::EK_ParenAggInitMember
:
6926 case InitializedEntity::EK_Binding
:
6927 case InitializedEntity::EK_Variable
:
6928 case InitializedEntity::EK_Parameter
:
6929 case InitializedEntity::EK_Parameter_CF_Audited
:
6930 case InitializedEntity::EK_TemplateParameter
:
6931 case InitializedEntity::EK_Temporary
:
6932 case InitializedEntity::EK_ArrayElement
:
6933 case InitializedEntity::EK_Exception
:
6934 case InitializedEntity::EK_CompoundLiteralInit
:
6935 case InitializedEntity::EK_RelatedResult
:
6939 llvm_unreachable("missed an InitializedEntity kind?");
6942 /// Get the location at which initialization diagnostics should appear.
6943 static SourceLocation
getInitializationLoc(const InitializedEntity
&Entity
,
6944 Expr
*Initializer
) {
6945 switch (Entity
.getKind()) {
6946 case InitializedEntity::EK_Result
:
6947 case InitializedEntity::EK_StmtExprResult
:
6948 return Entity
.getReturnLoc();
6950 case InitializedEntity::EK_Exception
:
6951 return Entity
.getThrowLoc();
6953 case InitializedEntity::EK_Variable
:
6954 case InitializedEntity::EK_Binding
:
6955 return Entity
.getDecl()->getLocation();
6957 case InitializedEntity::EK_LambdaCapture
:
6958 return Entity
.getCaptureLoc();
6960 case InitializedEntity::EK_ArrayElement
:
6961 case InitializedEntity::EK_Member
:
6962 case InitializedEntity::EK_ParenAggInitMember
:
6963 case InitializedEntity::EK_Parameter
:
6964 case InitializedEntity::EK_Parameter_CF_Audited
:
6965 case InitializedEntity::EK_TemplateParameter
:
6966 case InitializedEntity::EK_Temporary
:
6967 case InitializedEntity::EK_New
:
6968 case InitializedEntity::EK_Base
:
6969 case InitializedEntity::EK_Delegating
:
6970 case InitializedEntity::EK_VectorElement
:
6971 case InitializedEntity::EK_ComplexElement
:
6972 case InitializedEntity::EK_BlockElement
:
6973 case InitializedEntity::EK_LambdaToBlockConversionBlockElement
:
6974 case InitializedEntity::EK_CompoundLiteralInit
:
6975 case InitializedEntity::EK_RelatedResult
:
6976 return Initializer
->getBeginLoc();
6978 llvm_unreachable("missed an InitializedEntity kind?");
6981 /// Make a (potentially elidable) temporary copy of the object
6982 /// provided by the given initializer by calling the appropriate copy
6985 /// \param S The Sema object used for type-checking.
6987 /// \param T The type of the temporary object, which must either be
6988 /// the type of the initializer expression or a superclass thereof.
6990 /// \param Entity The entity being initialized.
6992 /// \param CurInit The initializer expression.
6994 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6995 /// is permitted in C++03 (but not C++0x) when binding a reference to
6998 /// \returns An expression that copies the initializer expression into
6999 /// a temporary object, or an error expression if a copy could not be
7001 static ExprResult
CopyObject(Sema
&S
,
7003 const InitializedEntity
&Entity
,
7005 bool IsExtraneousCopy
) {
7006 if (CurInit
.isInvalid())
7008 // Determine which class type we're copying to.
7009 Expr
*CurInitExpr
= (Expr
*)CurInit
.get();
7010 CXXRecordDecl
*Class
= nullptr;
7011 if (const RecordType
*Record
= T
->getAs
<RecordType
>())
7012 Class
= cast
<CXXRecordDecl
>(Record
->getDecl());
7016 SourceLocation Loc
= getInitializationLoc(Entity
, CurInit
.get());
7018 // Make sure that the type we are copying is complete.
7019 if (S
.RequireCompleteType(Loc
, T
, diag::err_temp_copy_incomplete
))
7022 // Perform overload resolution using the class's constructors. Per
7023 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7024 // is direct-initialization.
7025 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
7026 DeclContext::lookup_result Ctors
= S
.LookupConstructors(Class
);
7028 OverloadCandidateSet::iterator Best
;
7029 switch (ResolveConstructorOverload(
7030 S
, Loc
, CurInitExpr
, CandidateSet
, T
, Ctors
, Best
,
7031 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7032 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7033 /*RequireActualConstructor=*/false,
7034 /*SecondStepOfCopyInit=*/true)) {
7038 case OR_No_Viable_Function
:
7039 CandidateSet
.NoteCandidates(
7040 PartialDiagnosticAt(
7041 Loc
, S
.PDiag(IsExtraneousCopy
&& !S
.isSFINAEContext()
7042 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7043 : diag::err_temp_copy_no_viable
)
7044 << (int)Entity
.getKind() << CurInitExpr
->getType()
7045 << CurInitExpr
->getSourceRange()),
7046 S
, OCD_AllCandidates
, CurInitExpr
);
7047 if (!IsExtraneousCopy
|| S
.isSFINAEContext())
7052 CandidateSet
.NoteCandidates(
7053 PartialDiagnosticAt(Loc
, S
.PDiag(diag::err_temp_copy_ambiguous
)
7054 << (int)Entity
.getKind()
7055 << CurInitExpr
->getType()
7056 << CurInitExpr
->getSourceRange()),
7057 S
, OCD_AmbiguousCandidates
, CurInitExpr
);
7061 S
.Diag(Loc
, diag::err_temp_copy_deleted
)
7062 << (int)Entity
.getKind() << CurInitExpr
->getType()
7063 << CurInitExpr
->getSourceRange();
7064 S
.NoteDeletedFunction(Best
->Function
);
7068 bool HadMultipleCandidates
= CandidateSet
.size() > 1;
7070 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(Best
->Function
);
7071 SmallVector
<Expr
*, 8> ConstructorArgs
;
7072 CurInit
.get(); // Ownership transferred into MultiExprArg, below.
7074 S
.CheckConstructorAccess(Loc
, Constructor
, Best
->FoundDecl
, Entity
,
7077 if (IsExtraneousCopy
) {
7078 // If this is a totally extraneous copy for C++03 reference
7079 // binding purposes, just return the original initialization
7080 // expression. We don't generate an (elided) copy operation here
7081 // because doing so would require us to pass down a flag to avoid
7082 // infinite recursion, where each step adds another extraneous,
7085 // Instantiate the default arguments of any extra parameters in
7086 // the selected copy constructor, as if we were going to create a
7087 // proper call to the copy constructor.
7088 for (unsigned I
= 1, N
= Constructor
->getNumParams(); I
!= N
; ++I
) {
7089 ParmVarDecl
*Parm
= Constructor
->getParamDecl(I
);
7090 if (S
.RequireCompleteType(Loc
, Parm
->getType(),
7091 diag::err_call_incomplete_argument
))
7094 // Build the default argument expression; we don't actually care
7095 // if this succeeds or not, because this routine will complain
7096 // if there was a problem.
7097 S
.BuildCXXDefaultArgExpr(Loc
, Constructor
, Parm
);
7103 // Determine the arguments required to actually perform the
7104 // constructor call (we might have derived-to-base conversions, or
7105 // the copy constructor may have default arguments).
7106 if (S
.CompleteConstructorCall(Constructor
, T
, CurInitExpr
, Loc
,
7110 // C++0x [class.copy]p32:
7111 // When certain criteria are met, an implementation is allowed to
7112 // omit the copy/move construction of a class object, even if the
7113 // copy/move constructor and/or destructor for the object have
7114 // side effects. [...]
7115 // - when a temporary class object that has not been bound to a
7116 // reference (12.2) would be copied/moved to a class object
7117 // with the same cv-unqualified type, the copy/move operation
7118 // can be omitted by constructing the temporary object
7119 // directly into the target of the omitted copy/move
7121 // Note that the other three bullets are handled elsewhere. Copy
7122 // elision for return statements and throw expressions are handled as part
7123 // of constructor initialization, while copy elision for exception handlers
7124 // is handled by the run-time.
7126 // FIXME: If the function parameter is not the same type as the temporary, we
7127 // should still be able to elide the copy, but we don't have a way to
7128 // represent in the AST how much should be elided in this case.
7130 CurInitExpr
->isTemporaryObject(S
.Context
, Class
) &&
7131 S
.Context
.hasSameUnqualifiedType(
7132 Best
->Function
->getParamDecl(0)->getType().getNonReferenceType(),
7133 CurInitExpr
->getType());
7135 // Actually perform the constructor call.
7136 CurInit
= S
.BuildCXXConstructExpr(
7137 Loc
, T
, Best
->FoundDecl
, Constructor
, Elidable
, ConstructorArgs
,
7138 HadMultipleCandidates
,
7140 /*StdInitListInit*/ false,
7141 /*ZeroInit*/ false, CXXConstructionKind::Complete
, SourceRange());
7143 // If we're supposed to bind temporaries, do so.
7144 if (!CurInit
.isInvalid() && shouldBindAsTemporary(Entity
))
7145 CurInit
= S
.MaybeBindToTemporary(CurInit
.getAs
<Expr
>());
7149 /// Check whether elidable copy construction for binding a reference to
7150 /// a temporary would have succeeded if we were building in C++98 mode, for
7152 static void CheckCXX98CompatAccessibleCopy(Sema
&S
,
7153 const InitializedEntity
&Entity
,
7154 Expr
*CurInitExpr
) {
7155 assert(S
.getLangOpts().CPlusPlus11
);
7157 const RecordType
*Record
= CurInitExpr
->getType()->getAs
<RecordType
>();
7161 SourceLocation Loc
= getInitializationLoc(Entity
, CurInitExpr
);
7162 if (S
.Diags
.isIgnored(diag::warn_cxx98_compat_temp_copy
, Loc
))
7165 // Find constructors which would have been considered.
7166 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
7167 DeclContext::lookup_result Ctors
=
7168 S
.LookupConstructors(cast
<CXXRecordDecl
>(Record
->getDecl()));
7170 // Perform overload resolution.
7171 OverloadCandidateSet::iterator Best
;
7172 OverloadingResult OR
= ResolveConstructorOverload(
7173 S
, Loc
, CurInitExpr
, CandidateSet
, CurInitExpr
->getType(), Ctors
, Best
,
7174 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7175 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7176 /*RequireActualConstructor=*/false,
7177 /*SecondStepOfCopyInit=*/true);
7179 PartialDiagnostic Diag
= S
.PDiag(diag::warn_cxx98_compat_temp_copy
)
7180 << OR
<< (int)Entity
.getKind() << CurInitExpr
->getType()
7181 << CurInitExpr
->getSourceRange();
7185 S
.CheckConstructorAccess(Loc
, cast
<CXXConstructorDecl
>(Best
->Function
),
7186 Best
->FoundDecl
, Entity
, Diag
);
7187 // FIXME: Check default arguments as far as that's possible.
7190 case OR_No_Viable_Function
:
7191 CandidateSet
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
,
7192 OCD_AllCandidates
, CurInitExpr
);
7196 CandidateSet
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
,
7197 OCD_AmbiguousCandidates
, CurInitExpr
);
7202 S
.NoteDeletedFunction(Best
->Function
);
7207 void InitializationSequence::PrintInitLocationNote(Sema
&S
,
7208 const InitializedEntity
&Entity
) {
7209 if (Entity
.isParamOrTemplateParamKind() && Entity
.getDecl()) {
7210 if (Entity
.getDecl()->getLocation().isInvalid())
7213 if (Entity
.getDecl()->getDeclName())
7214 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_parameter_named_here
)
7215 << Entity
.getDecl()->getDeclName();
7217 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_parameter_here
);
7219 else if (Entity
.getKind() == InitializedEntity::EK_RelatedResult
&&
7220 Entity
.getMethodDecl())
7221 S
.Diag(Entity
.getMethodDecl()->getLocation(),
7222 diag::note_method_return_type_change
)
7223 << Entity
.getMethodDecl()->getDeclName();
7226 /// Returns true if the parameters describe a constructor initialization of
7227 /// an explicit temporary object, e.g. "Point(x, y)".
7228 static bool isExplicitTemporary(const InitializedEntity
&Entity
,
7229 const InitializationKind
&Kind
,
7231 switch (Entity
.getKind()) {
7232 case InitializedEntity::EK_Temporary
:
7233 case InitializedEntity::EK_CompoundLiteralInit
:
7234 case InitializedEntity::EK_RelatedResult
:
7240 switch (Kind
.getKind()) {
7241 case InitializationKind::IK_DirectList
:
7243 // FIXME: Hack to work around cast weirdness.
7244 case InitializationKind::IK_Direct
:
7245 case InitializationKind::IK_Value
:
7246 return NumArgs
!= 1;
7253 PerformConstructorInitialization(Sema
&S
,
7254 const InitializedEntity
&Entity
,
7255 const InitializationKind
&Kind
,
7257 const InitializationSequence::Step
& Step
,
7258 bool &ConstructorInitRequiresZeroInit
,
7259 bool IsListInitialization
,
7260 bool IsStdInitListInitialization
,
7261 SourceLocation LBraceLoc
,
7262 SourceLocation RBraceLoc
) {
7263 unsigned NumArgs
= Args
.size();
7264 CXXConstructorDecl
*Constructor
7265 = cast
<CXXConstructorDecl
>(Step
.Function
.Function
);
7266 bool HadMultipleCandidates
= Step
.Function
.HadMultipleCandidates
;
7268 // Build a call to the selected constructor.
7269 SmallVector
<Expr
*, 8> ConstructorArgs
;
7270 SourceLocation Loc
= (Kind
.isCopyInit() && Kind
.getEqualLoc().isValid())
7271 ? Kind
.getEqualLoc()
7272 : Kind
.getLocation();
7274 if (Kind
.getKind() == InitializationKind::IK_Default
) {
7275 // Force even a trivial, implicit default constructor to be
7276 // semantically checked. We do this explicitly because we don't build
7277 // the definition for completely trivial constructors.
7278 assert(Constructor
->getParent() && "No parent class for constructor.");
7279 if (Constructor
->isDefaulted() && Constructor
->isDefaultConstructor() &&
7280 Constructor
->isTrivial() && !Constructor
->isUsed(false)) {
7281 S
.runWithSufficientStackSpace(Loc
, [&] {
7282 S
.DefineImplicitDefaultConstructor(Loc
, Constructor
);
7287 ExprResult
CurInit((Expr
*)nullptr);
7289 // C++ [over.match.copy]p1:
7290 // - When initializing a temporary to be bound to the first parameter
7291 // of a constructor that takes a reference to possibly cv-qualified
7292 // T as its first argument, called with a single argument in the
7293 // context of direct-initialization, explicit conversion functions
7294 // are also considered.
7295 bool AllowExplicitConv
=
7296 Kind
.AllowExplicit() && !Kind
.isCopyInit() && Args
.size() == 1 &&
7297 hasCopyOrMoveCtorParam(S
.Context
,
7298 getConstructorInfo(Step
.Function
.FoundDecl
));
7300 // A smart pointer constructed from a nullable pointer is nullable.
7301 if (NumArgs
== 1 && !Kind
.isExplicitCast())
7302 S
.diagnoseNullableToNonnullConversion(
7303 Entity
.getType(), Args
.front()->getType(), Kind
.getLocation());
7305 // Determine the arguments required to actually perform the constructor
7307 if (S
.CompleteConstructorCall(Constructor
, Step
.Type
, Args
, Loc
,
7308 ConstructorArgs
, AllowExplicitConv
,
7309 IsListInitialization
))
7312 if (isExplicitTemporary(Entity
, Kind
, NumArgs
)) {
7313 // An explicitly-constructed temporary, e.g., X(1, 2).
7314 if (S
.DiagnoseUseOfDecl(Step
.Function
.FoundDecl
, Loc
))
7317 TypeSourceInfo
*TSInfo
= Entity
.getTypeSourceInfo();
7319 TSInfo
= S
.Context
.getTrivialTypeSourceInfo(Entity
.getType(), Loc
);
7320 SourceRange ParenOrBraceRange
=
7321 (Kind
.getKind() == InitializationKind::IK_DirectList
)
7322 ? SourceRange(LBraceLoc
, RBraceLoc
)
7323 : Kind
.getParenOrBraceRange();
7325 CXXConstructorDecl
*CalleeDecl
= Constructor
;
7326 if (auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(
7327 Step
.Function
.FoundDecl
.getDecl())) {
7328 CalleeDecl
= S
.findInheritingConstructor(Loc
, Constructor
, Shadow
);
7330 S
.MarkFunctionReferenced(Loc
, CalleeDecl
);
7332 CurInit
= S
.CheckForImmediateInvocation(
7333 CXXTemporaryObjectExpr::Create(
7334 S
.Context
, CalleeDecl
,
7335 Entity
.getType().getNonLValueExprType(S
.Context
), TSInfo
,
7336 ConstructorArgs
, ParenOrBraceRange
, HadMultipleCandidates
,
7337 IsListInitialization
, IsStdInitListInitialization
,
7338 ConstructorInitRequiresZeroInit
),
7341 CXXConstructionKind ConstructKind
= CXXConstructionKind::Complete
;
7343 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
7344 ConstructKind
= Entity
.getBaseSpecifier()->isVirtual()
7345 ? CXXConstructionKind::VirtualBase
7346 : CXXConstructionKind::NonVirtualBase
;
7347 } else if (Entity
.getKind() == InitializedEntity::EK_Delegating
) {
7348 ConstructKind
= CXXConstructionKind::Delegating
;
7351 // Only get the parenthesis or brace range if it is a list initialization or
7352 // direct construction.
7353 SourceRange ParenOrBraceRange
;
7354 if (IsListInitialization
)
7355 ParenOrBraceRange
= SourceRange(LBraceLoc
, RBraceLoc
);
7356 else if (Kind
.getKind() == InitializationKind::IK_Direct
)
7357 ParenOrBraceRange
= Kind
.getParenOrBraceRange();
7359 // If the entity allows NRVO, mark the construction as elidable
7361 if (Entity
.allowsNRVO())
7362 CurInit
= S
.BuildCXXConstructExpr(Loc
, Step
.Type
,
7363 Step
.Function
.FoundDecl
,
7364 Constructor
, /*Elidable=*/true,
7366 HadMultipleCandidates
,
7367 IsListInitialization
,
7368 IsStdInitListInitialization
,
7369 ConstructorInitRequiresZeroInit
,
7373 CurInit
= S
.BuildCXXConstructExpr(Loc
, Step
.Type
,
7374 Step
.Function
.FoundDecl
,
7377 HadMultipleCandidates
,
7378 IsListInitialization
,
7379 IsStdInitListInitialization
,
7380 ConstructorInitRequiresZeroInit
,
7384 if (CurInit
.isInvalid())
7387 // Only check access if all of that succeeded.
7388 S
.CheckConstructorAccess(Loc
, Constructor
, Step
.Function
.FoundDecl
, Entity
);
7389 if (S
.DiagnoseUseOfDecl(Step
.Function
.FoundDecl
, Loc
))
7392 if (const ArrayType
*AT
= S
.Context
.getAsArrayType(Entity
.getType()))
7393 if (checkDestructorReference(S
.Context
.getBaseElementType(AT
), Loc
, S
))
7396 if (shouldBindAsTemporary(Entity
))
7397 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
7402 void Sema::checkInitializerLifetime(const InitializedEntity
&Entity
,
7404 return sema::checkInitLifetime(*this, Entity
, Init
);
7407 static void DiagnoseNarrowingInInitList(Sema
&S
,
7408 const ImplicitConversionSequence
&ICS
,
7409 QualType PreNarrowingType
,
7410 QualType EntityType
,
7411 const Expr
*PostInit
);
7413 static void CheckC23ConstexprInitConversion(Sema
&S
, QualType FromType
,
7414 QualType ToType
, Expr
*Init
);
7416 /// Provide warnings when std::move is used on construction.
7417 static void CheckMoveOnConstruction(Sema
&S
, const Expr
*InitExpr
,
7418 bool IsReturnStmt
) {
7422 if (S
.inTemplateInstantiation())
7425 QualType DestType
= InitExpr
->getType();
7426 if (!DestType
->isRecordType())
7429 unsigned DiagID
= 0;
7431 const CXXConstructExpr
*CCE
=
7432 dyn_cast
<CXXConstructExpr
>(InitExpr
->IgnoreParens());
7433 if (!CCE
|| CCE
->getNumArgs() != 1)
7436 if (!CCE
->getConstructor()->isCopyOrMoveConstructor())
7439 InitExpr
= CCE
->getArg(0)->IgnoreImpCasts();
7442 // Find the std::move call and get the argument.
7443 const CallExpr
*CE
= dyn_cast
<CallExpr
>(InitExpr
->IgnoreParens());
7444 if (!CE
|| !CE
->isCallToStdMove())
7447 const Expr
*Arg
= CE
->getArg(0)->IgnoreImplicit();
7450 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Arg
->IgnoreParenImpCasts());
7451 if (!DRE
|| DRE
->refersToEnclosingVariableOrCapture())
7454 const VarDecl
*VD
= dyn_cast
<VarDecl
>(DRE
->getDecl());
7455 if (!VD
|| !VD
->hasLocalStorage())
7458 // __block variables are not moved implicitly.
7459 if (VD
->hasAttr
<BlocksAttr
>())
7462 QualType SourceType
= VD
->getType();
7463 if (!SourceType
->isRecordType())
7466 if (!S
.Context
.hasSameUnqualifiedType(DestType
, SourceType
)) {
7470 // If we're returning a function parameter, copy elision
7472 if (isa
<ParmVarDecl
>(VD
))
7473 DiagID
= diag::warn_redundant_move_on_return
;
7475 DiagID
= diag::warn_pessimizing_move_on_return
;
7477 DiagID
= diag::warn_pessimizing_move_on_initialization
;
7478 const Expr
*ArgStripped
= Arg
->IgnoreImplicit()->IgnoreParens();
7479 if (!ArgStripped
->isPRValue() || !ArgStripped
->getType()->isRecordType())
7483 S
.Diag(CE
->getBeginLoc(), DiagID
);
7485 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7486 // is within a macro.
7487 SourceLocation CallBegin
= CE
->getCallee()->getBeginLoc();
7488 if (CallBegin
.isMacroID())
7490 SourceLocation RParen
= CE
->getRParenLoc();
7491 if (RParen
.isMacroID())
7493 SourceLocation LParen
;
7494 SourceLocation ArgLoc
= Arg
->getBeginLoc();
7496 // Special testing for the argument location. Since the fix-it needs the
7497 // location right before the argument, the argument location can be in a
7498 // macro only if it is at the beginning of the macro.
7499 while (ArgLoc
.isMacroID() &&
7500 S
.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc
)) {
7501 ArgLoc
= S
.getSourceManager().getImmediateExpansionRange(ArgLoc
).getBegin();
7504 if (LParen
.isMacroID())
7507 LParen
= ArgLoc
.getLocWithOffset(-1);
7509 S
.Diag(CE
->getBeginLoc(), diag::note_remove_move
)
7510 << FixItHint::CreateRemoval(SourceRange(CallBegin
, LParen
))
7511 << FixItHint::CreateRemoval(SourceRange(RParen
, RParen
));
7514 static void CheckForNullPointerDereference(Sema
&S
, const Expr
*E
) {
7515 // Check to see if we are dereferencing a null pointer. If so, this is
7516 // undefined behavior, so warn about it. This only handles the pattern
7517 // "*null", which is a very syntactic check.
7518 if (const UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(E
->IgnoreParenCasts()))
7519 if (UO
->getOpcode() == UO_Deref
&&
7520 UO
->getSubExpr()->IgnoreParenCasts()->
7521 isNullPointerConstant(S
.Context
, Expr::NPC_ValueDependentIsNotNull
)) {
7522 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
7523 S
.PDiag(diag::warn_binding_null_to_reference
)
7524 << UO
->getSubExpr()->getSourceRange());
7528 MaterializeTemporaryExpr
*
7529 Sema::CreateMaterializeTemporaryExpr(QualType T
, Expr
*Temporary
,
7530 bool BoundToLvalueReference
) {
7531 auto MTE
= new (Context
)
7532 MaterializeTemporaryExpr(T
, Temporary
, BoundToLvalueReference
);
7534 // Order an ExprWithCleanups for lifetime marks.
7536 // TODO: It'll be good to have a single place to check the access of the
7537 // destructor and generate ExprWithCleanups for various uses. Currently these
7538 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7539 // but there may be a chance to merge them.
7540 Cleanup
.setExprNeedsCleanups(false);
7541 if (isInLifetimeExtendingContext())
7542 currentEvaluationContext().ForRangeLifetimeExtendTemps
.push_back(MTE
);
7546 ExprResult
Sema::TemporaryMaterializationConversion(Expr
*E
) {
7547 // In C++98, we don't want to implicitly create an xvalue.
7548 // FIXME: This means that AST consumers need to deal with "prvalues" that
7549 // denote materialized temporaries. Maybe we should add another ValueKind
7550 // for "xvalue pretending to be a prvalue" for C++98 support.
7551 if (!E
->isPRValue() || !getLangOpts().CPlusPlus11
)
7554 // C++1z [conv.rval]/1: T shall be a complete type.
7555 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7556 // If so, we should check for a non-abstract class type here too.
7557 QualType T
= E
->getType();
7558 if (RequireCompleteType(E
->getExprLoc(), T
, diag::err_incomplete_type
))
7561 return CreateMaterializeTemporaryExpr(E
->getType(), E
, false);
7564 ExprResult
Sema::PerformQualificationConversion(Expr
*E
, QualType Ty
,
7566 CheckedConversionKind CCK
) {
7568 CastKind CK
= CK_NoOp
;
7570 if (VK
== VK_PRValue
) {
7571 auto PointeeTy
= Ty
->getPointeeType();
7572 auto ExprPointeeTy
= E
->getType()->getPointeeType();
7573 if (!PointeeTy
.isNull() &&
7574 PointeeTy
.getAddressSpace() != ExprPointeeTy
.getAddressSpace())
7575 CK
= CK_AddressSpaceConversion
;
7576 } else if (Ty
.getAddressSpace() != E
->getType().getAddressSpace()) {
7577 CK
= CK_AddressSpaceConversion
;
7580 return ImpCastExprToType(E
, Ty
, CK
, VK
, /*BasePath=*/nullptr, CCK
);
7583 ExprResult
InitializationSequence::Perform(Sema
&S
,
7584 const InitializedEntity
&Entity
,
7585 const InitializationKind
&Kind
,
7587 QualType
*ResultType
) {
7589 Diagnose(S
, Entity
, Kind
, Args
);
7592 if (!ZeroInitializationFixit
.empty()) {
7593 const Decl
*D
= Entity
.getDecl();
7594 const auto *VD
= dyn_cast_or_null
<VarDecl
>(D
);
7595 QualType DestType
= Entity
.getType();
7597 // The initialization would have succeeded with this fixit. Since the fixit
7598 // is on the error, we need to build a valid AST in this case, so this isn't
7599 // handled in the Failed() branch above.
7600 if (!DestType
->isRecordType() && VD
&& VD
->isConstexpr()) {
7601 // Use a more useful diagnostic for constexpr variables.
7602 S
.Diag(Kind
.getLocation(), diag::err_constexpr_var_requires_const_init
)
7604 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc
,
7605 ZeroInitializationFixit
);
7607 unsigned DiagID
= diag::err_default_init_const
;
7608 if (S
.getLangOpts().MSVCCompat
&& D
&& D
->hasAttr
<SelectAnyAttr
>())
7609 DiagID
= diag::ext_default_init_const
;
7611 S
.Diag(Kind
.getLocation(), DiagID
)
7612 << DestType
<< (bool)DestType
->getAs
<RecordType
>()
7613 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc
,
7614 ZeroInitializationFixit
);
7618 if (getKind() == DependentSequence
) {
7619 // If the declaration is a non-dependent, incomplete array type
7620 // that has an initializer, then its type will be completed once
7621 // the initializer is instantiated.
7622 if (ResultType
&& !Entity
.getType()->isDependentType() &&
7624 QualType DeclType
= Entity
.getType();
7625 if (const IncompleteArrayType
*ArrayT
7626 = S
.Context
.getAsIncompleteArrayType(DeclType
)) {
7627 // FIXME: We don't currently have the ability to accurately
7628 // compute the length of an initializer list without
7629 // performing full type-checking of the initializer list
7630 // (since we have to determine where braces are implicitly
7631 // introduced and such). So, we fall back to making the array
7632 // type a dependently-sized array type with no specified
7634 if (isa
<InitListExpr
>((Expr
*)Args
[0])) {
7635 SourceRange Brackets
;
7637 // Scavange the location of the brackets from the entity, if we can.
7638 if (auto *DD
= dyn_cast_or_null
<DeclaratorDecl
>(Entity
.getDecl())) {
7639 if (TypeSourceInfo
*TInfo
= DD
->getTypeSourceInfo()) {
7640 TypeLoc TL
= TInfo
->getTypeLoc();
7641 if (IncompleteArrayTypeLoc ArrayLoc
=
7642 TL
.getAs
<IncompleteArrayTypeLoc
>())
7643 Brackets
= ArrayLoc
.getBracketsRange();
7648 = S
.Context
.getDependentSizedArrayType(ArrayT
->getElementType(),
7649 /*NumElts=*/nullptr,
7650 ArrayT
->getSizeModifier(),
7651 ArrayT
->getIndexTypeCVRQualifiers(),
7657 if (Kind
.getKind() == InitializationKind::IK_Direct
&&
7658 !Kind
.isExplicitCast()) {
7659 // Rebuild the ParenListExpr.
7660 SourceRange ParenRange
= Kind
.getParenOrBraceRange();
7661 return S
.ActOnParenListExpr(ParenRange
.getBegin(), ParenRange
.getEnd(),
7664 assert(Kind
.getKind() == InitializationKind::IK_Copy
||
7665 Kind
.isExplicitCast() ||
7666 Kind
.getKind() == InitializationKind::IK_DirectList
);
7667 return ExprResult(Args
[0]);
7670 // No steps means no initialization.
7672 return ExprResult((Expr
*)nullptr);
7674 if (S
.getLangOpts().CPlusPlus11
&& Entity
.getType()->isReferenceType() &&
7675 Args
.size() == 1 && isa
<InitListExpr
>(Args
[0]) &&
7676 !Entity
.isParamOrTemplateParamKind()) {
7677 // Produce a C++98 compatibility warning if we are initializing a reference
7678 // from an initializer list. For parameters, we produce a better warning
7680 Expr
*Init
= Args
[0];
7681 S
.Diag(Init
->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init
)
7682 << Init
->getSourceRange();
7685 if (S
.getLangOpts().MicrosoftExt
&& Args
.size() == 1 &&
7686 isa
<PredefinedExpr
>(Args
[0]) && Entity
.getType()->isArrayType()) {
7687 // Produce a Microsoft compatibility warning when initializing from a
7688 // predefined expression since MSVC treats predefined expressions as string
7690 Expr
*Init
= Args
[0];
7691 S
.Diag(Init
->getBeginLoc(), diag::ext_init_from_predefined
) << Init
;
7694 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7695 QualType ETy
= Entity
.getType();
7696 bool HasGlobalAS
= ETy
.hasAddressSpace() &&
7697 ETy
.getAddressSpace() == LangAS::opencl_global
;
7699 if (S
.getLangOpts().OpenCLVersion
>= 200 &&
7700 ETy
->isAtomicType() && !HasGlobalAS
&&
7701 Entity
.getKind() == InitializedEntity::EK_Variable
&& Args
.size() > 0) {
7702 S
.Diag(Args
[0]->getBeginLoc(), diag::err_opencl_atomic_init
)
7704 << SourceRange(Entity
.getDecl()->getBeginLoc(), Args
[0]->getEndLoc());
7708 QualType DestType
= Entity
.getType().getNonReferenceType();
7709 // FIXME: Ugly hack around the fact that Entity.getType() is not
7710 // the same as Entity.getDecl()->getType() in cases involving type merging,
7711 // and we want latter when it makes sense.
7713 *ResultType
= Entity
.getDecl() ? Entity
.getDecl()->getType() :
7716 ExprResult
CurInit((Expr
*)nullptr);
7717 SmallVector
<Expr
*, 4> ArrayLoopCommonExprs
;
7719 // HLSL allows vector initialization to function like list initialization, but
7720 // use the syntax of a C++-like constructor.
7721 bool IsHLSLVectorInit
= S
.getLangOpts().HLSL
&& DestType
->isExtVectorType() &&
7722 isa
<InitListExpr
>(Args
[0]);
7723 (void)IsHLSLVectorInit
;
7725 // For initialization steps that start with a single initializer,
7726 // grab the only argument out the Args and place it into the "current"
7728 switch (Steps
.front().Kind
) {
7729 case SK_ResolveAddressOfOverloadedFunction
:
7730 case SK_CastDerivedToBasePRValue
:
7731 case SK_CastDerivedToBaseXValue
:
7732 case SK_CastDerivedToBaseLValue
:
7733 case SK_BindReference
:
7734 case SK_BindReferenceToTemporary
:
7736 case SK_ExtraneousCopyToTemporary
:
7737 case SK_UserConversion
:
7738 case SK_QualificationConversionLValue
:
7739 case SK_QualificationConversionXValue
:
7740 case SK_QualificationConversionPRValue
:
7741 case SK_FunctionReferenceConversion
:
7742 case SK_AtomicConversion
:
7743 case SK_ConversionSequence
:
7744 case SK_ConversionSequenceNoNarrowing
:
7745 case SK_ListInitialization
:
7746 case SK_UnwrapInitList
:
7747 case SK_RewrapInitList
:
7748 case SK_CAssignment
:
7750 case SK_ObjCObjectConversion
:
7751 case SK_ArrayLoopIndex
:
7752 case SK_ArrayLoopInit
:
7754 case SK_GNUArrayInit
:
7755 case SK_ParenthesizedArrayInit
:
7756 case SK_PassByIndirectCopyRestore
:
7757 case SK_PassByIndirectRestore
:
7758 case SK_ProduceObjCObject
:
7759 case SK_StdInitializerList
:
7760 case SK_OCLSamplerInit
:
7761 case SK_OCLZeroOpaqueType
: {
7762 assert(Args
.size() == 1 || IsHLSLVectorInit
);
7764 if (!CurInit
.get()) return ExprError();
7768 case SK_ConstructorInitialization
:
7769 case SK_ConstructorInitializationFromList
:
7770 case SK_StdInitializerListConstructorCall
:
7771 case SK_ZeroInitialization
:
7772 case SK_ParenthesizedListInit
:
7776 // Promote from an unevaluated context to an unevaluated list context in
7777 // C++11 list-initialization; we need to instantiate entities usable in
7778 // constant expressions here in order to perform narrowing checks =(
7779 EnterExpressionEvaluationContext
Evaluated(
7780 S
, EnterExpressionEvaluationContext::InitList
,
7781 isa_and_nonnull
<InitListExpr
>(CurInit
.get()));
7783 // C++ [class.abstract]p2:
7784 // no objects of an abstract class can be created except as subobjects
7785 // of a class derived from it
7786 auto checkAbstractType
= [&](QualType T
) -> bool {
7787 if (Entity
.getKind() == InitializedEntity::EK_Base
||
7788 Entity
.getKind() == InitializedEntity::EK_Delegating
)
7790 return S
.RequireNonAbstractType(Kind
.getLocation(), T
,
7791 diag::err_allocation_of_abstract_type
);
7794 // Walk through the computed steps for the initialization sequence,
7795 // performing the specified conversions along the way.
7796 bool ConstructorInitRequiresZeroInit
= false;
7797 for (step_iterator Step
= step_begin(), StepEnd
= step_end();
7798 Step
!= StepEnd
; ++Step
) {
7799 if (CurInit
.isInvalid())
7802 QualType SourceType
= CurInit
.get() ? CurInit
.get()->getType() : QualType();
7804 switch (Step
->Kind
) {
7805 case SK_ResolveAddressOfOverloadedFunction
:
7806 // Overload resolution determined which function invoke; update the
7807 // initializer to reflect that choice.
7808 S
.CheckAddressOfMemberAccess(CurInit
.get(), Step
->Function
.FoundDecl
);
7809 if (S
.DiagnoseUseOfDecl(Step
->Function
.FoundDecl
, Kind
.getLocation()))
7811 CurInit
= S
.FixOverloadedFunctionReference(CurInit
,
7812 Step
->Function
.FoundDecl
,
7813 Step
->Function
.Function
);
7814 // We might get back another placeholder expression if we resolved to a
7816 if (!CurInit
.isInvalid())
7817 CurInit
= S
.CheckPlaceholderExpr(CurInit
.get());
7820 case SK_CastDerivedToBasePRValue
:
7821 case SK_CastDerivedToBaseXValue
:
7822 case SK_CastDerivedToBaseLValue
: {
7823 // We have a derived-to-base cast that produces either an rvalue or an
7824 // lvalue. Perform that cast.
7826 CXXCastPath BasePath
;
7828 // Casts to inaccessible base classes are allowed with C-style casts.
7829 bool IgnoreBaseAccess
= Kind
.isCStyleOrFunctionalCast();
7830 if (S
.CheckDerivedToBaseConversion(
7831 SourceType
, Step
->Type
, CurInit
.get()->getBeginLoc(),
7832 CurInit
.get()->getSourceRange(), &BasePath
, IgnoreBaseAccess
))
7836 Step
->Kind
== SK_CastDerivedToBaseLValue
7838 : (Step
->Kind
== SK_CastDerivedToBaseXValue
? VK_XValue
7840 CurInit
= ImplicitCastExpr::Create(S
.Context
, Step
->Type
,
7841 CK_DerivedToBase
, CurInit
.get(),
7842 &BasePath
, VK
, FPOptionsOverride());
7846 case SK_BindReference
:
7847 // Reference binding does not have any corresponding ASTs.
7849 // Check exception specifications
7850 if (S
.CheckExceptionSpecCompatibility(CurInit
.get(), DestType
))
7853 // We don't check for e.g. function pointers here, since address
7854 // availability checks should only occur when the function first decays
7855 // into a pointer or reference.
7856 if (CurInit
.get()->getType()->isFunctionProtoType()) {
7857 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(CurInit
.get()->IgnoreParens())) {
7858 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl())) {
7859 if (!S
.checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
7860 DRE
->getBeginLoc()))
7866 CheckForNullPointerDereference(S
, CurInit
.get());
7869 case SK_BindReferenceToTemporary
: {
7870 // Make sure the "temporary" is actually an rvalue.
7871 assert(CurInit
.get()->isPRValue() && "not a temporary");
7873 // Check exception specifications
7874 if (S
.CheckExceptionSpecCompatibility(CurInit
.get(), DestType
))
7877 QualType MTETy
= Step
->Type
;
7879 // When this is an incomplete array type (such as when this is
7880 // initializing an array of unknown bounds from an init list), use THAT
7881 // type instead so that we propagate the array bounds.
7882 if (MTETy
->isIncompleteArrayType() &&
7883 !CurInit
.get()->getType()->isIncompleteArrayType() &&
7884 S
.Context
.hasSameType(
7885 MTETy
->getPointeeOrArrayElementType(),
7886 CurInit
.get()->getType()->getPointeeOrArrayElementType()))
7887 MTETy
= CurInit
.get()->getType();
7889 // Materialize the temporary into memory.
7890 MaterializeTemporaryExpr
*MTE
= S
.CreateMaterializeTemporaryExpr(
7891 MTETy
, CurInit
.get(), Entity
.getType()->isLValueReferenceType());
7894 // If we're extending this temporary to automatic storage duration -- we
7895 // need to register its cleanup during the full-expression's cleanups.
7896 if (MTE
->getStorageDuration() == SD_Automatic
&&
7897 MTE
->getType().isDestructedType())
7898 S
.Cleanup
.setExprNeedsCleanups(true);
7903 if (checkAbstractType(Step
->Type
))
7906 // If the overall initialization is initializing a temporary, we already
7907 // bound our argument if it was necessary to do so. If not (if we're
7908 // ultimately initializing a non-temporary), our argument needs to be
7909 // bound since it's initializing a function parameter.
7910 // FIXME: This is a mess. Rationalize temporary destruction.
7911 if (!shouldBindAsTemporary(Entity
))
7912 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
7913 CurInit
= CopyObject(S
, Step
->Type
, Entity
, CurInit
,
7914 /*IsExtraneousCopy=*/false);
7917 case SK_ExtraneousCopyToTemporary
:
7918 CurInit
= CopyObject(S
, Step
->Type
, Entity
, CurInit
,
7919 /*IsExtraneousCopy=*/true);
7922 case SK_UserConversion
: {
7923 // We have a user-defined conversion that invokes either a constructor
7924 // or a conversion function.
7926 FunctionDecl
*Fn
= Step
->Function
.Function
;
7927 DeclAccessPair FoundFn
= Step
->Function
.FoundDecl
;
7928 bool HadMultipleCandidates
= Step
->Function
.HadMultipleCandidates
;
7929 bool CreatedObject
= false;
7930 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Fn
)) {
7931 // Build a call to the selected constructor.
7932 SmallVector
<Expr
*, 8> ConstructorArgs
;
7933 SourceLocation Loc
= CurInit
.get()->getBeginLoc();
7935 // Determine the arguments required to actually perform the constructor
7937 Expr
*Arg
= CurInit
.get();
7938 if (S
.CompleteConstructorCall(Constructor
, Step
->Type
,
7939 MultiExprArg(&Arg
, 1), Loc
,
7943 // Build an expression that constructs a temporary.
7944 CurInit
= S
.BuildCXXConstructExpr(
7945 Loc
, Step
->Type
, FoundFn
, Constructor
, ConstructorArgs
,
7946 HadMultipleCandidates
,
7948 /*StdInitListInit*/ false,
7949 /*ZeroInit*/ false, CXXConstructionKind::Complete
, SourceRange());
7950 if (CurInit
.isInvalid())
7953 S
.CheckConstructorAccess(Kind
.getLocation(), Constructor
, FoundFn
,
7955 if (S
.DiagnoseUseOfDecl(FoundFn
, Kind
.getLocation()))
7958 CastKind
= CK_ConstructorConversion
;
7959 CreatedObject
= true;
7961 // Build a call to the conversion function.
7962 CXXConversionDecl
*Conversion
= cast
<CXXConversionDecl
>(Fn
);
7963 S
.CheckMemberOperatorAccess(Kind
.getLocation(), CurInit
.get(), nullptr,
7965 if (S
.DiagnoseUseOfDecl(FoundFn
, Kind
.getLocation()))
7968 CurInit
= S
.BuildCXXMemberCallExpr(CurInit
.get(), FoundFn
, Conversion
,
7969 HadMultipleCandidates
);
7970 if (CurInit
.isInvalid())
7973 CastKind
= CK_UserDefinedConversion
;
7974 CreatedObject
= Conversion
->getReturnType()->isRecordType();
7977 if (CreatedObject
&& checkAbstractType(CurInit
.get()->getType()))
7980 CurInit
= ImplicitCastExpr::Create(
7981 S
.Context
, CurInit
.get()->getType(), CastKind
, CurInit
.get(), nullptr,
7982 CurInit
.get()->getValueKind(), S
.CurFPFeatureOverrides());
7984 if (shouldBindAsTemporary(Entity
))
7985 // The overall entity is temporary, so this expression should be
7986 // destroyed at the end of its full-expression.
7987 CurInit
= S
.MaybeBindToTemporary(CurInit
.getAs
<Expr
>());
7988 else if (CreatedObject
&& shouldDestroyEntity(Entity
)) {
7989 // The object outlasts the full-expression, but we need to prepare for
7990 // a destructor being run on it.
7991 // FIXME: It makes no sense to do this here. This should happen
7992 // regardless of how we initialized the entity.
7993 QualType T
= CurInit
.get()->getType();
7994 if (const RecordType
*Record
= T
->getAs
<RecordType
>()) {
7995 CXXDestructorDecl
*Destructor
7996 = S
.LookupDestructor(cast
<CXXRecordDecl
>(Record
->getDecl()));
7997 S
.CheckDestructorAccess(CurInit
.get()->getBeginLoc(), Destructor
,
7998 S
.PDiag(diag::err_access_dtor_temp
) << T
);
7999 S
.MarkFunctionReferenced(CurInit
.get()->getBeginLoc(), Destructor
);
8000 if (S
.DiagnoseUseOfDecl(Destructor
, CurInit
.get()->getBeginLoc()))
8007 case SK_QualificationConversionLValue
:
8008 case SK_QualificationConversionXValue
:
8009 case SK_QualificationConversionPRValue
: {
8010 // Perform a qualification conversion; these can never go wrong.
8012 Step
->Kind
== SK_QualificationConversionLValue
8014 : (Step
->Kind
== SK_QualificationConversionXValue
? VK_XValue
8016 CurInit
= S
.PerformQualificationConversion(CurInit
.get(), Step
->Type
, VK
);
8020 case SK_FunctionReferenceConversion
:
8021 assert(CurInit
.get()->isLValue() &&
8022 "function reference should be lvalue");
8024 S
.ImpCastExprToType(CurInit
.get(), Step
->Type
, CK_NoOp
, VK_LValue
);
8027 case SK_AtomicConversion
: {
8028 assert(CurInit
.get()->isPRValue() && "cannot convert glvalue to atomic");
8029 CurInit
= S
.ImpCastExprToType(CurInit
.get(), Step
->Type
,
8030 CK_NonAtomicToAtomic
, VK_PRValue
);
8034 case SK_ConversionSequence
:
8035 case SK_ConversionSequenceNoNarrowing
: {
8036 if (const auto *FromPtrType
=
8037 CurInit
.get()->getType()->getAs
<PointerType
>()) {
8038 if (const auto *ToPtrType
= Step
->Type
->getAs
<PointerType
>()) {
8039 if (FromPtrType
->getPointeeType()->hasAttr(attr::NoDeref
) &&
8040 !ToPtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
8041 // Do not check static casts here because they are checked earlier
8042 // in Sema::ActOnCXXNamedCast()
8043 if (!Kind
.isStaticCast()) {
8044 S
.Diag(CurInit
.get()->getExprLoc(),
8045 diag::warn_noderef_to_dereferenceable_pointer
)
8046 << CurInit
.get()->getSourceRange();
8051 Expr
*Init
= CurInit
.get();
8052 CheckedConversionKind CCK
=
8053 Kind
.isCStyleCast() ? CheckedConversionKind::CStyleCast
8054 : Kind
.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8055 : Kind
.isExplicitCast() ? CheckedConversionKind::OtherCast
8056 : CheckedConversionKind::Implicit
;
8057 ExprResult CurInitExprRes
= S
.PerformImplicitConversion(
8058 Init
, Step
->Type
, *Step
->ICS
, getAssignmentAction(Entity
), CCK
);
8059 if (CurInitExprRes
.isInvalid())
8062 S
.DiscardMisalignedMemberAddress(Step
->Type
.getTypePtr(), Init
);
8064 CurInit
= CurInitExprRes
;
8066 if (Step
->Kind
== SK_ConversionSequenceNoNarrowing
&&
8067 S
.getLangOpts().CPlusPlus
)
8068 DiagnoseNarrowingInInitList(S
, *Step
->ICS
, SourceType
, Entity
.getType(),
8074 case SK_ListInitialization
: {
8075 if (checkAbstractType(Step
->Type
))
8078 InitListExpr
*InitList
= cast
<InitListExpr
>(CurInit
.get());
8079 // If we're not initializing the top-level entity, we need to create an
8080 // InitializeTemporary entity for our target type.
8081 QualType Ty
= Step
->Type
;
8082 bool IsTemporary
= !S
.Context
.hasSameType(Entity
.getType(), Ty
);
8083 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(Ty
);
8084 InitializedEntity InitEntity
= IsTemporary
? TempEntity
: Entity
;
8085 InitListChecker
PerformInitList(S
, InitEntity
,
8086 InitList
, Ty
, /*VerifyOnly=*/false,
8087 /*TreatUnavailableAsInvalid=*/false);
8088 if (PerformInitList
.HadError())
8091 // Hack: We must update *ResultType if available in order to set the
8092 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8093 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8095 ResultType
->getNonReferenceType()->isIncompleteArrayType()) {
8096 if ((*ResultType
)->isRValueReferenceType())
8097 Ty
= S
.Context
.getRValueReferenceType(Ty
);
8098 else if ((*ResultType
)->isLValueReferenceType())
8099 Ty
= S
.Context
.getLValueReferenceType(Ty
,
8100 (*ResultType
)->castAs
<LValueReferenceType
>()->isSpelledAsLValue());
8104 InitListExpr
*StructuredInitList
=
8105 PerformInitList
.getFullyStructuredList();
8107 CurInit
= shouldBindAsTemporary(InitEntity
)
8108 ? S
.MaybeBindToTemporary(StructuredInitList
)
8109 : StructuredInitList
;
8113 case SK_ConstructorInitializationFromList
: {
8114 if (checkAbstractType(Step
->Type
))
8117 // When an initializer list is passed for a parameter of type "reference
8118 // to object", we don't get an EK_Temporary entity, but instead an
8119 // EK_Parameter entity with reference type.
8120 // FIXME: This is a hack. What we really should do is create a user
8121 // conversion step for this case, but this makes it considerably more
8122 // complicated. For now, this will do.
8123 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(
8124 Entity
.getType().getNonReferenceType());
8125 bool UseTemporary
= Entity
.getType()->isReferenceType();
8126 assert(Args
.size() == 1 && "expected a single argument for list init");
8127 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
8128 S
.Diag(InitList
->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init
)
8129 << InitList
->getSourceRange();
8130 MultiExprArg
Arg(InitList
->getInits(), InitList
->getNumInits());
8131 CurInit
= PerformConstructorInitialization(S
, UseTemporary
? TempEntity
:
8134 ConstructorInitRequiresZeroInit
,
8135 /*IsListInitialization*/true,
8136 /*IsStdInitListInit*/false,
8137 InitList
->getLBraceLoc(),
8138 InitList
->getRBraceLoc());
8142 case SK_UnwrapInitList
:
8143 CurInit
= cast
<InitListExpr
>(CurInit
.get())->getInit(0);
8146 case SK_RewrapInitList
: {
8147 Expr
*E
= CurInit
.get();
8148 InitListExpr
*Syntactic
= Step
->WrappingSyntacticList
;
8149 InitListExpr
*ILE
= new (S
.Context
) InitListExpr(S
.Context
,
8150 Syntactic
->getLBraceLoc(), E
, Syntactic
->getRBraceLoc());
8151 ILE
->setSyntacticForm(Syntactic
);
8152 ILE
->setType(E
->getType());
8153 ILE
->setValueKind(E
->getValueKind());
8158 case SK_ConstructorInitialization
:
8159 case SK_StdInitializerListConstructorCall
: {
8160 if (checkAbstractType(Step
->Type
))
8163 // When an initializer list is passed for a parameter of type "reference
8164 // to object", we don't get an EK_Temporary entity, but instead an
8165 // EK_Parameter entity with reference type.
8166 // FIXME: This is a hack. What we really should do is create a user
8167 // conversion step for this case, but this makes it considerably more
8168 // complicated. For now, this will do.
8169 InitializedEntity TempEntity
= InitializedEntity::InitializeTemporary(
8170 Entity
.getType().getNonReferenceType());
8171 bool UseTemporary
= Entity
.getType()->isReferenceType();
8172 bool IsStdInitListInit
=
8173 Step
->Kind
== SK_StdInitializerListConstructorCall
;
8174 Expr
*Source
= CurInit
.get();
8175 SourceRange Range
= Kind
.hasParenOrBraceRange()
8176 ? Kind
.getParenOrBraceRange()
8178 CurInit
= PerformConstructorInitialization(
8179 S
, UseTemporary
? TempEntity
: Entity
, Kind
,
8180 Source
? MultiExprArg(Source
) : Args
, *Step
,
8181 ConstructorInitRequiresZeroInit
,
8182 /*IsListInitialization*/ IsStdInitListInit
,
8183 /*IsStdInitListInitialization*/ IsStdInitListInit
,
8184 /*LBraceLoc*/ Range
.getBegin(),
8185 /*RBraceLoc*/ Range
.getEnd());
8189 case SK_ZeroInitialization
: {
8190 step_iterator NextStep
= Step
;
8192 if (NextStep
!= StepEnd
&&
8193 (NextStep
->Kind
== SK_ConstructorInitialization
||
8194 NextStep
->Kind
== SK_ConstructorInitializationFromList
)) {
8195 // The need for zero-initialization is recorded directly into
8196 // the call to the object's constructor within the next step.
8197 ConstructorInitRequiresZeroInit
= true;
8198 } else if (Kind
.getKind() == InitializationKind::IK_Value
&&
8199 S
.getLangOpts().CPlusPlus
&&
8200 !Kind
.isImplicitValueInit()) {
8201 TypeSourceInfo
*TSInfo
= Entity
.getTypeSourceInfo();
8203 TSInfo
= S
.Context
.getTrivialTypeSourceInfo(Step
->Type
,
8204 Kind
.getRange().getBegin());
8206 CurInit
= new (S
.Context
) CXXScalarValueInitExpr(
8207 Entity
.getType().getNonLValueExprType(S
.Context
), TSInfo
,
8208 Kind
.getRange().getEnd());
8210 CurInit
= new (S
.Context
) ImplicitValueInitExpr(Step
->Type
);
8215 case SK_CAssignment
: {
8216 QualType SourceType
= CurInit
.get()->getType();
8217 Expr
*Init
= CurInit
.get();
8219 // Save off the initial CurInit in case we need to emit a diagnostic
8220 ExprResult InitialCurInit
= Init
;
8221 ExprResult Result
= Init
;
8222 Sema::AssignConvertType ConvTy
=
8223 S
.CheckSingleAssignmentConstraints(Step
->Type
, Result
, true,
8224 Entity
.getKind() == InitializedEntity::EK_Parameter_CF_Audited
);
8225 if (Result
.isInvalid())
8229 // If this is a call, allow conversion to a transparent union.
8230 ExprResult CurInitExprRes
= CurInit
;
8231 if (ConvTy
!= Sema::Compatible
&&
8232 Entity
.isParameterKind() &&
8233 S
.CheckTransparentUnionArgumentConstraints(Step
->Type
, CurInitExprRes
)
8234 == Sema::Compatible
)
8235 ConvTy
= Sema::Compatible
;
8236 if (CurInitExprRes
.isInvalid())
8238 CurInit
= CurInitExprRes
;
8240 if (S
.getLangOpts().C23
&& initializingConstexprVariable(Entity
)) {
8241 CheckC23ConstexprInitConversion(S
, SourceType
, Entity
.getType(),
8244 // C23 6.7.1p6: If an object or subobject declared with storage-class
8245 // specifier constexpr has pointer, integer, or arithmetic type, any
8246 // explicit initializer value for it shall be null, an integer
8247 // constant expression, or an arithmetic constant expression,
8249 Expr::EvalResult ER
;
8250 if (Entity
.getType()->getAs
<PointerType
>() &&
8251 CurInit
.get()->EvaluateAsRValue(ER
, S
.Context
) &&
8252 !ER
.Val
.isNullPointer()) {
8253 S
.Diag(Kind
.getLocation(), diag::err_c23_constexpr_pointer_not_null
);
8258 if (S
.DiagnoseAssignmentResult(ConvTy
, Kind
.getLocation(),
8259 Step
->Type
, SourceType
,
8260 InitialCurInit
.get(),
8261 getAssignmentAction(Entity
, true),
8263 PrintInitLocationNote(S
, Entity
);
8265 } else if (Complained
)
8266 PrintInitLocationNote(S
, Entity
);
8270 case SK_StringInit
: {
8271 QualType Ty
= Step
->Type
;
8272 bool UpdateType
= ResultType
&& Entity
.getType()->isIncompleteArrayType();
8273 CheckStringInit(CurInit
.get(), UpdateType
? *ResultType
: Ty
,
8274 S
.Context
.getAsArrayType(Ty
), S
,
8275 S
.getLangOpts().C23
&&
8276 initializingConstexprVariable(Entity
));
8280 case SK_ObjCObjectConversion
:
8281 CurInit
= S
.ImpCastExprToType(CurInit
.get(), Step
->Type
,
8282 CK_ObjCObjectLValueCast
,
8283 CurInit
.get()->getValueKind());
8286 case SK_ArrayLoopIndex
: {
8287 Expr
*Cur
= CurInit
.get();
8288 Expr
*BaseExpr
= new (S
.Context
)
8289 OpaqueValueExpr(Cur
->getExprLoc(), Cur
->getType(),
8290 Cur
->getValueKind(), Cur
->getObjectKind(), Cur
);
8292 new (S
.Context
) ArrayInitIndexExpr(S
.Context
.getSizeType());
8293 CurInit
= S
.CreateBuiltinArraySubscriptExpr(
8294 BaseExpr
, Kind
.getLocation(), IndexExpr
, Kind
.getLocation());
8295 ArrayLoopCommonExprs
.push_back(BaseExpr
);
8299 case SK_ArrayLoopInit
: {
8300 assert(!ArrayLoopCommonExprs
.empty() &&
8301 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8302 Expr
*Common
= ArrayLoopCommonExprs
.pop_back_val();
8303 CurInit
= new (S
.Context
) ArrayInitLoopExpr(Step
->Type
, Common
,
8308 case SK_GNUArrayInit
:
8309 // Okay: we checked everything before creating this step. Note that
8310 // this is a GNU extension.
8311 S
.Diag(Kind
.getLocation(), diag::ext_array_init_copy
)
8312 << Step
->Type
<< CurInit
.get()->getType()
8313 << CurInit
.get()->getSourceRange();
8314 updateGNUCompoundLiteralRValue(CurInit
.get());
8317 // If the destination type is an incomplete array type, update the
8318 // type accordingly.
8320 if (const IncompleteArrayType
*IncompleteDest
8321 = S
.Context
.getAsIncompleteArrayType(Step
->Type
)) {
8322 if (const ConstantArrayType
*ConstantSource
8323 = S
.Context
.getAsConstantArrayType(CurInit
.get()->getType())) {
8324 *ResultType
= S
.Context
.getConstantArrayType(
8325 IncompleteDest
->getElementType(), ConstantSource
->getSize(),
8326 ConstantSource
->getSizeExpr(), ArraySizeModifier::Normal
, 0);
8332 case SK_ParenthesizedArrayInit
:
8333 // Okay: we checked everything before creating this step. Note that
8334 // this is a GNU extension.
8335 S
.Diag(Kind
.getLocation(), diag::ext_array_init_parens
)
8336 << CurInit
.get()->getSourceRange();
8339 case SK_PassByIndirectCopyRestore
:
8340 case SK_PassByIndirectRestore
:
8341 checkIndirectCopyRestoreSource(S
, CurInit
.get());
8342 CurInit
= new (S
.Context
) ObjCIndirectCopyRestoreExpr(
8343 CurInit
.get(), Step
->Type
,
8344 Step
->Kind
== SK_PassByIndirectCopyRestore
);
8347 case SK_ProduceObjCObject
:
8348 CurInit
= ImplicitCastExpr::Create(
8349 S
.Context
, Step
->Type
, CK_ARCProduceObject
, CurInit
.get(), nullptr,
8350 VK_PRValue
, FPOptionsOverride());
8353 case SK_StdInitializerList
: {
8354 S
.Diag(CurInit
.get()->getExprLoc(),
8355 diag::warn_cxx98_compat_initializer_list_init
)
8356 << CurInit
.get()->getSourceRange();
8358 // Materialize the temporary into memory.
8359 MaterializeTemporaryExpr
*MTE
= S
.CreateMaterializeTemporaryExpr(
8360 CurInit
.get()->getType(), CurInit
.get(),
8361 /*BoundToLvalueReference=*/false);
8363 // Wrap it in a construction of a std::initializer_list<T>.
8364 CurInit
= new (S
.Context
) CXXStdInitializerListExpr(Step
->Type
, MTE
);
8366 if (!Step
->Type
->isDependentType()) {
8367 QualType ElementType
;
8368 [[maybe_unused
]] bool IsStdInitializerList
=
8369 S
.isStdInitializerList(Step
->Type
, &ElementType
);
8370 assert(IsStdInitializerList
&&
8371 "StdInitializerList step to non-std::initializer_list");
8372 const CXXRecordDecl
*Record
=
8373 Step
->Type
->getAsCXXRecordDecl()->getDefinition();
8374 assert(Record
&& Record
->isCompleteDefinition() &&
8375 "std::initializer_list should have already be "
8376 "complete/instantiated by this point");
8378 auto InvalidType
= [&] {
8379 S
.Diag(Record
->getLocation(),
8380 diag::err_std_initializer_list_malformed
)
8381 << Step
->Type
.getUnqualifiedType();
8385 if (Record
->isUnion() || Record
->getNumBases() != 0 ||
8386 Record
->isPolymorphic())
8387 return InvalidType();
8389 RecordDecl::field_iterator Field
= Record
->field_begin();
8390 if (Field
== Record
->field_end())
8391 return InvalidType();
8394 if (!Field
->getType()->isPointerType() ||
8395 !S
.Context
.hasSameType(Field
->getType()->getPointeeType(),
8396 ElementType
.withConst()))
8397 return InvalidType();
8399 if (++Field
== Record
->field_end())
8400 return InvalidType();
8402 // Size or end pointer
8403 if (const auto *PT
= Field
->getType()->getAs
<PointerType
>()) {
8404 if (!S
.Context
.hasSameType(PT
->getPointeeType(),
8405 ElementType
.withConst()))
8406 return InvalidType();
8408 if (Field
->isBitField() ||
8409 !S
.Context
.hasSameType(Field
->getType(), S
.Context
.getSizeType()))
8410 return InvalidType();
8413 if (++Field
!= Record
->field_end())
8414 return InvalidType();
8417 // Bind the result, in case the library has given initializer_list a
8418 // non-trivial destructor.
8419 if (shouldBindAsTemporary(Entity
))
8420 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
8424 case SK_OCLSamplerInit
: {
8425 // Sampler initialization have 5 cases:
8426 // 1. function argument passing
8427 // 1a. argument is a file-scope variable
8428 // 1b. argument is a function-scope variable
8429 // 1c. argument is one of caller function's parameters
8430 // 2. variable initialization
8431 // 2a. initializing a file-scope variable
8432 // 2b. initializing a function-scope variable
8434 // For file-scope variables, since they cannot be initialized by function
8435 // call of __translate_sampler_initializer in LLVM IR, their references
8436 // need to be replaced by a cast from their literal initializers to
8437 // sampler type. Since sampler variables can only be used in function
8438 // calls as arguments, we only need to replace them when handling the
8439 // argument passing.
8440 assert(Step
->Type
->isSamplerT() &&
8441 "Sampler initialization on non-sampler type.");
8442 Expr
*Init
= CurInit
.get()->IgnoreParens();
8443 QualType SourceType
= Init
->getType();
8445 if (Entity
.isParameterKind()) {
8446 if (!SourceType
->isSamplerT() && !SourceType
->isIntegerType()) {
8447 S
.Diag(Kind
.getLocation(), diag::err_sampler_argument_required
)
8450 } else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Init
)) {
8451 auto Var
= cast
<VarDecl
>(DRE
->getDecl());
8453 // No cast from integer to sampler is needed.
8454 if (!Var
->hasGlobalStorage()) {
8455 CurInit
= ImplicitCastExpr::Create(
8456 S
.Context
, Step
->Type
, CK_LValueToRValue
, Init
,
8457 /*BasePath=*/nullptr, VK_PRValue
, FPOptionsOverride());
8461 // For function call with a file-scope sampler variable as argument,
8462 // get the integer literal.
8463 // Do not diagnose if the file-scope variable does not have initializer
8464 // since this has already been diagnosed when parsing the variable
8466 if (!Var
->getInit() || !isa
<ImplicitCastExpr
>(Var
->getInit()))
8468 Init
= cast
<ImplicitCastExpr
>(const_cast<Expr
*>(
8469 Var
->getInit()))->getSubExpr();
8470 SourceType
= Init
->getType();
8474 // Check initializer is 32 bit integer constant.
8475 // If the initializer is taken from global variable, do not diagnose since
8476 // this has already been done when parsing the variable declaration.
8477 if (!Init
->isConstantInitializer(S
.Context
, false))
8480 if (!SourceType
->isIntegerType() ||
8481 32 != S
.Context
.getIntWidth(SourceType
)) {
8482 S
.Diag(Kind
.getLocation(), diag::err_sampler_initializer_not_integer
)
8487 Expr::EvalResult EVResult
;
8488 Init
->EvaluateAsInt(EVResult
, S
.Context
);
8489 llvm::APSInt Result
= EVResult
.Val
.getInt();
8490 const uint64_t SamplerValue
= Result
.getLimitedValue();
8491 // 32-bit value of sampler's initializer is interpreted as
8492 // bit-field with the following structure:
8493 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8494 // |31 6|5 4|3 1| 0|
8495 // This structure corresponds to enum values of sampler properties
8496 // defined in SPIR spec v1.2 and also opencl-c.h
8497 unsigned AddressingMode
= (0x0E & SamplerValue
) >> 1;
8498 unsigned FilterMode
= (0x30 & SamplerValue
) >> 4;
8499 if (FilterMode
!= 1 && FilterMode
!= 2 &&
8500 !S
.getOpenCLOptions().isAvailableOption(
8501 "cl_intel_device_side_avc_motion_estimation", S
.getLangOpts()))
8502 S
.Diag(Kind
.getLocation(),
8503 diag::warn_sampler_initializer_invalid_bits
)
8505 if (AddressingMode
> 4)
8506 S
.Diag(Kind
.getLocation(),
8507 diag::warn_sampler_initializer_invalid_bits
)
8508 << "Addressing Mode";
8511 // Cases 1a, 2a and 2b
8512 // Insert cast from integer to sampler.
8513 CurInit
= S
.ImpCastExprToType(Init
, S
.Context
.OCLSamplerTy
,
8514 CK_IntToOCLSampler
);
8517 case SK_OCLZeroOpaqueType
: {
8518 assert((Step
->Type
->isEventT() || Step
->Type
->isQueueT() ||
8519 Step
->Type
->isOCLIntelSubgroupAVCType()) &&
8520 "Wrong type for initialization of OpenCL opaque type.");
8522 CurInit
= S
.ImpCastExprToType(CurInit
.get(), Step
->Type
,
8523 CK_ZeroToOCLOpaqueType
,
8524 CurInit
.get()->getValueKind());
8527 case SK_ParenthesizedListInit
: {
8529 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
8530 /*VerifyOnly=*/false, &CurInit
);
8531 if (CurInit
.get() && ResultType
)
8532 *ResultType
= CurInit
.get()->getType();
8533 if (shouldBindAsTemporary(Entity
))
8534 CurInit
= S
.MaybeBindToTemporary(CurInit
.get());
8540 Expr
*Init
= CurInit
.get();
8544 // Check whether the initializer has a shorter lifetime than the initialized
8545 // entity, and if not, either lifetime-extend or warn as appropriate.
8546 S
.checkInitializerLifetime(Entity
, Init
);
8548 // Diagnose non-fatal problems with the completed initialization.
8549 if (InitializedEntity::EntityKind EK
= Entity
.getKind();
8550 (EK
== InitializedEntity::EK_Member
||
8551 EK
== InitializedEntity::EK_ParenAggInitMember
) &&
8552 cast
<FieldDecl
>(Entity
.getDecl())->isBitField())
8553 S
.CheckBitFieldInitialization(Kind
.getLocation(),
8554 cast
<FieldDecl
>(Entity
.getDecl()), Init
);
8556 // Check for std::move on construction.
8557 CheckMoveOnConstruction(S
, Init
,
8558 Entity
.getKind() == InitializedEntity::EK_Result
);
8563 /// Somewhere within T there is an uninitialized reference subobject.
8564 /// Dig it out and diagnose it.
8565 static bool DiagnoseUninitializedReference(Sema
&S
, SourceLocation Loc
,
8567 if (T
->isReferenceType()) {
8568 S
.Diag(Loc
, diag::err_reference_without_init
)
8569 << T
.getNonReferenceType();
8573 CXXRecordDecl
*RD
= T
->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8574 if (!RD
|| !RD
->hasUninitializedReferenceMember())
8577 for (const auto *FI
: RD
->fields()) {
8578 if (FI
->isUnnamedBitField())
8581 if (DiagnoseUninitializedReference(S
, FI
->getLocation(), FI
->getType())) {
8582 S
.Diag(Loc
, diag::note_value_initialization_here
) << RD
;
8587 for (const auto &BI
: RD
->bases()) {
8588 if (DiagnoseUninitializedReference(S
, BI
.getBeginLoc(), BI
.getType())) {
8589 S
.Diag(Loc
, diag::note_value_initialization_here
) << RD
;
8598 //===----------------------------------------------------------------------===//
8599 // Diagnose initialization failures
8600 //===----------------------------------------------------------------------===//
8602 /// Emit notes associated with an initialization that failed due to a
8603 /// "simple" conversion failure.
8604 static void emitBadConversionNotes(Sema
&S
, const InitializedEntity
&entity
,
8606 QualType destType
= entity
.getType();
8607 if (destType
.getNonReferenceType()->isObjCObjectPointerType() &&
8608 op
->getType()->isObjCObjectPointerType()) {
8610 // Emit a possible note about the conversion failing because the
8611 // operand is a message send with a related result type.
8612 S
.ObjC().EmitRelatedResultTypeNote(op
);
8614 // Emit a possible note about a return failing because we're
8615 // expecting a related result type.
8616 if (entity
.getKind() == InitializedEntity::EK_Result
)
8617 S
.ObjC().EmitRelatedResultTypeNoteForReturn(destType
);
8619 QualType fromType
= op
->getType();
8620 QualType fromPointeeType
= fromType
.getCanonicalType()->getPointeeType();
8621 QualType destPointeeType
= destType
.getCanonicalType()->getPointeeType();
8622 auto *fromDecl
= fromType
->getPointeeCXXRecordDecl();
8623 auto *destDecl
= destType
->getPointeeCXXRecordDecl();
8624 if (fromDecl
&& destDecl
&& fromDecl
->getDeclKind() == Decl::CXXRecord
&&
8625 destDecl
->getDeclKind() == Decl::CXXRecord
&&
8626 !fromDecl
->isInvalidDecl() && !destDecl
->isInvalidDecl() &&
8627 !fromDecl
->hasDefinition() &&
8628 destPointeeType
.getQualifiers().compatiblyIncludes(
8629 fromPointeeType
.getQualifiers(), S
.getASTContext()))
8630 S
.Diag(fromDecl
->getLocation(), diag::note_forward_class_conversion
)
8631 << S
.getASTContext().getTagDeclType(fromDecl
)
8632 << S
.getASTContext().getTagDeclType(destDecl
);
8635 static void diagnoseListInit(Sema
&S
, const InitializedEntity
&Entity
,
8636 InitListExpr
*InitList
) {
8637 QualType DestType
= Entity
.getType();
8640 if (S
.getLangOpts().CPlusPlus11
&& S
.isStdInitializerList(DestType
, &E
)) {
8641 QualType ArrayType
= S
.Context
.getConstantArrayType(
8643 llvm::APInt(S
.Context
.getTypeSize(S
.Context
.getSizeType()),
8644 InitList
->getNumInits()),
8645 nullptr, clang::ArraySizeModifier::Normal
, 0);
8646 InitializedEntity HiddenArray
=
8647 InitializedEntity::InitializeTemporary(ArrayType
);
8648 return diagnoseListInit(S
, HiddenArray
, InitList
);
8651 if (DestType
->isReferenceType()) {
8652 // A list-initialization failure for a reference means that we tried to
8653 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8654 // inner initialization failed.
8655 QualType T
= DestType
->castAs
<ReferenceType
>()->getPointeeType();
8656 diagnoseListInit(S
, InitializedEntity::InitializeTemporary(T
), InitList
);
8657 SourceLocation Loc
= InitList
->getBeginLoc();
8658 if (auto *D
= Entity
.getDecl())
8659 Loc
= D
->getLocation();
8660 S
.Diag(Loc
, diag::note_in_reference_temporary_list_initializer
) << T
;
8664 InitListChecker
DiagnoseInitList(S
, Entity
, InitList
, DestType
,
8665 /*VerifyOnly=*/false,
8666 /*TreatUnavailableAsInvalid=*/false);
8667 assert(DiagnoseInitList
.HadError() &&
8668 "Inconsistent init list check result.");
8671 bool InitializationSequence::Diagnose(Sema
&S
,
8672 const InitializedEntity
&Entity
,
8673 const InitializationKind
&Kind
,
8674 ArrayRef
<Expr
*> Args
) {
8678 QualType DestType
= Entity
.getType();
8680 // When we want to diagnose only one element of a braced-init-list,
8681 // we need to factor it out.
8683 if (Args
.size() == 1) {
8684 auto *List
= dyn_cast
<InitListExpr
>(Args
[0]);
8685 if (List
&& List
->getNumInits() == 1)
8686 OnlyArg
= List
->getInit(0);
8690 if (OnlyArg
->getType() == S
.Context
.OverloadTy
) {
8691 DeclAccessPair Found
;
8692 if (FunctionDecl
*FD
= S
.ResolveAddressOfOverloadedFunction(
8693 OnlyArg
, DestType
.getNonReferenceType(), /*Complain=*/false,
8695 if (Expr
*Resolved
=
8696 S
.FixOverloadedFunctionReference(OnlyArg
, Found
, FD
).get())
8705 case FK_TooManyInitsForReference
:
8706 // FIXME: Customize for the initialized entity?
8708 // Dig out the reference subobject which is uninitialized and diagnose it.
8709 // If this is value-initialization, this could be nested some way within
8711 assert(Kind
.getKind() == InitializationKind::IK_Value
||
8712 DestType
->isReferenceType());
8714 DiagnoseUninitializedReference(S
, Kind
.getLocation(), DestType
);
8715 assert(Diagnosed
&& "couldn't find uninitialized reference to diagnose");
8717 } else // FIXME: diagnostic below could be better!
8718 S
.Diag(Kind
.getLocation(), diag::err_reference_has_multiple_inits
)
8719 << SourceRange(Args
.front()->getBeginLoc(), Args
.back()->getEndLoc());
8721 case FK_ParenthesizedListInitForReference
:
8722 S
.Diag(Kind
.getLocation(), diag::err_list_init_in_parens
)
8723 << 1 << Entity
.getType() << Args
[0]->getSourceRange();
8726 case FK_ArrayNeedsInitList
:
8727 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
) << 0;
8729 case FK_ArrayNeedsInitListOrStringLiteral
:
8730 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
) << 1;
8732 case FK_ArrayNeedsInitListOrWideStringLiteral
:
8733 S
.Diag(Kind
.getLocation(), diag::err_array_init_not_init_list
) << 2;
8735 case FK_NarrowStringIntoWideCharArray
:
8736 S
.Diag(Kind
.getLocation(), diag::err_array_init_narrow_string_into_wchar
);
8738 case FK_WideStringIntoCharArray
:
8739 S
.Diag(Kind
.getLocation(), diag::err_array_init_wide_string_into_char
);
8741 case FK_IncompatWideStringIntoWideChar
:
8742 S
.Diag(Kind
.getLocation(),
8743 diag::err_array_init_incompat_wide_string_into_wchar
);
8745 case FK_PlainStringIntoUTF8Char
:
8746 S
.Diag(Kind
.getLocation(),
8747 diag::err_array_init_plain_string_into_char8_t
);
8748 S
.Diag(Args
.front()->getBeginLoc(),
8749 diag::note_array_init_plain_string_into_char8_t
)
8750 << FixItHint::CreateInsertion(Args
.front()->getBeginLoc(), "u8");
8752 case FK_UTF8StringIntoPlainChar
:
8753 S
.Diag(Kind
.getLocation(), diag::err_array_init_utf8_string_into_char
)
8754 << DestType
->isSignedIntegerType() << S
.getLangOpts().CPlusPlus20
;
8756 case FK_ArrayTypeMismatch
:
8757 case FK_NonConstantArrayInit
:
8758 S
.Diag(Kind
.getLocation(),
8759 (Failure
== FK_ArrayTypeMismatch
8760 ? diag::err_array_init_different_type
8761 : diag::err_array_init_non_constant_array
))
8762 << DestType
.getNonReferenceType()
8763 << OnlyArg
->getType()
8764 << Args
[0]->getSourceRange();
8767 case FK_VariableLengthArrayHasInitializer
:
8768 S
.Diag(Kind
.getLocation(), diag::err_variable_object_no_init
)
8769 << Args
[0]->getSourceRange();
8772 case FK_AddressOfOverloadFailed
: {
8773 DeclAccessPair Found
;
8774 S
.ResolveAddressOfOverloadedFunction(OnlyArg
,
8775 DestType
.getNonReferenceType(),
8781 case FK_AddressOfUnaddressableFunction
: {
8782 auto *FD
= cast
<FunctionDecl
>(cast
<DeclRefExpr
>(OnlyArg
)->getDecl());
8783 S
.checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
8784 OnlyArg
->getBeginLoc());
8788 case FK_ReferenceInitOverloadFailed
:
8789 case FK_UserConversionOverloadFailed
:
8790 switch (FailedOverloadResult
) {
8793 FailedCandidateSet
.NoteCandidates(
8794 PartialDiagnosticAt(
8796 Failure
== FK_UserConversionOverloadFailed
8797 ? (S
.PDiag(diag::err_typecheck_ambiguous_condition
)
8798 << OnlyArg
->getType() << DestType
8799 << Args
[0]->getSourceRange())
8800 : (S
.PDiag(diag::err_ref_init_ambiguous
)
8801 << DestType
<< OnlyArg
->getType()
8802 << Args
[0]->getSourceRange())),
8803 S
, OCD_AmbiguousCandidates
, Args
);
8806 case OR_No_Viable_Function
: {
8807 auto Cands
= FailedCandidateSet
.CompleteCandidates(S
, OCD_AllCandidates
, Args
);
8808 if (!S
.RequireCompleteType(Kind
.getLocation(),
8809 DestType
.getNonReferenceType(),
8810 diag::err_typecheck_nonviable_condition_incomplete
,
8811 OnlyArg
->getType(), Args
[0]->getSourceRange()))
8812 S
.Diag(Kind
.getLocation(), diag::err_typecheck_nonviable_condition
)
8813 << (Entity
.getKind() == InitializedEntity::EK_Result
)
8814 << OnlyArg
->getType() << Args
[0]->getSourceRange()
8815 << DestType
.getNonReferenceType();
8817 FailedCandidateSet
.NoteCandidates(S
, Args
, Cands
);
8821 OverloadCandidateSet::iterator Best
;
8822 OverloadingResult Ovl
8823 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
8825 StringLiteral
*Msg
= Best
->Function
->getDeletedMessage();
8826 S
.Diag(Kind
.getLocation(), diag::err_typecheck_deleted_function
)
8827 << OnlyArg
->getType() << DestType
.getNonReferenceType()
8828 << (Msg
!= nullptr) << (Msg
? Msg
->getString() : StringRef())
8829 << Args
[0]->getSourceRange();
8830 if (Ovl
== OR_Deleted
) {
8831 S
.NoteDeletedFunction(Best
->Function
);
8833 llvm_unreachable("Inconsistent overload resolution?");
8839 llvm_unreachable("Conversion did not fail!");
8843 case FK_NonConstLValueReferenceBindingToTemporary
:
8844 if (isa
<InitListExpr
>(Args
[0])) {
8845 S
.Diag(Kind
.getLocation(),
8846 diag::err_lvalue_reference_bind_to_initlist
)
8847 << DestType
.getNonReferenceType().isVolatileQualified()
8848 << DestType
.getNonReferenceType()
8849 << Args
[0]->getSourceRange();
8854 case FK_NonConstLValueReferenceBindingToUnrelated
:
8855 S
.Diag(Kind
.getLocation(),
8856 Failure
== FK_NonConstLValueReferenceBindingToTemporary
8857 ? diag::err_lvalue_reference_bind_to_temporary
8858 : diag::err_lvalue_reference_bind_to_unrelated
)
8859 << DestType
.getNonReferenceType().isVolatileQualified()
8860 << DestType
.getNonReferenceType()
8861 << OnlyArg
->getType()
8862 << Args
[0]->getSourceRange();
8865 case FK_NonConstLValueReferenceBindingToBitfield
: {
8866 // We don't necessarily have an unambiguous source bit-field.
8867 FieldDecl
*BitField
= Args
[0]->getSourceBitField();
8868 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_bitfield
)
8869 << DestType
.isVolatileQualified()
8870 << (BitField
? BitField
->getDeclName() : DeclarationName())
8871 << (BitField
!= nullptr)
8872 << Args
[0]->getSourceRange();
8874 S
.Diag(BitField
->getLocation(), diag::note_bitfield_decl
);
8878 case FK_NonConstLValueReferenceBindingToVectorElement
:
8879 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_vector_element
)
8880 << DestType
.isVolatileQualified()
8881 << Args
[0]->getSourceRange();
8884 case FK_NonConstLValueReferenceBindingToMatrixElement
:
8885 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_to_matrix_element
)
8886 << DestType
.isVolatileQualified() << Args
[0]->getSourceRange();
8889 case FK_RValueReferenceBindingToLValue
:
8890 S
.Diag(Kind
.getLocation(), diag::err_lvalue_to_rvalue_ref
)
8891 << DestType
.getNonReferenceType() << OnlyArg
->getType()
8892 << Args
[0]->getSourceRange();
8895 case FK_ReferenceAddrspaceMismatchTemporary
:
8896 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_temporary_addrspace
)
8897 << DestType
<< Args
[0]->getSourceRange();
8900 case FK_ReferenceInitDropsQualifiers
: {
8901 QualType SourceType
= OnlyArg
->getType();
8902 QualType NonRefType
= DestType
.getNonReferenceType();
8903 Qualifiers DroppedQualifiers
=
8904 SourceType
.getQualifiers() - NonRefType
.getQualifiers();
8906 if (!NonRefType
.getQualifiers().isAddressSpaceSupersetOf(
8907 SourceType
.getQualifiers(), S
.getASTContext()))
8908 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
8909 << NonRefType
<< SourceType
<< 1 /*addr space*/
8910 << Args
[0]->getSourceRange();
8911 else if (DroppedQualifiers
.hasQualifiers())
8912 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
8913 << NonRefType
<< SourceType
<< 0 /*cv quals*/
8914 << Qualifiers::fromCVRMask(DroppedQualifiers
.getCVRQualifiers())
8915 << DroppedQualifiers
.getCVRQualifiers() << Args
[0]->getSourceRange();
8917 // FIXME: Consider decomposing the type and explaining which qualifiers
8918 // were dropped where, or on which level a 'const' is missing, etc.
8919 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_drops_quals
)
8920 << NonRefType
<< SourceType
<< 2 /*incompatible quals*/
8921 << Args
[0]->getSourceRange();
8925 case FK_ReferenceInitFailed
:
8926 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_failed
)
8927 << DestType
.getNonReferenceType()
8928 << DestType
.getNonReferenceType()->isIncompleteType()
8929 << OnlyArg
->isLValue()
8930 << OnlyArg
->getType()
8931 << Args
[0]->getSourceRange();
8932 emitBadConversionNotes(S
, Entity
, Args
[0]);
8935 case FK_ConversionFailed
: {
8936 QualType FromType
= OnlyArg
->getType();
8937 PartialDiagnostic PDiag
= S
.PDiag(diag::err_init_conversion_failed
)
8938 << (int)Entity
.getKind()
8940 << OnlyArg
->isLValue()
8942 << Args
[0]->getSourceRange();
8943 S
.HandleFunctionTypeMismatch(PDiag
, FromType
, DestType
);
8944 S
.Diag(Kind
.getLocation(), PDiag
);
8945 emitBadConversionNotes(S
, Entity
, Args
[0]);
8949 case FK_ConversionFromPropertyFailed
:
8950 // No-op. This error has already been reported.
8953 case FK_TooManyInitsForScalar
: {
8956 auto *InitList
= dyn_cast
<InitListExpr
>(Args
[0]);
8957 if (InitList
&& InitList
->getNumInits() >= 1) {
8958 R
= SourceRange(InitList
->getInit(0)->getEndLoc(), InitList
->getEndLoc());
8960 assert(Args
.size() > 1 && "Expected multiple initializers!");
8961 R
= SourceRange(Args
.front()->getEndLoc(), Args
.back()->getEndLoc());
8964 R
.setBegin(S
.getLocForEndOfToken(R
.getBegin()));
8965 if (Kind
.isCStyleOrFunctionalCast())
8966 S
.Diag(Kind
.getLocation(), diag::err_builtin_func_cast_more_than_one_arg
)
8969 S
.Diag(Kind
.getLocation(), diag::err_excess_initializers
)
8970 << /*scalar=*/2 << R
;
8974 case FK_ParenthesizedListInitForScalar
:
8975 S
.Diag(Kind
.getLocation(), diag::err_list_init_in_parens
)
8976 << 0 << Entity
.getType() << Args
[0]->getSourceRange();
8979 case FK_ReferenceBindingToInitList
:
8980 S
.Diag(Kind
.getLocation(), diag::err_reference_bind_init_list
)
8981 << DestType
.getNonReferenceType() << Args
[0]->getSourceRange();
8984 case FK_InitListBadDestinationType
:
8985 S
.Diag(Kind
.getLocation(), diag::err_init_list_bad_dest_type
)
8986 << (DestType
->isRecordType()) << DestType
<< Args
[0]->getSourceRange();
8989 case FK_ListConstructorOverloadFailed
:
8990 case FK_ConstructorOverloadFailed
: {
8991 SourceRange ArgsRange
;
8994 SourceRange(Args
.front()->getBeginLoc(), Args
.back()->getEndLoc());
8996 if (Failure
== FK_ListConstructorOverloadFailed
) {
8997 assert(Args
.size() == 1 &&
8998 "List construction from other than 1 argument.");
8999 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
9000 Args
= MultiExprArg(InitList
->getInits(), InitList
->getNumInits());
9003 // FIXME: Using "DestType" for the entity we're printing is probably
9005 switch (FailedOverloadResult
) {
9007 FailedCandidateSet
.NoteCandidates(
9008 PartialDiagnosticAt(Kind
.getLocation(),
9009 S
.PDiag(diag::err_ovl_ambiguous_init
)
9010 << DestType
<< ArgsRange
),
9011 S
, OCD_AmbiguousCandidates
, Args
);
9014 case OR_No_Viable_Function
:
9015 if (Kind
.getKind() == InitializationKind::IK_Default
&&
9016 (Entity
.getKind() == InitializedEntity::EK_Base
||
9017 Entity
.getKind() == InitializedEntity::EK_Member
||
9018 Entity
.getKind() == InitializedEntity::EK_ParenAggInitMember
) &&
9019 isa
<CXXConstructorDecl
>(S
.CurContext
)) {
9020 // This is implicit default initialization of a member or
9021 // base within a constructor. If no viable function was
9022 // found, notify the user that they need to explicitly
9023 // initialize this base/member.
9024 CXXConstructorDecl
*Constructor
9025 = cast
<CXXConstructorDecl
>(S
.CurContext
);
9026 const CXXRecordDecl
*InheritedFrom
= nullptr;
9027 if (auto Inherited
= Constructor
->getInheritedConstructor())
9028 InheritedFrom
= Inherited
.getShadowDecl()->getNominatedBaseClass();
9029 if (Entity
.getKind() == InitializedEntity::EK_Base
) {
9030 S
.Diag(Kind
.getLocation(), diag::err_missing_default_ctor
)
9031 << (InheritedFrom
? 2 : Constructor
->isImplicit() ? 1 : 0)
9032 << S
.Context
.getTypeDeclType(Constructor
->getParent())
9037 RecordDecl
*BaseDecl
9038 = Entity
.getBaseSpecifier()->getType()->castAs
<RecordType
>()
9040 S
.Diag(BaseDecl
->getLocation(), diag::note_previous_decl
)
9041 << S
.Context
.getTagDeclType(BaseDecl
);
9043 S
.Diag(Kind
.getLocation(), diag::err_missing_default_ctor
)
9044 << (InheritedFrom
? 2 : Constructor
->isImplicit() ? 1 : 0)
9045 << S
.Context
.getTypeDeclType(Constructor
->getParent())
9049 S
.Diag(Entity
.getDecl()->getLocation(),
9050 diag::note_member_declared_at
);
9052 if (const RecordType
*Record
9053 = Entity
.getType()->getAs
<RecordType
>())
9054 S
.Diag(Record
->getDecl()->getLocation(),
9055 diag::note_previous_decl
)
9056 << S
.Context
.getTagDeclType(Record
->getDecl());
9061 FailedCandidateSet
.NoteCandidates(
9062 PartialDiagnosticAt(
9064 S
.PDiag(diag::err_ovl_no_viable_function_in_init
)
9065 << DestType
<< ArgsRange
),
9066 S
, OCD_AllCandidates
, Args
);
9070 OverloadCandidateSet::iterator Best
;
9071 OverloadingResult Ovl
9072 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
9073 if (Ovl
!= OR_Deleted
) {
9074 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_init
)
9075 << DestType
<< ArgsRange
;
9076 llvm_unreachable("Inconsistent overload resolution?");
9080 // If this is a defaulted or implicitly-declared function, then
9081 // it was implicitly deleted. Make it clear that the deletion was
9083 if (S
.isImplicitlyDeleted(Best
->Function
))
9084 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_special_init
)
9085 << llvm::to_underlying(
9086 S
.getSpecialMember(cast
<CXXMethodDecl
>(Best
->Function
)))
9087 << DestType
<< ArgsRange
;
9089 StringLiteral
*Msg
= Best
->Function
->getDeletedMessage();
9090 S
.Diag(Kind
.getLocation(), diag::err_ovl_deleted_init
)
9091 << DestType
<< (Msg
!= nullptr)
9092 << (Msg
? Msg
->getString() : StringRef()) << ArgsRange
;
9095 S
.NoteDeletedFunction(Best
->Function
);
9100 llvm_unreachable("Conversion did not fail!");
9105 case FK_DefaultInitOfConst
:
9106 if (Entity
.getKind() == InitializedEntity::EK_Member
&&
9107 isa
<CXXConstructorDecl
>(S
.CurContext
)) {
9108 // This is implicit default-initialization of a const member in
9109 // a constructor. Complain that it needs to be explicitly
9111 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(S
.CurContext
);
9112 S
.Diag(Kind
.getLocation(), diag::err_uninitialized_member_in_ctor
)
9113 << (Constructor
->getInheritedConstructor() ? 2 :
9114 Constructor
->isImplicit() ? 1 : 0)
9115 << S
.Context
.getTypeDeclType(Constructor
->getParent())
9117 << Entity
.getName();
9118 S
.Diag(Entity
.getDecl()->getLocation(), diag::note_previous_decl
)
9119 << Entity
.getName();
9120 } else if (const auto *VD
= dyn_cast_if_present
<VarDecl
>(Entity
.getDecl());
9121 VD
&& VD
->isConstexpr()) {
9122 S
.Diag(Kind
.getLocation(), diag::err_constexpr_var_requires_const_init
)
9125 S
.Diag(Kind
.getLocation(), diag::err_default_init_const
)
9126 << DestType
<< (bool)DestType
->getAs
<RecordType
>();
9131 S
.RequireCompleteType(Kind
.getLocation(), FailedIncompleteType
,
9132 diag::err_init_incomplete_type
);
9135 case FK_ListInitializationFailed
: {
9136 // Run the init list checker again to emit diagnostics.
9137 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
9138 diagnoseListInit(S
, Entity
, InitList
);
9142 case FK_PlaceholderType
: {
9143 // FIXME: Already diagnosed!
9147 case FK_ExplicitConstructor
: {
9148 S
.Diag(Kind
.getLocation(), diag::err_selected_explicit_constructor
)
9149 << Args
[0]->getSourceRange();
9150 OverloadCandidateSet::iterator Best
;
9151 OverloadingResult Ovl
9152 = FailedCandidateSet
.BestViableFunction(S
, Kind
.getLocation(), Best
);
9154 assert(Ovl
== OR_Success
&& "Inconsistent overload resolution");
9155 CXXConstructorDecl
*CtorDecl
= cast
<CXXConstructorDecl
>(Best
->Function
);
9156 S
.Diag(CtorDecl
->getLocation(),
9157 diag::note_explicit_ctor_deduction_guide_here
) << false;
9161 case FK_ParenthesizedListInitFailed
:
9162 TryOrBuildParenListInitialization(S
, Entity
, Kind
, Args
, *this,
9163 /*VerifyOnly=*/false);
9166 case FK_DesignatedInitForNonAggregate
:
9167 InitListExpr
*InitList
= cast
<InitListExpr
>(Args
[0]);
9168 S
.Diag(Kind
.getLocation(), diag::err_designated_init_for_non_aggregate
)
9169 << Entity
.getType() << InitList
->getSourceRange();
9173 PrintInitLocationNote(S
, Entity
);
9177 void InitializationSequence::dump(raw_ostream
&OS
) const {
9178 switch (SequenceKind
) {
9179 case FailedSequence
: {
9180 OS
<< "Failed sequence: ";
9182 case FK_TooManyInitsForReference
:
9183 OS
<< "too many initializers for reference";
9186 case FK_ParenthesizedListInitForReference
:
9187 OS
<< "parenthesized list init for reference";
9190 case FK_ArrayNeedsInitList
:
9191 OS
<< "array requires initializer list";
9194 case FK_AddressOfUnaddressableFunction
:
9195 OS
<< "address of unaddressable function was taken";
9198 case FK_ArrayNeedsInitListOrStringLiteral
:
9199 OS
<< "array requires initializer list or string literal";
9202 case FK_ArrayNeedsInitListOrWideStringLiteral
:
9203 OS
<< "array requires initializer list or wide string literal";
9206 case FK_NarrowStringIntoWideCharArray
:
9207 OS
<< "narrow string into wide char array";
9210 case FK_WideStringIntoCharArray
:
9211 OS
<< "wide string into char array";
9214 case FK_IncompatWideStringIntoWideChar
:
9215 OS
<< "incompatible wide string into wide char array";
9218 case FK_PlainStringIntoUTF8Char
:
9219 OS
<< "plain string literal into char8_t array";
9222 case FK_UTF8StringIntoPlainChar
:
9223 OS
<< "u8 string literal into char array";
9226 case FK_ArrayTypeMismatch
:
9227 OS
<< "array type mismatch";
9230 case FK_NonConstantArrayInit
:
9231 OS
<< "non-constant array initializer";
9234 case FK_AddressOfOverloadFailed
:
9235 OS
<< "address of overloaded function failed";
9238 case FK_ReferenceInitOverloadFailed
:
9239 OS
<< "overload resolution for reference initialization failed";
9242 case FK_NonConstLValueReferenceBindingToTemporary
:
9243 OS
<< "non-const lvalue reference bound to temporary";
9246 case FK_NonConstLValueReferenceBindingToBitfield
:
9247 OS
<< "non-const lvalue reference bound to bit-field";
9250 case FK_NonConstLValueReferenceBindingToVectorElement
:
9251 OS
<< "non-const lvalue reference bound to vector element";
9254 case FK_NonConstLValueReferenceBindingToMatrixElement
:
9255 OS
<< "non-const lvalue reference bound to matrix element";
9258 case FK_NonConstLValueReferenceBindingToUnrelated
:
9259 OS
<< "non-const lvalue reference bound to unrelated type";
9262 case FK_RValueReferenceBindingToLValue
:
9263 OS
<< "rvalue reference bound to an lvalue";
9266 case FK_ReferenceInitDropsQualifiers
:
9267 OS
<< "reference initialization drops qualifiers";
9270 case FK_ReferenceAddrspaceMismatchTemporary
:
9271 OS
<< "reference with mismatching address space bound to temporary";
9274 case FK_ReferenceInitFailed
:
9275 OS
<< "reference initialization failed";
9278 case FK_ConversionFailed
:
9279 OS
<< "conversion failed";
9282 case FK_ConversionFromPropertyFailed
:
9283 OS
<< "conversion from property failed";
9286 case FK_TooManyInitsForScalar
:
9287 OS
<< "too many initializers for scalar";
9290 case FK_ParenthesizedListInitForScalar
:
9291 OS
<< "parenthesized list init for reference";
9294 case FK_ReferenceBindingToInitList
:
9295 OS
<< "referencing binding to initializer list";
9298 case FK_InitListBadDestinationType
:
9299 OS
<< "initializer list for non-aggregate, non-scalar type";
9302 case FK_UserConversionOverloadFailed
:
9303 OS
<< "overloading failed for user-defined conversion";
9306 case FK_ConstructorOverloadFailed
:
9307 OS
<< "constructor overloading failed";
9310 case FK_DefaultInitOfConst
:
9311 OS
<< "default initialization of a const variable";
9315 OS
<< "initialization of incomplete type";
9318 case FK_ListInitializationFailed
:
9319 OS
<< "list initialization checker failure";
9322 case FK_VariableLengthArrayHasInitializer
:
9323 OS
<< "variable length array has an initializer";
9326 case FK_PlaceholderType
:
9327 OS
<< "initializer expression isn't contextually valid";
9330 case FK_ListConstructorOverloadFailed
:
9331 OS
<< "list constructor overloading failed";
9334 case FK_ExplicitConstructor
:
9335 OS
<< "list copy initialization chose explicit constructor";
9338 case FK_ParenthesizedListInitFailed
:
9339 OS
<< "parenthesized list initialization failed";
9342 case FK_DesignatedInitForNonAggregate
:
9343 OS
<< "designated initializer for non-aggregate type";
9350 case DependentSequence
:
9351 OS
<< "Dependent sequence\n";
9354 case NormalSequence
:
9355 OS
<< "Normal sequence: ";
9359 for (step_iterator S
= step_begin(), SEnd
= step_end(); S
!= SEnd
; ++S
) {
9360 if (S
!= step_begin()) {
9365 case SK_ResolveAddressOfOverloadedFunction
:
9366 OS
<< "resolve address of overloaded function";
9369 case SK_CastDerivedToBasePRValue
:
9370 OS
<< "derived-to-base (prvalue)";
9373 case SK_CastDerivedToBaseXValue
:
9374 OS
<< "derived-to-base (xvalue)";
9377 case SK_CastDerivedToBaseLValue
:
9378 OS
<< "derived-to-base (lvalue)";
9381 case SK_BindReference
:
9382 OS
<< "bind reference to lvalue";
9385 case SK_BindReferenceToTemporary
:
9386 OS
<< "bind reference to a temporary";
9390 OS
<< "final copy in class direct-initialization";
9393 case SK_ExtraneousCopyToTemporary
:
9394 OS
<< "extraneous C++03 copy to temporary";
9397 case SK_UserConversion
:
9398 OS
<< "user-defined conversion via " << *S
->Function
.Function
;
9401 case SK_QualificationConversionPRValue
:
9402 OS
<< "qualification conversion (prvalue)";
9405 case SK_QualificationConversionXValue
:
9406 OS
<< "qualification conversion (xvalue)";
9409 case SK_QualificationConversionLValue
:
9410 OS
<< "qualification conversion (lvalue)";
9413 case SK_FunctionReferenceConversion
:
9414 OS
<< "function reference conversion";
9417 case SK_AtomicConversion
:
9418 OS
<< "non-atomic-to-atomic conversion";
9421 case SK_ConversionSequence
:
9422 OS
<< "implicit conversion sequence (";
9423 S
->ICS
->dump(); // FIXME: use OS
9427 case SK_ConversionSequenceNoNarrowing
:
9428 OS
<< "implicit conversion sequence with narrowing prohibited (";
9429 S
->ICS
->dump(); // FIXME: use OS
9433 case SK_ListInitialization
:
9434 OS
<< "list aggregate initialization";
9437 case SK_UnwrapInitList
:
9438 OS
<< "unwrap reference initializer list";
9441 case SK_RewrapInitList
:
9442 OS
<< "rewrap reference initializer list";
9445 case SK_ConstructorInitialization
:
9446 OS
<< "constructor initialization";
9449 case SK_ConstructorInitializationFromList
:
9450 OS
<< "list initialization via constructor";
9453 case SK_ZeroInitialization
:
9454 OS
<< "zero initialization";
9457 case SK_CAssignment
:
9458 OS
<< "C assignment";
9462 OS
<< "string initialization";
9465 case SK_ObjCObjectConversion
:
9466 OS
<< "Objective-C object conversion";
9469 case SK_ArrayLoopIndex
:
9470 OS
<< "indexing for array initialization loop";
9473 case SK_ArrayLoopInit
:
9474 OS
<< "array initialization loop";
9478 OS
<< "array initialization";
9481 case SK_GNUArrayInit
:
9482 OS
<< "array initialization (GNU extension)";
9485 case SK_ParenthesizedArrayInit
:
9486 OS
<< "parenthesized array initialization";
9489 case SK_PassByIndirectCopyRestore
:
9490 OS
<< "pass by indirect copy and restore";
9493 case SK_PassByIndirectRestore
:
9494 OS
<< "pass by indirect restore";
9497 case SK_ProduceObjCObject
:
9498 OS
<< "Objective-C object retension";
9501 case SK_StdInitializerList
:
9502 OS
<< "std::initializer_list from initializer list";
9505 case SK_StdInitializerListConstructorCall
:
9506 OS
<< "list initialization from std::initializer_list";
9509 case SK_OCLSamplerInit
:
9510 OS
<< "OpenCL sampler_t from integer constant";
9513 case SK_OCLZeroOpaqueType
:
9514 OS
<< "OpenCL opaque type from zero";
9516 case SK_ParenthesizedListInit
:
9517 OS
<< "initialization from a parenthesized list of values";
9521 OS
<< " [" << S
->Type
<< ']';
9527 void InitializationSequence::dump() const {
9531 static void DiagnoseNarrowingInInitList(Sema
&S
,
9532 const ImplicitConversionSequence
&ICS
,
9533 QualType PreNarrowingType
,
9534 QualType EntityType
,
9535 const Expr
*PostInit
) {
9536 const StandardConversionSequence
*SCS
= nullptr;
9537 switch (ICS
.getKind()) {
9538 case ImplicitConversionSequence::StandardConversion
:
9539 SCS
= &ICS
.Standard
;
9541 case ImplicitConversionSequence::UserDefinedConversion
:
9542 SCS
= &ICS
.UserDefined
.After
;
9544 case ImplicitConversionSequence::AmbiguousConversion
:
9545 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
9546 case ImplicitConversionSequence::EllipsisConversion
:
9547 case ImplicitConversionSequence::BadConversion
:
9551 auto MakeDiag
= [&](bool IsConstRef
, unsigned DefaultDiagID
,
9552 unsigned ConstRefDiagID
, unsigned WarnDiagID
) {
9554 auto &L
= S
.getLangOpts();
9555 if (L
.CPlusPlus11
&& !L
.HLSL
&&
9556 (!L
.MicrosoftExt
|| L
.isCompatibleWithMSVC(LangOptions::MSVC2015
)))
9557 DiagID
= IsConstRef
? ConstRefDiagID
: DefaultDiagID
;
9559 DiagID
= WarnDiagID
;
9560 return S
.Diag(PostInit
->getBeginLoc(), DiagID
)
9561 << PostInit
->getSourceRange();
9564 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9565 APValue ConstantValue
;
9566 QualType ConstantType
;
9567 switch (SCS
->getNarrowingKind(S
.Context
, PostInit
, ConstantValue
,
9569 case NK_Not_Narrowing
:
9570 case NK_Dependent_Narrowing
:
9571 // No narrowing occurred.
9574 case NK_Type_Narrowing
: {
9575 // This was a floating-to-integer conversion, which is always considered a
9576 // narrowing conversion even if the value is a constant and can be
9577 // represented exactly as an integer.
9578 QualType T
= EntityType
.getNonReferenceType();
9579 MakeDiag(T
!= EntityType
, diag::ext_init_list_type_narrowing
,
9580 diag::ext_init_list_type_narrowing_const_reference
,
9581 diag::warn_init_list_type_narrowing
)
9582 << PreNarrowingType
.getLocalUnqualifiedType()
9583 << T
.getLocalUnqualifiedType();
9587 case NK_Constant_Narrowing
: {
9588 // A constant value was narrowed.
9589 MakeDiag(EntityType
.getNonReferenceType() != EntityType
,
9590 diag::ext_init_list_constant_narrowing
,
9591 diag::ext_init_list_constant_narrowing_const_reference
,
9592 diag::warn_init_list_constant_narrowing
)
9593 << ConstantValue
.getAsString(S
.getASTContext(), ConstantType
)
9594 << EntityType
.getNonReferenceType().getLocalUnqualifiedType();
9598 case NK_Variable_Narrowing
: {
9599 // A variable's value may have been narrowed.
9600 MakeDiag(EntityType
.getNonReferenceType() != EntityType
,
9601 diag::ext_init_list_variable_narrowing
,
9602 diag::ext_init_list_variable_narrowing_const_reference
,
9603 diag::warn_init_list_variable_narrowing
)
9604 << PreNarrowingType
.getLocalUnqualifiedType()
9605 << EntityType
.getNonReferenceType().getLocalUnqualifiedType();
9610 SmallString
<128> StaticCast
;
9611 llvm::raw_svector_ostream
OS(StaticCast
);
9612 OS
<< "static_cast<";
9613 if (const TypedefType
*TT
= EntityType
->getAs
<TypedefType
>()) {
9614 // It's important to use the typedef's name if there is one so that the
9615 // fixit doesn't break code using types like int64_t.
9617 // FIXME: This will break if the typedef requires qualification. But
9618 // getQualifiedNameAsString() includes non-machine-parsable components.
9619 OS
<< *TT
->getDecl();
9620 } else if (const BuiltinType
*BT
= EntityType
->getAs
<BuiltinType
>())
9621 OS
<< BT
->getName(S
.getLangOpts());
9623 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9624 // with a broken cast.
9628 S
.Diag(PostInit
->getBeginLoc(), diag::note_init_list_narrowing_silence
)
9629 << PostInit
->getSourceRange()
9630 << FixItHint::CreateInsertion(PostInit
->getBeginLoc(), OS
.str())
9631 << FixItHint::CreateInsertion(
9632 S
.getLocForEndOfToken(PostInit
->getEndLoc()), ")");
9635 static void CheckC23ConstexprInitConversion(Sema
&S
, QualType FromType
,
9636 QualType ToType
, Expr
*Init
) {
9637 assert(S
.getLangOpts().C23
);
9638 ImplicitConversionSequence ICS
= S
.TryImplicitConversion(
9639 Init
->IgnoreParenImpCasts(), ToType
, /*SuppressUserConversions*/ false,
9640 Sema::AllowedExplicit::None
,
9641 /*InOverloadResolution*/ false,
9643 /*AllowObjCWritebackConversion=*/false);
9645 if (!ICS
.isStandard())
9649 QualType PreNarrowingType
;
9650 // Reuse C++ narrowing check.
9651 switch (ICS
.Standard
.getNarrowingKind(
9652 S
.Context
, Init
, Value
, PreNarrowingType
,
9653 /*IgnoreFloatToIntegralConversion*/ false)) {
9654 // The value doesn't fit.
9655 case NK_Constant_Narrowing
:
9656 S
.Diag(Init
->getBeginLoc(), diag::err_c23_constexpr_init_not_representable
)
9657 << Value
.getAsString(S
.Context
, PreNarrowingType
) << ToType
;
9660 // Conversion to a narrower type.
9661 case NK_Type_Narrowing
:
9662 S
.Diag(Init
->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch
)
9663 << ToType
<< FromType
;
9666 // Since we only reuse narrowing check for C23 constexpr variables here, we're
9667 // not really interested in these cases.
9668 case NK_Dependent_Narrowing
:
9669 case NK_Variable_Narrowing
:
9670 case NK_Not_Narrowing
:
9673 llvm_unreachable("unhandled case in switch");
9676 static void CheckC23ConstexprInitStringLiteral(const StringLiteral
*SE
,
9677 Sema
&SemaRef
, QualType
&TT
) {
9678 assert(SemaRef
.getLangOpts().C23
);
9679 // character that string literal contains fits into TT - target type.
9680 const ArrayType
*AT
= SemaRef
.Context
.getAsArrayType(TT
);
9681 QualType CharType
= AT
->getElementType();
9682 uint32_t BitWidth
= SemaRef
.Context
.getTypeSize(CharType
);
9683 bool isUnsigned
= CharType
->isUnsignedIntegerType();
9684 llvm::APSInt
Value(BitWidth
, isUnsigned
);
9685 for (unsigned I
= 0, N
= SE
->getLength(); I
!= N
; ++I
) {
9686 int64_t C
= SE
->getCodeUnitS(I
, SemaRef
.Context
.getCharWidth());
9689 SemaRef
.Diag(SemaRef
.getLocationOfStringLiteralByte(SE
, I
),
9690 diag::err_c23_constexpr_init_not_representable
)
9698 //===----------------------------------------------------------------------===//
9699 // Initialization helper functions
9700 //===----------------------------------------------------------------------===//
9702 Sema::CanPerformCopyInitialization(const InitializedEntity
&Entity
,
9704 if (Init
.isInvalid())
9707 Expr
*InitE
= Init
.get();
9708 assert(InitE
&& "No initialization expression");
9710 InitializationKind Kind
=
9711 InitializationKind::CreateCopy(InitE
->getBeginLoc(), SourceLocation());
9712 InitializationSequence
Seq(*this, Entity
, Kind
, InitE
);
9713 return !Seq
.Failed();
9717 Sema::PerformCopyInitialization(const InitializedEntity
&Entity
,
9718 SourceLocation EqualLoc
,
9720 bool TopLevelOfInitList
,
9721 bool AllowExplicit
) {
9722 if (Init
.isInvalid())
9725 Expr
*InitE
= Init
.get();
9726 assert(InitE
&& "No initialization expression?");
9728 if (EqualLoc
.isInvalid())
9729 EqualLoc
= InitE
->getBeginLoc();
9731 InitializationKind Kind
= InitializationKind::CreateCopy(
9732 InitE
->getBeginLoc(), EqualLoc
, AllowExplicit
);
9733 InitializationSequence
Seq(*this, Entity
, Kind
, InitE
, TopLevelOfInitList
);
9735 // Prevent infinite recursion when performing parameter copy-initialization.
9736 const bool ShouldTrackCopy
=
9737 Entity
.isParameterKind() && Seq
.isConstructorInitialization();
9738 if (ShouldTrackCopy
) {
9739 if (llvm::is_contained(CurrentParameterCopyTypes
, Entity
.getType())) {
9740 Seq
.SetOverloadFailure(
9741 InitializationSequence::FK_ConstructorOverloadFailed
,
9742 OR_No_Viable_Function
);
9744 // Try to give a meaningful diagnostic note for the problematic
9746 const auto LastStep
= Seq
.step_end() - 1;
9747 assert(LastStep
->Kind
==
9748 InitializationSequence::SK_ConstructorInitialization
);
9749 const FunctionDecl
*Function
= LastStep
->Function
.Function
;
9751 llvm::find_if(Seq
.getFailedCandidateSet(),
9752 [Function
](const OverloadCandidate
&Candidate
) -> bool {
9753 return Candidate
.Viable
&&
9754 Candidate
.Function
== Function
&&
9755 Candidate
.Conversions
.size() > 0;
9757 if (Candidate
!= Seq
.getFailedCandidateSet().end() &&
9758 Function
->getNumParams() > 0) {
9759 Candidate
->Viable
= false;
9760 Candidate
->FailureKind
= ovl_fail_bad_conversion
;
9761 Candidate
->Conversions
[0].setBad(BadConversionSequence::no_conversion
,
9763 Function
->getParamDecl(0)->getType());
9766 CurrentParameterCopyTypes
.push_back(Entity
.getType());
9769 ExprResult Result
= Seq
.Perform(*this, Entity
, Kind
, InitE
);
9771 if (ShouldTrackCopy
)
9772 CurrentParameterCopyTypes
.pop_back();
9777 /// Determine whether RD is, or is derived from, a specialization of CTD.
9778 static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl
*RD
,
9779 ClassTemplateDecl
*CTD
) {
9780 auto NotSpecialization
= [&] (const CXXRecordDecl
*Candidate
) {
9781 auto *CTSD
= dyn_cast
<ClassTemplateSpecializationDecl
>(Candidate
);
9782 return !CTSD
|| !declaresSameEntity(CTSD
->getSpecializedTemplate(), CTD
);
9784 return !(NotSpecialization(RD
) && RD
->forallBases(NotSpecialization
));
9787 QualType
Sema::DeduceTemplateSpecializationFromInitializer(
9788 TypeSourceInfo
*TSInfo
, const InitializedEntity
&Entity
,
9789 const InitializationKind
&Kind
, MultiExprArg Inits
) {
9790 auto *DeducedTST
= dyn_cast
<DeducedTemplateSpecializationType
>(
9791 TSInfo
->getType()->getContainedDeducedType());
9792 assert(DeducedTST
&& "not a deduced template specialization type");
9794 auto TemplateName
= DeducedTST
->getTemplateName();
9795 if (TemplateName
.isDependent())
9796 return SubstAutoTypeDependent(TSInfo
->getType());
9798 // We can only perform deduction for class templates or alias templates.
9800 dyn_cast_or_null
<ClassTemplateDecl
>(TemplateName
.getAsTemplateDecl());
9801 TemplateDecl
*LookupTemplateDecl
= Template
;
9803 if (auto *AliasTemplate
= dyn_cast_or_null
<TypeAliasTemplateDecl
>(
9804 TemplateName
.getAsTemplateDecl())) {
9805 Diag(Kind
.getLocation(),
9806 diag::warn_cxx17_compat_ctad_for_alias_templates
);
9807 LookupTemplateDecl
= AliasTemplate
;
9808 auto UnderlyingType
= AliasTemplate
->getTemplatedDecl()
9809 ->getUnderlyingType()
9810 .getCanonicalType();
9811 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
9813 // [typename] [nested-name-specifier] [template] simple-template-id
9814 if (const auto *TST
=
9815 UnderlyingType
->getAs
<TemplateSpecializationType
>()) {
9816 Template
= dyn_cast_or_null
<ClassTemplateDecl
>(
9817 TST
->getTemplateName().getAsTemplateDecl());
9818 } else if (const auto *RT
= UnderlyingType
->getAs
<RecordType
>()) {
9819 // Cases where template arguments in the RHS of the alias are not
9821 // using AliasFoo = Foo<bool>;
9822 if (const auto *CTSD
= llvm::dyn_cast
<ClassTemplateSpecializationDecl
>(
9823 RT
->getAsCXXRecordDecl()))
9824 Template
= CTSD
->getSpecializedTemplate();
9829 Diag(Kind
.getLocation(),
9830 diag::err_deduced_non_class_or_alias_template_specialization_type
)
9831 << (int)getTemplateNameKindForDiagnostics(TemplateName
) << TemplateName
;
9832 if (auto *TD
= TemplateName
.getAsTemplateDecl())
9833 NoteTemplateLocation(*TD
);
9837 // Can't deduce from dependent arguments.
9838 if (Expr::hasAnyTypeDependentArguments(Inits
)) {
9839 Diag(TSInfo
->getTypeLoc().getBeginLoc(),
9840 diag::warn_cxx14_compat_class_template_argument_deduction
)
9841 << TSInfo
->getTypeLoc().getSourceRange() << 0;
9842 return SubstAutoTypeDependent(TSInfo
->getType());
9845 // FIXME: Perform "exact type" matching first, per CWG discussion?
9846 // Or implement this via an implied 'T(T) -> T' deduction guide?
9848 // Look up deduction guides, including those synthesized from constructors.
9850 // C++1z [over.match.class.deduct]p1:
9851 // A set of functions and function templates is formed comprising:
9852 // - For each constructor of the class template designated by the
9853 // template-name, a function template [...]
9854 // - For each deduction-guide, a function or function template [...]
9855 DeclarationNameInfo
NameInfo(
9856 Context
.DeclarationNames
.getCXXDeductionGuideName(LookupTemplateDecl
),
9857 TSInfo
->getTypeLoc().getEndLoc());
9858 LookupResult
Guides(*this, NameInfo
, LookupOrdinaryName
);
9859 LookupQualifiedName(Guides
, LookupTemplateDecl
->getDeclContext());
9861 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
9862 // clear on this, but they're not found by name so access does not apply.
9863 Guides
.suppressDiagnostics();
9865 // Figure out if this is list-initialization.
9866 InitListExpr
*ListInit
=
9867 (Inits
.size() == 1 && Kind
.getKind() != InitializationKind::IK_Direct
)
9868 ? dyn_cast
<InitListExpr
>(Inits
[0])
9871 // C++1z [over.match.class.deduct]p1:
9872 // Initialization and overload resolution are performed as described in
9873 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
9874 // (as appropriate for the type of initialization performed) for an object
9875 // of a hypothetical class type, where the selected functions and function
9876 // templates are considered to be the constructors of that class type
9878 // Since we know we're initializing a class type of a type unrelated to that
9879 // of the initializer, this reduces to something fairly reasonable.
9880 OverloadCandidateSet
Candidates(Kind
.getLocation(),
9881 OverloadCandidateSet::CSK_Normal
);
9882 OverloadCandidateSet::iterator Best
;
9884 bool AllowExplicit
= !Kind
.isCopyInit() || ListInit
;
9886 // Return true if the candidate is added successfully, false otherwise.
9887 auto addDeductionCandidate
= [&](FunctionTemplateDecl
*TD
,
9888 CXXDeductionGuideDecl
*GD
,
9889 DeclAccessPair FoundDecl
,
9890 bool OnlyListConstructors
,
9891 bool AllowAggregateDeductionCandidate
) {
9892 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
9893 // For copy-initialization, the candidate functions are all the
9894 // converting constructors (12.3.1) of that class.
9895 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
9896 // The converting constructors of T are candidate functions.
9897 if (!AllowExplicit
) {
9898 // Overload resolution checks whether the deduction guide is declared
9901 // When looking for a converting constructor, deduction guides that
9902 // could never be called with one argument are not interesting to
9904 if (GD
->getMinRequiredArguments() > 1 ||
9905 (GD
->getNumParams() == 0 && !GD
->isVariadic()))
9909 // C++ [over.match.list]p1.1: (first phase list initialization)
9910 // Initially, the candidate functions are the initializer-list
9911 // constructors of the class T
9912 if (OnlyListConstructors
&& !isInitListConstructor(GD
))
9915 if (!AllowAggregateDeductionCandidate
&&
9916 GD
->getDeductionCandidateKind() == DeductionCandidate::Aggregate
)
9919 // C++ [over.match.list]p1.2: (second phase list initialization)
9920 // the candidate functions are all the constructors of the class T
9921 // C++ [over.match.ctor]p1: (all other cases)
9922 // the candidate functions are all the constructors of the class of
9923 // the object being initialized
9925 // C++ [over.best.ics]p4:
9926 // When [...] the constructor [...] is a candidate by
9927 // - [over.match.copy] (in all cases)
9929 SmallVector
<Expr
*, 8> TmpInits
;
9930 for (Expr
*E
: Inits
)
9931 if (auto *DI
= dyn_cast
<DesignatedInitExpr
>(E
))
9932 TmpInits
.push_back(DI
->getInit());
9934 TmpInits
.push_back(E
);
9935 AddTemplateOverloadCandidate(
9936 TD
, FoundDecl
, /*ExplicitArgs=*/nullptr, TmpInits
, Candidates
,
9937 /*SuppressUserConversions=*/false,
9938 /*PartialOverloading=*/false, AllowExplicit
, ADLCallKind::NotADL
,
9939 /*PO=*/{}, AllowAggregateDeductionCandidate
);
9941 AddOverloadCandidate(GD
, FoundDecl
, Inits
, Candidates
,
9942 /*SuppressUserConversions=*/false,
9943 /*PartialOverloading=*/false, AllowExplicit
);
9947 bool FoundDeductionGuide
= false;
9949 auto TryToResolveOverload
=
9950 [&](bool OnlyListConstructors
) -> OverloadingResult
{
9951 Candidates
.clear(OverloadCandidateSet::CSK_Normal
);
9952 bool HasAnyDeductionGuide
= false;
9954 auto SynthesizeAggrGuide
= [&](InitListExpr
*ListInit
) {
9955 auto *Pattern
= Template
;
9956 while (Pattern
->getInstantiatedFromMemberTemplate()) {
9957 if (Pattern
->isMemberSpecialization())
9959 Pattern
= Pattern
->getInstantiatedFromMemberTemplate();
9962 auto *RD
= cast
<CXXRecordDecl
>(Pattern
->getTemplatedDecl());
9963 if (!(RD
->getDefinition() && RD
->isAggregate()))
9965 QualType Ty
= Context
.getRecordType(RD
);
9966 SmallVector
<QualType
, 8> ElementTypes
;
9968 InitListChecker
CheckInitList(*this, Entity
, ListInit
, Ty
, ElementTypes
);
9969 if (!CheckInitList
.HadError()) {
9970 // C++ [over.match.class.deduct]p1.8:
9971 // if e_i is of array type and x_i is a braced-init-list, T_i is an
9972 // rvalue reference to the declared type of e_i and
9973 // C++ [over.match.class.deduct]p1.9:
9974 // if e_i is of array type and x_i is a string-literal, T_i is an
9975 // lvalue reference to the const-qualified declared type of e_i and
9976 // C++ [over.match.class.deduct]p1.10:
9977 // otherwise, T_i is the declared type of e_i
9978 for (int I
= 0, E
= ListInit
->getNumInits();
9979 I
< E
&& !isa
<PackExpansionType
>(ElementTypes
[I
]); ++I
)
9980 if (ElementTypes
[I
]->isArrayType()) {
9981 if (isa
<InitListExpr
, DesignatedInitExpr
>(ListInit
->getInit(I
)))
9982 ElementTypes
[I
] = Context
.getRValueReferenceType(ElementTypes
[I
]);
9983 else if (isa
<StringLiteral
>(
9984 ListInit
->getInit(I
)->IgnoreParenImpCasts()))
9986 Context
.getLValueReferenceType(ElementTypes
[I
].withConst());
9989 if (FunctionTemplateDecl
*TD
=
9990 DeclareAggregateDeductionGuideFromInitList(
9991 LookupTemplateDecl
, ElementTypes
,
9992 TSInfo
->getTypeLoc().getEndLoc())) {
9993 auto *GD
= cast
<CXXDeductionGuideDecl
>(TD
->getTemplatedDecl());
9994 addDeductionCandidate(TD
, GD
, DeclAccessPair::make(TD
, AS_public
),
9995 OnlyListConstructors
,
9996 /*AllowAggregateDeductionCandidate=*/true);
9997 HasAnyDeductionGuide
= true;
10002 for (auto I
= Guides
.begin(), E
= Guides
.end(); I
!= E
; ++I
) {
10003 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
10004 if (D
->isInvalidDecl())
10007 auto *TD
= dyn_cast
<FunctionTemplateDecl
>(D
);
10008 auto *GD
= dyn_cast_if_present
<CXXDeductionGuideDecl
>(
10009 TD
? TD
->getTemplatedDecl() : dyn_cast
<FunctionDecl
>(D
));
10013 if (!GD
->isImplicit())
10014 HasAnyDeductionGuide
= true;
10016 addDeductionCandidate(TD
, GD
, I
.getPair(), OnlyListConstructors
,
10017 /*AllowAggregateDeductionCandidate=*/false);
10020 // C++ [over.match.class.deduct]p1.4:
10021 // if C is defined and its definition satisfies the conditions for an
10022 // aggregate class ([dcl.init.aggr]) with the assumption that any
10023 // dependent base class has no virtual functions and no virtual base
10024 // classes, and the initializer is a non-empty braced-init-list or
10025 // parenthesized expression-list, and there are no deduction-guides for
10026 // C, the set contains an additional function template, called the
10027 // aggregate deduction candidate, defined as follows.
10028 if (getLangOpts().CPlusPlus20
&& !HasAnyDeductionGuide
) {
10029 if (ListInit
&& ListInit
->getNumInits()) {
10030 SynthesizeAggrGuide(ListInit
);
10031 } else if (Inits
.size()) { // parenthesized expression-list
10032 // Inits are expressions inside the parentheses. We don't have
10033 // the parentheses source locations, use the begin/end of Inits as the
10035 InitListExpr
TempListInit(getASTContext(), Inits
.front()->getBeginLoc(),
10036 Inits
, Inits
.back()->getEndLoc());
10037 SynthesizeAggrGuide(&TempListInit
);
10041 FoundDeductionGuide
= FoundDeductionGuide
|| HasAnyDeductionGuide
;
10043 return Candidates
.BestViableFunction(*this, Kind
.getLocation(), Best
);
10046 OverloadingResult Result
= OR_No_Viable_Function
;
10048 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10049 // try initializer-list constructors.
10051 bool TryListConstructors
= true;
10053 // Try list constructors unless the list is empty and the class has one or
10054 // more default constructors, in which case those constructors win.
10055 if (!ListInit
->getNumInits()) {
10056 for (NamedDecl
*D
: Guides
) {
10057 auto *FD
= dyn_cast
<FunctionDecl
>(D
->getUnderlyingDecl());
10058 if (FD
&& FD
->getMinRequiredArguments() == 0) {
10059 TryListConstructors
= false;
10063 } else if (ListInit
->getNumInits() == 1) {
10064 // C++ [over.match.class.deduct]:
10065 // As an exception, the first phase in [over.match.list] (considering
10066 // initializer-list constructors) is omitted if the initializer list
10067 // consists of a single expression of type cv U, where U is a
10068 // specialization of C or a class derived from a specialization of C.
10069 Expr
*E
= ListInit
->getInit(0);
10070 auto *RD
= E
->getType()->getAsCXXRecordDecl();
10071 if (!isa
<InitListExpr
>(E
) && RD
&&
10072 isCompleteType(Kind
.getLocation(), E
->getType()) &&
10073 isOrIsDerivedFromSpecializationOf(RD
, Template
))
10074 TryListConstructors
= false;
10077 if (TryListConstructors
)
10078 Result
= TryToResolveOverload(/*OnlyListConstructor*/true);
10079 // Then unwrap the initializer list and try again considering all
10081 Inits
= MultiExprArg(ListInit
->getInits(), ListInit
->getNumInits());
10084 // If list-initialization fails, or if we're doing any other kind of
10085 // initialization, we (eventually) consider constructors.
10086 if (Result
== OR_No_Viable_Function
)
10087 Result
= TryToResolveOverload(/*OnlyListConstructor*/false);
10091 // FIXME: For list-initialization candidates, it'd usually be better to
10092 // list why they were not viable when given the initializer list itself as
10094 Candidates
.NoteCandidates(
10095 PartialDiagnosticAt(
10096 Kind
.getLocation(),
10097 PDiag(diag::err_deduced_class_template_ctor_ambiguous
)
10099 *this, OCD_AmbiguousCandidates
, Inits
);
10102 case OR_No_Viable_Function
: {
10103 CXXRecordDecl
*Primary
=
10104 cast
<ClassTemplateDecl
>(Template
)->getTemplatedDecl();
10106 isCompleteType(Kind
.getLocation(), Context
.getTypeDeclType(Primary
));
10107 Candidates
.NoteCandidates(
10108 PartialDiagnosticAt(
10109 Kind
.getLocation(),
10110 PDiag(Complete
? diag::err_deduced_class_template_ctor_no_viable
10111 : diag::err_deduced_class_template_incomplete
)
10112 << TemplateName
<< !Guides
.empty()),
10113 *this, OCD_AllCandidates
, Inits
);
10118 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10119 // like we ever get here; attempts to trigger this seem to yield a
10120 // generic c'all to deleted function' diagnostic instead.
10121 Diag(Kind
.getLocation(), diag::err_deduced_class_template_deleted
)
10123 NoteDeletedFunction(Best
->Function
);
10128 // C++ [over.match.list]p1:
10129 // In copy-list-initialization, if an explicit constructor is chosen, the
10130 // initialization is ill-formed.
10131 if (Kind
.isCopyInit() && ListInit
&&
10132 cast
<CXXDeductionGuideDecl
>(Best
->Function
)->isExplicit()) {
10133 bool IsDeductionGuide
= !Best
->Function
->isImplicit();
10134 Diag(Kind
.getLocation(), diag::err_deduced_class_template_explicit
)
10135 << TemplateName
<< IsDeductionGuide
;
10136 Diag(Best
->Function
->getLocation(),
10137 diag::note_explicit_ctor_deduction_guide_here
)
10138 << IsDeductionGuide
;
10142 // Make sure we didn't select an unusable deduction guide, and mark it
10144 DiagnoseUseOfDecl(Best
->FoundDecl
, Kind
.getLocation());
10145 MarkFunctionReferenced(Kind
.getLocation(), Best
->Function
);
10149 // C++ [dcl.type.class.deduct]p1:
10150 // The placeholder is replaced by the return type of the function selected
10151 // by overload resolution for class template deduction.
10152 QualType DeducedType
=
10153 SubstAutoType(TSInfo
->getType(), Best
->Function
->getReturnType());
10154 Diag(TSInfo
->getTypeLoc().getBeginLoc(),
10155 diag::warn_cxx14_compat_class_template_argument_deduction
)
10156 << TSInfo
->getTypeLoc().getSourceRange() << 1 << DeducedType
;
10158 // Warn if CTAD was used on a type that does not have any user-defined
10159 // deduction guides.
10160 if (!FoundDeductionGuide
) {
10161 Diag(TSInfo
->getTypeLoc().getBeginLoc(),
10162 diag::warn_ctad_maybe_unsupported
)
10164 Diag(Template
->getLocation(), diag::note_suppress_ctad_maybe_unsupported
);
10167 return DeducedType
;