1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
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/TypeBase.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Specifiers.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Designator.h"
27#include "clang/Sema/EnterExpressionEvaluationContext.h"
28#include "clang/Sema/Initialization.h"
29#include "clang/Sema/Lookup.h"
30#include "clang/Sema/Ownership.h"
31#include "clang/Sema/SemaHLSL.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/PointerIntPair.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// Sema Initialization Checking
47//===----------------------------------------------------------------------===//
48
49/// Check whether T is compatible with a wide character type (wchar_t,
50/// char16_t or char32_t).
51static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
52 if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: T))
53 return true;
54 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
55 return Context.typesAreCompatible(T1: Context.Char16Ty, T2: T) ||
56 Context.typesAreCompatible(T1: Context.Char32Ty, T2: T);
57 }
58 return false;
59}
60
61enum StringInitFailureKind {
62 SIF_None,
63 SIF_NarrowStringIntoWideChar,
64 SIF_WideStringIntoChar,
65 SIF_IncompatWideStringIntoWideChar,
66 SIF_UTF8StringIntoPlainChar,
67 SIF_PlainStringIntoUTF8Char,
68 SIF_Other
69};
70
71/// Check whether the array of type AT can be initialized by the Init
72/// expression by means of string initialization. Returns SIF_None if so,
73/// otherwise returns a StringInitFailureKind that describes why the
74/// initialization would not work.
75static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
76 ASTContext &Context) {
77 if (!isa<ConstantArrayType>(Val: AT) && !isa<IncompleteArrayType>(Val: AT))
78 return SIF_Other;
79
80 // See if this is a string literal or @encode.
81 Init = Init->IgnoreParens();
82
83 // Handle @encode, which is a narrow string.
84 if (isa<ObjCEncodeExpr>(Val: Init) && AT->getElementType()->isCharType())
85 return SIF_None;
86
87 // Otherwise we can only handle string literals.
88 StringLiteral *SL = dyn_cast<StringLiteral>(Val: Init);
89 if (!SL)
90 return SIF_Other;
91
92 const QualType ElemTy =
93 Context.getCanonicalType(T: AT->getElementType()).getUnqualifiedType();
94
95 auto IsCharOrUnsignedChar = [](const QualType &T) {
96 const BuiltinType *BT = dyn_cast<BuiltinType>(Val: T.getTypePtr());
97 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
98 };
99
100 switch (SL->getKind()) {
101 case StringLiteralKind::UTF8:
102 // char8_t array can be initialized with a UTF-8 string.
103 // - C++20 [dcl.init.string] (DR)
104 // Additionally, an array of char or unsigned char may be initialized
105 // by a UTF-8 string literal.
106 if (ElemTy->isChar8Type() ||
107 (Context.getLangOpts().Char8 &&
108 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
109 return SIF_None;
110 [[fallthrough]];
111 case StringLiteralKind::Ordinary:
112 case StringLiteralKind::Binary:
113 // char array can be initialized with a narrow string.
114 // Only allow char x[] = "foo"; not char x[] = L"foo";
115 if (ElemTy->isCharType())
116 return (SL->getKind() == StringLiteralKind::UTF8 &&
117 Context.getLangOpts().Char8)
118 ? SIF_UTF8StringIntoPlainChar
119 : SIF_None;
120 if (ElemTy->isChar8Type())
121 return SIF_PlainStringIntoUTF8Char;
122 if (IsWideCharCompatible(T: ElemTy, Context))
123 return SIF_NarrowStringIntoWideChar;
124 return SIF_Other;
125 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
126 // "An array with element type compatible with a qualified or unqualified
127 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
128 // string literal with the corresponding encoding prefix (L, u, or U,
129 // respectively), optionally enclosed in braces.
130 case StringLiteralKind::UTF16:
131 if (Context.typesAreCompatible(T1: Context.Char16Ty, T2: ElemTy))
132 return SIF_None;
133 if (ElemTy->isCharType() || ElemTy->isChar8Type())
134 return SIF_WideStringIntoChar;
135 if (IsWideCharCompatible(T: ElemTy, Context))
136 return SIF_IncompatWideStringIntoWideChar;
137 return SIF_Other;
138 case StringLiteralKind::UTF32:
139 if (Context.typesAreCompatible(T1: Context.Char32Ty, T2: ElemTy))
140 return SIF_None;
141 if (ElemTy->isCharType() || ElemTy->isChar8Type())
142 return SIF_WideStringIntoChar;
143 if (IsWideCharCompatible(T: ElemTy, Context))
144 return SIF_IncompatWideStringIntoWideChar;
145 return SIF_Other;
146 case StringLiteralKind::Wide:
147 if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: ElemTy))
148 return SIF_None;
149 if (ElemTy->isCharType() || ElemTy->isChar8Type())
150 return SIF_WideStringIntoChar;
151 if (IsWideCharCompatible(T: ElemTy, Context))
152 return SIF_IncompatWideStringIntoWideChar;
153 return SIF_Other;
154 case StringLiteralKind::Unevaluated:
155 assert(false && "Unevaluated string literal in initialization");
156 break;
157 }
158
159 llvm_unreachable("missed a StringLiteral kind?");
160}
161
162static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
163 ASTContext &Context) {
164 const ArrayType *arrayType = Context.getAsArrayType(T: declType);
165 if (!arrayType)
166 return SIF_Other;
167 return IsStringInit(Init: init, AT: arrayType, Context);
168}
169
170bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
171 return ::IsStringInit(Init, AT, Context) == SIF_None;
172}
173
174/// Update the type of a string literal, including any surrounding parentheses,
175/// to match the type of the object which it is initializing.
176static void updateStringLiteralType(Expr *E, QualType Ty) {
177 while (true) {
178 E->setType(Ty);
179 E->setValueKind(VK_PRValue);
180 if (isa<StringLiteral>(Val: E) || isa<ObjCEncodeExpr>(Val: E))
181 break;
182 E = IgnoreParensSingleStep(E);
183 }
184}
185
186/// Fix a compound literal initializing an array so it's correctly marked
187/// as an rvalue.
188static void updateGNUCompoundLiteralRValue(Expr *E) {
189 while (true) {
190 E->setValueKind(VK_PRValue);
191 if (isa<CompoundLiteralExpr>(Val: E))
192 break;
193 E = IgnoreParensSingleStep(E);
194 }
195}
196
197static bool initializingConstexprVariable(const InitializedEntity &Entity) {
198 Decl *D = Entity.getDecl();
199 const InitializedEntity *Parent = &Entity;
200
201 while (Parent) {
202 D = Parent->getDecl();
203 Parent = Parent->getParent();
204 }
205
206 if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); VD && VD->isConstexpr())
207 return true;
208
209 return false;
210}
211
212static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
213 Sema &SemaRef, QualType &TT);
214
215static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
216 Sema &S, const InitializedEntity &Entity,
217 bool CheckC23ConstexprInit = false) {
218 // Get the length of the string as parsed.
219 auto *ConstantArrayTy =
220 cast<ConstantArrayType>(Val: Str->getType()->getAsArrayTypeUnsafe());
221 uint64_t StrLength = ConstantArrayTy->getZExtSize();
222
223 if (CheckC23ConstexprInit)
224 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens()))
225 CheckC23ConstexprInitStringLiteral(SE: SL, SemaRef&: S, TT&: DeclT);
226
227 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
228 // C99 6.7.8p14. We have an array of character type with unknown size
229 // being initialized to a string literal.
230 llvm::APInt ConstVal(32, StrLength);
231 // Return a new array type (C99 6.7.8p22).
232 DeclT = S.Context.getConstantArrayType(
233 EltTy: IAT->getElementType(), ArySize: ConstVal, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
234 updateStringLiteralType(E: Str, Ty: DeclT);
235 return;
236 }
237
238 const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: AT);
239 uint64_t ArrayLen = CAT->getZExtSize();
240
241 // We have an array of character type with known size. However,
242 // the size may be smaller or larger than the string we are initializing.
243 // FIXME: Avoid truncation for 64-bit length strings.
244 if (S.getLangOpts().CPlusPlus) {
245 if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) {
246 // For Pascal strings it's OK to strip off the terminating null character,
247 // so the example below is valid:
248 //
249 // unsigned char a[2] = "\pa";
250 if (SL->isPascal())
251 StrLength--;
252 }
253
254 // [dcl.init.string]p2
255 if (StrLength > ArrayLen)
256 S.Diag(Loc: Str->getBeginLoc(),
257 DiagID: diag::err_initializer_string_for_char_array_too_long)
258 << ArrayLen << StrLength << Str->getSourceRange();
259 } else {
260 // C99 6.7.8p14.
261 if (StrLength - 1 > ArrayLen)
262 S.Diag(Loc: Str->getBeginLoc(),
263 DiagID: diag::ext_initializer_string_for_char_array_too_long)
264 << Str->getSourceRange();
265 else if (StrLength - 1 == ArrayLen) {
266 // In C, if the string literal is null-terminated explicitly, e.g., `char
267 // a[4] = "ABC\0"`, there should be no warning:
268 const auto *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens());
269 bool IsSLSafe = SL && SL->getLength() > 0 &&
270 SL->getCodeUnit(i: SL->getLength() - 1) == 0;
271
272 if (!IsSLSafe) {
273 // If the entity being initialized has the nonstring attribute, then
274 // silence the "missing nonstring" diagnostic. If there's no entity,
275 // check whether we're initializing an array of arrays; if so, walk the
276 // parents to find an entity.
277 auto FindCorrectEntity =
278 [](const InitializedEntity *Entity) -> const ValueDecl * {
279 while (Entity) {
280 if (const ValueDecl *VD = Entity->getDecl())
281 return VD;
282 if (!Entity->getType()->isArrayType())
283 return nullptr;
284 Entity = Entity->getParent();
285 }
286
287 return nullptr;
288 };
289 if (const ValueDecl *D = FindCorrectEntity(&Entity);
290 !D || !D->hasAttr<NonStringAttr>())
291 S.Diag(
292 Loc: Str->getBeginLoc(),
293 DiagID: diag::
294 warn_initializer_string_for_char_array_too_long_no_nonstring)
295 << ArrayLen << StrLength << Str->getSourceRange();
296 }
297 // Always emit the C++ compatibility diagnostic.
298 S.Diag(Loc: Str->getBeginLoc(),
299 DiagID: diag::warn_initializer_string_for_char_array_too_long_for_cpp)
300 << ArrayLen << StrLength << Str->getSourceRange();
301 }
302 }
303
304 // Set the type to the actual size that we are initializing. If we have
305 // something like:
306 // char x[1] = "foo";
307 // then this will set the string literal's type to char[1].
308 updateStringLiteralType(E: Str, Ty: DeclT);
309}
310
311void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R) {
312 for (const FieldDecl *Field : R->fields()) {
313 if (Field->hasAttr<ExplicitInitAttr>())
314 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at) << Field;
315 }
316}
317
318//===----------------------------------------------------------------------===//
319// Semantic checking for initializer lists.
320//===----------------------------------------------------------------------===//
321
322namespace {
323
324/// Semantic checking for initializer lists.
325///
326/// The InitListChecker class contains a set of routines that each
327/// handle the initialization of a certain kind of entity, e.g.,
328/// arrays, vectors, struct/union types, scalars, etc. The
329/// InitListChecker itself performs a recursive walk of the subobject
330/// structure of the type to be initialized, while stepping through
331/// the initializer list one element at a time. The IList and Index
332/// parameters to each of the Check* routines contain the active
333/// (syntactic) initializer list and the index into that initializer
334/// list that represents the current initializer. Each routine is
335/// responsible for moving that Index forward as it consumes elements.
336///
337/// Each Check* routine also has a StructuredList/StructuredIndex
338/// arguments, which contains the current "structured" (semantic)
339/// initializer list and the index into that initializer list where we
340/// are copying initializers as we map them over to the semantic
341/// list. Once we have completed our recursive walk of the subobject
342/// structure, we will have constructed a full semantic initializer
343/// list.
344///
345/// C99 designators cause changes in the initializer list traversal,
346/// because they make the initialization "jump" into a specific
347/// subobject and then continue the initialization from that
348/// point. CheckDesignatedInitializer() recursively steps into the
349/// designated subobject and manages backing out the recursion to
350/// initialize the subobjects after the one designated.
351///
352/// If an initializer list contains any designators, we build a placeholder
353/// structured list even in 'verify only' mode, so that we can track which
354/// elements need 'empty' initializtion.
355class InitListChecker {
356 Sema &SemaRef;
357 bool hadError = false;
358 bool VerifyOnly; // No diagnostics.
359 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
360 bool InOverloadResolution;
361 InitListExpr *FullyStructuredList = nullptr;
362 NoInitExpr *DummyExpr = nullptr;
363 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
364 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
365 unsigned CurEmbedIndex = 0;
366
367 NoInitExpr *getDummyInit() {
368 if (!DummyExpr)
369 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
370 return DummyExpr;
371 }
372
373 void CheckImplicitInitList(const InitializedEntity &Entity,
374 InitListExpr *ParentIList, QualType T,
375 unsigned &Index, InitListExpr *StructuredList,
376 unsigned &StructuredIndex);
377 void CheckExplicitInitList(const InitializedEntity &Entity,
378 InitListExpr *IList, QualType &T,
379 InitListExpr *StructuredList,
380 bool TopLevelObject = false);
381 void CheckListElementTypes(const InitializedEntity &Entity,
382 InitListExpr *IList, QualType &DeclType,
383 bool SubobjectIsDesignatorContext,
384 unsigned &Index,
385 InitListExpr *StructuredList,
386 unsigned &StructuredIndex,
387 bool TopLevelObject = false);
388 void CheckSubElementType(const InitializedEntity &Entity,
389 InitListExpr *IList, QualType ElemType,
390 unsigned &Index,
391 InitListExpr *StructuredList,
392 unsigned &StructuredIndex,
393 bool DirectlyDesignated = false);
394 void CheckComplexType(const InitializedEntity &Entity,
395 InitListExpr *IList, QualType DeclType,
396 unsigned &Index,
397 InitListExpr *StructuredList,
398 unsigned &StructuredIndex);
399 void CheckScalarType(const InitializedEntity &Entity,
400 InitListExpr *IList, QualType DeclType,
401 unsigned &Index,
402 InitListExpr *StructuredList,
403 unsigned &StructuredIndex);
404 void CheckReferenceType(const InitializedEntity &Entity,
405 InitListExpr *IList, QualType DeclType,
406 unsigned &Index,
407 InitListExpr *StructuredList,
408 unsigned &StructuredIndex);
409 void CheckMatrixType(const InitializedEntity &Entity, InitListExpr *IList,
410 QualType DeclType, unsigned &Index,
411 InitListExpr *StructuredList, unsigned &StructuredIndex);
412 void CheckVectorType(const InitializedEntity &Entity,
413 InitListExpr *IList, QualType DeclType, unsigned &Index,
414 InitListExpr *StructuredList,
415 unsigned &StructuredIndex);
416 void CheckStructUnionTypes(const InitializedEntity &Entity,
417 InitListExpr *IList, QualType DeclType,
418 CXXRecordDecl::base_class_const_range Bases,
419 RecordDecl::field_iterator Field,
420 bool SubobjectIsDesignatorContext, unsigned &Index,
421 InitListExpr *StructuredList,
422 unsigned &StructuredIndex,
423 bool TopLevelObject = false);
424 void CheckArrayType(const InitializedEntity &Entity,
425 InitListExpr *IList, QualType &DeclType,
426 llvm::APSInt elementIndex,
427 bool SubobjectIsDesignatorContext, unsigned &Index,
428 InitListExpr *StructuredList,
429 unsigned &StructuredIndex);
430 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
431 InitListExpr *IList, DesignatedInitExpr *DIE,
432 unsigned DesigIdx,
433 QualType &CurrentObjectType,
434 RecordDecl::field_iterator *NextField,
435 llvm::APSInt *NextElementIndex,
436 unsigned &Index,
437 InitListExpr *StructuredList,
438 unsigned &StructuredIndex,
439 bool FinishSubobjectInit,
440 bool TopLevelObject);
441 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
442 QualType CurrentObjectType,
443 InitListExpr *StructuredList,
444 unsigned StructuredIndex,
445 SourceRange InitRange,
446 bool IsFullyOverwritten = false);
447 void UpdateStructuredListElement(InitListExpr *StructuredList,
448 unsigned &StructuredIndex,
449 Expr *expr);
450 InitListExpr *createInitListExpr(QualType CurrentObjectType,
451 SourceRange InitRange,
452 unsigned ExpectedNumInits);
453 int numArrayElements(QualType DeclType);
454 int numStructUnionElements(QualType DeclType);
455
456 ExprResult PerformEmptyInit(SourceLocation Loc,
457 const InitializedEntity &Entity);
458
459 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
460 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
461 bool UnionOverride = false,
462 bool FullyOverwritten = true) {
463 // Overriding an initializer via a designator is valid with C99 designated
464 // initializers, but ill-formed with C++20 designated initializers.
465 unsigned DiagID =
466 SemaRef.getLangOpts().CPlusPlus
467 ? (UnionOverride ? diag::ext_initializer_union_overrides
468 : diag::ext_initializer_overrides)
469 : diag::warn_initializer_overrides;
470
471 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
472 // In overload resolution, we have to strictly enforce the rules, and so
473 // don't allow any overriding of prior initializers. This matters for a
474 // case such as:
475 //
476 // union U { int a, b; };
477 // struct S { int a, b; };
478 // void f(U), f(S);
479 //
480 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
481 // consistency, we disallow all overriding of prior initializers in
482 // overload resolution, not only overriding of union members.
483 hadError = true;
484 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
485 // If we'll be keeping around the old initializer but overwriting part of
486 // the object it initialized, and that object is not trivially
487 // destructible, this can leak. Don't allow that, not even as an
488 // extension.
489 //
490 // FIXME: It might be reasonable to allow this in cases where the part of
491 // the initializer that we're overriding has trivial destruction.
492 DiagID = diag::err_initializer_overrides_destructed;
493 } else if (!OldInit->getSourceRange().isValid()) {
494 // We need to check on source range validity because the previous
495 // initializer does not have to be an explicit initializer. e.g.,
496 //
497 // struct P { int a, b; };
498 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
499 //
500 // There is an overwrite taking place because the first braced initializer
501 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
502 //
503 // Such overwrites are harmless, so we don't diagnose them. (Note that in
504 // C++, this cannot be reached unless we've already seen and diagnosed a
505 // different conformance issue, such as a mixture of designated and
506 // non-designated initializers or a multi-level designator.)
507 return;
508 }
509
510 if (!VerifyOnly) {
511 SemaRef.Diag(Loc: NewInitRange.getBegin(), DiagID)
512 << NewInitRange << FullyOverwritten << OldInit->getType();
513 SemaRef.Diag(Loc: OldInit->getBeginLoc(), DiagID: diag::note_previous_initializer)
514 << (OldInit->HasSideEffects(Ctx: SemaRef.Context) && FullyOverwritten)
515 << OldInit->getSourceRange();
516 }
517 }
518
519 // Explanation on the "FillWithNoInit" mode:
520 //
521 // Assume we have the following definitions (Case#1):
522 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
523 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
524 //
525 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
526 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
527 //
528 // But if we have (Case#2):
529 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
530 //
531 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
532 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
533 //
534 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
535 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
536 // initializers but with special "NoInitExpr" place holders, which tells the
537 // CodeGen not to generate any initializers for these parts.
538 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
539 const InitializedEntity &ParentEntity,
540 InitListExpr *ILE, bool &RequiresSecondPass,
541 bool FillWithNoInit);
542 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
543 const InitializedEntity &ParentEntity,
544 InitListExpr *ILE, bool &RequiresSecondPass,
545 bool FillWithNoInit = false);
546 void FillInEmptyInitializations(const InitializedEntity &Entity,
547 InitListExpr *ILE, bool &RequiresSecondPass,
548 InitListExpr *OuterILE, unsigned OuterIndex,
549 bool FillWithNoInit = false);
550 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
551 Expr *InitExpr, FieldDecl *Field,
552 bool TopLevelObject);
553 void CheckEmptyInitializable(const InitializedEntity &Entity,
554 SourceLocation Loc);
555
556 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
557 Expr *Result = nullptr;
558 // Undrestand which part of embed we'd like to reference.
559 if (!CurEmbed) {
560 CurEmbed = Embed;
561 CurEmbedIndex = 0;
562 }
563 // Reference just one if we're initializing a single scalar.
564 uint64_t ElsCount = 1;
565 // Otherwise try to fill whole array with embed data.
566 if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
567 unsigned ArrIndex = Entity.getElementIndex();
568 auto *AType =
569 SemaRef.Context.getAsArrayType(T: Entity.getParent()->getType());
570 assert(AType && "expected array type when initializing array");
571 ElsCount = Embed->getDataElementCount();
572 if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType))
573 ElsCount = std::min(a: CAType->getSize().getZExtValue() - ArrIndex,
574 b: ElsCount - CurEmbedIndex);
575 if (ElsCount == Embed->getDataElementCount()) {
576 CurEmbed = nullptr;
577 CurEmbedIndex = 0;
578 return Embed;
579 }
580 }
581
582 Result = new (SemaRef.Context)
583 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
584 CurEmbedIndex, ElsCount);
585 CurEmbedIndex += ElsCount;
586 if (CurEmbedIndex >= Embed->getDataElementCount()) {
587 CurEmbed = nullptr;
588 CurEmbedIndex = 0;
589 }
590 return Result;
591 }
592
593public:
594 InitListChecker(
595 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
596 bool VerifyOnly, bool TreatUnavailableAsInvalid,
597 bool InOverloadResolution = false,
598 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
599 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
600 QualType &T,
601 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
602 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
603 /*TreatUnavailableAsInvalid=*/false,
604 /*InOverloadResolution=*/false,
605 &AggrDeductionCandidateParamTypes) {}
606
607 bool HadError() { return hadError; }
608
609 // Retrieves the fully-structured initializer list used for
610 // semantic analysis and code generation.
611 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
612};
613
614} // end anonymous namespace
615
616ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
617 const InitializedEntity &Entity) {
618 InitializationKind Kind = InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc,
619 isImplicit: true);
620 MultiExprArg SubInit;
621 Expr *InitExpr;
622 InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc);
623
624 // C++ [dcl.init.aggr]p7:
625 // If there are fewer initializer-clauses in the list than there are
626 // members in the aggregate, then each member not explicitly initialized
627 // ...
628 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
629 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
630 if (EmptyInitList) {
631 // C++1y / DR1070:
632 // shall be initialized [...] from an empty initializer list.
633 //
634 // We apply the resolution of this DR to C++11 but not C++98, since C++98
635 // does not have useful semantics for initialization from an init list.
636 // We treat this as copy-initialization, because aggregate initialization
637 // always performs copy-initialization on its elements.
638 //
639 // Only do this if we're initializing a class type, to avoid filling in
640 // the initializer list where possible.
641 InitExpr = VerifyOnly ? &DummyInitList
642 : new (SemaRef.Context)
643 InitListExpr(SemaRef.Context, Loc, {}, Loc);
644 InitExpr->setType(SemaRef.Context.VoidTy);
645 SubInit = InitExpr;
646 Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
647 } else {
648 // C++03:
649 // shall be value-initialized.
650 }
651
652 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
653 // HACK: libstdc++ prior to 4.9 marks the vector default constructor
654 // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic
655 // in that case. stlport does so too.
656 // Look for std::__debug for libstdc++, and for std:: for stlport.
657 // This is effectively a compiler-side implementation of LWG2193.
658 if (!InitSeq && EmptyInitList &&
659 InitSeq.getFailureKind() ==
660 InitializationSequence::FK_ExplicitConstructor &&
661 SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2014'04'22)) {
662 OverloadCandidateSet::iterator Best;
663 OverloadingResult O =
664 InitSeq.getFailedCandidateSet()
665 .BestViableFunction(S&: SemaRef, Loc: Kind.getLocation(), Best);
666 (void)O;
667 assert(O == OR_Success && "Inconsistent overload resolution");
668 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
669 CXXRecordDecl *R = CtorDecl->getParent();
670
671 if (CtorDecl->getMinRequiredArguments() == 0 &&
672 CtorDecl->isExplicit() && R->getDeclName() &&
673 SemaRef.SourceMgr.isInSystemHeader(Loc: CtorDecl->getLocation())) {
674 bool IsInStd = false;
675 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: R->getDeclContext());
676 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(Val: ND->getParent())) {
677 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(NS: ND))
678 IsInStd = true;
679 }
680
681 if (IsInStd &&
682 llvm::StringSwitch<bool>(R->getName())
683 .Cases(CaseStrings: {"basic_string", "deque", "forward_list"}, Value: true)
684 .Cases(CaseStrings: {"list", "map", "multimap", "multiset"}, Value: true)
685 .Cases(CaseStrings: {"priority_queue", "queue", "set", "stack"}, Value: true)
686 .Cases(CaseStrings: {"unordered_map", "unordered_set", "vector"}, Value: true)
687 .Default(Value: false)) {
688 InitSeq.InitializeFrom(
689 S&: SemaRef, Entity,
690 Kind: InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, isImplicit: true),
691 Args: MultiExprArg(), /*TopLevelOfInitList=*/false,
692 TreatUnavailableAsInvalid);
693 // Emit a warning for this. System header warnings aren't shown
694 // by default, but people working on system headers should see it.
695 if (!VerifyOnly) {
696 SemaRef.Diag(Loc: CtorDecl->getLocation(),
697 DiagID: diag::warn_invalid_initializer_from_system_header);
698 if (Entity.getKind() == InitializedEntity::EK_Member)
699 SemaRef.Diag(Loc: Entity.getDecl()->getLocation(),
700 DiagID: diag::note_used_in_initialization_here);
701 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
702 SemaRef.Diag(Loc, DiagID: diag::note_used_in_initialization_here);
703 }
704 }
705 }
706 }
707 if (!InitSeq) {
708 if (!VerifyOnly) {
709 InitSeq.Diagnose(S&: SemaRef, Entity, Kind, Args: SubInit);
710 if (Entity.getKind() == InitializedEntity::EK_Member)
711 SemaRef.Diag(Loc: Entity.getDecl()->getLocation(),
712 DiagID: diag::note_in_omitted_aggregate_initializer)
713 << /*field*/1 << Entity.getDecl();
714 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
715 bool IsTrailingArrayNewMember =
716 Entity.getParent() &&
717 Entity.getParent()->isVariableLengthArrayNew();
718 SemaRef.Diag(Loc, DiagID: diag::note_in_omitted_aggregate_initializer)
719 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
720 << Entity.getElementIndex();
721 }
722 }
723 hadError = true;
724 return ExprError();
725 }
726
727 return VerifyOnly ? ExprResult()
728 : InitSeq.Perform(S&: SemaRef, Entity, Kind, Args: SubInit);
729}
730
731void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
732 SourceLocation Loc) {
733 // If we're building a fully-structured list, we'll check this at the end
734 // once we know which elements are actually initialized. Otherwise, we know
735 // that there are no designators so we can just check now.
736 if (FullyStructuredList)
737 return;
738 PerformEmptyInit(Loc, Entity);
739}
740
741void InitListChecker::FillInEmptyInitForBase(
742 unsigned Init, const CXXBaseSpecifier &Base,
743 const InitializedEntity &ParentEntity, InitListExpr *ILE,
744 bool &RequiresSecondPass, bool FillWithNoInit) {
745 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
746 Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &ParentEntity);
747
748 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
749 ExprResult BaseInit = FillWithNoInit
750 ? new (SemaRef.Context) NoInitExpr(Base.getType())
751 : PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: BaseEntity);
752 if (BaseInit.isInvalid()) {
753 hadError = true;
754 return;
755 }
756
757 if (!VerifyOnly) {
758 assert(Init < ILE->getNumInits() && "should have been expanded");
759 ILE->setInit(Init, expr: BaseInit.getAs<Expr>());
760 }
761 } else if (InitListExpr *InnerILE =
762 dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) {
763 FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerILE, RequiresSecondPass,
764 OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
765 } else if (DesignatedInitUpdateExpr *InnerDIUE =
766 dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) {
767 FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerDIUE->getUpdater(),
768 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
769 /*FillWithNoInit =*/true);
770 }
771}
772
773void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
774 const InitializedEntity &ParentEntity,
775 InitListExpr *ILE,
776 bool &RequiresSecondPass,
777 bool FillWithNoInit) {
778 SourceLocation Loc = ILE->getEndLoc();
779 unsigned NumInits = ILE->getNumInits();
780 InitializedEntity MemberEntity
781 = InitializedEntity::InitializeMember(Member: Field, Parent: &ParentEntity);
782
783 if (Init >= NumInits || !ILE->getInit(Init)) {
784 if (const RecordType *RType = ILE->getType()->getAsCanonical<RecordType>())
785 if (!RType->getDecl()->isUnion())
786 assert((Init < NumInits || VerifyOnly) &&
787 "This ILE should have been expanded");
788
789 if (FillWithNoInit) {
790 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
791 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
792 if (Init < NumInits)
793 ILE->setInit(Init, expr: Filler);
794 else
795 ILE->updateInit(C: SemaRef.Context, Init, expr: Filler);
796 return;
797 }
798
799 if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() &&
800 !SemaRef.isUnevaluatedContext()) {
801 SemaRef.Diag(Loc: ILE->getExprLoc(), DiagID: diag::warn_field_requires_explicit_init)
802 << /* Var-in-Record */ 0 << Field;
803 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at)
804 << Field;
805 }
806
807 // C++1y [dcl.init.aggr]p7:
808 // If there are fewer initializer-clauses in the list than there are
809 // members in the aggregate, then each member not explicitly initialized
810 // shall be initialized from its brace-or-equal-initializer [...]
811 if (Field->hasInClassInitializer()) {
812 if (VerifyOnly)
813 return;
814
815 ExprResult DIE;
816 {
817 // Enter a default initializer rebuild context, then we can support
818 // lifetime extension of temporary created by aggregate initialization
819 // using a default member initializer.
820 // CWG1815 (https://wg21.link/CWG1815).
821 EnterExpressionEvaluationContext RebuildDefaultInit(
822 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
823 SemaRef.currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
824 true;
825 SemaRef.currentEvaluationContext().DelayedDefaultInitializationContext =
826 SemaRef.parentEvaluationContext()
827 .DelayedDefaultInitializationContext;
828 SemaRef.currentEvaluationContext().InLifetimeExtendingContext =
829 SemaRef.parentEvaluationContext().InLifetimeExtendingContext;
830 DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
831 }
832 if (DIE.isInvalid()) {
833 hadError = true;
834 return;
835 }
836 SemaRef.checkInitializerLifetime(Entity: MemberEntity, Init: DIE.get());
837 if (Init < NumInits)
838 ILE->setInit(Init, expr: DIE.get());
839 else {
840 ILE->updateInit(C: SemaRef.Context, Init, expr: DIE.get());
841 RequiresSecondPass = true;
842 }
843 return;
844 }
845
846 if (Field->getType()->isReferenceType()) {
847 if (!VerifyOnly) {
848 // C++ [dcl.init.aggr]p9:
849 // If an incomplete or empty initializer-list leaves a
850 // member of reference type uninitialized, the program is
851 // ill-formed.
852 SemaRef.Diag(Loc, DiagID: diag::err_init_reference_member_uninitialized)
853 << Field->getType()
854 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
855 ->getSourceRange();
856 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_uninit_reference_member);
857 }
858 hadError = true;
859 return;
860 }
861
862 ExprResult MemberInit = PerformEmptyInit(Loc, Entity: MemberEntity);
863 if (MemberInit.isInvalid()) {
864 hadError = true;
865 return;
866 }
867
868 if (hadError || VerifyOnly) {
869 // Do nothing
870 } else if (Init < NumInits) {
871 ILE->setInit(Init, expr: MemberInit.getAs<Expr>());
872 } else if (!isa<ImplicitValueInitExpr>(Val: MemberInit.get())) {
873 // Empty initialization requires a constructor call, so
874 // extend the initializer list to include the constructor
875 // call and make a note that we'll need to take another pass
876 // through the initializer list.
877 ILE->updateInit(C: SemaRef.Context, Init, expr: MemberInit.getAs<Expr>());
878 RequiresSecondPass = true;
879 }
880 } else if (InitListExpr *InnerILE
881 = dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) {
882 FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerILE,
883 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
884 } else if (DesignatedInitUpdateExpr *InnerDIUE =
885 dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) {
886 FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerDIUE->getUpdater(),
887 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
888 /*FillWithNoInit =*/true);
889 }
890}
891
892/// Recursively replaces NULL values within the given initializer list
893/// with expressions that perform value-initialization of the
894/// appropriate type, and finish off the InitListExpr formation.
895void
896InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
897 InitListExpr *ILE,
898 bool &RequiresSecondPass,
899 InitListExpr *OuterILE,
900 unsigned OuterIndex,
901 bool FillWithNoInit) {
902 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
903 "Should not have void type");
904
905 // We don't need to do any checks when just filling NoInitExprs; that can't
906 // fail.
907 if (FillWithNoInit && VerifyOnly)
908 return;
909
910 // If this is a nested initializer list, we might have changed its contents
911 // (and therefore some of its properties, such as instantiation-dependence)
912 // while filling it in. Inform the outer initializer list so that its state
913 // can be updated to match.
914 // FIXME: We should fully build the inner initializers before constructing
915 // the outer InitListExpr instead of mutating AST nodes after they have
916 // been used as subexpressions of other nodes.
917 struct UpdateOuterILEWithUpdatedInit {
918 InitListExpr *Outer;
919 unsigned OuterIndex;
920 ~UpdateOuterILEWithUpdatedInit() {
921 if (Outer)
922 Outer->setInit(Init: OuterIndex, expr: Outer->getInit(Init: OuterIndex));
923 }
924 } UpdateOuterRAII = {.Outer: OuterILE, .OuterIndex: OuterIndex};
925
926 // A transparent ILE is not performing aggregate initialization and should
927 // not be filled in.
928 if (ILE->isTransparent())
929 return;
930
931 if (const auto *RDecl = ILE->getType()->getAsRecordDecl()) {
932 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
933 FillInEmptyInitForField(Init: 0, Field: ILE->getInitializedFieldInUnion(), ParentEntity: Entity, ILE,
934 RequiresSecondPass, FillWithNoInit);
935 } else {
936 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
937 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
938 "We should have computed initialized fields already");
939 // The fields beyond ILE->getNumInits() are default initialized, so in
940 // order to leave them uninitialized, the ILE is expanded and the extra
941 // fields are then filled with NoInitExpr.
942 unsigned NumElems = numStructUnionElements(DeclType: ILE->getType());
943 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
944 ++NumElems;
945 if (!VerifyOnly && ILE->getNumInits() < NumElems)
946 ILE->resizeInits(Context: SemaRef.Context, NumInits: NumElems);
947
948 unsigned Init = 0;
949
950 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RDecl)) {
951 for (auto &Base : CXXRD->bases()) {
952 if (hadError)
953 return;
954
955 FillInEmptyInitForBase(Init, Base, ParentEntity: Entity, ILE, RequiresSecondPass,
956 FillWithNoInit);
957 ++Init;
958 }
959 }
960
961 for (auto *Field : RDecl->fields()) {
962 if (Field->isUnnamedBitField())
963 continue;
964
965 if (hadError)
966 return;
967
968 FillInEmptyInitForField(Init, Field, ParentEntity: Entity, ILE, RequiresSecondPass,
969 FillWithNoInit);
970 if (hadError)
971 return;
972
973 ++Init;
974
975 // Only look at the first initialization of a union.
976 if (RDecl->isUnion())
977 break;
978 }
979 }
980
981 return;
982 }
983
984 QualType ElementType;
985
986 InitializedEntity ElementEntity = Entity;
987 unsigned NumInits = ILE->getNumInits();
988 uint64_t NumElements = NumInits;
989 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(T: ILE->getType())) {
990 ElementType = AType->getElementType();
991 if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType))
992 NumElements = CAType->getZExtSize();
993 // For an array new with an unknown bound, ask for one additional element
994 // in order to populate the array filler.
995 if (Entity.isVariableLengthArrayNew())
996 ++NumElements;
997 ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context,
998 Index: 0, Parent: Entity);
999 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
1000 ElementType = VType->getElementType();
1001 NumElements = VType->getNumElements();
1002 ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context,
1003 Index: 0, Parent: Entity);
1004 } else
1005 ElementType = ILE->getType();
1006
1007 bool SkipEmptyInitChecks = false;
1008 for (uint64_t Init = 0; Init != NumElements; ++Init) {
1009 if (hadError)
1010 return;
1011
1012 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
1013 ElementEntity.getKind() == InitializedEntity::EK_VectorElement ||
1014 ElementEntity.getKind() == InitializedEntity::EK_MatrixElement)
1015 ElementEntity.setElementIndex(Init);
1016
1017 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
1018 return;
1019
1020 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
1021 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1022 ILE->setInit(Init, expr: ILE->getArrayFiller());
1023 else if (!InitExpr && !ILE->hasArrayFiller()) {
1024 // In VerifyOnly mode, there's no point performing empty initialization
1025 // more than once.
1026 if (SkipEmptyInitChecks)
1027 continue;
1028
1029 Expr *Filler = nullptr;
1030
1031 if (FillWithNoInit)
1032 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
1033 else {
1034 ExprResult ElementInit =
1035 PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: ElementEntity);
1036 if (ElementInit.isInvalid()) {
1037 hadError = true;
1038 return;
1039 }
1040
1041 Filler = ElementInit.getAs<Expr>();
1042 }
1043
1044 if (hadError) {
1045 // Do nothing
1046 } else if (VerifyOnly) {
1047 SkipEmptyInitChecks = true;
1048 } else if (Init < NumInits) {
1049 // For arrays, just set the expression used for value-initialization
1050 // of the "holes" in the array.
1051 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
1052 ILE->setArrayFiller(Filler);
1053 else
1054 ILE->setInit(Init, expr: Filler);
1055 } else {
1056 // For arrays, just set the expression used for value-initialization
1057 // of the rest of elements and exit.
1058 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
1059 ILE->setArrayFiller(Filler);
1060 return;
1061 }
1062
1063 if (!isa<ImplicitValueInitExpr>(Val: Filler) && !isa<NoInitExpr>(Val: Filler)) {
1064 // Empty initialization requires a constructor call, so
1065 // extend the initializer list to include the constructor
1066 // call and make a note that we'll need to take another pass
1067 // through the initializer list.
1068 ILE->updateInit(C: SemaRef.Context, Init, expr: Filler);
1069 RequiresSecondPass = true;
1070 }
1071 }
1072 } else if (InitListExpr *InnerILE
1073 = dyn_cast_or_null<InitListExpr>(Val: InitExpr)) {
1074 FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerILE, RequiresSecondPass,
1075 OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
1076 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1077 dyn_cast_or_null<DesignatedInitUpdateExpr>(Val: InitExpr)) {
1078 FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerDIUE->getUpdater(),
1079 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
1080 /*FillWithNoInit =*/true);
1081 }
1082 }
1083}
1084
1085static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1086 for (const Stmt *Init : *IL)
1087 if (isa_and_nonnull<DesignatedInitExpr>(Val: Init))
1088 return true;
1089 return false;
1090}
1091
1092InitListChecker::InitListChecker(
1093 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1094 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1095 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1096 : SemaRef(S), VerifyOnly(VerifyOnly),
1097 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1098 InOverloadResolution(InOverloadResolution),
1099 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1100 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1101 FullyStructuredList =
1102 createInitListExpr(CurrentObjectType: T, InitRange: IL->getSourceRange(), ExpectedNumInits: IL->getNumInits());
1103
1104 // FIXME: Check that IL isn't already the semantic form of some other
1105 // InitListExpr. If it is, we'd create a broken AST.
1106 if (!VerifyOnly)
1107 FullyStructuredList->setSyntacticForm(IL);
1108 }
1109
1110 CheckExplicitInitList(Entity, IList: IL, T, StructuredList: FullyStructuredList,
1111 /*TopLevelObject=*/true);
1112
1113 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1114 bool RequiresSecondPass = false;
1115 FillInEmptyInitializations(Entity, ILE: FullyStructuredList, RequiresSecondPass,
1116 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1117 if (RequiresSecondPass && !hadError)
1118 FillInEmptyInitializations(Entity, ILE: FullyStructuredList,
1119 RequiresSecondPass, OuterILE: nullptr, OuterIndex: 0);
1120 }
1121 if (hadError && FullyStructuredList)
1122 FullyStructuredList->markError();
1123}
1124
1125int InitListChecker::numArrayElements(QualType DeclType) {
1126 // FIXME: use a proper constant
1127 int maxElements = 0x7FFFFFFF;
1128 if (const ConstantArrayType *CAT =
1129 SemaRef.Context.getAsConstantArrayType(T: DeclType)) {
1130 maxElements = static_cast<int>(CAT->getZExtSize());
1131 }
1132 return maxElements;
1133}
1134
1135int InitListChecker::numStructUnionElements(QualType DeclType) {
1136 auto *structDecl = DeclType->castAsRecordDecl();
1137 int InitializableMembers = 0;
1138 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: structDecl))
1139 InitializableMembers += CXXRD->getNumBases();
1140 for (const auto *Field : structDecl->fields())
1141 if (!Field->isUnnamedBitField())
1142 ++InitializableMembers;
1143
1144 if (structDecl->isUnion())
1145 return std::min(a: InitializableMembers, b: 1);
1146 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1147}
1148
1149/// Determine whether Entity is an entity for which it is idiomatic to elide
1150/// the braces in aggregate initialization.
1151static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1152 // Recursive initialization of the one and only field within an aggregate
1153 // class is considered idiomatic. This case arises in particular for
1154 // initialization of std::array, where the C++ standard suggests the idiom of
1155 //
1156 // std::array<T, N> arr = {1, 2, 3};
1157 //
1158 // (where std::array is an aggregate struct containing a single array field.
1159
1160 if (!Entity.getParent())
1161 return false;
1162
1163 // Allows elide brace initialization for aggregates with empty base.
1164 if (Entity.getKind() == InitializedEntity::EK_Base) {
1165 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1166 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(Val: ParentRD);
1167 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1168 }
1169
1170 // Allow brace elision if the only subobject is a field.
1171 if (Entity.getKind() == InitializedEntity::EK_Member) {
1172 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1173 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: ParentRD)) {
1174 if (CXXRD->getNumBases()) {
1175 return false;
1176 }
1177 }
1178 auto FieldIt = ParentRD->field_begin();
1179 assert(FieldIt != ParentRD->field_end() &&
1180 "no fields but have initializer for member?");
1181 return ++FieldIt == ParentRD->field_end();
1182 }
1183
1184 return false;
1185}
1186
1187/// Check whether the range of the initializer \p ParentIList from element
1188/// \p Index onwards can be used to initialize an object of type \p T. Update
1189/// \p Index to indicate how many elements of the list were consumed.
1190///
1191/// This also fills in \p StructuredList, from element \p StructuredIndex
1192/// onwards, with the fully-braced, desugared form of the initialization.
1193void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1194 InitListExpr *ParentIList,
1195 QualType T, unsigned &Index,
1196 InitListExpr *StructuredList,
1197 unsigned &StructuredIndex) {
1198 int maxElements = 0;
1199
1200 if (T->isArrayType())
1201 maxElements = numArrayElements(DeclType: T);
1202 else if (T->isRecordType())
1203 maxElements = numStructUnionElements(DeclType: T);
1204 else if (T->isVectorType())
1205 maxElements = T->castAs<VectorType>()->getNumElements();
1206 else
1207 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1208
1209 if (maxElements == 0) {
1210 if (!VerifyOnly)
1211 SemaRef.Diag(Loc: ParentIList->getInit(Init: Index)->getBeginLoc(),
1212 DiagID: diag::err_implicit_empty_initializer);
1213 ++Index;
1214 hadError = true;
1215 return;
1216 }
1217
1218 // Build a structured initializer list corresponding to this subobject.
1219 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1220 IList: ParentIList, Index, CurrentObjectType: T, StructuredList, StructuredIndex,
1221 InitRange: SourceRange(ParentIList->getInit(Init: Index)->getBeginLoc(),
1222 ParentIList->getSourceRange().getEnd()));
1223 unsigned StructuredSubobjectInitIndex = 0;
1224
1225 // Check the element types and build the structural subobject.
1226 unsigned StartIndex = Index;
1227 CheckListElementTypes(Entity, IList: ParentIList, DeclType&: T,
1228 /*SubobjectIsDesignatorContext=*/false, Index,
1229 StructuredList: StructuredSubobjectInitList,
1230 StructuredIndex&: StructuredSubobjectInitIndex);
1231
1232 if (StructuredSubobjectInitList) {
1233 StructuredSubobjectInitList->setType(T);
1234
1235 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1236 // Update the structured sub-object initializer so that it's ending
1237 // range corresponds with the end of the last initializer it used.
1238 if (EndIndex < ParentIList->getNumInits() &&
1239 ParentIList->getInit(Init: EndIndex)) {
1240 SourceLocation EndLoc
1241 = ParentIList->getInit(Init: EndIndex)->getSourceRange().getEnd();
1242 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1243 }
1244
1245 // Complain about missing braces.
1246 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1247 !ParentIList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) &&
1248 !isIdiomaticBraceElisionEntity(Entity)) {
1249 SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(),
1250 DiagID: diag::warn_missing_braces)
1251 << StructuredSubobjectInitList->getSourceRange()
1252 << FixItHint::CreateInsertion(
1253 InsertionLoc: StructuredSubobjectInitList->getBeginLoc(), Code: "{")
1254 << FixItHint::CreateInsertion(
1255 InsertionLoc: SemaRef.getLocForEndOfToken(
1256 Loc: StructuredSubobjectInitList->getEndLoc()),
1257 Code: "}");
1258 }
1259
1260 // Warn if this type won't be an aggregate in future versions of C++.
1261 auto *CXXRD = T->getAsCXXRecordDecl();
1262 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1263 SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(),
1264 DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors)
1265 << StructuredSubobjectInitList->getSourceRange() << T;
1266 }
1267 }
1268}
1269
1270/// Warn that \p Entity was of scalar type and was initialized by a
1271/// single-element braced initializer list.
1272static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1273 SourceRange Braces) {
1274 // Don't warn during template instantiation. If the initialization was
1275 // non-dependent, we warned during the initial parse; otherwise, the
1276 // type might not be scalar in some uses of the template.
1277 if (S.inTemplateInstantiation())
1278 return;
1279
1280 unsigned DiagID = 0;
1281
1282 switch (Entity.getKind()) {
1283 case InitializedEntity::EK_VectorElement:
1284 case InitializedEntity::EK_MatrixElement:
1285 case InitializedEntity::EK_ComplexElement:
1286 case InitializedEntity::EK_ArrayElement:
1287 case InitializedEntity::EK_Parameter:
1288 case InitializedEntity::EK_Parameter_CF_Audited:
1289 case InitializedEntity::EK_TemplateParameter:
1290 case InitializedEntity::EK_Result:
1291 case InitializedEntity::EK_ParenAggInitMember:
1292 // Extra braces here are suspicious.
1293 DiagID = diag::warn_braces_around_init;
1294 break;
1295
1296 case InitializedEntity::EK_Member:
1297 // Warn on aggregate initialization but not on ctor init list or
1298 // default member initializer.
1299 if (Entity.getParent())
1300 DiagID = diag::warn_braces_around_init;
1301 break;
1302
1303 case InitializedEntity::EK_Variable:
1304 case InitializedEntity::EK_LambdaCapture:
1305 // No warning, might be direct-list-initialization.
1306 // FIXME: Should we warn for copy-list-initialization in these cases?
1307 break;
1308
1309 case InitializedEntity::EK_New:
1310 case InitializedEntity::EK_Temporary:
1311 case InitializedEntity::EK_CompoundLiteralInit:
1312 // No warning, braces are part of the syntax of the underlying construct.
1313 break;
1314
1315 case InitializedEntity::EK_RelatedResult:
1316 // No warning, we already warned when initializing the result.
1317 break;
1318
1319 case InitializedEntity::EK_Exception:
1320 case InitializedEntity::EK_Base:
1321 case InitializedEntity::EK_Delegating:
1322 case InitializedEntity::EK_BlockElement:
1323 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1324 case InitializedEntity::EK_Binding:
1325 case InitializedEntity::EK_StmtExprResult:
1326 llvm_unreachable("unexpected braced scalar init");
1327 }
1328
1329 if (DiagID) {
1330 S.Diag(Loc: Braces.getBegin(), DiagID)
1331 << Entity.getType()->isSizelessBuiltinType() << Braces
1332 << FixItHint::CreateRemoval(RemoveRange: Braces.getBegin())
1333 << FixItHint::CreateRemoval(RemoveRange: Braces.getEnd());
1334 }
1335}
1336
1337/// Check whether the initializer \p IList (that was written with explicit
1338/// braces) can be used to initialize an object of type \p T.
1339///
1340/// This also fills in \p StructuredList with the fully-braced, desugared
1341/// form of the initialization.
1342void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1343 InitListExpr *IList, QualType &T,
1344 InitListExpr *StructuredList,
1345 bool TopLevelObject) {
1346 unsigned Index = 0, StructuredIndex = 0;
1347 CheckListElementTypes(Entity, IList, DeclType&: T, /*SubobjectIsDesignatorContext=*/true,
1348 Index, StructuredList, StructuredIndex, TopLevelObject);
1349 if (StructuredList) {
1350 QualType ExprTy = T;
1351 if (!ExprTy->isArrayType())
1352 ExprTy = ExprTy.getNonLValueExprType(Context: SemaRef.Context);
1353 if (!VerifyOnly)
1354 IList->setType(ExprTy);
1355 StructuredList->setType(ExprTy);
1356 }
1357 if (hadError)
1358 return;
1359
1360 // Don't complain for incomplete types, since we'll get an error elsewhere.
1361 if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) {
1362 // We have leftover initializers
1363 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1364 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1365 hadError = ExtraInitsIsError;
1366 if (VerifyOnly) {
1367 return;
1368 } else if (StructuredIndex == 1 &&
1369 IsStringInit(init: StructuredList->getInit(Init: 0), declType: T, Context&: SemaRef.Context) ==
1370 SIF_None) {
1371 unsigned DK =
1372 ExtraInitsIsError
1373 ? diag::err_excess_initializers_in_char_array_initializer
1374 : diag::ext_excess_initializers_in_char_array_initializer;
1375 SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK)
1376 << IList->getInit(Init: Index)->getSourceRange();
1377 } else if (T->isSizelessBuiltinType()) {
1378 unsigned DK = ExtraInitsIsError
1379 ? diag::err_excess_initializers_for_sizeless_type
1380 : diag::ext_excess_initializers_for_sizeless_type;
1381 SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK)
1382 << T << IList->getInit(Init: Index)->getSourceRange();
1383 } else {
1384 int initKind = T->isArrayType() ? 0
1385 : T->isVectorType() ? 1
1386 : T->isMatrixType() ? 2
1387 : T->isScalarType() ? 3
1388 : T->isUnionType() ? 4
1389 : 5;
1390
1391 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1392 : diag::ext_excess_initializers;
1393 SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK)
1394 << initKind << IList->getInit(Init: Index)->getSourceRange();
1395 }
1396 }
1397
1398 if (!VerifyOnly) {
1399 if (T->isScalarType() && IList->getNumInits() == 1 &&
1400 !isa<InitListExpr>(Val: IList->getInit(Init: 0)))
1401 warnBracedScalarInit(S&: SemaRef, Entity, Braces: IList->getSourceRange());
1402
1403 // Warn if this is a class type that won't be an aggregate in future
1404 // versions of C++.
1405 auto *CXXRD = T->getAsCXXRecordDecl();
1406 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1407 // Don't warn if there's an equivalent default constructor that would be
1408 // used instead.
1409 bool HasEquivCtor = false;
1410 if (IList->getNumInits() == 0) {
1411 auto *CD = SemaRef.LookupDefaultConstructor(Class: CXXRD);
1412 HasEquivCtor = CD && !CD->isDeleted();
1413 }
1414
1415 if (!HasEquivCtor) {
1416 SemaRef.Diag(Loc: IList->getBeginLoc(),
1417 DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors)
1418 << IList->getSourceRange() << T;
1419 }
1420 }
1421 }
1422}
1423
1424void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1425 InitListExpr *IList,
1426 QualType &DeclType,
1427 bool SubobjectIsDesignatorContext,
1428 unsigned &Index,
1429 InitListExpr *StructuredList,
1430 unsigned &StructuredIndex,
1431 bool TopLevelObject) {
1432 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1433 // Explicitly braced initializer for complex type can be real+imaginary
1434 // parts.
1435 CheckComplexType(Entity, IList, DeclType, Index,
1436 StructuredList, StructuredIndex);
1437 } else if (DeclType->isScalarType()) {
1438 CheckScalarType(Entity, IList, DeclType, Index,
1439 StructuredList, StructuredIndex);
1440 } else if (DeclType->isVectorType()) {
1441 CheckVectorType(Entity, IList, DeclType, Index,
1442 StructuredList, StructuredIndex);
1443 } else if (DeclType->isMatrixType()) {
1444 CheckMatrixType(Entity, IList, DeclType, Index, StructuredList,
1445 StructuredIndex);
1446 } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) {
1447 auto Bases =
1448 CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1449 CXXRecordDecl::base_class_const_iterator());
1450 if (DeclType->isRecordType()) {
1451 assert(DeclType->isAggregateType() &&
1452 "non-aggregate records should be handed in CheckSubElementType");
1453 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
1454 Bases = CXXRD->bases();
1455 } else {
1456 Bases = cast<CXXRecordDecl>(Val: RD)->bases();
1457 }
1458 CheckStructUnionTypes(Entity, IList, DeclType, Bases, Field: RD->field_begin(),
1459 SubobjectIsDesignatorContext, Index, StructuredList,
1460 StructuredIndex, TopLevelObject);
1461 } else if (DeclType->isArrayType()) {
1462 llvm::APSInt Zero(
1463 SemaRef.Context.getTypeSize(T: SemaRef.Context.getSizeType()),
1464 false);
1465 CheckArrayType(Entity, IList, DeclType, elementIndex: Zero,
1466 SubobjectIsDesignatorContext, Index,
1467 StructuredList, StructuredIndex);
1468 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1469 // This type is invalid, issue a diagnostic.
1470 ++Index;
1471 if (!VerifyOnly)
1472 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type)
1473 << DeclType;
1474 hadError = true;
1475 } else if (DeclType->isReferenceType()) {
1476 CheckReferenceType(Entity, IList, DeclType, Index,
1477 StructuredList, StructuredIndex);
1478 } else if (DeclType->isObjCObjectType()) {
1479 if (!VerifyOnly)
1480 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_objc_class) << DeclType;
1481 hadError = true;
1482 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1483 DeclType->isSizelessBuiltinType()) {
1484 // Checks for scalar type are sufficient for these types too.
1485 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1486 StructuredIndex);
1487 } else if (DeclType->isDependentType()) {
1488 // C++ [over.match.class.deduct]p1.5:
1489 // brace elision is not considered for any aggregate element that has a
1490 // dependent non-array type or an array type with a value-dependent bound
1491 ++Index;
1492 assert(AggrDeductionCandidateParamTypes);
1493 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1494 } else {
1495 if (!VerifyOnly)
1496 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type)
1497 << DeclType;
1498 hadError = true;
1499 }
1500}
1501
1502void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1503 InitListExpr *IList,
1504 QualType ElemType,
1505 unsigned &Index,
1506 InitListExpr *StructuredList,
1507 unsigned &StructuredIndex,
1508 bool DirectlyDesignated) {
1509 Expr *expr = IList->getInit(Init: Index);
1510
1511 if (ElemType->isReferenceType())
1512 return CheckReferenceType(Entity, IList, DeclType: ElemType, Index,
1513 StructuredList, StructuredIndex);
1514
1515 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(Val: expr)) {
1516 if (SubInitList->getNumInits() == 1 &&
1517 IsStringInit(init: SubInitList->getInit(Init: 0), declType: ElemType, Context&: SemaRef.Context) ==
1518 SIF_None) {
1519 // FIXME: It would be more faithful and no less correct to include an
1520 // InitListExpr in the semantic form of the initializer list in this case.
1521 expr = SubInitList->getInit(Init: 0);
1522 }
1523 // Nested aggregate initialization and C++ initialization are handled later.
1524 } else if (isa<ImplicitValueInitExpr>(Val: expr)) {
1525 // This happens during template instantiation when we see an InitListExpr
1526 // that we've already checked once.
1527 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1528 "found implicit initialization for the wrong type");
1529 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1530 ++Index;
1531 return;
1532 }
1533
1534 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(Val: expr)) {
1535 // C++ [dcl.init.aggr]p2:
1536 // Each member is copy-initialized from the corresponding
1537 // initializer-clause.
1538
1539 // FIXME: Better EqualLoc?
1540 InitializationKind Kind =
1541 InitializationKind::CreateCopy(InitLoc: expr->getBeginLoc(), EqualLoc: SourceLocation());
1542
1543 // Vector elements can be initialized from other vectors in which case
1544 // we need initialization entity with a type of a vector (and not a vector
1545 // element!) initializing multiple vector elements.
1546 auto TmpEntity =
1547 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1548 ? InitializedEntity::InitializeTemporary(Type: ElemType)
1549 : Entity;
1550
1551 if (TmpEntity.getType()->isDependentType()) {
1552 // C++ [over.match.class.deduct]p1.5:
1553 // brace elision is not considered for any aggregate element that has a
1554 // dependent non-array type or an array type with a value-dependent
1555 // bound
1556 assert(AggrDeductionCandidateParamTypes);
1557
1558 // In the presence of a braced-init-list within the initializer, we should
1559 // not perform brace-elision, even if brace elision would otherwise be
1560 // applicable. For example, given:
1561 //
1562 // template <class T> struct Foo {
1563 // T t[2];
1564 // };
1565 //
1566 // Foo t = {{1, 2}};
1567 //
1568 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1569 // {{1, 2}}.
1570 if (isa<InitListExpr, DesignatedInitExpr>(Val: expr) ||
1571 !isa_and_present<ConstantArrayType>(
1572 Val: SemaRef.Context.getAsArrayType(T: ElemType))) {
1573 ++Index;
1574 AggrDeductionCandidateParamTypes->push_back(Elt: ElemType);
1575 return;
1576 }
1577 } else {
1578 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1579 /*TopLevelOfInitList*/ true);
1580 // C++14 [dcl.init.aggr]p13:
1581 // If the assignment-expression can initialize a member, the member is
1582 // initialized. Otherwise [...] brace elision is assumed
1583 //
1584 // Brace elision is never performed if the element is not an
1585 // assignment-expression.
1586 if (Seq || isa<InitListExpr>(Val: expr)) {
1587 if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) {
1588 expr = HandleEmbed(Embed, Entity);
1589 }
1590 if (!VerifyOnly) {
1591 ExprResult Result = Seq.Perform(S&: SemaRef, Entity: TmpEntity, Kind, Args: expr);
1592 if (Result.isInvalid())
1593 hadError = true;
1594
1595 UpdateStructuredListElement(StructuredList, StructuredIndex,
1596 expr: Result.getAs<Expr>());
1597 } else if (!Seq) {
1598 hadError = true;
1599 } else if (StructuredList) {
1600 UpdateStructuredListElement(StructuredList, StructuredIndex,
1601 expr: getDummyInit());
1602 }
1603 if (!CurEmbed)
1604 ++Index;
1605 if (AggrDeductionCandidateParamTypes)
1606 AggrDeductionCandidateParamTypes->push_back(Elt: ElemType);
1607 return;
1608 }
1609 }
1610
1611 // Fall through for subaggregate initialization
1612 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1613 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1614 return CheckScalarType(Entity, IList, DeclType: ElemType, Index,
1615 StructuredList, StructuredIndex);
1616 } else if (const ArrayType *arrayType =
1617 SemaRef.Context.getAsArrayType(T: ElemType)) {
1618 // arrayType can be incomplete if we're initializing a flexible
1619 // array member. There's nothing we can do with the completed
1620 // type here, though.
1621
1622 if (IsStringInit(Init: expr, AT: arrayType, Context&: SemaRef.Context) == SIF_None) {
1623 // FIXME: Should we do this checking in verify-only mode?
1624 if (!VerifyOnly)
1625 CheckStringInit(Str: expr, DeclT&: ElemType, AT: arrayType, S&: SemaRef, Entity,
1626 CheckC23ConstexprInit: SemaRef.getLangOpts().C23 &&
1627 initializingConstexprVariable(Entity));
1628 if (StructuredList)
1629 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1630 ++Index;
1631 return;
1632 }
1633
1634 // Fall through for subaggregate initialization.
1635
1636 } else {
1637 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1638 ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1639 "Unexpected type");
1640
1641 // C99 6.7.8p13:
1642 //
1643 // The initializer for a structure or union object that has
1644 // automatic storage duration shall be either an initializer
1645 // list as described below, or a single expression that has
1646 // compatible structure or union type. In the latter case, the
1647 // initial value of the object, including unnamed members, is
1648 // that of the expression.
1649 ExprResult ExprRes = expr;
1650 if (SemaRef.CheckSingleAssignmentConstraints(LHSType: ElemType, RHS&: ExprRes,
1651 Diagnose: !VerifyOnly) !=
1652 AssignConvertType::Incompatible) {
1653 if (ExprRes.isInvalid())
1654 hadError = true;
1655 else {
1656 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(E: ExprRes.get());
1657 if (ExprRes.isInvalid())
1658 hadError = true;
1659 }
1660 UpdateStructuredListElement(StructuredList, StructuredIndex,
1661 expr: ExprRes.getAs<Expr>());
1662 ++Index;
1663 return;
1664 }
1665 ExprRes.get();
1666 // Fall through for subaggregate initialization
1667 }
1668
1669 // C++ [dcl.init.aggr]p12:
1670 //
1671 // [...] Otherwise, if the member is itself a non-empty
1672 // subaggregate, brace elision is assumed and the initializer is
1673 // considered for the initialization of the first member of
1674 // the subaggregate.
1675 // OpenCL vector initializer is handled elsewhere.
1676 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1677 ElemType->isAggregateType()) {
1678 CheckImplicitInitList(Entity, ParentIList: IList, T: ElemType, Index, StructuredList,
1679 StructuredIndex);
1680 ++StructuredIndex;
1681
1682 // In C++20, brace elision is not permitted for a designated initializer.
1683 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1684 if (InOverloadResolution)
1685 hadError = true;
1686 if (!VerifyOnly) {
1687 SemaRef.Diag(Loc: expr->getBeginLoc(),
1688 DiagID: diag::ext_designated_init_brace_elision)
1689 << expr->getSourceRange()
1690 << FixItHint::CreateInsertion(InsertionLoc: expr->getBeginLoc(), Code: "{")
1691 << FixItHint::CreateInsertion(
1692 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: expr->getEndLoc()), Code: "}");
1693 }
1694 }
1695 } else {
1696 if (!VerifyOnly) {
1697 // We cannot initialize this element, so let PerformCopyInitialization
1698 // produce the appropriate diagnostic. We already checked that this
1699 // initialization will fail.
1700 ExprResult Copy =
1701 SemaRef.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: expr,
1702 /*TopLevelOfInitList=*/true);
1703 (void)Copy;
1704 assert(Copy.isInvalid() &&
1705 "expected non-aggregate initialization to fail");
1706 }
1707 hadError = true;
1708 ++Index;
1709 ++StructuredIndex;
1710 }
1711}
1712
1713void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1714 InitListExpr *IList, QualType DeclType,
1715 unsigned &Index,
1716 InitListExpr *StructuredList,
1717 unsigned &StructuredIndex) {
1718 assert(Index == 0 && "Index in explicit init list must be zero");
1719
1720 // As an extension, clang supports complex initializers, which initialize
1721 // a complex number component-wise. When an explicit initializer list for
1722 // a complex number contains two initializers, this extension kicks in:
1723 // it expects the initializer list to contain two elements convertible to
1724 // the element type of the complex type. The first element initializes
1725 // the real part, and the second element intitializes the imaginary part.
1726
1727 if (IList->getNumInits() < 2)
1728 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1729 StructuredIndex);
1730
1731 // This is an extension in C. (The builtin _Complex type does not exist
1732 // in the C++ standard.)
1733 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1734 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_complex_component_init)
1735 << IList->getSourceRange();
1736
1737 // Initialize the complex number.
1738 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1739 InitializedEntity ElementEntity =
1740 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1741
1742 for (unsigned i = 0; i < 2; ++i) {
1743 ElementEntity.setElementIndex(Index);
1744 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1745 StructuredList, StructuredIndex);
1746 }
1747}
1748
1749void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1750 InitListExpr *IList, QualType DeclType,
1751 unsigned &Index,
1752 InitListExpr *StructuredList,
1753 unsigned &StructuredIndex) {
1754 if (Index >= IList->getNumInits()) {
1755 if (!VerifyOnly) {
1756 if (SemaRef.getLangOpts().CPlusPlus) {
1757 if (DeclType->isSizelessBuiltinType())
1758 SemaRef.Diag(Loc: IList->getBeginLoc(),
1759 DiagID: SemaRef.getLangOpts().CPlusPlus11
1760 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1761 : diag::err_empty_sizeless_initializer)
1762 << DeclType << IList->getSourceRange();
1763 else
1764 SemaRef.Diag(Loc: IList->getBeginLoc(),
1765 DiagID: SemaRef.getLangOpts().CPlusPlus11
1766 ? diag::warn_cxx98_compat_empty_scalar_initializer
1767 : diag::err_empty_scalar_initializer)
1768 << IList->getSourceRange();
1769 }
1770 }
1771 hadError =
1772 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1773 ++Index;
1774 ++StructuredIndex;
1775 return;
1776 }
1777
1778 Expr *expr = IList->getInit(Init: Index);
1779 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(Val: expr)) {
1780 // FIXME: This is invalid, and accepting it causes overload resolution
1781 // to pick the wrong overload in some corner cases.
1782 if (!VerifyOnly)
1783 SemaRef.Diag(Loc: SubIList->getBeginLoc(), DiagID: diag::ext_many_braces_around_init)
1784 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1785
1786 CheckScalarType(Entity, IList: SubIList, DeclType, Index, StructuredList,
1787 StructuredIndex);
1788 return;
1789 } else if (isa<DesignatedInitExpr>(Val: expr)) {
1790 if (!VerifyOnly)
1791 SemaRef.Diag(Loc: expr->getBeginLoc(),
1792 DiagID: diag::err_designator_for_scalar_or_sizeless_init)
1793 << DeclType->isSizelessBuiltinType() << DeclType
1794 << expr->getSourceRange();
1795 hadError = true;
1796 ++Index;
1797 ++StructuredIndex;
1798 return;
1799 } else if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) {
1800 expr = HandleEmbed(Embed, Entity);
1801 }
1802
1803 ExprResult Result;
1804 if (VerifyOnly) {
1805 if (SemaRef.CanPerformCopyInitialization(Entity, Init: expr))
1806 Result = getDummyInit();
1807 else
1808 Result = ExprError();
1809 } else {
1810 Result =
1811 SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr,
1812 /*TopLevelOfInitList=*/true);
1813 }
1814
1815 Expr *ResultExpr = nullptr;
1816
1817 if (Result.isInvalid())
1818 hadError = true; // types weren't compatible.
1819 else {
1820 ResultExpr = Result.getAs<Expr>();
1821
1822 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1823 // The type was promoted, update initializer list.
1824 // FIXME: Why are we updating the syntactic init list?
1825 IList->setInit(Init: Index, expr: ResultExpr);
1826 }
1827 }
1828
1829 UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr);
1830 if (!CurEmbed)
1831 ++Index;
1832 if (AggrDeductionCandidateParamTypes)
1833 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1834}
1835
1836void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1837 InitListExpr *IList, QualType DeclType,
1838 unsigned &Index,
1839 InitListExpr *StructuredList,
1840 unsigned &StructuredIndex) {
1841 if (Index >= IList->getNumInits()) {
1842 // FIXME: It would be wonderful if we could point at the actual member. In
1843 // general, it would be useful to pass location information down the stack,
1844 // so that we know the location (or decl) of the "current object" being
1845 // initialized.
1846 if (!VerifyOnly)
1847 SemaRef.Diag(Loc: IList->getBeginLoc(),
1848 DiagID: diag::err_init_reference_member_uninitialized)
1849 << DeclType << IList->getSourceRange();
1850 hadError = true;
1851 ++Index;
1852 ++StructuredIndex;
1853 return;
1854 }
1855
1856 Expr *expr = IList->getInit(Init: Index);
1857 if (isa<InitListExpr>(Val: expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1858 if (!VerifyOnly)
1859 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_non_aggr_init_list)
1860 << DeclType << IList->getSourceRange();
1861 hadError = true;
1862 ++Index;
1863 ++StructuredIndex;
1864 return;
1865 }
1866
1867 ExprResult Result;
1868 if (VerifyOnly) {
1869 if (SemaRef.CanPerformCopyInitialization(Entity,Init: expr))
1870 Result = getDummyInit();
1871 else
1872 Result = ExprError();
1873 } else {
1874 Result =
1875 SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr,
1876 /*TopLevelOfInitList=*/true);
1877 }
1878
1879 if (Result.isInvalid())
1880 hadError = true;
1881
1882 expr = Result.getAs<Expr>();
1883 // FIXME: Why are we updating the syntactic init list?
1884 if (!VerifyOnly && expr)
1885 IList->setInit(Init: Index, expr);
1886
1887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1888 ++Index;
1889 if (AggrDeductionCandidateParamTypes)
1890 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1891}
1892
1893void InitListChecker::CheckMatrixType(const InitializedEntity &Entity,
1894 InitListExpr *IList, QualType DeclType,
1895 unsigned &Index,
1896 InitListExpr *StructuredList,
1897 unsigned &StructuredIndex) {
1898 if (!SemaRef.getLangOpts().HLSL)
1899 return;
1900
1901 const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>();
1902
1903 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1904 // initializer list diagnostics. That means the execution should require
1905 // getNumElementsFlattened to equal getNumInits. In other words the execution
1906 // should never reach this point if this condition is not true".
1907 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1908 "Inits must equal Matrix element count");
1909
1910 QualType ElemTy = MT->getElementType();
1911
1912 Index = 0;
1913 InitializedEntity ElemEnt =
1914 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1915
1916 while (Index < IList->getNumInits()) {
1917 // Not a sublist: just consume directly.
1918 unsigned ColMajorIndex = (Index % MT->getNumRows()) * MT->getNumColumns() +
1919 (Index / MT->getNumRows());
1920 ElemEnt.setElementIndex(ColMajorIndex);
1921 CheckSubElementType(Entity: ElemEnt, IList, ElemType: ElemTy, Index&: ColMajorIndex, StructuredList,
1922 StructuredIndex);
1923 ++Index;
1924 }
1925}
1926
1927void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1928 InitListExpr *IList, QualType DeclType,
1929 unsigned &Index,
1930 InitListExpr *StructuredList,
1931 unsigned &StructuredIndex) {
1932 const VectorType *VT = DeclType->castAs<VectorType>();
1933 unsigned maxElements = VT->getNumElements();
1934 unsigned numEltsInit = 0;
1935 QualType elementType = VT->getElementType();
1936
1937 if (Index >= IList->getNumInits()) {
1938 // Make sure the element type can be value-initialized.
1939 CheckEmptyInitializable(
1940 Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity),
1941 Loc: IList->getEndLoc());
1942 return;
1943 }
1944
1945 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1946 // If the initializing element is a vector, try to copy-initialize
1947 // instead of breaking it apart (which is doomed to failure anyway).
1948 Expr *Init = IList->getInit(Init: Index);
1949 if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVectorType()) {
1950 ExprResult Result;
1951 if (VerifyOnly) {
1952 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1953 Result = getDummyInit();
1954 else
1955 Result = ExprError();
1956 } else {
1957 Result =
1958 SemaRef.PerformCopyInitialization(Entity, EqualLoc: Init->getBeginLoc(), Init,
1959 /*TopLevelOfInitList=*/true);
1960 }
1961
1962 Expr *ResultExpr = nullptr;
1963 if (Result.isInvalid())
1964 hadError = true; // types weren't compatible.
1965 else {
1966 ResultExpr = Result.getAs<Expr>();
1967
1968 if (ResultExpr != Init && !VerifyOnly) {
1969 // The type was promoted, update initializer list.
1970 // FIXME: Why are we updating the syntactic init list?
1971 IList->setInit(Init: Index, expr: ResultExpr);
1972 }
1973 }
1974 UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr);
1975 ++Index;
1976 if (AggrDeductionCandidateParamTypes)
1977 AggrDeductionCandidateParamTypes->push_back(Elt: elementType);
1978 return;
1979 }
1980
1981 InitializedEntity ElementEntity =
1982 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1983
1984 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1985 // Don't attempt to go past the end of the init list
1986 if (Index >= IList->getNumInits()) {
1987 CheckEmptyInitializable(Entity: ElementEntity, Loc: IList->getEndLoc());
1988 break;
1989 }
1990
1991 ElementEntity.setElementIndex(Index);
1992 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1993 StructuredList, StructuredIndex);
1994 }
1995
1996 if (VerifyOnly)
1997 return;
1998
1999 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
2000 const VectorType *T = Entity.getType()->castAs<VectorType>();
2001 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2002 T->getVectorKind() == VectorKind::NeonPoly)) {
2003 // The ability to use vector initializer lists is a GNU vector extension
2004 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2005 // endian machines it works fine, however on big endian machines it
2006 // exhibits surprising behaviour:
2007 //
2008 // uint32x2_t x = {42, 64};
2009 // return vget_lane_u32(x, 0); // Will return 64.
2010 //
2011 // Because of this, explicitly call out that it is non-portable.
2012 //
2013 SemaRef.Diag(Loc: IList->getBeginLoc(),
2014 DiagID: diag::warn_neon_vector_initializer_non_portable);
2015
2016 const char *typeCode;
2017 unsigned typeSize = SemaRef.Context.getTypeSize(T: elementType);
2018
2019 if (elementType->isFloatingType())
2020 typeCode = "f";
2021 else if (elementType->isSignedIntegerType())
2022 typeCode = "s";
2023 else if (elementType->isUnsignedIntegerType())
2024 typeCode = "u";
2025 else if (elementType->isMFloat8Type())
2026 typeCode = "mf";
2027 else
2028 llvm_unreachable("Invalid element type!");
2029
2030 SemaRef.Diag(Loc: IList->getBeginLoc(),
2031 DiagID: SemaRef.Context.getTypeSize(T: VT) > 64
2032 ? diag::note_neon_vector_initializer_non_portable_q
2033 : diag::note_neon_vector_initializer_non_portable)
2034 << typeCode << typeSize;
2035 }
2036
2037 return;
2038 }
2039
2040 InitializedEntity ElementEntity =
2041 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
2042
2043 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2044 for (unsigned i = 0; i < maxElements; ++i) {
2045 // Don't attempt to go past the end of the init list
2046 if (Index >= IList->getNumInits())
2047 break;
2048
2049 ElementEntity.setElementIndex(Index);
2050
2051 QualType IType = IList->getInit(Init: Index)->getType();
2052 if (!IType->isVectorType()) {
2053 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
2054 StructuredList, StructuredIndex);
2055 ++numEltsInit;
2056 } else {
2057 QualType VecType;
2058 const VectorType *IVT = IType->castAs<VectorType>();
2059 unsigned numIElts = IVT->getNumElements();
2060
2061 if (IType->isExtVectorType())
2062 VecType = SemaRef.Context.getExtVectorType(VectorType: elementType, NumElts: numIElts);
2063 else
2064 VecType = SemaRef.Context.getVectorType(VectorType: elementType, NumElts: numIElts,
2065 VecKind: IVT->getVectorKind());
2066 CheckSubElementType(Entity: ElementEntity, IList, ElemType: VecType, Index,
2067 StructuredList, StructuredIndex);
2068 numEltsInit += numIElts;
2069 }
2070 }
2071
2072 // OpenCL and HLSL require all elements to be initialized.
2073 if (numEltsInit != maxElements) {
2074 if (!VerifyOnly)
2075 SemaRef.Diag(Loc: IList->getBeginLoc(),
2076 DiagID: diag::err_vector_incorrect_num_elements)
2077 << (numEltsInit < maxElements) << maxElements << numEltsInit
2078 << /*initialization*/ 0;
2079 hadError = true;
2080 }
2081}
2082
2083/// Check if the type of a class element has an accessible destructor, and marks
2084/// it referenced. Returns true if we shouldn't form a reference to the
2085/// destructor.
2086///
2087/// Aggregate initialization requires a class element's destructor be
2088/// accessible per 11.6.1 [dcl.init.aggr]:
2089///
2090/// The destructor for each element of class type is potentially invoked
2091/// (15.4 [class.dtor]) from the context where the aggregate initialization
2092/// occurs.
2093static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
2094 Sema &SemaRef) {
2095 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2096 if (!CXXRD)
2097 return false;
2098
2099 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Class: CXXRD);
2100 if (!Destructor)
2101 return false;
2102
2103 SemaRef.CheckDestructorAccess(Loc, Dtor: Destructor,
2104 PDiag: SemaRef.PDiag(DiagID: diag::err_access_dtor_temp)
2105 << ElementType);
2106 SemaRef.MarkFunctionReferenced(Loc, Func: Destructor);
2107 return SemaRef.DiagnoseUseOfDecl(D: Destructor, Locs: Loc);
2108}
2109
2110static bool
2111canInitializeArrayWithEmbedDataString(ArrayRef<Expr *> ExprList,
2112 const InitializedEntity &Entity,
2113 ASTContext &Context) {
2114 QualType InitType = Entity.getType();
2115 const InitializedEntity *Parent = &Entity;
2116
2117 while (Parent) {
2118 InitType = Parent->getType();
2119 Parent = Parent->getParent();
2120 }
2121
2122 // Only one initializer, it's an embed and the types match;
2123 EmbedExpr *EE =
2124 ExprList.size() == 1
2125 ? dyn_cast_if_present<EmbedExpr>(Val: ExprList[0]->IgnoreParens())
2126 : nullptr;
2127 if (!EE)
2128 return false;
2129
2130 if (InitType->isArrayType()) {
2131 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2132 StringLiteral *SL = EE->getDataStringLiteral();
2133 return IsStringInit(Init: SL, AT: InitArrayType, Context) == SIF_None;
2134 }
2135 return false;
2136}
2137
2138void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2139 InitListExpr *IList, QualType &DeclType,
2140 llvm::APSInt elementIndex,
2141 bool SubobjectIsDesignatorContext,
2142 unsigned &Index,
2143 InitListExpr *StructuredList,
2144 unsigned &StructuredIndex) {
2145 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(T: DeclType);
2146
2147 if (!VerifyOnly) {
2148 if (checkDestructorReference(ElementType: arrayType->getElementType(),
2149 Loc: IList->getEndLoc(), SemaRef)) {
2150 hadError = true;
2151 return;
2152 }
2153 }
2154
2155 if (canInitializeArrayWithEmbedDataString(ExprList: IList->inits(), Entity,
2156 Context&: SemaRef.Context)) {
2157 EmbedExpr *Embed = cast<EmbedExpr>(Val: IList->inits()[0]);
2158 IList->setInit(Init: 0, expr: Embed->getDataStringLiteral());
2159 }
2160
2161 // Check for the special-case of initializing an array with a string.
2162 if (Index < IList->getNumInits()) {
2163 if (IsStringInit(Init: IList->getInit(Init: Index), AT: arrayType, Context&: SemaRef.Context) ==
2164 SIF_None) {
2165 // We place the string literal directly into the resulting
2166 // initializer list. This is the only place where the structure
2167 // of the structured initializer list doesn't match exactly,
2168 // because doing so would involve allocating one character
2169 // constant for each string.
2170 // FIXME: Should we do these checks in verify-only mode too?
2171 if (!VerifyOnly)
2172 CheckStringInit(
2173 Str: IList->getInit(Init: Index), DeclT&: DeclType, AT: arrayType, S&: SemaRef, Entity,
2174 CheckC23ConstexprInit: SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2175 if (StructuredList) {
2176 UpdateStructuredListElement(StructuredList, StructuredIndex,
2177 expr: IList->getInit(Init: Index));
2178 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: StructuredIndex);
2179 }
2180 ++Index;
2181 if (AggrDeductionCandidateParamTypes)
2182 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
2183 return;
2184 }
2185 }
2186 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Val: arrayType)) {
2187 // Check for VLAs; in standard C it would be possible to check this
2188 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2189 // them in all sorts of strange places).
2190 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2191 if (!VerifyOnly) {
2192 // C23 6.7.10p4: An entity of variable length array type shall not be
2193 // initialized except by an empty initializer.
2194 //
2195 // The C extension warnings are issued from ParseBraceInitializer() and
2196 // do not need to be issued here. However, we continue to issue an error
2197 // in the case there are initializers or we are compiling C++. We allow
2198 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2199 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2200 // FIXME: should we allow this construct in C++ when it makes sense to do
2201 // so?
2202 if (HasErr)
2203 SemaRef.Diag(Loc: VAT->getSizeExpr()->getBeginLoc(),
2204 DiagID: diag::err_variable_object_no_init)
2205 << VAT->getSizeExpr()->getSourceRange();
2206 }
2207 hadError = HasErr;
2208 ++Index;
2209 ++StructuredIndex;
2210 return;
2211 }
2212
2213 // We might know the maximum number of elements in advance.
2214 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2215 elementIndex.isUnsigned());
2216 bool maxElementsKnown = false;
2217 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: arrayType)) {
2218 maxElements = CAT->getSize();
2219 elementIndex = elementIndex.extOrTrunc(width: maxElements.getBitWidth());
2220 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2221 maxElementsKnown = true;
2222 }
2223
2224 QualType elementType = arrayType->getElementType();
2225 while (Index < IList->getNumInits()) {
2226 Expr *Init = IList->getInit(Init: Index);
2227 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) {
2228 // If we're not the subobject that matches up with the '{' for
2229 // the designator, we shouldn't be handling the
2230 // designator. Return immediately.
2231 if (!SubobjectIsDesignatorContext)
2232 return;
2233
2234 // Handle this designated initializer. elementIndex will be
2235 // updated to be the next array element we'll initialize.
2236 if (CheckDesignatedInitializer(Entity, IList, DIE, DesigIdx: 0,
2237 CurrentObjectType&: DeclType, NextField: nullptr, NextElementIndex: &elementIndex, Index,
2238 StructuredList, StructuredIndex, FinishSubobjectInit: true,
2239 TopLevelObject: false)) {
2240 hadError = true;
2241 continue;
2242 }
2243
2244 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2245 maxElements = maxElements.extend(width: elementIndex.getBitWidth());
2246 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2247 elementIndex = elementIndex.extend(width: maxElements.getBitWidth());
2248 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2249
2250 // If the array is of incomplete type, keep track of the number of
2251 // elements in the initializer.
2252 if (!maxElementsKnown && elementIndex > maxElements)
2253 maxElements = elementIndex;
2254
2255 continue;
2256 }
2257
2258 // If we know the maximum number of elements, and we've already
2259 // hit it, stop consuming elements in the initializer list.
2260 if (maxElementsKnown && elementIndex == maxElements)
2261 break;
2262
2263 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2264 Context&: SemaRef.Context, Index: StructuredIndex, Parent: Entity);
2265 ElementEntity.setElementIndex(elementIndex.getExtValue());
2266
2267 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2268 // Check this element.
2269 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
2270 StructuredList, StructuredIndex);
2271 ++elementIndex;
2272 if ((CurEmbed || isa<EmbedExpr>(Val: Init)) && elementType->isScalarType()) {
2273 if (CurEmbed) {
2274 elementIndex =
2275 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2276 } else {
2277 auto Embed = cast<EmbedExpr>(Val: Init);
2278 elementIndex = elementIndex + Embed->getDataElementCount() -
2279 EmbedElementIndexBeforeInit - 1;
2280 }
2281 }
2282
2283 // If the array is of incomplete type, keep track of the number of
2284 // elements in the initializer.
2285 if (!maxElementsKnown && elementIndex > maxElements)
2286 maxElements = elementIndex;
2287 }
2288 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2289 // If this is an incomplete array type, the actual type needs to
2290 // be calculated here.
2291 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2292 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2293 // Sizing an array implicitly to zero is not allowed by ISO C,
2294 // but is supported by GNU.
2295 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_typecheck_zero_array_size);
2296 }
2297
2298 DeclType = SemaRef.Context.getConstantArrayType(
2299 EltTy: elementType, ArySize: maxElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
2300 }
2301 if (!hadError) {
2302 // If there are any members of the array that get value-initialized, check
2303 // that is possible. That happens if we know the bound and don't have
2304 // enough elements, or if we're performing an array new with an unknown
2305 // bound.
2306 if ((maxElementsKnown && elementIndex < maxElements) ||
2307 Entity.isVariableLengthArrayNew())
2308 CheckEmptyInitializable(
2309 Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity),
2310 Loc: IList->getEndLoc());
2311 }
2312}
2313
2314bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2315 Expr *InitExpr,
2316 FieldDecl *Field,
2317 bool TopLevelObject) {
2318 // Handle GNU flexible array initializers.
2319 unsigned FlexArrayDiag;
2320 if (isa<InitListExpr>(Val: InitExpr) &&
2321 cast<InitListExpr>(Val: InitExpr)->getNumInits() == 0) {
2322 // Empty flexible array init always allowed as an extension
2323 FlexArrayDiag = diag::ext_flexible_array_init;
2324 } else if (!TopLevelObject) {
2325 // Disallow flexible array init on non-top-level object
2326 FlexArrayDiag = diag::err_flexible_array_init;
2327 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2328 // Disallow flexible array init on anything which is not a variable.
2329 FlexArrayDiag = diag::err_flexible_array_init;
2330 } else if (cast<VarDecl>(Val: Entity.getDecl())->hasLocalStorage()) {
2331 // Disallow flexible array init on local variables.
2332 FlexArrayDiag = diag::err_flexible_array_init;
2333 } else {
2334 // Allow other cases.
2335 FlexArrayDiag = diag::ext_flexible_array_init;
2336 }
2337
2338 if (!VerifyOnly) {
2339 SemaRef.Diag(Loc: InitExpr->getBeginLoc(), DiagID: FlexArrayDiag)
2340 << InitExpr->getBeginLoc();
2341 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member)
2342 << Field;
2343 }
2344
2345 return FlexArrayDiag != diag::ext_flexible_array_init;
2346}
2347
2348static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2349 return StructuredList && StructuredList->getNumInits() == 1U;
2350}
2351
2352void InitListChecker::CheckStructUnionTypes(
2353 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2354 CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,
2355 bool SubobjectIsDesignatorContext, unsigned &Index,
2356 InitListExpr *StructuredList, unsigned &StructuredIndex,
2357 bool TopLevelObject) {
2358 const RecordDecl *RD = DeclType->getAsRecordDecl();
2359
2360 // If the record is invalid, some of it's members are invalid. To avoid
2361 // confusion, we forgo checking the initializer for the entire record.
2362 if (RD->isInvalidDecl()) {
2363 // Assume it was supposed to consume a single initializer.
2364 ++Index;
2365 hadError = true;
2366 return;
2367 }
2368
2369 if (RD->isUnion() && IList->getNumInits() == 0) {
2370 if (!VerifyOnly)
2371 for (FieldDecl *FD : RD->fields()) {
2372 QualType ET = SemaRef.Context.getBaseElementType(QT: FD->getType());
2373 if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) {
2374 hadError = true;
2375 return;
2376 }
2377 }
2378
2379 // If there's a default initializer, use it.
2380 if (isa<CXXRecordDecl>(Val: RD) &&
2381 cast<CXXRecordDecl>(Val: RD)->hasInClassInitializer()) {
2382 if (!StructuredList)
2383 return;
2384 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2385 Field != FieldEnd; ++Field) {
2386 if (Field->hasInClassInitializer() ||
2387 (Field->isAnonymousStructOrUnion() &&
2388 Field->getType()
2389 ->castAsCXXRecordDecl()
2390 ->hasInClassInitializer())) {
2391 StructuredList->setInitializedFieldInUnion(*Field);
2392 // FIXME: Actually build a CXXDefaultInitExpr?
2393 return;
2394 }
2395 }
2396 llvm_unreachable("Couldn't find in-class initializer");
2397 }
2398
2399 // Value-initialize the first member of the union that isn't an unnamed
2400 // bitfield.
2401 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2402 Field != FieldEnd; ++Field) {
2403 if (!Field->isUnnamedBitField()) {
2404 CheckEmptyInitializable(
2405 Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity),
2406 Loc: IList->getEndLoc());
2407 if (StructuredList)
2408 StructuredList->setInitializedFieldInUnion(*Field);
2409 break;
2410 }
2411 }
2412 return;
2413 }
2414
2415 bool InitializedSomething = false;
2416
2417 // If we have any base classes, they are initialized prior to the fields.
2418 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2419 auto &Base = *I;
2420 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Init: Index) : nullptr;
2421
2422 // Designated inits always initialize fields, so if we see one, all
2423 // remaining base classes have no explicit initializer.
2424 if (isa_and_nonnull<DesignatedInitExpr>(Val: Init))
2425 Init = nullptr;
2426
2427 // C++ [over.match.class.deduct]p1.6:
2428 // each non-trailing aggregate element that is a pack expansion is assumed
2429 // to correspond to no elements of the initializer list, and (1.7) a
2430 // trailing aggregate element that is a pack expansion is assumed to
2431 // correspond to all remaining elements of the initializer list (if any).
2432
2433 // C++ [over.match.class.deduct]p1.9:
2434 // ... except that additional parameter packs of the form P_j... are
2435 // inserted into the parameter list in their original aggregate element
2436 // position corresponding to each non-trailing aggregate element of
2437 // type P_j that was skipped because it was a parameter pack, and the
2438 // trailing sequence of parameters corresponding to a trailing
2439 // aggregate element that is a pack expansion (if any) is replaced
2440 // by a single parameter of the form T_n....
2441 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2442 AggrDeductionCandidateParamTypes->push_back(
2443 Elt: SemaRef.Context.getPackExpansionType(Pattern: Base.getType(), NumExpansions: std::nullopt));
2444
2445 // Trailing pack expansion
2446 if (I + 1 == E && RD->field_empty()) {
2447 if (Index < IList->getNumInits())
2448 Index = IList->getNumInits();
2449 return;
2450 }
2451
2452 continue;
2453 }
2454
2455 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2456 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2457 Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity);
2458 if (Init) {
2459 CheckSubElementType(Entity: BaseEntity, IList, ElemType: Base.getType(), Index,
2460 StructuredList, StructuredIndex);
2461 InitializedSomething = true;
2462 } else {
2463 CheckEmptyInitializable(Entity: BaseEntity, Loc: InitLoc);
2464 }
2465
2466 if (!VerifyOnly)
2467 if (checkDestructorReference(ElementType: Base.getType(), Loc: InitLoc, SemaRef)) {
2468 hadError = true;
2469 return;
2470 }
2471 }
2472
2473 // If structDecl is a forward declaration, this loop won't do
2474 // anything except look at designated initializers; That's okay,
2475 // because an error should get printed out elsewhere. It might be
2476 // worthwhile to skip over the rest of the initializer, though.
2477 RecordDecl::field_iterator FieldEnd = RD->field_end();
2478 size_t NumRecordDecls = llvm::count_if(Range: RD->decls(), P: [&](const Decl *D) {
2479 return isa<FieldDecl>(Val: D) || isa<RecordDecl>(Val: D);
2480 });
2481 bool HasDesignatedInit = false;
2482
2483 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2484
2485 while (Index < IList->getNumInits()) {
2486 Expr *Init = IList->getInit(Init: Index);
2487 SourceLocation InitLoc = Init->getBeginLoc();
2488
2489 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) {
2490 // If we're not the subobject that matches up with the '{' for
2491 // the designator, we shouldn't be handling the
2492 // designator. Return immediately.
2493 if (!SubobjectIsDesignatorContext)
2494 return;
2495
2496 HasDesignatedInit = true;
2497
2498 // Handle this designated initializer. Field will be updated to
2499 // the next field that we'll be initializing.
2500 bool DesignatedInitFailed = CheckDesignatedInitializer(
2501 Entity, IList, DIE, DesigIdx: 0, CurrentObjectType&: DeclType, NextField: &Field, NextElementIndex: nullptr, Index,
2502 StructuredList, StructuredIndex, FinishSubobjectInit: true, TopLevelObject);
2503 if (DesignatedInitFailed)
2504 hadError = true;
2505
2506 // Find the field named by the designated initializer.
2507 DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: 0);
2508 if (!VerifyOnly && D->isFieldDesignator()) {
2509 FieldDecl *F = D->getFieldDecl();
2510 InitializedFields.insert(Ptr: F);
2511 if (!DesignatedInitFailed) {
2512 QualType ET = SemaRef.Context.getBaseElementType(QT: F->getType());
2513 if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) {
2514 hadError = true;
2515 return;
2516 }
2517 }
2518 }
2519
2520 InitializedSomething = true;
2521 continue;
2522 }
2523
2524 // Check if this is an initializer of forms:
2525 //
2526 // struct foo f = {};
2527 // struct foo g = {0};
2528 //
2529 // These are okay for randomized structures. [C99 6.7.8p19]
2530 //
2531 // Also, if there is only one element in the structure, we allow something
2532 // like this, because it's really not randomized in the traditional sense.
2533 //
2534 // struct foo h = {bar};
2535 auto IsZeroInitializer = [&](const Expr *I) {
2536 if (IList->getNumInits() == 1) {
2537 if (NumRecordDecls == 1)
2538 return true;
2539 if (const auto *IL = dyn_cast<IntegerLiteral>(Val: I))
2540 return IL->getValue().isZero();
2541 }
2542 return false;
2543 };
2544
2545 // Don't allow non-designated initializers on randomized structures.
2546 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2547 if (!VerifyOnly)
2548 SemaRef.Diag(Loc: InitLoc, DiagID: diag::err_non_designated_init_used);
2549 hadError = true;
2550 break;
2551 }
2552
2553 if (Field == FieldEnd) {
2554 // We've run out of fields. We're done.
2555 break;
2556 }
2557
2558 // We've already initialized a member of a union. We can stop entirely.
2559 if (InitializedSomething && RD->isUnion())
2560 return;
2561
2562 // Stop if we've hit a flexible array member.
2563 if (Field->getType()->isIncompleteArrayType())
2564 break;
2565
2566 if (Field->isUnnamedBitField()) {
2567 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2568 ++Field;
2569 continue;
2570 }
2571
2572 // Make sure we can use this declaration.
2573 bool InvalidUse;
2574 if (VerifyOnly)
2575 InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid);
2576 else
2577 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2578 D: *Field, Locs: IList->getInit(Init: Index)->getBeginLoc());
2579 if (InvalidUse) {
2580 ++Index;
2581 ++Field;
2582 hadError = true;
2583 continue;
2584 }
2585
2586 if (!VerifyOnly) {
2587 QualType ET = SemaRef.Context.getBaseElementType(QT: Field->getType());
2588 if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) {
2589 hadError = true;
2590 return;
2591 }
2592 }
2593
2594 InitializedEntity MemberEntity =
2595 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2596 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2597 StructuredList, StructuredIndex);
2598 InitializedSomething = true;
2599 InitializedFields.insert(Ptr: *Field);
2600 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2601 // Initialize the first field within the union.
2602 StructuredList->setInitializedFieldInUnion(*Field);
2603 }
2604
2605 ++Field;
2606 }
2607
2608 // Emit warnings for missing struct field initializers.
2609 // This check is disabled for designated initializers in C.
2610 // This matches gcc behaviour.
2611 bool IsCDesignatedInitializer =
2612 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2613 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2614 !IList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) &&
2615 !IsCDesignatedInitializer) {
2616 // It is possible we have one or more unnamed bitfields remaining.
2617 // Find first (if any) named field and emit warning.
2618 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2619 : Field,
2620 end = RD->field_end();
2621 it != end; ++it) {
2622 if (HasDesignatedInit && InitializedFields.count(Ptr: *it))
2623 continue;
2624
2625 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2626 !it->getType()->isIncompleteArrayType()) {
2627 auto Diag = HasDesignatedInit
2628 ? diag::warn_missing_designated_field_initializers
2629 : diag::warn_missing_field_initializers;
2630 SemaRef.Diag(Loc: IList->getSourceRange().getEnd(), DiagID: Diag) << *it;
2631 break;
2632 }
2633 }
2634 }
2635
2636 // Check that any remaining fields can be value-initialized if we're not
2637 // building a structured list. (If we are, we'll check this later.)
2638 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2639 !Field->getType()->isIncompleteArrayType()) {
2640 for (; Field != FieldEnd && !hadError; ++Field) {
2641 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2642 CheckEmptyInitializable(
2643 Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity),
2644 Loc: IList->getEndLoc());
2645 }
2646 }
2647
2648 // Check that the types of the remaining fields have accessible destructors.
2649 if (!VerifyOnly) {
2650 // If the initializer expression has a designated initializer, check the
2651 // elements for which a designated initializer is not provided too.
2652 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2653 : Field;
2654 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2655 QualType ET = SemaRef.Context.getBaseElementType(QT: I->getType());
2656 if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) {
2657 hadError = true;
2658 return;
2659 }
2660 }
2661 }
2662
2663 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2664 Index >= IList->getNumInits())
2665 return;
2666
2667 if (CheckFlexibleArrayInit(Entity, InitExpr: IList->getInit(Init: Index), Field: *Field,
2668 TopLevelObject)) {
2669 hadError = true;
2670 ++Index;
2671 return;
2672 }
2673
2674 InitializedEntity MemberEntity =
2675 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2676
2677 if (isa<InitListExpr>(Val: IList->getInit(Init: Index)) ||
2678 AggrDeductionCandidateParamTypes)
2679 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2680 StructuredList, StructuredIndex);
2681 else
2682 CheckImplicitInitList(Entity: MemberEntity, ParentIList: IList, T: Field->getType(), Index,
2683 StructuredList, StructuredIndex);
2684
2685 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2686 // Initialize the first field within the union.
2687 StructuredList->setInitializedFieldInUnion(*Field);
2688 }
2689}
2690
2691/// Expand a field designator that refers to a member of an
2692/// anonymous struct or union into a series of field designators that
2693/// refers to the field within the appropriate subobject.
2694///
2695static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2696 DesignatedInitExpr *DIE,
2697 unsigned DesigIdx,
2698 IndirectFieldDecl *IndirectField) {
2699 typedef DesignatedInitExpr::Designator Designator;
2700
2701 // Build the replacement designators.
2702 SmallVector<Designator, 4> Replacements;
2703 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2704 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2705 if (PI + 1 == PE)
2706 Replacements.push_back(Elt: Designator::CreateFieldDesignator(
2707 FieldName: (IdentifierInfo *)nullptr, DotLoc: DIE->getDesignator(Idx: DesigIdx)->getDotLoc(),
2708 FieldLoc: DIE->getDesignator(Idx: DesigIdx)->getFieldLoc()));
2709 else
2710 Replacements.push_back(Elt: Designator::CreateFieldDesignator(
2711 FieldName: (IdentifierInfo *)nullptr, DotLoc: SourceLocation(), FieldLoc: SourceLocation()));
2712 assert(isa<FieldDecl>(*PI));
2713 Replacements.back().setFieldDecl(cast<FieldDecl>(Val: *PI));
2714 }
2715
2716 // Expand the current designator into the set of replacement
2717 // designators, so we have a full subobject path down to where the
2718 // member of the anonymous struct/union is actually stored.
2719 DIE->ExpandDesignator(C: SemaRef.Context, Idx: DesigIdx, First: &Replacements[0],
2720 Last: &Replacements[0] + Replacements.size());
2721}
2722
2723static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2724 DesignatedInitExpr *DIE) {
2725 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2726 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2727 for (unsigned I = 0; I < NumIndexExprs; ++I)
2728 IndexExprs[I] = DIE->getSubExpr(Idx: I + 1);
2729 return DesignatedInitExpr::Create(C: SemaRef.Context, Designators: DIE->designators(),
2730 IndexExprs,
2731 EqualOrColonLoc: DIE->getEqualOrColonLoc(),
2732 GNUSyntax: DIE->usesGNUSyntax(), Init: DIE->getInit());
2733}
2734
2735namespace {
2736
2737// Callback to only accept typo corrections that are for field members of
2738// the given struct or union.
2739class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2740 public:
2741 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2742 : Record(RD) {}
2743
2744 bool ValidateCandidate(const TypoCorrection &candidate) override {
2745 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2746 return FD && FD->getDeclContext()->getRedeclContext()->Equals(DC: Record);
2747 }
2748
2749 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2750 return std::make_unique<FieldInitializerValidatorCCC>(args&: *this);
2751 }
2752
2753 private:
2754 const RecordDecl *Record;
2755};
2756
2757} // end anonymous namespace
2758
2759/// Check the well-formedness of a C99 designated initializer.
2760///
2761/// Determines whether the designated initializer @p DIE, which
2762/// resides at the given @p Index within the initializer list @p
2763/// IList, is well-formed for a current object of type @p DeclType
2764/// (C99 6.7.8). The actual subobject that this designator refers to
2765/// within the current subobject is returned in either
2766/// @p NextField or @p NextElementIndex (whichever is appropriate).
2767///
2768/// @param IList The initializer list in which this designated
2769/// initializer occurs.
2770///
2771/// @param DIE The designated initializer expression.
2772///
2773/// @param DesigIdx The index of the current designator.
2774///
2775/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2776/// into which the designation in @p DIE should refer.
2777///
2778/// @param NextField If non-NULL and the first designator in @p DIE is
2779/// a field, this will be set to the field declaration corresponding
2780/// to the field named by the designator. On input, this is expected to be
2781/// the next field that would be initialized in the absence of designation,
2782/// if the complete object being initialized is a struct.
2783///
2784/// @param NextElementIndex If non-NULL and the first designator in @p
2785/// DIE is an array designator or GNU array-range designator, this
2786/// will be set to the last index initialized by this designator.
2787///
2788/// @param Index Index into @p IList where the designated initializer
2789/// @p DIE occurs.
2790///
2791/// @param StructuredList The initializer list expression that
2792/// describes all of the subobject initializers in the order they'll
2793/// actually be initialized.
2794///
2795/// @returns true if there was an error, false otherwise.
2796bool
2797InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2798 InitListExpr *IList,
2799 DesignatedInitExpr *DIE,
2800 unsigned DesigIdx,
2801 QualType &CurrentObjectType,
2802 RecordDecl::field_iterator *NextField,
2803 llvm::APSInt *NextElementIndex,
2804 unsigned &Index,
2805 InitListExpr *StructuredList,
2806 unsigned &StructuredIndex,
2807 bool FinishSubobjectInit,
2808 bool TopLevelObject) {
2809 if (DesigIdx == DIE->size()) {
2810 // C++20 designated initialization can result in direct-list-initialization
2811 // of the designated subobject. This is the only way that we can end up
2812 // performing direct initialization as part of aggregate initialization, so
2813 // it needs special handling.
2814 if (DIE->isDirectInit()) {
2815 Expr *Init = DIE->getInit();
2816 assert(isa<InitListExpr>(Init) &&
2817 "designator result in direct non-list initialization?");
2818 InitializationKind Kind = InitializationKind::CreateDirectList(
2819 InitLoc: DIE->getBeginLoc(), LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc());
2820 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2821 /*TopLevelOfInitList*/ true);
2822 if (StructuredList) {
2823 ExprResult Result = VerifyOnly
2824 ? getDummyInit()
2825 : Seq.Perform(S&: SemaRef, Entity, Kind, Args: Init);
2826 UpdateStructuredListElement(StructuredList, StructuredIndex,
2827 expr: Result.get());
2828 }
2829 ++Index;
2830 if (AggrDeductionCandidateParamTypes)
2831 AggrDeductionCandidateParamTypes->push_back(Elt: CurrentObjectType);
2832 return !Seq;
2833 }
2834
2835 // Check the actual initialization for the designated object type.
2836 bool prevHadError = hadError;
2837
2838 // Temporarily remove the designator expression from the
2839 // initializer list that the child calls see, so that we don't try
2840 // to re-process the designator.
2841 unsigned OldIndex = Index;
2842 auto *OldDIE =
2843 dyn_cast_if_present<DesignatedInitExpr>(Val: IList->getInit(Init: OldIndex));
2844 if (!OldDIE)
2845 OldDIE = DIE;
2846 IList->setInit(Init: OldIndex, expr: OldDIE->getInit());
2847
2848 CheckSubElementType(Entity, IList, ElemType: CurrentObjectType, Index, StructuredList,
2849 StructuredIndex, /*DirectlyDesignated=*/true);
2850
2851 // Restore the designated initializer expression in the syntactic
2852 // form of the initializer list.
2853 if (IList->getInit(Init: OldIndex) != OldDIE->getInit())
2854 OldDIE->setInit(IList->getInit(Init: OldIndex));
2855 IList->setInit(Init: OldIndex, expr: OldDIE);
2856
2857 return hadError && !prevHadError;
2858 }
2859
2860 DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: DesigIdx);
2861 bool IsFirstDesignator = (DesigIdx == 0);
2862 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2863 // Determine the structural initializer list that corresponds to the
2864 // current subobject.
2865 if (IsFirstDesignator)
2866 StructuredList = FullyStructuredList;
2867 else {
2868 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2869 StructuredList->getInit(Init: StructuredIndex) : nullptr;
2870 if (!ExistingInit && StructuredList->hasArrayFiller())
2871 ExistingInit = StructuredList->getArrayFiller();
2872
2873 if (!ExistingInit)
2874 StructuredList = getStructuredSubobjectInit(
2875 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2876 InitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2877 else if (InitListExpr *Result = dyn_cast<InitListExpr>(Val: ExistingInit))
2878 StructuredList = Result;
2879 else {
2880 // We are creating an initializer list that initializes the
2881 // subobjects of the current object, but there was already an
2882 // initialization that completely initialized the current
2883 // subobject, e.g., by a compound literal:
2884 //
2885 // struct X { int a, b; };
2886 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2887 //
2888 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2889 // designated initializer re-initializes only its current object
2890 // subobject [0].b.
2891 diagnoseInitOverride(OldInit: ExistingInit,
2892 NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2893 /*UnionOverride=*/false,
2894 /*FullyOverwritten=*/false);
2895
2896 if (!VerifyOnly) {
2897 if (DesignatedInitUpdateExpr *E =
2898 dyn_cast<DesignatedInitUpdateExpr>(Val: ExistingInit))
2899 StructuredList = E->getUpdater();
2900 else {
2901 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2902 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2903 ExistingInit, DIE->getEndLoc());
2904 StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: DIUE);
2905 StructuredList = DIUE->getUpdater();
2906 }
2907 } else {
2908 // We don't need to track the structured representation of a
2909 // designated init update of an already-fully-initialized object in
2910 // verify-only mode. The only reason we would need the structure is
2911 // to determine where the uninitialized "holes" are, and in this
2912 // case, we know there aren't any and we can't introduce any.
2913 StructuredList = nullptr;
2914 }
2915 }
2916 }
2917 }
2918
2919 if (D->isFieldDesignator()) {
2920 // C99 6.7.8p7:
2921 //
2922 // If a designator has the form
2923 //
2924 // . identifier
2925 //
2926 // then the current object (defined below) shall have
2927 // structure or union type and the identifier shall be the
2928 // name of a member of that type.
2929 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2930 if (!RD) {
2931 SourceLocation Loc = D->getDotLoc();
2932 if (Loc.isInvalid())
2933 Loc = D->getFieldLoc();
2934 if (!VerifyOnly)
2935 SemaRef.Diag(Loc, DiagID: diag::err_field_designator_non_aggr)
2936 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2937 ++Index;
2938 return true;
2939 }
2940
2941 FieldDecl *KnownField = D->getFieldDecl();
2942 if (!KnownField) {
2943 const IdentifierInfo *FieldName = D->getFieldName();
2944 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(ClassDecl: RD, MemberOrBase: FieldName);
2945 if (auto *FD = dyn_cast_if_present<FieldDecl>(Val: VD)) {
2946 KnownField = FD;
2947 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(Val: VD)) {
2948 // In verify mode, don't modify the original.
2949 if (VerifyOnly)
2950 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2951 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IndirectField: IFD);
2952 D = DIE->getDesignator(Idx: DesigIdx);
2953 KnownField = cast<FieldDecl>(Val: *IFD->chain_begin());
2954 }
2955 if (!KnownField) {
2956 if (VerifyOnly) {
2957 ++Index;
2958 return true; // No typo correction when just trying this out.
2959 }
2960
2961 // We found a placeholder variable
2962 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(Loc: DIE->getBeginLoc(), ClassDecl: RD,
2963 Name: FieldName)) {
2964 ++Index;
2965 return true;
2966 }
2967 // Name lookup found something, but it wasn't a field.
2968 if (DeclContextLookupResult Lookup = RD->lookup(Name: FieldName);
2969 !Lookup.empty()) {
2970 SemaRef.Diag(Loc: D->getFieldLoc(), DiagID: diag::err_field_designator_nonfield)
2971 << FieldName;
2972 SemaRef.Diag(Loc: Lookup.front()->getLocation(),
2973 DiagID: diag::note_field_designator_found);
2974 ++Index;
2975 return true;
2976 }
2977
2978 // Name lookup didn't find anything.
2979 // Determine whether this was a typo for another field name.
2980 FieldInitializerValidatorCCC CCC(RD);
2981 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2982 Typo: DeclarationNameInfo(FieldName, D->getFieldLoc()),
2983 LookupKind: Sema::LookupMemberName, /*Scope=*/S: nullptr, /*SS=*/nullptr, CCC,
2984 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: RD)) {
2985 SemaRef.diagnoseTypo(
2986 Correction: Corrected,
2987 TypoDiag: SemaRef.PDiag(DiagID: diag::err_field_designator_unknown_suggest)
2988 << FieldName << CurrentObjectType);
2989 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2990 hadError = true;
2991 } else {
2992 // Typo correction didn't find anything.
2993 SourceLocation Loc = D->getFieldLoc();
2994
2995 // The loc can be invalid with a "null" designator (i.e. an anonymous
2996 // union/struct). Do our best to approximate the location.
2997 if (Loc.isInvalid())
2998 Loc = IList->getBeginLoc();
2999
3000 SemaRef.Diag(Loc, DiagID: diag::err_field_designator_unknown)
3001 << FieldName << CurrentObjectType << DIE->getSourceRange();
3002 ++Index;
3003 return true;
3004 }
3005 }
3006 }
3007
3008 unsigned NumBases = 0;
3009 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
3010 NumBases = CXXRD->getNumBases();
3011
3012 unsigned FieldIndex = NumBases;
3013
3014 for (auto *FI : RD->fields()) {
3015 if (FI->isUnnamedBitField())
3016 continue;
3017 if (declaresSameEntity(D1: KnownField, D2: FI)) {
3018 KnownField = FI;
3019 break;
3020 }
3021 ++FieldIndex;
3022 }
3023
3024 RecordDecl::field_iterator Field =
3025 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3026
3027 // All of the fields of a union are located at the same place in
3028 // the initializer list.
3029 if (RD->isUnion()) {
3030 FieldIndex = 0;
3031 if (StructuredList) {
3032 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3033 if (CurrentField && !declaresSameEntity(D1: CurrentField, D2: *Field)) {
3034 assert(StructuredList->getNumInits() == 1
3035 && "A union should never have more than one initializer!");
3036
3037 Expr *ExistingInit = StructuredList->getInit(Init: 0);
3038 if (ExistingInit) {
3039 // We're about to throw away an initializer, emit warning.
3040 diagnoseInitOverride(
3041 OldInit: ExistingInit, NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3042 /*UnionOverride=*/true,
3043 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3044 : true);
3045 }
3046
3047 // remove existing initializer
3048 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: 0);
3049 StructuredList->setInitializedFieldInUnion(nullptr);
3050 }
3051
3052 StructuredList->setInitializedFieldInUnion(*Field);
3053 }
3054 }
3055
3056 // Make sure we can use this declaration.
3057 bool InvalidUse;
3058 if (VerifyOnly)
3059 InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid);
3060 else
3061 InvalidUse = SemaRef.DiagnoseUseOfDecl(D: *Field, Locs: D->getFieldLoc());
3062 if (InvalidUse) {
3063 ++Index;
3064 return true;
3065 }
3066
3067 // C++20 [dcl.init.list]p3:
3068 // The ordered identifiers in the designators of the designated-
3069 // initializer-list shall form a subsequence of the ordered identifiers
3070 // in the direct non-static data members of T.
3071 //
3072 // Note that this is not a condition on forming the aggregate
3073 // initialization, only on actually performing initialization,
3074 // so it is not checked in VerifyOnly mode.
3075 //
3076 // FIXME: This is the only reordering diagnostic we produce, and it only
3077 // catches cases where we have a top-level field designator that jumps
3078 // backwards. This is the only such case that is reachable in an
3079 // otherwise-valid C++20 program, so is the only case that's required for
3080 // conformance, but for consistency, we should diagnose all the other
3081 // cases where a designator takes us backwards too.
3082 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3083 NextField &&
3084 (*NextField == RD->field_end() ||
3085 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3086 // Find the field that we just initialized.
3087 FieldDecl *PrevField = nullptr;
3088 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3089 if (FI->isUnnamedBitField())
3090 continue;
3091 if (*NextField != RD->field_end() &&
3092 declaresSameEntity(D1: *FI, D2: **NextField))
3093 break;
3094 PrevField = *FI;
3095 }
3096
3097 const auto GenerateDesignatedInitReorderingFixit =
3098 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3099 struct ReorderInfo {
3100 int Pos{};
3101 const Expr *InitExpr{};
3102 };
3103
3104 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3105 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3106
3107 const auto *CxxRecord =
3108 IList->getSemanticForm()->getType()->getAsCXXRecordDecl();
3109
3110 for (const FieldDecl *Field : CxxRecord->fields())
3111 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3112
3113 for (const Expr *Init : IList->inits()) {
3114 if (const auto *DI =
3115 dyn_cast_if_present<DesignatedInitExpr>(Val: Init)) {
3116 // We expect only one Designator
3117 if (DI->size() != 1)
3118 return;
3119
3120 const IdentifierInfo *const FieldName =
3121 DI->getDesignator(Idx: 0)->getFieldName();
3122 // In case we have an unknown initializer in the source, not in
3123 // the record
3124 if (MemberNameInx.contains(Val: FieldName))
3125 ReorderedInitExprs.emplace_back(
3126 Args: ReorderInfo{.Pos: MemberNameInx.at(Val: FieldName), .InitExpr: Init});
3127 }
3128 }
3129
3130 llvm::sort(C&: ReorderedInitExprs,
3131 Comp: [](const ReorderInfo &A, const ReorderInfo &B) {
3132 return A.Pos < B.Pos;
3133 });
3134
3135 llvm::SmallString<128> FixedInitList{};
3136 SourceManager &SM = SemaRef.getSourceManager();
3137 const LangOptions &LangOpts = SemaRef.getLangOpts();
3138
3139 // In a derived Record, first n base-classes are initialized first.
3140 // They do not use designated init, so skip them
3141 const ArrayRef<clang::Expr *> IListInits =
3142 IList->inits().drop_front(N: CxxRecord->getNumBases());
3143 // loop over each existing expressions and apply replacement
3144 for (const auto &[OrigExpr, Repl] :
3145 llvm::zip(t: IListInits, u&: ReorderedInitExprs)) {
3146 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3147 R: Repl.InitExpr->getSourceRange());
3148 const StringRef InitText =
3149 Lexer::getSourceText(Range: CharRange, SM, LangOpts);
3150
3151 Diag << FixItHint::CreateReplacement(RemoveRange: OrigExpr->getSourceRange(),
3152 Code: InitText.str());
3153 }
3154 };
3155
3156 if (PrevField &&
3157 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3158 SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(),
3159 DiagID: diag::ext_designated_init_reordered)
3160 << KnownField << PrevField << DIE->getSourceRange();
3161
3162 unsigned OldIndex = StructuredIndex - 1;
3163 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3164 if (Expr *PrevInit = StructuredList->getInit(Init: OldIndex)) {
3165 auto Diag = SemaRef.Diag(Loc: PrevInit->getBeginLoc(),
3166 DiagID: diag::note_previous_field_init)
3167 << PrevField << PrevInit->getSourceRange();
3168 GenerateDesignatedInitReorderingFixit(Diag);
3169 }
3170 }
3171 }
3172 }
3173
3174
3175 // Update the designator with the field declaration.
3176 if (!VerifyOnly)
3177 D->setFieldDecl(*Field);
3178
3179 // Make sure that our non-designated initializer list has space
3180 // for a subobject corresponding to this field.
3181 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3182 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: FieldIndex + 1);
3183
3184 // This designator names a flexible array member.
3185 if (Field->getType()->isIncompleteArrayType()) {
3186 bool Invalid = false;
3187 if ((DesigIdx + 1) != DIE->size()) {
3188 // We can't designate an object within the flexible array
3189 // member (because GCC doesn't allow it).
3190 if (!VerifyOnly) {
3191 DesignatedInitExpr::Designator *NextD
3192 = DIE->getDesignator(Idx: DesigIdx + 1);
3193 SemaRef.Diag(Loc: NextD->getBeginLoc(),
3194 DiagID: diag::err_designator_into_flexible_array_member)
3195 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3196 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member)
3197 << *Field;
3198 }
3199 Invalid = true;
3200 }
3201
3202 if (!hadError && !isa<InitListExpr>(Val: DIE->getInit()) &&
3203 !isa<StringLiteral>(Val: DIE->getInit())) {
3204 // The initializer is not an initializer list.
3205 if (!VerifyOnly) {
3206 SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(),
3207 DiagID: diag::err_flexible_array_init_needs_braces)
3208 << DIE->getInit()->getSourceRange();
3209 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member)
3210 << *Field;
3211 }
3212 Invalid = true;
3213 }
3214
3215 // Check GNU flexible array initializer.
3216 if (!Invalid && CheckFlexibleArrayInit(Entity, InitExpr: DIE->getInit(), Field: *Field,
3217 TopLevelObject))
3218 Invalid = true;
3219
3220 if (Invalid) {
3221 ++Index;
3222 return true;
3223 }
3224
3225 // Initialize the array.
3226 bool prevHadError = hadError;
3227 unsigned newStructuredIndex = FieldIndex;
3228 unsigned OldIndex = Index;
3229 IList->setInit(Init: Index, expr: DIE->getInit());
3230
3231 InitializedEntity MemberEntity =
3232 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
3233 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
3234 StructuredList, StructuredIndex&: newStructuredIndex);
3235
3236 IList->setInit(Init: OldIndex, expr: DIE);
3237 if (hadError && !prevHadError) {
3238 ++Field;
3239 ++FieldIndex;
3240 if (NextField)
3241 *NextField = Field;
3242 StructuredIndex = FieldIndex;
3243 return true;
3244 }
3245 } else {
3246 // Recurse to check later designated subobjects.
3247 QualType FieldType = Field->getType();
3248 unsigned newStructuredIndex = FieldIndex;
3249
3250 InitializedEntity MemberEntity =
3251 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
3252 if (CheckDesignatedInitializer(Entity: MemberEntity, IList, DIE, DesigIdx: DesigIdx + 1,
3253 CurrentObjectType&: FieldType, NextField: nullptr, NextElementIndex: nullptr, Index,
3254 StructuredList, StructuredIndex&: newStructuredIndex,
3255 FinishSubobjectInit, TopLevelObject: false))
3256 return true;
3257 }
3258
3259 // Find the position of the next field to be initialized in this
3260 // subobject.
3261 ++Field;
3262 ++FieldIndex;
3263
3264 // If this the first designator, our caller will continue checking
3265 // the rest of this struct/class/union subobject.
3266 if (IsFirstDesignator) {
3267 if (Field != RD->field_end() && Field->isUnnamedBitField())
3268 ++Field;
3269
3270 if (NextField)
3271 *NextField = Field;
3272
3273 StructuredIndex = FieldIndex;
3274 return false;
3275 }
3276
3277 if (!FinishSubobjectInit)
3278 return false;
3279
3280 // We've already initialized something in the union; we're done.
3281 if (RD->isUnion())
3282 return hadError;
3283
3284 // Check the remaining fields within this class/struct/union subobject.
3285 bool prevHadError = hadError;
3286
3287 auto NoBases =
3288 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
3289 CXXRecordDecl::base_class_iterator());
3290 CheckStructUnionTypes(Entity, IList, DeclType: CurrentObjectType, Bases: NoBases, Field,
3291 SubobjectIsDesignatorContext: false, Index, StructuredList, StructuredIndex&: FieldIndex);
3292 return hadError && !prevHadError;
3293 }
3294
3295 // C99 6.7.8p6:
3296 //
3297 // If a designator has the form
3298 //
3299 // [ constant-expression ]
3300 //
3301 // then the current object (defined below) shall have array
3302 // type and the expression shall be an integer constant
3303 // expression. If the array is of unknown size, any
3304 // nonnegative value is valid.
3305 //
3306 // Additionally, cope with the GNU extension that permits
3307 // designators of the form
3308 //
3309 // [ constant-expression ... constant-expression ]
3310 const ArrayType *AT = SemaRef.Context.getAsArrayType(T: CurrentObjectType);
3311 if (!AT) {
3312 if (!VerifyOnly)
3313 SemaRef.Diag(Loc: D->getLBracketLoc(), DiagID: diag::err_array_designator_non_array)
3314 << CurrentObjectType;
3315 ++Index;
3316 return true;
3317 }
3318
3319 Expr *IndexExpr = nullptr;
3320 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3321 if (D->isArrayDesignator()) {
3322 IndexExpr = DIE->getArrayIndex(D: *D);
3323 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3324 DesignatedEndIndex = DesignatedStartIndex;
3325 } else {
3326 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3327
3328 DesignatedStartIndex =
3329 DIE->getArrayRangeStart(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3330 DesignatedEndIndex =
3331 DIE->getArrayRangeEnd(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3332 IndexExpr = DIE->getArrayRangeEnd(D: *D);
3333
3334 // Codegen can't handle evaluating array range designators that have side
3335 // effects, because we replicate the AST value for each initialized element.
3336 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3337 // elements with something that has a side effect, so codegen can emit an
3338 // "error unsupported" error instead of miscompiling the app.
3339 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3340 DIE->getInit()->HasSideEffects(Ctx: SemaRef.Context) && !VerifyOnly)
3341 FullyStructuredList->sawArrayRangeDesignator();
3342 }
3343
3344 if (isa<ConstantArrayType>(Val: AT)) {
3345 llvm::APSInt MaxElements(cast<ConstantArrayType>(Val: AT)->getSize(), false);
3346 DesignatedStartIndex
3347 = DesignatedStartIndex.extOrTrunc(width: MaxElements.getBitWidth());
3348 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3349 DesignatedEndIndex
3350 = DesignatedEndIndex.extOrTrunc(width: MaxElements.getBitWidth());
3351 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3352 if (DesignatedEndIndex >= MaxElements) {
3353 if (!VerifyOnly)
3354 SemaRef.Diag(Loc: IndexExpr->getBeginLoc(),
3355 DiagID: diag::err_array_designator_too_large)
3356 << toString(I: DesignatedEndIndex, Radix: 10) << toString(I: MaxElements, Radix: 10)
3357 << IndexExpr->getSourceRange();
3358 ++Index;
3359 return true;
3360 }
3361 } else {
3362 unsigned DesignatedIndexBitWidth =
3363 ConstantArrayType::getMaxSizeBits(Context: SemaRef.Context);
3364 DesignatedStartIndex =
3365 DesignatedStartIndex.extOrTrunc(width: DesignatedIndexBitWidth);
3366 DesignatedEndIndex =
3367 DesignatedEndIndex.extOrTrunc(width: DesignatedIndexBitWidth);
3368 DesignatedStartIndex.setIsUnsigned(true);
3369 DesignatedEndIndex.setIsUnsigned(true);
3370 }
3371
3372 bool IsStringLiteralInitUpdate =
3373 StructuredList && StructuredList->isStringLiteralInit();
3374 if (IsStringLiteralInitUpdate && VerifyOnly) {
3375 // We're just verifying an update to a string literal init. We don't need
3376 // to split the string up into individual characters to do that.
3377 StructuredList = nullptr;
3378 } else if (IsStringLiteralInitUpdate) {
3379 // We're modifying a string literal init; we have to decompose the string
3380 // so we can modify the individual characters.
3381 ASTContext &Context = SemaRef.Context;
3382 Expr *SubExpr = StructuredList->getInit(Init: 0)->IgnoreParenImpCasts();
3383
3384 // Compute the character type
3385 QualType CharTy = AT->getElementType();
3386
3387 // Compute the type of the integer literals.
3388 QualType PromotedCharTy = CharTy;
3389 if (Context.isPromotableIntegerType(T: CharTy))
3390 PromotedCharTy = Context.getPromotedIntegerType(PromotableType: CharTy);
3391 unsigned PromotedCharTyWidth = Context.getTypeSize(T: PromotedCharTy);
3392
3393 if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: SubExpr)) {
3394 // Get the length of the string.
3395 uint64_t StrLen = SL->getLength();
3396 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT);
3397 CAT && CAT->getSize().ult(RHS: StrLen))
3398 StrLen = CAT->getZExtSize();
3399 StructuredList->resizeInits(Context, NumInits: StrLen);
3400
3401 // Build a literal for each character in the string, and put them into
3402 // the init list.
3403 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3404 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3405 Expr *Init = new (Context) IntegerLiteral(
3406 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3407 if (CharTy != PromotedCharTy)
3408 Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast,
3409 Operand: Init, BasePath: nullptr, Cat: VK_PRValue,
3410 FPO: FPOptionsOverride());
3411 StructuredList->updateInit(C: Context, Init: i, expr: Init);
3412 }
3413 } else {
3414 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(Val: SubExpr);
3415 std::string Str;
3416 Context.getObjCEncodingForType(T: E->getEncodedType(), S&: Str);
3417
3418 // Get the length of the string.
3419 uint64_t StrLen = Str.size();
3420 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT);
3421 CAT && CAT->getSize().ult(RHS: StrLen))
3422 StrLen = CAT->getZExtSize();
3423 StructuredList->resizeInits(Context, NumInits: StrLen);
3424
3425 // Build a literal for each character in the string, and put them into
3426 // the init list.
3427 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3428 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3429 Expr *Init = new (Context) IntegerLiteral(
3430 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3431 if (CharTy != PromotedCharTy)
3432 Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast,
3433 Operand: Init, BasePath: nullptr, Cat: VK_PRValue,
3434 FPO: FPOptionsOverride());
3435 StructuredList->updateInit(C: Context, Init: i, expr: Init);
3436 }
3437 }
3438 }
3439
3440 // Make sure that our non-designated initializer list has space
3441 // for a subobject corresponding to this array element.
3442 if (StructuredList &&
3443 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3444 StructuredList->resizeInits(Context: SemaRef.Context,
3445 NumInits: DesignatedEndIndex.getZExtValue() + 1);
3446
3447 // Repeatedly perform subobject initializations in the range
3448 // [DesignatedStartIndex, DesignatedEndIndex].
3449
3450 // Move to the next designator
3451 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3452 unsigned OldIndex = Index;
3453
3454 InitializedEntity ElementEntity =
3455 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
3456
3457 while (DesignatedStartIndex <= DesignatedEndIndex) {
3458 // Recurse to check later designated subobjects.
3459 QualType ElementType = AT->getElementType();
3460 Index = OldIndex;
3461
3462 ElementEntity.setElementIndex(ElementIndex);
3463 if (CheckDesignatedInitializer(
3464 Entity: ElementEntity, IList, DIE, DesigIdx: DesigIdx + 1, CurrentObjectType&: ElementType, NextField: nullptr,
3465 NextElementIndex: nullptr, Index, StructuredList, StructuredIndex&: ElementIndex,
3466 FinishSubobjectInit: FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3467 TopLevelObject: false))
3468 return true;
3469
3470 // Move to the next index in the array that we'll be initializing.
3471 ++DesignatedStartIndex;
3472 ElementIndex = DesignatedStartIndex.getZExtValue();
3473 }
3474
3475 // If this the first designator, our caller will continue checking
3476 // the rest of this array subobject.
3477 if (IsFirstDesignator) {
3478 if (NextElementIndex)
3479 *NextElementIndex = DesignatedStartIndex;
3480 StructuredIndex = ElementIndex;
3481 return false;
3482 }
3483
3484 if (!FinishSubobjectInit)
3485 return false;
3486
3487 // Check the remaining elements within this array subobject.
3488 bool prevHadError = hadError;
3489 CheckArrayType(Entity, IList, DeclType&: CurrentObjectType, elementIndex: DesignatedStartIndex,
3490 /*SubobjectIsDesignatorContext=*/false, Index,
3491 StructuredList, StructuredIndex&: ElementIndex);
3492 return hadError && !prevHadError;
3493}
3494
3495// Get the structured initializer list for a subobject of type
3496// @p CurrentObjectType.
3497InitListExpr *
3498InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3499 QualType CurrentObjectType,
3500 InitListExpr *StructuredList,
3501 unsigned StructuredIndex,
3502 SourceRange InitRange,
3503 bool IsFullyOverwritten) {
3504 if (!StructuredList)
3505 return nullptr;
3506
3507 Expr *ExistingInit = nullptr;
3508 if (StructuredIndex < StructuredList->getNumInits())
3509 ExistingInit = StructuredList->getInit(Init: StructuredIndex);
3510
3511 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(Val: ExistingInit))
3512 // There might have already been initializers for subobjects of the current
3513 // object, but a subsequent initializer list will overwrite the entirety
3514 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3515 //
3516 // struct P { char x[6]; };
3517 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3518 //
3519 // The first designated initializer is ignored, and l.x is just "f".
3520 if (!IsFullyOverwritten)
3521 return Result;
3522
3523 if (ExistingInit) {
3524 // We are creating an initializer list that initializes the
3525 // subobjects of the current object, but there was already an
3526 // initialization that completely initialized the current
3527 // subobject:
3528 //
3529 // struct X { int a, b; };
3530 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3531 //
3532 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3533 // designated initializer overwrites the [0].b initializer
3534 // from the prior initialization.
3535 //
3536 // When the existing initializer is an expression rather than an
3537 // initializer list, we cannot decompose and update it in this way.
3538 // For example:
3539 //
3540 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3541 //
3542 // This case is handled by CheckDesignatedInitializer.
3543 diagnoseInitOverride(OldInit: ExistingInit, NewInitRange: InitRange);
3544 }
3545
3546 unsigned ExpectedNumInits = 0;
3547 if (Index < IList->getNumInits()) {
3548 if (auto *Init = dyn_cast_or_null<InitListExpr>(Val: IList->getInit(Init: Index)))
3549 ExpectedNumInits = Init->getNumInits();
3550 else
3551 ExpectedNumInits = IList->getNumInits() - Index;
3552 }
3553
3554 InitListExpr *Result =
3555 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3556
3557 // Link this new initializer list into the structured initializer
3558 // lists.
3559 StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: Result);
3560 return Result;
3561}
3562
3563InitListExpr *
3564InitListChecker::createInitListExpr(QualType CurrentObjectType,
3565 SourceRange InitRange,
3566 unsigned ExpectedNumInits) {
3567 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3568 SemaRef.Context, InitRange.getBegin(), {}, InitRange.getEnd());
3569
3570 QualType ResultType = CurrentObjectType;
3571 if (!ResultType->isArrayType())
3572 ResultType = ResultType.getNonLValueExprType(Context: SemaRef.Context);
3573 Result->setType(ResultType);
3574
3575 // Pre-allocate storage for the structured initializer list.
3576 unsigned NumElements = 0;
3577
3578 if (const ArrayType *AType
3579 = SemaRef.Context.getAsArrayType(T: CurrentObjectType)) {
3580 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(Val: AType)) {
3581 NumElements = CAType->getZExtSize();
3582 // Simple heuristic so that we don't allocate a very large
3583 // initializer with many empty entries at the end.
3584 if (NumElements > ExpectedNumInits)
3585 NumElements = 0;
3586 }
3587 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3588 NumElements = VType->getNumElements();
3589 } else if (CurrentObjectType->isRecordType()) {
3590 NumElements = numStructUnionElements(DeclType: CurrentObjectType);
3591 } else if (CurrentObjectType->isDependentType()) {
3592 NumElements = 1;
3593 }
3594
3595 Result->reserveInits(C: SemaRef.Context, NumInits: NumElements);
3596
3597 return Result;
3598}
3599
3600/// Update the initializer at index @p StructuredIndex within the
3601/// structured initializer list to the value @p expr.
3602void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3603 unsigned &StructuredIndex,
3604 Expr *expr) {
3605 // No structured initializer list to update
3606 if (!StructuredList)
3607 return;
3608
3609 if (Expr *PrevInit = StructuredList->updateInit(C: SemaRef.Context,
3610 Init: StructuredIndex, expr)) {
3611 // This initializer overwrites a previous initializer.
3612 // No need to diagnose when `expr` is nullptr because a more relevant
3613 // diagnostic has already been issued and this diagnostic is potentially
3614 // noise.
3615 if (expr)
3616 diagnoseInitOverride(OldInit: PrevInit, NewInitRange: expr->getSourceRange());
3617 }
3618
3619 ++StructuredIndex;
3620}
3621
3622bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3623 const InitializedEntity &Entity, InitListExpr *From) {
3624 QualType Type = Entity.getType();
3625 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3626 /*TreatUnavailableAsInvalid=*/false,
3627 /*InOverloadResolution=*/true);
3628 return !Check.HadError();
3629}
3630
3631/// Check that the given Index expression is a valid array designator
3632/// value. This is essentially just a wrapper around
3633/// VerifyIntegerConstantExpression that also checks for negative values
3634/// and produces a reasonable diagnostic if there is a
3635/// failure. Returns the index expression, possibly with an implicit cast
3636/// added, on success. If everything went okay, Value will receive the
3637/// value of the constant expression.
3638static ExprResult
3639CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3640 SourceLocation Loc = Index->getBeginLoc();
3641
3642 // Make sure this is an integer constant expression.
3643 ExprResult Result =
3644 S.VerifyIntegerConstantExpression(E: Index, Result: &Value, CanFold: AllowFoldKind::Allow);
3645 if (Result.isInvalid())
3646 return Result;
3647
3648 if (Value.isSigned() && Value.isNegative())
3649 return S.Diag(Loc, DiagID: diag::err_array_designator_negative)
3650 << toString(I: Value, Radix: 10) << Index->getSourceRange();
3651
3652 Value.setIsUnsigned(true);
3653 return Result;
3654}
3655
3656ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3657 SourceLocation EqualOrColonLoc,
3658 bool GNUSyntax,
3659 ExprResult Init) {
3660 typedef DesignatedInitExpr::Designator ASTDesignator;
3661
3662 bool Invalid = false;
3663 SmallVector<ASTDesignator, 32> Designators;
3664 SmallVector<Expr *, 32> InitExpressions;
3665
3666 // Build designators and check array designator expressions.
3667 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3668 const Designator &D = Desig.getDesignator(Idx);
3669
3670 if (D.isFieldDesignator()) {
3671 Designators.push_back(Elt: ASTDesignator::CreateFieldDesignator(
3672 FieldName: D.getFieldDecl(), DotLoc: D.getDotLoc(), FieldLoc: D.getFieldLoc()));
3673 } else if (D.isArrayDesignator()) {
3674 Expr *Index = D.getArrayIndex();
3675 llvm::APSInt IndexValue;
3676 if (!Index->isTypeDependent() && !Index->isValueDependent())
3677 Index = CheckArrayDesignatorExpr(S&: *this, Index, Value&: IndexValue).get();
3678 if (!Index)
3679 Invalid = true;
3680 else {
3681 Designators.push_back(Elt: ASTDesignator::CreateArrayDesignator(
3682 Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), RBracketLoc: D.getRBracketLoc()));
3683 InitExpressions.push_back(Elt: Index);
3684 }
3685 } else if (D.isArrayRangeDesignator()) {
3686 Expr *StartIndex = D.getArrayRangeStart();
3687 Expr *EndIndex = D.getArrayRangeEnd();
3688 llvm::APSInt StartValue;
3689 llvm::APSInt EndValue;
3690 bool StartDependent = StartIndex->isTypeDependent() ||
3691 StartIndex->isValueDependent();
3692 bool EndDependent = EndIndex->isTypeDependent() ||
3693 EndIndex->isValueDependent();
3694 if (!StartDependent)
3695 StartIndex =
3696 CheckArrayDesignatorExpr(S&: *this, Index: StartIndex, Value&: StartValue).get();
3697 if (!EndDependent)
3698 EndIndex = CheckArrayDesignatorExpr(S&: *this, Index: EndIndex, Value&: EndValue).get();
3699
3700 if (!StartIndex || !EndIndex)
3701 Invalid = true;
3702 else {
3703 // Make sure we're comparing values with the same bit width.
3704 if (StartDependent || EndDependent) {
3705 // Nothing to compute.
3706 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3707 EndValue = EndValue.extend(width: StartValue.getBitWidth());
3708 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3709 StartValue = StartValue.extend(width: EndValue.getBitWidth());
3710
3711 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3712 Diag(Loc: D.getEllipsisLoc(), DiagID: diag::err_array_designator_empty_range)
3713 << toString(I: StartValue, Radix: 10) << toString(I: EndValue, Radix: 10)
3714 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3715 Invalid = true;
3716 } else {
3717 Designators.push_back(Elt: ASTDesignator::CreateArrayRangeDesignator(
3718 Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), EllipsisLoc: D.getEllipsisLoc(),
3719 RBracketLoc: D.getRBracketLoc()));
3720 InitExpressions.push_back(Elt: StartIndex);
3721 InitExpressions.push_back(Elt: EndIndex);
3722 }
3723 }
3724 }
3725 }
3726
3727 if (Invalid || Init.isInvalid())
3728 return ExprError();
3729
3730 return DesignatedInitExpr::Create(C: Context, Designators, IndexExprs: InitExpressions,
3731 EqualOrColonLoc, GNUSyntax,
3732 Init: Init.getAs<Expr>());
3733}
3734
3735//===----------------------------------------------------------------------===//
3736// Initialization entity
3737//===----------------------------------------------------------------------===//
3738
3739InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3740 const InitializedEntity &Parent)
3741 : Parent(&Parent), Index(Index)
3742{
3743 if (const ArrayType *AT = Context.getAsArrayType(T: Parent.getType())) {
3744 Kind = EK_ArrayElement;
3745 Type = AT->getElementType();
3746 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3747 Kind = EK_VectorElement;
3748 Type = VT->getElementType();
3749 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3750 Kind = EK_MatrixElement;
3751 Type = MT->getElementType();
3752 } else {
3753 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3754 assert(CT && "Unexpected type");
3755 Kind = EK_ComplexElement;
3756 Type = CT->getElementType();
3757 }
3758}
3759
3760InitializedEntity
3761InitializedEntity::InitializeBase(ASTContext &Context,
3762 const CXXBaseSpecifier *Base,
3763 bool IsInheritedVirtualBase,
3764 const InitializedEntity *Parent) {
3765 InitializedEntity Result;
3766 Result.Kind = EK_Base;
3767 Result.Parent = Parent;
3768 Result.Base = {Base, IsInheritedVirtualBase};
3769 Result.Type = Base->getType();
3770 return Result;
3771}
3772
3773DeclarationName InitializedEntity::getName() const {
3774 switch (getKind()) {
3775 case EK_Parameter:
3776 case EK_Parameter_CF_Audited: {
3777 ParmVarDecl *D = Parameter.getPointer();
3778 return (D ? D->getDeclName() : DeclarationName());
3779 }
3780
3781 case EK_Variable:
3782 case EK_Member:
3783 case EK_ParenAggInitMember:
3784 case EK_Binding:
3785 case EK_TemplateParameter:
3786 return Variable.VariableOrMember->getDeclName();
3787
3788 case EK_LambdaCapture:
3789 return DeclarationName(Capture.VarID);
3790
3791 case EK_Result:
3792 case EK_StmtExprResult:
3793 case EK_Exception:
3794 case EK_New:
3795 case EK_Temporary:
3796 case EK_Base:
3797 case EK_Delegating:
3798 case EK_ArrayElement:
3799 case EK_VectorElement:
3800 case EK_MatrixElement:
3801 case EK_ComplexElement:
3802 case EK_BlockElement:
3803 case EK_LambdaToBlockConversionBlockElement:
3804 case EK_CompoundLiteralInit:
3805 case EK_RelatedResult:
3806 return DeclarationName();
3807 }
3808
3809 llvm_unreachable("Invalid EntityKind!");
3810}
3811
3812ValueDecl *InitializedEntity::getDecl() const {
3813 switch (getKind()) {
3814 case EK_Variable:
3815 case EK_Member:
3816 case EK_ParenAggInitMember:
3817 case EK_Binding:
3818 case EK_TemplateParameter:
3819 return cast<ValueDecl>(Val: Variable.VariableOrMember);
3820
3821 case EK_Parameter:
3822 case EK_Parameter_CF_Audited:
3823 return Parameter.getPointer();
3824
3825 case EK_Result:
3826 case EK_StmtExprResult:
3827 case EK_Exception:
3828 case EK_New:
3829 case EK_Temporary:
3830 case EK_Base:
3831 case EK_Delegating:
3832 case EK_ArrayElement:
3833 case EK_VectorElement:
3834 case EK_MatrixElement:
3835 case EK_ComplexElement:
3836 case EK_BlockElement:
3837 case EK_LambdaToBlockConversionBlockElement:
3838 case EK_LambdaCapture:
3839 case EK_CompoundLiteralInit:
3840 case EK_RelatedResult:
3841 return nullptr;
3842 }
3843
3844 llvm_unreachable("Invalid EntityKind!");
3845}
3846
3847bool InitializedEntity::allowsNRVO() const {
3848 switch (getKind()) {
3849 case EK_Result:
3850 case EK_Exception:
3851 return LocAndNRVO.NRVO;
3852
3853 case EK_StmtExprResult:
3854 case EK_Variable:
3855 case EK_Parameter:
3856 case EK_Parameter_CF_Audited:
3857 case EK_TemplateParameter:
3858 case EK_Member:
3859 case EK_ParenAggInitMember:
3860 case EK_Binding:
3861 case EK_New:
3862 case EK_Temporary:
3863 case EK_CompoundLiteralInit:
3864 case EK_Base:
3865 case EK_Delegating:
3866 case EK_ArrayElement:
3867 case EK_VectorElement:
3868 case EK_MatrixElement:
3869 case EK_ComplexElement:
3870 case EK_BlockElement:
3871 case EK_LambdaToBlockConversionBlockElement:
3872 case EK_LambdaCapture:
3873 case EK_RelatedResult:
3874 break;
3875 }
3876
3877 return false;
3878}
3879
3880unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3881 assert(getParent() != this);
3882 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3883 for (unsigned I = 0; I != Depth; ++I)
3884 OS << "`-";
3885
3886 switch (getKind()) {
3887 case EK_Variable: OS << "Variable"; break;
3888 case EK_Parameter: OS << "Parameter"; break;
3889 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3890 break;
3891 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3892 case EK_Result: OS << "Result"; break;
3893 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3894 case EK_Exception: OS << "Exception"; break;
3895 case EK_Member:
3896 case EK_ParenAggInitMember:
3897 OS << "Member";
3898 break;
3899 case EK_Binding: OS << "Binding"; break;
3900 case EK_New: OS << "New"; break;
3901 case EK_Temporary: OS << "Temporary"; break;
3902 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3903 case EK_RelatedResult: OS << "RelatedResult"; break;
3904 case EK_Base: OS << "Base"; break;
3905 case EK_Delegating: OS << "Delegating"; break;
3906 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3907 case EK_VectorElement: OS << "VectorElement " << Index; break;
3908 case EK_MatrixElement:
3909 OS << "MatrixElement " << Index;
3910 break;
3911 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3912 case EK_BlockElement: OS << "Block"; break;
3913 case EK_LambdaToBlockConversionBlockElement:
3914 OS << "Block (lambda)";
3915 break;
3916 case EK_LambdaCapture:
3917 OS << "LambdaCapture ";
3918 OS << DeclarationName(Capture.VarID);
3919 break;
3920 }
3921
3922 if (auto *D = getDecl()) {
3923 OS << " ";
3924 D->printQualifiedName(OS);
3925 }
3926
3927 OS << " '" << getType() << "'\n";
3928
3929 return Depth + 1;
3930}
3931
3932LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3933 dumpImpl(OS&: llvm::errs());
3934}
3935
3936//===----------------------------------------------------------------------===//
3937// Initialization sequence
3938//===----------------------------------------------------------------------===//
3939
3940void InitializationSequence::Step::Destroy() {
3941 switch (Kind) {
3942 case SK_ResolveAddressOfOverloadedFunction:
3943 case SK_CastDerivedToBasePRValue:
3944 case SK_CastDerivedToBaseXValue:
3945 case SK_CastDerivedToBaseLValue:
3946 case SK_BindReference:
3947 case SK_BindReferenceToTemporary:
3948 case SK_FinalCopy:
3949 case SK_ExtraneousCopyToTemporary:
3950 case SK_UserConversion:
3951 case SK_QualificationConversionPRValue:
3952 case SK_QualificationConversionXValue:
3953 case SK_QualificationConversionLValue:
3954 case SK_FunctionReferenceConversion:
3955 case SK_AtomicConversion:
3956 case SK_ListInitialization:
3957 case SK_UnwrapInitList:
3958 case SK_RewrapInitList:
3959 case SK_ConstructorInitialization:
3960 case SK_ConstructorInitializationFromList:
3961 case SK_ZeroInitialization:
3962 case SK_CAssignment:
3963 case SK_StringInit:
3964 case SK_ObjCObjectConversion:
3965 case SK_ArrayLoopIndex:
3966 case SK_ArrayLoopInit:
3967 case SK_ArrayInit:
3968 case SK_GNUArrayInit:
3969 case SK_ParenthesizedArrayInit:
3970 case SK_PassByIndirectCopyRestore:
3971 case SK_PassByIndirectRestore:
3972 case SK_ProduceObjCObject:
3973 case SK_StdInitializerList:
3974 case SK_StdInitializerListConstructorCall:
3975 case SK_OCLSamplerInit:
3976 case SK_OCLZeroOpaqueType:
3977 case SK_ParenthesizedListInit:
3978 break;
3979
3980 case SK_ConversionSequence:
3981 case SK_ConversionSequenceNoNarrowing:
3982 delete ICS;
3983 }
3984}
3985
3986bool InitializationSequence::isDirectReferenceBinding() const {
3987 // There can be some lvalue adjustments after the SK_BindReference step.
3988 for (const Step &S : llvm::reverse(C: Steps)) {
3989 if (S.Kind == SK_BindReference)
3990 return true;
3991 if (S.Kind == SK_BindReferenceToTemporary)
3992 return false;
3993 }
3994 return false;
3995}
3996
3997bool InitializationSequence::isAmbiguous() const {
3998 if (!Failed())
3999 return false;
4000
4001 switch (getFailureKind()) {
4002 case FK_TooManyInitsForReference:
4003 case FK_ParenthesizedListInitForReference:
4004 case FK_ArrayNeedsInitList:
4005 case FK_ArrayNeedsInitListOrStringLiteral:
4006 case FK_ArrayNeedsInitListOrWideStringLiteral:
4007 case FK_NarrowStringIntoWideCharArray:
4008 case FK_WideStringIntoCharArray:
4009 case FK_IncompatWideStringIntoWideChar:
4010 case FK_PlainStringIntoUTF8Char:
4011 case FK_UTF8StringIntoPlainChar:
4012 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4013 case FK_NonConstLValueReferenceBindingToTemporary:
4014 case FK_NonConstLValueReferenceBindingToBitfield:
4015 case FK_NonConstLValueReferenceBindingToVectorElement:
4016 case FK_NonConstLValueReferenceBindingToMatrixElement:
4017 case FK_NonConstLValueReferenceBindingToUnrelated:
4018 case FK_RValueReferenceBindingToLValue:
4019 case FK_ReferenceAddrspaceMismatchTemporary:
4020 case FK_ReferenceInitDropsQualifiers:
4021 case FK_ReferenceInitFailed:
4022 case FK_ConversionFailed:
4023 case FK_ConversionFromPropertyFailed:
4024 case FK_TooManyInitsForScalar:
4025 case FK_ParenthesizedListInitForScalar:
4026 case FK_ReferenceBindingToInitList:
4027 case FK_InitListBadDestinationType:
4028 case FK_DefaultInitOfConst:
4029 case FK_Incomplete:
4030 case FK_ArrayTypeMismatch:
4031 case FK_NonConstantArrayInit:
4032 case FK_ListInitializationFailed:
4033 case FK_VariableLengthArrayHasInitializer:
4034 case FK_PlaceholderType:
4035 case FK_ExplicitConstructor:
4036 case FK_AddressOfUnaddressableFunction:
4037 case FK_ParenthesizedListInitFailed:
4038 case FK_DesignatedInitForNonAggregate:
4039 case FK_HLSLInitListFlatteningFailed:
4040 return false;
4041
4042 case FK_ReferenceInitOverloadFailed:
4043 case FK_UserConversionOverloadFailed:
4044 case FK_ConstructorOverloadFailed:
4045 case FK_ListConstructorOverloadFailed:
4046 return FailedOverloadResult == OR_Ambiguous;
4047 }
4048
4049 llvm_unreachable("Invalid EntityKind!");
4050}
4051
4052bool InitializationSequence::isConstructorInitialization() const {
4053 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4054}
4055
4056void
4057InitializationSequence
4058::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4059 DeclAccessPair Found,
4060 bool HadMultipleCandidates) {
4061 Step S;
4062 S.Kind = SK_ResolveAddressOfOverloadedFunction;
4063 S.Type = Function->getType();
4064 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4065 S.Function.Function = Function;
4066 S.Function.FoundDecl = Found;
4067 Steps.push_back(Elt: S);
4068}
4069
4070void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
4071 ExprValueKind VK) {
4072 Step S;
4073 switch (VK) {
4074 case VK_PRValue:
4075 S.Kind = SK_CastDerivedToBasePRValue;
4076 break;
4077 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4078 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4079 }
4080 S.Type = BaseType;
4081 Steps.push_back(Elt: S);
4082}
4083
4084void InitializationSequence::AddReferenceBindingStep(QualType T,
4085 bool BindingTemporary) {
4086 Step S;
4087 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4088 S.Type = T;
4089 Steps.push_back(Elt: S);
4090}
4091
4092void InitializationSequence::AddFinalCopy(QualType T) {
4093 Step S;
4094 S.Kind = SK_FinalCopy;
4095 S.Type = T;
4096 Steps.push_back(Elt: S);
4097}
4098
4099void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
4100 Step S;
4101 S.Kind = SK_ExtraneousCopyToTemporary;
4102 S.Type = T;
4103 Steps.push_back(Elt: S);
4104}
4105
4106void
4107InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
4108 DeclAccessPair FoundDecl,
4109 QualType T,
4110 bool HadMultipleCandidates) {
4111 Step S;
4112 S.Kind = SK_UserConversion;
4113 S.Type = T;
4114 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4115 S.Function.Function = Function;
4116 S.Function.FoundDecl = FoundDecl;
4117 Steps.push_back(Elt: S);
4118}
4119
4120void InitializationSequence::AddQualificationConversionStep(QualType Ty,
4121 ExprValueKind VK) {
4122 Step S;
4123 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4124 switch (VK) {
4125 case VK_PRValue:
4126 S.Kind = SK_QualificationConversionPRValue;
4127 break;
4128 case VK_XValue:
4129 S.Kind = SK_QualificationConversionXValue;
4130 break;
4131 case VK_LValue:
4132 S.Kind = SK_QualificationConversionLValue;
4133 break;
4134 }
4135 S.Type = Ty;
4136 Steps.push_back(Elt: S);
4137}
4138
4139void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
4140 Step S;
4141 S.Kind = SK_FunctionReferenceConversion;
4142 S.Type = Ty;
4143 Steps.push_back(Elt: S);
4144}
4145
4146void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
4147 Step S;
4148 S.Kind = SK_AtomicConversion;
4149 S.Type = Ty;
4150 Steps.push_back(Elt: S);
4151}
4152
4153void InitializationSequence::AddConversionSequenceStep(
4154 const ImplicitConversionSequence &ICS, QualType T,
4155 bool TopLevelOfInitList) {
4156 Step S;
4157 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4158 : SK_ConversionSequence;
4159 S.Type = T;
4160 S.ICS = new ImplicitConversionSequence(ICS);
4161 Steps.push_back(Elt: S);
4162}
4163
4164void InitializationSequence::AddListInitializationStep(QualType T) {
4165 Step S;
4166 S.Kind = SK_ListInitialization;
4167 S.Type = T;
4168 Steps.push_back(Elt: S);
4169}
4170
4171void InitializationSequence::AddConstructorInitializationStep(
4172 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
4173 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4174 Step S;
4175 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4176 : SK_ConstructorInitializationFromList
4177 : SK_ConstructorInitialization;
4178 S.Type = T;
4179 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4180 S.Function.Function = Constructor;
4181 S.Function.FoundDecl = FoundDecl;
4182 Steps.push_back(Elt: S);
4183}
4184
4185void InitializationSequence::AddZeroInitializationStep(QualType T) {
4186 Step S;
4187 S.Kind = SK_ZeroInitialization;
4188 S.Type = T;
4189 Steps.push_back(Elt: S);
4190}
4191
4192void InitializationSequence::AddCAssignmentStep(QualType T) {
4193 Step S;
4194 S.Kind = SK_CAssignment;
4195 S.Type = T;
4196 Steps.push_back(Elt: S);
4197}
4198
4199void InitializationSequence::AddStringInitStep(QualType T) {
4200 Step S;
4201 S.Kind = SK_StringInit;
4202 S.Type = T;
4203 Steps.push_back(Elt: S);
4204}
4205
4206void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
4207 Step S;
4208 S.Kind = SK_ObjCObjectConversion;
4209 S.Type = T;
4210 Steps.push_back(Elt: S);
4211}
4212
4213void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
4214 Step S;
4215 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4216 S.Type = T;
4217 Steps.push_back(Elt: S);
4218}
4219
4220void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
4221 Step S;
4222 S.Kind = SK_ArrayLoopIndex;
4223 S.Type = EltT;
4224 Steps.insert(I: Steps.begin(), Elt: S);
4225
4226 S.Kind = SK_ArrayLoopInit;
4227 S.Type = T;
4228 Steps.push_back(Elt: S);
4229}
4230
4231void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
4232 Step S;
4233 S.Kind = SK_ParenthesizedArrayInit;
4234 S.Type = T;
4235 Steps.push_back(Elt: S);
4236}
4237
4238void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
4239 bool shouldCopy) {
4240 Step s;
4241 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4242 : SK_PassByIndirectRestore);
4243 s.Type = type;
4244 Steps.push_back(Elt: s);
4245}
4246
4247void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
4248 Step S;
4249 S.Kind = SK_ProduceObjCObject;
4250 S.Type = T;
4251 Steps.push_back(Elt: S);
4252}
4253
4254void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
4255 Step S;
4256 S.Kind = SK_StdInitializerList;
4257 S.Type = T;
4258 Steps.push_back(Elt: S);
4259}
4260
4261void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
4262 Step S;
4263 S.Kind = SK_OCLSamplerInit;
4264 S.Type = T;
4265 Steps.push_back(Elt: S);
4266}
4267
4268void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
4269 Step S;
4270 S.Kind = SK_OCLZeroOpaqueType;
4271 S.Type = T;
4272 Steps.push_back(Elt: S);
4273}
4274
4275void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
4276 Step S;
4277 S.Kind = SK_ParenthesizedListInit;
4278 S.Type = T;
4279 Steps.push_back(Elt: S);
4280}
4281
4282void InitializationSequence::AddUnwrapInitListInitStep(
4283 InitListExpr *Syntactic) {
4284 assert(Syntactic->getNumInits() == 1 &&
4285 "Can only unwrap trivial init lists.");
4286 Step S;
4287 S.Kind = SK_UnwrapInitList;
4288 S.Type = Syntactic->getInit(Init: 0)->getType();
4289 Steps.insert(I: Steps.begin(), Elt: S);
4290}
4291
4292void InitializationSequence::RewrapReferenceInitList(QualType T,
4293 InitListExpr *Syntactic) {
4294 assert(Syntactic->getNumInits() == 1 &&
4295 "Can only rewrap trivial init lists.");
4296 Step S;
4297 S.Kind = SK_UnwrapInitList;
4298 S.Type = Syntactic->getInit(Init: 0)->getType();
4299 Steps.insert(I: Steps.begin(), Elt: S);
4300
4301 S.Kind = SK_RewrapInitList;
4302 S.Type = T;
4303 S.WrappingSyntacticList = Syntactic;
4304 Steps.push_back(Elt: S);
4305}
4306
4307void InitializationSequence::SetOverloadFailure(FailureKind Failure,
4308 OverloadingResult Result) {
4309 setSequenceKind(FailedSequence);
4310 this->Failure = Failure;
4311 this->FailedOverloadResult = Result;
4312}
4313
4314//===----------------------------------------------------------------------===//
4315// Attempt initialization
4316//===----------------------------------------------------------------------===//
4317
4318/// Tries to add a zero initializer. Returns true if that worked.
4319static bool
4320maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
4321 const InitializedEntity &Entity) {
4322 if (Entity.getKind() != InitializedEntity::EK_Variable)
4323 return false;
4324
4325 VarDecl *VD = cast<VarDecl>(Val: Entity.getDecl());
4326 if (VD->getInit() || VD->getEndLoc().isMacroID())
4327 return false;
4328
4329 QualType VariableTy = VD->getType().getCanonicalType();
4330 SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc());
4331 std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc);
4332 if (!Init.empty()) {
4333 Sequence.AddZeroInitializationStep(T: Entity.getType());
4334 Sequence.SetZeroInitializationFixit(Fixit: Init, L: Loc);
4335 return true;
4336 }
4337 return false;
4338}
4339
4340static void MaybeProduceObjCObject(Sema &S,
4341 InitializationSequence &Sequence,
4342 const InitializedEntity &Entity) {
4343 if (!S.getLangOpts().ObjCAutoRefCount) return;
4344
4345 /// When initializing a parameter, produce the value if it's marked
4346 /// __attribute__((ns_consumed)).
4347 if (Entity.isParameterKind()) {
4348 if (!Entity.isParameterConsumed())
4349 return;
4350
4351 assert(Entity.getType()->isObjCRetainableType() &&
4352 "consuming an object of unretainable type?");
4353 Sequence.AddProduceObjCObjectStep(T: Entity.getType());
4354
4355 /// When initializing a return value, if the return type is a
4356 /// retainable type, then returns need to immediately retain the
4357 /// object. If an autorelease is required, it will be done at the
4358 /// last instant.
4359 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4360 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
4361 if (!Entity.getType()->isObjCRetainableType())
4362 return;
4363
4364 Sequence.AddProduceObjCObjectStep(T: Entity.getType());
4365 }
4366}
4367
4368/// Initialize an array from another array
4369static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4370 const InitializedEntity &Entity, Expr *Initializer,
4371 QualType DestType, InitializationSequence &Sequence,
4372 bool TreatUnavailableAsInvalid) {
4373 // If source is a prvalue, use it directly.
4374 if (Initializer->isPRValue()) {
4375 Sequence.AddArrayInitStep(T: DestType, /*IsGNUExtension*/ false);
4376 return;
4377 }
4378
4379 // Emit element-at-a-time copy loop.
4380 InitializedEntity Element =
4381 InitializedEntity::InitializeElement(Context&: S.Context, Index: 0, Parent: Entity);
4382 QualType InitEltT =
4383 S.Context.getAsArrayType(T: Initializer->getType())->getElementType();
4384 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
4385 Initializer->getValueKind(),
4386 Initializer->getObjectKind());
4387 Expr *OVEAsExpr = &OVE;
4388 Sequence.InitializeFrom(S, Entity: Element, Kind, Args: OVEAsExpr,
4389 /*TopLevelOfInitList*/ false,
4390 TreatUnavailableAsInvalid);
4391 if (Sequence)
4392 Sequence.AddArrayInitLoopStep(T: Entity.getType(), EltT: InitEltT);
4393}
4394
4395static void TryListInitialization(Sema &S,
4396 const InitializedEntity &Entity,
4397 const InitializationKind &Kind,
4398 InitListExpr *InitList,
4399 InitializationSequence &Sequence,
4400 bool TreatUnavailableAsInvalid);
4401
4402/// When initializing from init list via constructor, handle
4403/// initialization of an object of type std::initializer_list<T>.
4404///
4405/// \return true if we have handled initialization of an object of type
4406/// std::initializer_list<T>, false otherwise.
4407static bool TryInitializerListConstruction(Sema &S,
4408 InitListExpr *List,
4409 QualType DestType,
4410 InitializationSequence &Sequence,
4411 bool TreatUnavailableAsInvalid) {
4412 QualType E;
4413 if (!S.isStdInitializerList(Ty: DestType, Element: &E))
4414 return false;
4415
4416 if (!S.isCompleteType(Loc: List->getExprLoc(), T: E)) {
4417 Sequence.setIncompleteTypeFailure(E);
4418 return true;
4419 }
4420
4421 // Try initializing a temporary array from the init list.
4422 QualType ArrayType = S.Context.getConstantArrayType(
4423 EltTy: E.withConst(),
4424 ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()),
4425 List->getNumInitsWithEmbedExpanded()),
4426 SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0);
4427 InitializedEntity HiddenArray =
4428 InitializedEntity::InitializeTemporary(Type: ArrayType);
4429 InitializationKind Kind = InitializationKind::CreateDirectList(
4430 InitLoc: List->getExprLoc(), LBraceLoc: List->getBeginLoc(), RBraceLoc: List->getEndLoc());
4431 TryListInitialization(S, Entity: HiddenArray, Kind, InitList: List, Sequence,
4432 TreatUnavailableAsInvalid);
4433 if (Sequence)
4434 Sequence.AddStdInitializerListConstructionStep(T: DestType);
4435 return true;
4436}
4437
4438/// Determine if the constructor has the signature of a copy or move
4439/// constructor for the type T of the class in which it was found. That is,
4440/// determine if its first parameter is of type T or reference to (possibly
4441/// cv-qualified) T.
4442static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
4443 const ConstructorInfo &Info) {
4444 if (Info.Constructor->getNumParams() == 0)
4445 return false;
4446
4447 QualType ParmT =
4448 Info.Constructor->getParamDecl(i: 0)->getType().getNonReferenceType();
4449 CanQualType ClassT = Ctx.getCanonicalTagType(
4450 TD: cast<CXXRecordDecl>(Val: Info.FoundDecl->getDeclContext()));
4451
4452 return Ctx.hasSameUnqualifiedType(T1: ParmT, T2: ClassT);
4453}
4454
4455static OverloadingResult ResolveConstructorOverload(
4456 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4457 OverloadCandidateSet &CandidateSet, QualType DestType,
4458 DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,
4459 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4460 bool IsListInit, bool RequireActualConstructor,
4461 bool SecondStepOfCopyInit = false) {
4462 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByConstructor);
4463 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4464
4465 for (NamedDecl *D : Ctors) {
4466 auto Info = getConstructorInfo(ND: D);
4467 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4468 continue;
4469
4470 if (OnlyListConstructors && !S.isInitListConstructor(Ctor: Info.Constructor))
4471 continue;
4472
4473 // C++11 [over.best.ics]p4:
4474 // ... and the constructor or user-defined conversion function is a
4475 // candidate by
4476 // - 13.3.1.3, when the argument is the temporary in the second step
4477 // of a class copy-initialization, or
4478 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4479 // - the second phase of 13.3.1.7 when the initializer list has exactly
4480 // one element that is itself an initializer list, and the target is
4481 // the first parameter of a constructor of class X, and the conversion
4482 // is to X or reference to (possibly cv-qualified X),
4483 // user-defined conversion sequences are not considered.
4484 bool SuppressUserConversions =
4485 SecondStepOfCopyInit ||
4486 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) &&
4487 hasCopyOrMoveCtorParam(Ctx&: S.Context, Info));
4488
4489 if (Info.ConstructorTmpl)
4490 S.AddTemplateOverloadCandidate(
4491 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4492 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args, CandidateSet, SuppressUserConversions,
4493 /*PartialOverloading=*/false, AllowExplicit);
4494 else {
4495 // C++ [over.match.copy]p1:
4496 // - When initializing a temporary to be bound to the first parameter
4497 // of a constructor [for type T] that takes a reference to possibly
4498 // cv-qualified T as its first argument, called with a single
4499 // argument in the context of direct-initialization, explicit
4500 // conversion functions are also considered.
4501 // FIXME: What if a constructor template instantiates to such a signature?
4502 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4503 Args.size() == 1 &&
4504 hasCopyOrMoveCtorParam(Ctx&: S.Context, Info);
4505 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args,
4506 CandidateSet, SuppressUserConversions,
4507 /*PartialOverloading=*/false, AllowExplicit,
4508 AllowExplicitConversion: AllowExplicitConv);
4509 }
4510 }
4511
4512 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4513 //
4514 // When initializing an object of class type T by constructor
4515 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4516 // from a single expression of class type U, conversion functions of
4517 // U that convert to the non-reference type cv T are candidates.
4518 // Explicit conversion functions are only candidates during
4519 // direct-initialization.
4520 //
4521 // Note: SecondStepOfCopyInit is only ever true in this case when
4522 // evaluating whether to produce a C++98 compatibility warning.
4523 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4524 !RequireActualConstructor && !SecondStepOfCopyInit) {
4525 Expr *Initializer = Args[0];
4526 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4527 if (SourceRD && S.isCompleteType(Loc: DeclLoc, T: Initializer->getType())) {
4528 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4529 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4530 NamedDecl *D = *I;
4531 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
4532 D = D->getUnderlyingDecl();
4533
4534 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
4535 CXXConversionDecl *Conv;
4536 if (ConvTemplate)
4537 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4538 else
4539 Conv = cast<CXXConversionDecl>(Val: D);
4540
4541 if (ConvTemplate)
4542 S.AddTemplateConversionCandidate(
4543 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
4544 CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit,
4545 /*AllowResultConversion*/ false);
4546 else
4547 S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer,
4548 ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit,
4549 AllowExplicit,
4550 /*AllowResultConversion*/ false);
4551 }
4552 }
4553 }
4554
4555 // Perform overload resolution and return the result.
4556 return CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best);
4557}
4558
4559/// Attempt initialization by constructor (C++ [dcl.init]), which
4560/// enumerates the constructors of the initialized entity and performs overload
4561/// resolution to select the best.
4562/// \param DestType The destination class type.
4563/// \param DestArrayType The destination type, which is either DestType or
4564/// a (possibly multidimensional) array of DestType.
4565/// \param IsListInit Is this list-initialization?
4566/// \param IsInitListCopy Is this non-list-initialization resulting from a
4567/// list-initialization from {x} where x is the same
4568/// aggregate type as the entity?
4569static void TryConstructorInitialization(Sema &S,
4570 const InitializedEntity &Entity,
4571 const InitializationKind &Kind,
4572 MultiExprArg Args, QualType DestType,
4573 QualType DestArrayType,
4574 InitializationSequence &Sequence,
4575 bool IsListInit = false,
4576 bool IsInitListCopy = false) {
4577 assert(((!IsListInit && !IsInitListCopy) ||
4578 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4579 "IsListInit/IsInitListCopy must come with a single initializer list "
4580 "argument.");
4581 InitListExpr *ILE =
4582 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Val: Args[0]) : nullptr;
4583 MultiExprArg UnwrappedArgs =
4584 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4585
4586 // The type we're constructing needs to be complete.
4587 if (!S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) {
4588 Sequence.setIncompleteTypeFailure(DestType);
4589 return;
4590 }
4591
4592 bool RequireActualConstructor =
4593 !(Entity.getKind() != InitializedEntity::EK_Base &&
4594 Entity.getKind() != InitializedEntity::EK_Delegating &&
4595 Entity.getKind() !=
4596 InitializedEntity::EK_LambdaToBlockConversionBlockElement);
4597
4598 bool CopyElisionPossible = false;
4599 auto ElideConstructor = [&] {
4600 // Convert qualifications if necessary.
4601 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
4602 if (ILE)
4603 Sequence.RewrapReferenceInitList(T: DestType, Syntactic: ILE);
4604 };
4605
4606 // C++17 [dcl.init]p17:
4607 // - If the initializer expression is a prvalue and the cv-unqualified
4608 // version of the source type is the same class as the class of the
4609 // destination, the initializer expression is used to initialize the
4610 // destination object.
4611 // Per DR (no number yet), this does not apply when initializing a base
4612 // class or delegating to another constructor from a mem-initializer.
4613 // ObjC++: Lambda captured by the block in the lambda to block conversion
4614 // should avoid copy elision.
4615 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4616 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4617 S.Context.hasSameUnqualifiedType(T1: UnwrappedArgs[0]->getType(), T2: DestType)) {
4618 if (ILE && !DestType->isAggregateType()) {
4619 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4620 // Make this an elision if this won't call an initializer-list
4621 // constructor. (Always on an aggregate type or check constructors first.)
4622
4623 // This effectively makes our resolution as follows. The parts in angle
4624 // brackets are additions.
4625 // C++17 [over.match.list]p(1.2):
4626 // - If no viable initializer-list constructor is found <and the
4627 // initializer list does not consist of exactly a single element with
4628 // the same cv-unqualified class type as T>, [...]
4629 // C++17 [dcl.init.list]p(3.6):
4630 // - Otherwise, if T is a class type, constructors are considered. The
4631 // applicable constructors are enumerated and the best one is chosen
4632 // through overload resolution. <If no constructor is found and the
4633 // initializer list consists of exactly a single element with the same
4634 // cv-unqualified class type as T, the object is initialized from that
4635 // element (by copy-initialization for copy-list-initialization, or by
4636 // direct-initialization for direct-list-initialization). Otherwise, >
4637 // if a narrowing conversion [...]
4638 assert(!IsInitListCopy &&
4639 "IsInitListCopy only possible with aggregate types");
4640 CopyElisionPossible = true;
4641 } else {
4642 ElideConstructor();
4643 return;
4644 }
4645 }
4646
4647 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4648 // Build the candidate set directly in the initialization sequence
4649 // structure, so that it will persist if we fail.
4650 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4651
4652 // Determine whether we are allowed to call explicit constructors or
4653 // explicit conversion operators.
4654 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4655 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4656
4657 // - Otherwise, if T is a class type, constructors are considered. The
4658 // applicable constructors are enumerated, and the best one is chosen
4659 // through overload resolution.
4660 DeclContext::lookup_result Ctors = S.LookupConstructors(Class: DestRecordDecl);
4661
4662 OverloadingResult Result = OR_No_Viable_Function;
4663 OverloadCandidateSet::iterator Best;
4664 bool AsInitializerList = false;
4665
4666 // C++11 [over.match.list]p1, per DR1467:
4667 // When objects of non-aggregate type T are list-initialized, such that
4668 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4669 // according to the rules in this section, overload resolution selects
4670 // the constructor in two phases:
4671 //
4672 // - Initially, the candidate functions are the initializer-list
4673 // constructors of the class T and the argument list consists of the
4674 // initializer list as a single argument.
4675 if (IsListInit) {
4676 AsInitializerList = true;
4677
4678 // If the initializer list has no elements and T has a default constructor,
4679 // the first phase is omitted.
4680 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(Class: DestRecordDecl)))
4681 Result = ResolveConstructorOverload(
4682 S, DeclLoc: Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4683 CopyInitializing: CopyInitialization, AllowExplicit,
4684 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4685
4686 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4687 // No initializer list candidate
4688 ElideConstructor();
4689 return;
4690 }
4691 }
4692
4693 // C++11 [over.match.list]p1:
4694 // - If no viable initializer-list constructor is found, overload resolution
4695 // is performed again, where the candidate functions are all the
4696 // constructors of the class T and the argument list consists of the
4697 // elements of the initializer list.
4698 if (Result == OR_No_Viable_Function) {
4699 AsInitializerList = false;
4700 Result = ResolveConstructorOverload(
4701 S, DeclLoc: Kind.getLocation(), Args: UnwrappedArgs, CandidateSet, DestType, Ctors,
4702 Best, CopyInitializing: CopyInitialization, AllowExplicit,
4703 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4704 }
4705 if (Result) {
4706 Sequence.SetOverloadFailure(
4707 Failure: IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4708 : InitializationSequence::FK_ConstructorOverloadFailed,
4709 Result);
4710
4711 if (Result != OR_Deleted)
4712 return;
4713 }
4714
4715 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4716
4717 // In C++17, ResolveConstructorOverload can select a conversion function
4718 // instead of a constructor.
4719 if (auto *CD = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4720 // Add the user-defined conversion step that calls the conversion function.
4721 QualType ConvType = CD->getConversionType();
4722 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4723 "should not have selected this conversion function");
4724 Sequence.AddUserConversionStep(Function: CD, FoundDecl: Best->FoundDecl, T: ConvType,
4725 HadMultipleCandidates);
4726 if (!S.Context.hasSameType(T1: ConvType, T2: DestType))
4727 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
4728 if (IsListInit)
4729 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: ILE);
4730 return;
4731 }
4732
4733 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
4734 if (Result != OR_Deleted) {
4735 if (!IsListInit &&
4736 (Kind.getKind() == InitializationKind::IK_Default ||
4737 Kind.getKind() == InitializationKind::IK_Direct) &&
4738 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4739 DestRecordDecl->isAggregate() &&
4740 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4741 !S.isUnevaluatedContext()) {
4742 S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init)
4743 << /* Var-in-Record */ 1 << DestRecordDecl;
4744 emitUninitializedExplicitInitFields(S, R: DestRecordDecl);
4745 }
4746
4747 // C++11 [dcl.init]p6:
4748 // If a program calls for the default initialization of an object
4749 // of a const-qualified type T, T shall be a class type with a
4750 // user-provided default constructor.
4751 // C++ core issue 253 proposal:
4752 // If the implicit default constructor initializes all subobjects, no
4753 // initializer should be required.
4754 // The 253 proposal is for example needed to process libstdc++ headers
4755 // in 5.x.
4756 if (Kind.getKind() == InitializationKind::IK_Default &&
4757 Entity.getType().isConstQualified()) {
4758 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4759 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4760 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4761 return;
4762 }
4763 }
4764
4765 // C++11 [over.match.list]p1:
4766 // In copy-list-initialization, if an explicit constructor is chosen, the
4767 // initializer is ill-formed.
4768 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4769 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4770 return;
4771 }
4772 }
4773
4774 // [class.copy.elision]p3:
4775 // In some copy-initialization contexts, a two-stage overload resolution
4776 // is performed.
4777 // If the first overload resolution selects a deleted function, we also
4778 // need the initialization sequence to decide whether to perform the second
4779 // overload resolution.
4780 // For deleted functions in other contexts, there is no need to get the
4781 // initialization sequence.
4782 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4783 return;
4784
4785 // Add the constructor initialization step. Any cv-qualification conversion is
4786 // subsumed by the initialization.
4787 Sequence.AddConstructorInitializationStep(
4788 FoundDecl: Best->FoundDecl, Constructor: CtorDecl, T: DestArrayType, HadMultipleCandidates,
4789 FromInitList: IsListInit | IsInitListCopy, AsInitList: AsInitializerList);
4790}
4791
4792static void TryOrBuildParenListInitialization(
4793 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4794 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4795 ExprResult *Result = nullptr);
4796
4797/// Attempt to initialize an object of a class type either by
4798/// direct-initialization, or by copy-initialization from an
4799/// expression of the same or derived class type. This corresponds
4800/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4801///
4802/// \param IsAggrListInit Is this non-list-initialization being done as
4803/// part of a list-initialization of an aggregate
4804/// from a single expression of the same or
4805/// derived class type (C++2c [dcl.init.list] p3.2)?
4806static void TryConstructorOrParenListInitialization(
4807 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4808 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4809 bool IsAggrListInit) {
4810 // C++2c [dcl.init.general] p16.6:
4811 // * Otherwise, if the destination type is a class type:
4812 // * If the initializer expression is a prvalue and
4813 // the cv-unqualified version of the source type is the same
4814 // as the destination type, the initializer expression is used
4815 // to initialize the destination object.
4816 // * Otherwise, if the initialization is direct-initialization,
4817 // or if it is copy-initialization where the cv-unqualified
4818 // version of the source type is the same as or is derived from
4819 // the class of the destination type, constructors are considered.
4820 // The applicable constructors are enumerated, and the best one
4821 // is chosen through overload resolution. Then:
4822 // * If overload resolution is successful, the selected
4823 // constructor is called to initialize the object, with
4824 // the initializer expression or expression-list as its
4825 // argument(s).
4826 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestArrayType: DestType,
4827 Sequence, /*IsListInit=*/false, IsInitListCopy: IsAggrListInit);
4828
4829 // * Otherwise, if no constructor is viable, the destination type
4830 // is an aggregate class, and the initializer is a parenthesized
4831 // expression-list, the object is initialized as follows. [...]
4832 // Parenthesized initialization of aggregates is a C++20 feature.
4833 if (S.getLangOpts().CPlusPlus20 &&
4834 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4835 Sequence.getFailureKind() ==
4836 InitializationSequence::FK_ConstructorOverloadFailed &&
4837 Sequence.getFailedOverloadResult() == OR_No_Viable_Function &&
4838 (IsAggrListInit || DestType->isAggregateType()))
4839 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4840 /*VerifyOnly=*/true);
4841
4842 // * Otherwise, the initialization is ill-formed.
4843}
4844
4845static bool
4846ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4847 Expr *Initializer,
4848 QualType &SourceType,
4849 QualType &UnqualifiedSourceType,
4850 QualType UnqualifiedTargetType,
4851 InitializationSequence &Sequence) {
4852 if (S.Context.getCanonicalType(T: UnqualifiedSourceType) ==
4853 S.Context.OverloadTy) {
4854 DeclAccessPair Found;
4855 bool HadMultipleCandidates = false;
4856 if (FunctionDecl *Fn
4857 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer,
4858 TargetType: UnqualifiedTargetType,
4859 Complain: false, Found,
4860 pHadMultipleCandidates: &HadMultipleCandidates)) {
4861 Sequence.AddAddressOverloadResolutionStep(Function: Fn, Found,
4862 HadMultipleCandidates);
4863 SourceType = Fn->getType();
4864 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4865 } else if (!UnqualifiedTargetType->isRecordType()) {
4866 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4867 return true;
4868 }
4869 }
4870 return false;
4871}
4872
4873static void TryReferenceInitializationCore(Sema &S,
4874 const InitializedEntity &Entity,
4875 const InitializationKind &Kind,
4876 Expr *Initializer,
4877 QualType cv1T1, QualType T1,
4878 Qualifiers T1Quals,
4879 QualType cv2T2, QualType T2,
4880 Qualifiers T2Quals,
4881 InitializationSequence &Sequence,
4882 bool TopLevelOfInitList);
4883
4884static void TryValueInitialization(Sema &S,
4885 const InitializedEntity &Entity,
4886 const InitializationKind &Kind,
4887 InitializationSequence &Sequence,
4888 InitListExpr *InitList = nullptr);
4889
4890/// Attempt list initialization of a reference.
4891static void TryReferenceListInitialization(Sema &S,
4892 const InitializedEntity &Entity,
4893 const InitializationKind &Kind,
4894 InitListExpr *InitList,
4895 InitializationSequence &Sequence,
4896 bool TreatUnavailableAsInvalid) {
4897 // First, catch C++03 where this isn't possible.
4898 if (!S.getLangOpts().CPlusPlus11) {
4899 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4900 return;
4901 }
4902 // Can't reference initialize a compound literal.
4903 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4904 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4905 return;
4906 }
4907
4908 QualType DestType = Entity.getType();
4909 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4910 Qualifiers T1Quals;
4911 QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals);
4912
4913 // Reference initialization via an initializer list works thus:
4914 // If the initializer list consists of a single element that is
4915 // reference-related to the referenced type, bind directly to that element
4916 // (possibly creating temporaries).
4917 // Otherwise, initialize a temporary with the initializer list and
4918 // bind to that.
4919 if (InitList->getNumInits() == 1) {
4920 Expr *Initializer = InitList->getInit(Init: 0);
4921 QualType cv2T2 = S.getCompletedType(E: Initializer);
4922 Qualifiers T2Quals;
4923 QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals);
4924
4925 // If this fails, creating a temporary wouldn't work either.
4926 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2,
4927 UnqualifiedTargetType: T1, Sequence))
4928 return;
4929
4930 SourceLocation DeclLoc = Initializer->getBeginLoc();
4931 Sema::ReferenceCompareResult RefRelationship
4932 = S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2);
4933 if (RefRelationship >= Sema::Ref_Related) {
4934 // Try to bind the reference here.
4935 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4936 T1Quals, cv2T2, T2, T2Quals, Sequence,
4937 /*TopLevelOfInitList=*/true);
4938 if (Sequence)
4939 Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList);
4940 return;
4941 }
4942
4943 // Update the initializer if we've resolved an overloaded function.
4944 if (!Sequence.steps().empty())
4945 Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList);
4946 }
4947 // Perform address space compatibility check.
4948 QualType cv1T1IgnoreAS = cv1T1;
4949 if (T1Quals.hasAddressSpace()) {
4950 Qualifiers T2Quals;
4951 (void)S.Context.getUnqualifiedArrayType(T: InitList->getType(), Quals&: T2Quals);
4952 if (!T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext())) {
4953 Sequence.SetFailed(
4954 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4955 return;
4956 }
4957 // Ignore address space of reference type at this point and perform address
4958 // space conversion after the reference binding step.
4959 cv1T1IgnoreAS =
4960 S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace());
4961 }
4962 // Not reference-related. Create a temporary and bind to that.
4963 InitializedEntity TempEntity =
4964 InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS);
4965
4966 TryListInitialization(S, Entity: TempEntity, Kind, InitList, Sequence,
4967 TreatUnavailableAsInvalid);
4968 if (Sequence) {
4969 if (DestType->isRValueReferenceType() ||
4970 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4971 if (S.getLangOpts().CPlusPlus20 &&
4972 isa<IncompleteArrayType>(Val: T1->getUnqualifiedDesugaredType()) &&
4973 DestType->isRValueReferenceType()) {
4974 // C++20 [dcl.init.list]p3.10:
4975 // List-initialization of an object or reference of type T is defined as
4976 // follows:
4977 // ..., unless T is “reference to array of unknown bound of U”, in which
4978 // case the type of the prvalue is the type of x in the declaration U
4979 // x[] H, where H is the initializer list.
4980 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: clang::VK_PRValue);
4981 }
4982 Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS,
4983 /*BindingTemporary=*/true);
4984 if (T1Quals.hasAddressSpace())
4985 Sequence.AddQualificationConversionStep(
4986 Ty: cv1T1, VK: DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4987 } else
4988 Sequence.SetFailed(
4989 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4990 }
4991}
4992
4993/// Attempt list initialization (C++0x [dcl.init.list])
4994static void TryListInitialization(Sema &S,
4995 const InitializedEntity &Entity,
4996 const InitializationKind &Kind,
4997 InitListExpr *InitList,
4998 InitializationSequence &Sequence,
4999 bool TreatUnavailableAsInvalid) {
5000 QualType DestType = Entity.getType();
5001
5002 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, Init: InitList)) {
5003 Sequence.SetFailed(InitializationSequence::FK_HLSLInitListFlatteningFailed);
5004 return;
5005 }
5006
5007 // C++ doesn't allow scalar initialization with more than one argument.
5008 // But C99 complex numbers are scalars and it makes sense there.
5009 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5010 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5011 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
5012 return;
5013 }
5014 if (DestType->isReferenceType()) {
5015 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5016 TreatUnavailableAsInvalid);
5017 return;
5018 }
5019
5020 if (DestType->isRecordType() &&
5021 !S.isCompleteType(Loc: InitList->getBeginLoc(), T: DestType)) {
5022 Sequence.setIncompleteTypeFailure(DestType);
5023 return;
5024 }
5025
5026 // C++20 [dcl.init.list]p3:
5027 // - If the braced-init-list contains a designated-initializer-list, T shall
5028 // be an aggregate class. [...] Aggregate initialization is performed.
5029 //
5030 // We allow arrays here too in order to support array designators.
5031 //
5032 // FIXME: This check should precede the handling of reference initialization.
5033 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5034 // as a tentative DR resolution.
5035 bool IsDesignatedInit = InitList->hasDesignatedInit();
5036 if (!DestType->isAggregateType() && IsDesignatedInit) {
5037 Sequence.SetFailed(
5038 InitializationSequence::FK_DesignatedInitForNonAggregate);
5039 return;
5040 }
5041
5042 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5043 // - If T is an aggregate class and the initializer list has a single element
5044 // of type cv U, where U is T or a class derived from T, the object is
5045 // initialized from that element (by copy-initialization for
5046 // copy-list-initialization, or by direct-initialization for
5047 // direct-list-initialization).
5048 // - Otherwise, if T is a character array and the initializer list has a
5049 // single element that is an appropriately-typed string literal
5050 // (8.5.2 [dcl.init.string]), initialization is performed as described
5051 // in that section.
5052 // - Otherwise, if T is an aggregate, [...] (continue below).
5053 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5054 !IsDesignatedInit) {
5055 if (DestType->isRecordType() && DestType->isAggregateType()) {
5056 QualType InitType = InitList->getInit(Init: 0)->getType();
5057 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: DestType) ||
5058 S.IsDerivedFrom(Loc: InitList->getBeginLoc(), Derived: InitType, Base: DestType)) {
5059 InitializationKind SubKind =
5060 Kind.getKind() == InitializationKind::IK_DirectList
5061 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5062 LParenLoc: InitList->getLBraceLoc(),
5063 RParenLoc: InitList->getRBraceLoc())
5064 : Kind;
5065 Expr *InitListAsExpr = InitList;
5066 TryConstructorOrParenListInitialization(
5067 S, Entity, Kind: SubKind, Args: InitListAsExpr, DestType, Sequence,
5068 /*IsAggrListInit=*/true);
5069 return;
5070 }
5071 }
5072 if (const ArrayType *DestAT = S.Context.getAsArrayType(T: DestType)) {
5073 Expr *SubInit[1] = {InitList->getInit(Init: 0)};
5074
5075 // C++17 [dcl.struct.bind]p1:
5076 // ... If the assignment-expression in the initializer has array type A
5077 // and no ref-qualifier is present, e has type cv A and each element is
5078 // copy-initialized or direct-initialized from the corresponding element
5079 // of the assignment-expression as specified by the form of the
5080 // initializer. ...
5081 //
5082 // This is a special case not following list-initialization.
5083 if (isa<ConstantArrayType>(Val: DestAT) &&
5084 Entity.getKind() == InitializedEntity::EK_Variable &&
5085 isa<DecompositionDecl>(Val: Entity.getDecl())) {
5086 assert(
5087 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5088 "Deduced to other type?");
5089 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5090 "List-initialize structured bindings but not "
5091 "direct-list-initialization?");
5092 TryArrayCopy(S,
5093 Kind: InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5094 LParenLoc: InitList->getLBraceLoc(),
5095 RParenLoc: InitList->getRBraceLoc()),
5096 Entity, Initializer: SubInit[0], DestType, Sequence,
5097 TreatUnavailableAsInvalid);
5098 if (Sequence)
5099 Sequence.AddUnwrapInitListInitStep(Syntactic: InitList);
5100 return;
5101 }
5102
5103 if (!isa<VariableArrayType>(Val: DestAT) &&
5104 IsStringInit(Init: SubInit[0], AT: DestAT, Context&: S.Context) == SIF_None) {
5105 InitializationKind SubKind =
5106 Kind.getKind() == InitializationKind::IK_DirectList
5107 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5108 LParenLoc: InitList->getLBraceLoc(),
5109 RParenLoc: InitList->getRBraceLoc())
5110 : Kind;
5111 Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit,
5112 /*TopLevelOfInitList*/ true,
5113 TreatUnavailableAsInvalid);
5114
5115 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5116 // the element is not an appropriately-typed string literal, in which
5117 // case we should proceed as in C++11 (below).
5118 if (Sequence) {
5119 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
5120 return;
5121 }
5122 }
5123 }
5124 }
5125
5126 // C++11 [dcl.init.list]p3:
5127 // - If T is an aggregate, aggregate initialization is performed.
5128 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5129 (S.getLangOpts().CPlusPlus11 &&
5130 S.isStdInitializerList(Ty: DestType, Element: nullptr) && !IsDesignatedInit)) {
5131 if (S.getLangOpts().CPlusPlus11) {
5132 // - Otherwise, if the initializer list has no elements and T is a
5133 // class type with a default constructor, the object is
5134 // value-initialized.
5135 if (InitList->getNumInits() == 0) {
5136 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5137 if (S.LookupDefaultConstructor(Class: RD)) {
5138 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5139 return;
5140 }
5141 }
5142
5143 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5144 // an initializer_list object constructed [...]
5145 if (TryInitializerListConstruction(S, List: InitList, DestType, Sequence,
5146 TreatUnavailableAsInvalid))
5147 return;
5148
5149 // - Otherwise, if T is a class type, constructors are considered.
5150 Expr *InitListAsExpr = InitList;
5151 TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType,
5152 DestArrayType: DestType, Sequence, /*InitListSyntax*/IsListInit: true);
5153 } else
5154 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
5155 return;
5156 }
5157
5158 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5159 InitList->getNumInits() == 1) {
5160 Expr *E = InitList->getInit(Init: 0);
5161
5162 // - Otherwise, if T is an enumeration with a fixed underlying type,
5163 // the initializer-list has a single element v, and the initialization
5164 // is direct-list-initialization, the object is initialized with the
5165 // value T(v); if a narrowing conversion is required to convert v to
5166 // the underlying type of T, the program is ill-formed.
5167 if (S.getLangOpts().CPlusPlus17 &&
5168 Kind.getKind() == InitializationKind::IK_DirectList &&
5169 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5170 !S.Context.hasSameUnqualifiedType(T1: E->getType(), T2: DestType) &&
5171 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
5172 E->getType()->isFloatingType())) {
5173 // There are two ways that T(v) can work when T is an enumeration type.
5174 // If there is either an implicit conversion sequence from v to T or
5175 // a conversion function that can convert from v to T, then we use that.
5176 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5177 // type, it is converted to the enumeration type via its underlying type.
5178 // There is no overlap possible between these two cases (except when the
5179 // source value is already of the destination type), and the first
5180 // case is handled by the general case for single-element lists below.
5181 ImplicitConversionSequence ICS;
5182 ICS.setStandard();
5183 ICS.Standard.setAsIdentityConversion();
5184 if (!E->isPRValue())
5185 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5186 // If E is of a floating-point type, then the conversion is ill-formed
5187 // due to narrowing, but go through the motions in order to produce the
5188 // right diagnostic.
5189 ICS.Standard.Second = E->getType()->isFloatingType()
5190 ? ICK_Floating_Integral
5191 : ICK_Integral_Conversion;
5192 ICS.Standard.setFromType(E->getType());
5193 ICS.Standard.setToType(Idx: 0, T: E->getType());
5194 ICS.Standard.setToType(Idx: 1, T: DestType);
5195 ICS.Standard.setToType(Idx: 2, T: DestType);
5196 Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2),
5197 /*TopLevelOfInitList*/true);
5198 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
5199 return;
5200 }
5201
5202 // - Otherwise, if the initializer list has a single element of type E
5203 // [...references are handled above...], the object or reference is
5204 // initialized from that element (by copy-initialization for
5205 // copy-list-initialization, or by direct-initialization for
5206 // direct-list-initialization); if a narrowing conversion is required
5207 // to convert the element to T, the program is ill-formed.
5208 //
5209 // Per core-24034, this is direct-initialization if we were performing
5210 // direct-list-initialization and copy-initialization otherwise.
5211 // We can't use InitListChecker for this, because it always performs
5212 // copy-initialization. This only matters if we might use an 'explicit'
5213 // conversion operator, or for the special case conversion of nullptr_t to
5214 // bool, so we only need to handle those cases.
5215 //
5216 // FIXME: Why not do this in all cases?
5217 Expr *Init = InitList->getInit(Init: 0);
5218 if (Init->getType()->isRecordType() ||
5219 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5220 InitializationKind SubKind =
5221 Kind.getKind() == InitializationKind::IK_DirectList
5222 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5223 LParenLoc: InitList->getLBraceLoc(),
5224 RParenLoc: InitList->getRBraceLoc())
5225 : Kind;
5226 Expr *SubInit[1] = { Init };
5227 Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit,
5228 /*TopLevelOfInitList*/true,
5229 TreatUnavailableAsInvalid);
5230 if (Sequence)
5231 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
5232 return;
5233 }
5234 }
5235
5236 InitListChecker CheckInitList(S, Entity, InitList,
5237 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5238 if (CheckInitList.HadError()) {
5239 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
5240 return;
5241 }
5242
5243 // Add the list initialization step with the built init list.
5244 Sequence.AddListInitializationStep(T: DestType);
5245}
5246
5247/// Try a reference initialization that involves calling a conversion
5248/// function.
5249static OverloadingResult TryRefInitWithConversionFunction(
5250 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5251 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5252 InitializationSequence &Sequence) {
5253 QualType DestType = Entity.getType();
5254 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5255 QualType T1 = cv1T1.getUnqualifiedType();
5256 QualType cv2T2 = Initializer->getType();
5257 QualType T2 = cv2T2.getUnqualifiedType();
5258
5259 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5260 "Must have incompatible references when binding via conversion");
5261
5262 // Build the candidate set directly in the initialization sequence
5263 // structure, so that it will persist if we fail.
5264 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5265 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5266
5267 // Determine whether we are allowed to call explicit conversion operators.
5268 // Note that none of [over.match.copy], [over.match.conv], nor
5269 // [over.match.ref] permit an explicit constructor to be chosen when
5270 // initializing a reference, not even for direct-initialization.
5271 bool AllowExplicitCtors = false;
5272 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5273
5274 if (AllowRValues && T1->isRecordType() &&
5275 S.isCompleteType(Loc: Kind.getLocation(), T: T1)) {
5276 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5277 if (T1RecordDecl->isInvalidDecl())
5278 return OR_No_Viable_Function;
5279 // The type we're converting to is a class type. Enumerate its constructors
5280 // to see if there is a suitable conversion.
5281 for (NamedDecl *D : S.LookupConstructors(Class: T1RecordDecl)) {
5282 auto Info = getConstructorInfo(ND: D);
5283 if (!Info.Constructor)
5284 continue;
5285
5286 if (!Info.Constructor->isInvalidDecl() &&
5287 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5288 if (Info.ConstructorTmpl)
5289 S.AddTemplateOverloadCandidate(
5290 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
5291 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet,
5292 /*SuppressUserConversions=*/true,
5293 /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors);
5294 else
5295 S.AddOverloadCandidate(
5296 Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: Initializer, CandidateSet,
5297 /*SuppressUserConversions=*/true,
5298 /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors);
5299 }
5300 }
5301 }
5302
5303 if (T2->isRecordType() && S.isCompleteType(Loc: Kind.getLocation(), T: T2)) {
5304 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5305 if (T2RecordDecl->isInvalidDecl())
5306 return OR_No_Viable_Function;
5307 // The type we're converting from is a class type, enumerate its conversion
5308 // functions.
5309 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5310 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5311 NamedDecl *D = *I;
5312 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5313 if (isa<UsingShadowDecl>(Val: D))
5314 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5315
5316 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
5317 CXXConversionDecl *Conv;
5318 if (ConvTemplate)
5319 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5320 else
5321 Conv = cast<CXXConversionDecl>(Val: D);
5322
5323 // If the conversion function doesn't return a reference type,
5324 // it can't be considered for this conversion unless we're allowed to
5325 // consider rvalues.
5326 // FIXME: Do we need to make sure that we only consider conversion
5327 // candidates with reference-compatible results? That might be needed to
5328 // break recursion.
5329 if ((AllowRValues ||
5330 Conv->getConversionType()->isLValueReferenceType())) {
5331 if (ConvTemplate)
5332 S.AddTemplateConversionCandidate(
5333 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
5334 CandidateSet,
5335 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs);
5336 else
5337 S.AddConversionCandidate(
5338 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, CandidateSet,
5339 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs);
5340 }
5341 }
5342 }
5343
5344 SourceLocation DeclLoc = Initializer->getBeginLoc();
5345
5346 // Perform overload resolution. If it fails, return the failed result.
5347 OverloadCandidateSet::iterator Best;
5348 if (OverloadingResult Result
5349 = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best))
5350 return Result;
5351
5352 FunctionDecl *Function = Best->Function;
5353 // This is the overload that will be used for this initialization step if we
5354 // use this initialization. Mark it as referenced.
5355 Function->setReferenced();
5356
5357 // Compute the returned type and value kind of the conversion.
5358 QualType cv3T3;
5359 if (isa<CXXConversionDecl>(Val: Function))
5360 cv3T3 = Function->getReturnType();
5361 else
5362 cv3T3 = T1;
5363
5364 ExprValueKind VK = VK_PRValue;
5365 if (cv3T3->isLValueReferenceType())
5366 VK = VK_LValue;
5367 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5368 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5369 cv3T3 = cv3T3.getNonLValueExprType(Context: S.Context);
5370
5371 // Add the user-defined conversion step.
5372 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5373 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: cv3T3,
5374 HadMultipleCandidates);
5375
5376 // Determine whether we'll need to perform derived-to-base adjustments or
5377 // other conversions.
5378 Sema::ReferenceConversions RefConv;
5379 Sema::ReferenceCompareResult NewRefRelationship =
5380 S.CompareReferenceRelationship(Loc: DeclLoc, T1, T2: cv3T3, Conv: &RefConv);
5381
5382 // Add the final conversion sequence, if necessary.
5383 if (NewRefRelationship == Sema::Ref_Incompatible) {
5384 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5385 "should not have conversion after constructor");
5386
5387 ImplicitConversionSequence ICS;
5388 ICS.setStandard();
5389 ICS.Standard = Best->FinalConversion;
5390 Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2));
5391
5392 // Every implicit conversion results in a prvalue, except for a glvalue
5393 // derived-to-base conversion, which we handle below.
5394 cv3T3 = ICS.Standard.getToType(Idx: 2);
5395 VK = VK_PRValue;
5396 }
5397
5398 // If the converted initializer is a prvalue, its type T4 is adjusted to
5399 // type "cv1 T4" and the temporary materialization conversion is applied.
5400 //
5401 // We adjust the cv-qualifications to match the reference regardless of
5402 // whether we have a prvalue so that the AST records the change. In this
5403 // case, T4 is "cv3 T3".
5404 QualType cv1T4 = S.Context.getQualifiedType(T: cv3T3, Qs: cv1T1.getQualifiers());
5405 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5406 Sequence.AddQualificationConversionStep(Ty: cv1T4, VK);
5407 Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: VK == VK_PRValue);
5408 VK = IsLValueRef ? VK_LValue : VK_XValue;
5409
5410 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5411 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK);
5412 else if (RefConv & Sema::ReferenceConversions::ObjC)
5413 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5414 else if (RefConv & Sema::ReferenceConversions::Function)
5415 Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1);
5416 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5417 if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1))
5418 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK);
5419 }
5420
5421 return OR_Success;
5422}
5423
5424static void CheckCXX98CompatAccessibleCopy(Sema &S,
5425 const InitializedEntity &Entity,
5426 Expr *CurInitExpr);
5427
5428/// Attempt reference initialization (C++0x [dcl.init.ref])
5429static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,
5430 const InitializationKind &Kind,
5431 Expr *Initializer,
5432 InitializationSequence &Sequence,
5433 bool TopLevelOfInitList) {
5434 QualType DestType = Entity.getType();
5435 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5436 Qualifiers T1Quals;
5437 QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals);
5438 QualType cv2T2 = S.getCompletedType(E: Initializer);
5439 Qualifiers T2Quals;
5440 QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals);
5441
5442 // If the initializer is the address of an overloaded function, try
5443 // to resolve the overloaded function. If all goes well, T2 is the
5444 // type of the resulting function.
5445 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2,
5446 UnqualifiedTargetType: T1, Sequence))
5447 return;
5448
5449 // Delegate everything else to a subfunction.
5450 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5451 T1Quals, cv2T2, T2, T2Quals, Sequence,
5452 TopLevelOfInitList);
5453}
5454
5455/// Determine whether an expression is a non-referenceable glvalue (one to
5456/// which a reference can never bind). Attempting to bind a reference to
5457/// such a glvalue will always create a temporary.
5458static bool isNonReferenceableGLValue(Expr *E) {
5459 return E->refersToBitField() || E->refersToVectorElement() ||
5460 E->refersToMatrixElement();
5461}
5462
5463/// Reference initialization without resolving overloaded functions.
5464///
5465/// We also can get here in C if we call a builtin which is declared as
5466/// a function with a parameter of reference type (such as __builtin_va_end()).
5467static void TryReferenceInitializationCore(Sema &S,
5468 const InitializedEntity &Entity,
5469 const InitializationKind &Kind,
5470 Expr *Initializer,
5471 QualType cv1T1, QualType T1,
5472 Qualifiers T1Quals,
5473 QualType cv2T2, QualType T2,
5474 Qualifiers T2Quals,
5475 InitializationSequence &Sequence,
5476 bool TopLevelOfInitList) {
5477 QualType DestType = Entity.getType();
5478 SourceLocation DeclLoc = Initializer->getBeginLoc();
5479
5480 // Compute some basic properties of the types and the initializer.
5481 bool isLValueRef = DestType->isLValueReferenceType();
5482 bool isRValueRef = !isLValueRef;
5483 Expr::Classification InitCategory = Initializer->Classify(Ctx&: S.Context);
5484
5485 Sema::ReferenceConversions RefConv;
5486 Sema::ReferenceCompareResult RefRelationship =
5487 S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2, Conv: &RefConv);
5488
5489 // C++0x [dcl.init.ref]p5:
5490 // A reference to type "cv1 T1" is initialized by an expression of type
5491 // "cv2 T2" as follows:
5492 //
5493 // - If the reference is an lvalue reference and the initializer
5494 // expression
5495 // Note the analogous bullet points for rvalue refs to functions. Because
5496 // there are no function rvalues in C++, rvalue refs to functions are treated
5497 // like lvalue refs.
5498 OverloadingResult ConvOvlResult = OR_Success;
5499 bool T1Function = T1->isFunctionType();
5500 if (isLValueRef || T1Function) {
5501 if (InitCategory.isLValue() && !isNonReferenceableGLValue(E: Initializer) &&
5502 (RefRelationship == Sema::Ref_Compatible ||
5503 (Kind.isCStyleOrFunctionalCast() &&
5504 RefRelationship == Sema::Ref_Related))) {
5505 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5506 // reference-compatible with "cv2 T2," or
5507 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5508 Sema::ReferenceConversions::ObjC)) {
5509 // If we're converting the pointee, add any qualifiers first;
5510 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5511 if (RefConv & (Sema::ReferenceConversions::Qualification))
5512 Sequence.AddQualificationConversionStep(
5513 Ty: S.Context.getQualifiedType(T: T2, Qs: T1Quals),
5514 VK: Initializer->getValueKind());
5515 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5516 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: VK_LValue);
5517 else
5518 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5519 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5520 // Perform a (possibly multi-level) qualification conversion.
5521 Sequence.AddQualificationConversionStep(Ty: cv1T1,
5522 VK: Initializer->getValueKind());
5523 } else if (RefConv & Sema::ReferenceConversions::Function) {
5524 Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1);
5525 }
5526
5527 // We only create a temporary here when binding a reference to a
5528 // bit-field or vector element. Those cases are't supposed to be
5529 // handled by this bullet, but the outcome is the same either way.
5530 Sequence.AddReferenceBindingStep(T: cv1T1, BindingTemporary: false);
5531 return;
5532 }
5533
5534 // - has a class type (i.e., T2 is a class type), where T1 is not
5535 // reference-related to T2, and can be implicitly converted to an
5536 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5537 // with "cv3 T3" (this conversion is selected by enumerating the
5538 // applicable conversion functions (13.3.1.6) and choosing the best
5539 // one through overload resolution (13.3)),
5540 // If we have an rvalue ref to function type here, the rhs must be
5541 // an rvalue. DR1287 removed the "implicitly" here.
5542 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5543 (isLValueRef || InitCategory.isRValue())) {
5544 if (S.getLangOpts().CPlusPlus) {
5545 // Try conversion functions only for C++.
5546 ConvOvlResult = TryRefInitWithConversionFunction(
5547 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5548 /*IsLValueRef*/ isLValueRef, Sequence);
5549 if (ConvOvlResult == OR_Success)
5550 return;
5551 if (ConvOvlResult != OR_No_Viable_Function)
5552 Sequence.SetOverloadFailure(
5553 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5554 Result: ConvOvlResult);
5555 } else {
5556 ConvOvlResult = OR_No_Viable_Function;
5557 }
5558 }
5559 }
5560
5561 // - Otherwise, the reference shall be an lvalue reference to a
5562 // non-volatile const type (i.e., cv1 shall be const), or the reference
5563 // shall be an rvalue reference.
5564 // For address spaces, we interpret this to mean that an addr space
5565 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5566 if (isLValueRef &&
5567 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5568 T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) {
5569 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy)
5570 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5571 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5572 Sequence.SetOverloadFailure(
5573 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5574 Result: ConvOvlResult);
5575 else if (!InitCategory.isLValue())
5576 Sequence.SetFailed(
5577 T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext())
5578 ? InitializationSequence::
5579 FK_NonConstLValueReferenceBindingToTemporary
5580 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
5581 else {
5582 InitializationSequence::FailureKind FK;
5583 switch (RefRelationship) {
5584 case Sema::Ref_Compatible:
5585 if (Initializer->refersToBitField())
5586 FK = InitializationSequence::
5587 FK_NonConstLValueReferenceBindingToBitfield;
5588 else if (Initializer->refersToVectorElement())
5589 FK = InitializationSequence::
5590 FK_NonConstLValueReferenceBindingToVectorElement;
5591 else if (Initializer->refersToMatrixElement())
5592 FK = InitializationSequence::
5593 FK_NonConstLValueReferenceBindingToMatrixElement;
5594 else
5595 llvm_unreachable("unexpected kind of compatible initializer");
5596 break;
5597 case Sema::Ref_Related:
5598 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5599 break;
5600 case Sema::Ref_Incompatible:
5601 FK = InitializationSequence::
5602 FK_NonConstLValueReferenceBindingToUnrelated;
5603 break;
5604 }
5605 Sequence.SetFailed(FK);
5606 }
5607 return;
5608 }
5609
5610 // - If the initializer expression
5611 // - is an
5612 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5613 // [1z] rvalue (but not a bit-field) or
5614 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5615 //
5616 // Note: functions are handled above and below rather than here...
5617 if (!T1Function &&
5618 (RefRelationship == Sema::Ref_Compatible ||
5619 (Kind.isCStyleOrFunctionalCast() &&
5620 RefRelationship == Sema::Ref_Related)) &&
5621 ((InitCategory.isXValue() && !isNonReferenceableGLValue(E: Initializer)) ||
5622 (InitCategory.isPRValue() &&
5623 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5624 T2->isArrayType())))) {
5625 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5626 if (InitCategory.isPRValue() && T2->isRecordType()) {
5627 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5628 // compiler the freedom to perform a copy here or bind to the
5629 // object, while C++0x requires that we bind directly to the
5630 // object. Hence, we always bind to the object without making an
5631 // extra copy. However, in C++03 requires that we check for the
5632 // presence of a suitable copy constructor:
5633 //
5634 // The constructor that would be used to make the copy shall
5635 // be callable whether or not the copy is actually done.
5636 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5637 Sequence.AddExtraneousCopyToTemporary(T: cv2T2);
5638 else if (S.getLangOpts().CPlusPlus11)
5639 CheckCXX98CompatAccessibleCopy(S, Entity, CurInitExpr: Initializer);
5640 }
5641
5642 // C++1z [dcl.init.ref]/5.2.1.2:
5643 // If the converted initializer is a prvalue, its type T4 is adjusted
5644 // to type "cv1 T4" and the temporary materialization conversion is
5645 // applied.
5646 // Postpone address space conversions to after the temporary materialization
5647 // conversion to allow creating temporaries in the alloca address space.
5648 auto T1QualsIgnoreAS = T1Quals;
5649 auto T2QualsIgnoreAS = T2Quals;
5650 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5651 T1QualsIgnoreAS.removeAddressSpace();
5652 T2QualsIgnoreAS.removeAddressSpace();
5653 }
5654 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5655 // with T1's qualifiers.
5656 QualType T2ForQualConv = cv2T2;
5657 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5658 Qualifiers T2BaseQuals =
5659 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5660 T2ForQualConv = S.Context.getQualifiedType(
5661 T: T2ForQualConv.getUnqualifiedType(), Qs: T2BaseQuals);
5662 }
5663 QualType cv1T4 = S.Context.getQualifiedType(T: T2ForQualConv, Qs: T1QualsIgnoreAS);
5664 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5665 Sequence.AddQualificationConversionStep(Ty: cv1T4, VK: ValueKind);
5666 Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: ValueKind == VK_PRValue);
5667 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5668 // Add addr space conversion if required.
5669 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5670 auto T4Quals = cv1T4.getQualifiers();
5671 T4Quals.addAddressSpace(space: T1Quals.getAddressSpace());
5672 QualType cv1T4WithAS = S.Context.getQualifiedType(T: T2, Qs: T4Quals);
5673 Sequence.AddQualificationConversionStep(Ty: cv1T4WithAS, VK: ValueKind);
5674 cv1T4 = cv1T4WithAS;
5675 }
5676
5677 // In any case, the reference is bound to the resulting glvalue (or to
5678 // an appropriate base class subobject).
5679 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5680 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: ValueKind);
5681 else if (RefConv & Sema::ReferenceConversions::ObjC)
5682 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5683 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5684 if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1))
5685 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: ValueKind);
5686 }
5687 return;
5688 }
5689
5690 // - has a class type (i.e., T2 is a class type), where T1 is not
5691 // reference-related to T2, and can be implicitly converted to an
5692 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5693 // where "cv1 T1" is reference-compatible with "cv3 T3",
5694 //
5695 // DR1287 removes the "implicitly" here.
5696 if (T2->isRecordType()) {
5697 if (RefRelationship == Sema::Ref_Incompatible) {
5698 ConvOvlResult = TryRefInitWithConversionFunction(
5699 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5700 /*IsLValueRef*/ isLValueRef, Sequence);
5701 if (ConvOvlResult)
5702 Sequence.SetOverloadFailure(
5703 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5704 Result: ConvOvlResult);
5705
5706 return;
5707 }
5708
5709 if (RefRelationship == Sema::Ref_Compatible &&
5710 isRValueRef && InitCategory.isLValue()) {
5711 Sequence.SetFailed(
5712 InitializationSequence::FK_RValueReferenceBindingToLValue);
5713 return;
5714 }
5715
5716 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5717 return;
5718 }
5719
5720 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5721 // from the initializer expression using the rules for a non-reference
5722 // copy-initialization (8.5). The reference is then bound to the
5723 // temporary. [...]
5724
5725 // Ignore address space of reference type at this point and perform address
5726 // space conversion after the reference binding step.
5727 QualType cv1T1IgnoreAS =
5728 T1Quals.hasAddressSpace()
5729 ? S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace())
5730 : cv1T1;
5731
5732 InitializedEntity TempEntity =
5733 InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS);
5734
5735 // FIXME: Why do we use an implicit conversion here rather than trying
5736 // copy-initialization?
5737 ImplicitConversionSequence ICS
5738 = S.TryImplicitConversion(From: Initializer, ToType: TempEntity.getType(),
5739 /*SuppressUserConversions=*/false,
5740 AllowExplicit: Sema::AllowedExplicit::None,
5741 /*FIXME:InOverloadResolution=*/InOverloadResolution: false,
5742 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5743 /*AllowObjCWritebackConversion=*/false);
5744
5745 if (ICS.isBad()) {
5746 // FIXME: Use the conversion function set stored in ICS to turn
5747 // this into an overloading ambiguity diagnostic. However, we need
5748 // to keep that set as an OverloadCandidateSet rather than as some
5749 // other kind of set.
5750 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5751 Sequence.SetOverloadFailure(
5752 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5753 Result: ConvOvlResult);
5754 else if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy)
5755 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5756 else
5757 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5758 return;
5759 } else {
5760 Sequence.AddConversionSequenceStep(ICS, T: TempEntity.getType(),
5761 TopLevelOfInitList);
5762 }
5763
5764 // [...] If T1 is reference-related to T2, cv1 must be the
5765 // same cv-qualification as, or greater cv-qualification
5766 // than, cv2; otherwise, the program is ill-formed.
5767 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5768 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5769 if (RefRelationship == Sema::Ref_Related &&
5770 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5771 !T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) {
5772 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5773 return;
5774 }
5775
5776 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5777 // reference, the initializer expression shall not be an lvalue.
5778 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5779 InitCategory.isLValue()) {
5780 Sequence.SetFailed(
5781 InitializationSequence::FK_RValueReferenceBindingToLValue);
5782 return;
5783 }
5784
5785 Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, /*BindingTemporary=*/true);
5786
5787 if (T1Quals.hasAddressSpace()) {
5788 if (!Qualifiers::isAddressSpaceSupersetOf(
5789 A: T1Quals.getAddressSpace(), B: LangAS::Default, Ctx: S.getASTContext())) {
5790 Sequence.SetFailed(
5791 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5792 return;
5793 }
5794 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: isLValueRef ? VK_LValue
5795 : VK_XValue);
5796 }
5797}
5798
5799/// Attempt character array initialization from a string literal
5800/// (C++ [dcl.init.string], C99 6.7.8).
5801static void TryStringLiteralInitialization(Sema &S,
5802 const InitializedEntity &Entity,
5803 const InitializationKind &Kind,
5804 Expr *Initializer,
5805 InitializationSequence &Sequence) {
5806 Sequence.AddStringInitStep(T: Entity.getType());
5807}
5808
5809/// Attempt value initialization (C++ [dcl.init]p7).
5810static void TryValueInitialization(Sema &S,
5811 const InitializedEntity &Entity,
5812 const InitializationKind &Kind,
5813 InitializationSequence &Sequence,
5814 InitListExpr *InitList) {
5815 assert((!InitList || InitList->getNumInits() == 0) &&
5816 "Shouldn't use value-init for non-empty init lists");
5817
5818 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5819 //
5820 // To value-initialize an object of type T means:
5821 QualType T = Entity.getType();
5822 assert(!T->isVoidType() && "Cannot value-init void");
5823
5824 // -- if T is an array type, then each element is value-initialized;
5825 T = S.Context.getBaseElementType(QT: T);
5826
5827 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5828 bool NeedZeroInitialization = true;
5829 // C++98:
5830 // -- if T is a class type (clause 9) with a user-declared constructor
5831 // (12.1), then the default constructor for T is called (and the
5832 // initialization is ill-formed if T has no accessible default
5833 // constructor);
5834 // C++11:
5835 // -- if T is a class type (clause 9) with either no default constructor
5836 // (12.1 [class.ctor]) or a default constructor that is user-provided
5837 // or deleted, then the object is default-initialized;
5838 //
5839 // Note that the C++11 rule is the same as the C++98 rule if there are no
5840 // defaulted or deleted constructors, so we just use it unconditionally.
5841 CXXConstructorDecl *CD = S.LookupDefaultConstructor(Class: ClassDecl);
5842 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5843 NeedZeroInitialization = false;
5844
5845 // -- if T is a (possibly cv-qualified) non-union class type without a
5846 // user-provided or deleted default constructor, then the object is
5847 // zero-initialized and, if T has a non-trivial default constructor,
5848 // default-initialized;
5849 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5850 // constructor' part was removed by DR1507.
5851 if (NeedZeroInitialization)
5852 Sequence.AddZeroInitializationStep(T: Entity.getType());
5853
5854 // C++03:
5855 // -- if T is a non-union class type without a user-declared constructor,
5856 // then every non-static data member and base class component of T is
5857 // value-initialized;
5858 // [...] A program that calls for [...] value-initialization of an
5859 // entity of reference type is ill-formed.
5860 //
5861 // C++11 doesn't need this handling, because value-initialization does not
5862 // occur recursively there, and the implicit default constructor is
5863 // defined as deleted in the problematic cases.
5864 if (!S.getLangOpts().CPlusPlus11 &&
5865 ClassDecl->hasUninitializedReferenceMember()) {
5866 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5867 return;
5868 }
5869
5870 // If this is list-value-initialization, pass the empty init list on when
5871 // building the constructor call. This affects the semantics of a few
5872 // things (such as whether an explicit default constructor can be called).
5873 Expr *InitListAsExpr = InitList;
5874 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5875 bool InitListSyntax = InitList;
5876
5877 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5878 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5879 return TryConstructorInitialization(
5880 S, Entity, Kind, Args, DestType: T, DestArrayType: Entity.getType(), Sequence, IsListInit: InitListSyntax);
5881 }
5882
5883 Sequence.AddZeroInitializationStep(T: Entity.getType());
5884}
5885
5886/// Attempt default initialization (C++ [dcl.init]p6).
5887static void TryDefaultInitialization(Sema &S,
5888 const InitializedEntity &Entity,
5889 const InitializationKind &Kind,
5890 InitializationSequence &Sequence) {
5891 assert(Kind.getKind() == InitializationKind::IK_Default);
5892
5893 // C++ [dcl.init]p6:
5894 // To default-initialize an object of type T means:
5895 // - if T is an array type, each element is default-initialized;
5896 QualType DestType = S.Context.getBaseElementType(QT: Entity.getType());
5897
5898 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5899 // constructor for T is called (and the initialization is ill-formed if
5900 // T has no accessible default constructor);
5901 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5902 TryConstructorInitialization(S, Entity, Kind, Args: {}, DestType,
5903 DestArrayType: Entity.getType(), Sequence);
5904 return;
5905 }
5906
5907 // - otherwise, no initialization is performed.
5908
5909 // If a program calls for the default initialization of an object of
5910 // a const-qualified type T, T shall be a class type with a user-provided
5911 // default constructor.
5912 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5913 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5914 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5915 return;
5916 }
5917
5918 // If the destination type has a lifetime property, zero-initialize it.
5919 if (DestType.getQualifiers().hasObjCLifetime()) {
5920 Sequence.AddZeroInitializationStep(T: Entity.getType());
5921 return;
5922 }
5923}
5924
5925static void TryOrBuildParenListInitialization(
5926 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5927 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5928 ExprResult *Result) {
5929 unsigned EntityIndexToProcess = 0;
5930 SmallVector<Expr *, 4> InitExprs;
5931 QualType ResultType;
5932 Expr *ArrayFiller = nullptr;
5933 FieldDecl *InitializedFieldInUnion = nullptr;
5934
5935 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5936 const InitializationKind &SubKind,
5937 Expr *Arg, Expr **InitExpr = nullptr) {
5938 InitializationSequence IS = InitializationSequence(
5939 S, SubEntity, SubKind,
5940 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5941
5942 if (IS.Failed()) {
5943 if (!VerifyOnly) {
5944 IS.Diagnose(S, Entity: SubEntity, Kind: SubKind,
5945 Args: Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5946 } else {
5947 Sequence.SetFailed(
5948 InitializationSequence::FK_ParenthesizedListInitFailed);
5949 }
5950
5951 return false;
5952 }
5953 if (!VerifyOnly) {
5954 ExprResult ER;
5955 ER = IS.Perform(S, Entity: SubEntity, Kind: SubKind,
5956 Args: Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5957
5958 if (ER.isInvalid())
5959 return false;
5960
5961 if (InitExpr)
5962 *InitExpr = ER.get();
5963 else
5964 InitExprs.push_back(Elt: ER.get());
5965 }
5966 return true;
5967 };
5968
5969 if (const ArrayType *AT =
5970 S.getASTContext().getAsArrayType(T: Entity.getType())) {
5971 uint64_t ArrayLength;
5972 // C++ [dcl.init]p16.5
5973 // if the destination type is an array, the object is initialized as
5974 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5975 // the destination type is an array of unknown bound, it is defined as
5976 // having k elements.
5977 if (const ConstantArrayType *CAT =
5978 S.getASTContext().getAsConstantArrayType(T: Entity.getType())) {
5979 ArrayLength = CAT->getZExtSize();
5980 ResultType = Entity.getType();
5981 } else if (const VariableArrayType *VAT =
5982 S.getASTContext().getAsVariableArrayType(T: Entity.getType())) {
5983 // Braced-initialization of variable array types is not allowed, even if
5984 // the size is greater than or equal to the number of args, so we don't
5985 // allow them to be initialized via parenthesized aggregate initialization
5986 // either.
5987 const Expr *SE = VAT->getSizeExpr();
5988 S.Diag(Loc: SE->getBeginLoc(), DiagID: diag::err_variable_object_no_init)
5989 << SE->getSourceRange();
5990 return;
5991 } else {
5992 assert(Entity.getType()->isIncompleteArrayType());
5993 ArrayLength = Args.size();
5994 }
5995 EntityIndexToProcess = ArrayLength;
5996
5997 // ...the ith array element is copy-initialized with xi for each
5998 // 1 <= i <= k
5999 for (Expr *E : Args) {
6000 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
6001 Context&: S.getASTContext(), Index: EntityIndexToProcess, Parent: Entity);
6002 InitializationKind SubKind = InitializationKind::CreateForInit(
6003 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
6004 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6005 return;
6006 }
6007 // ...and value-initialized for each k < i <= n;
6008 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6009 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
6010 Context&: S.getASTContext(), Index: Args.size(), Parent: Entity);
6011 InitializationKind SubKind = InitializationKind::CreateValue(
6012 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true);
6013 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6014 return;
6015 }
6016
6017 if (ResultType.isNull()) {
6018 ResultType = S.Context.getConstantArrayType(
6019 EltTy: AT->getElementType(), ArySize: llvm::APInt(/*numBits=*/32, ArrayLength),
6020 /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6021 }
6022 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6023 bool IsUnion = RD->isUnion();
6024 if (RD->isInvalidDecl()) {
6025 // Exit early to avoid confusion when processing members.
6026 // We do the same for braced list initialization in
6027 // `CheckStructUnionTypes`.
6028 Sequence.SetFailed(
6029 clang::InitializationSequence::FK_ParenthesizedListInitFailed);
6030 return;
6031 }
6032
6033 if (!IsUnion) {
6034 for (const CXXBaseSpecifier &Base : RD->bases()) {
6035 InitializedEntity SubEntity = InitializedEntity::InitializeBase(
6036 Context&: S.getASTContext(), Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity);
6037 if (EntityIndexToProcess < Args.size()) {
6038 // C++ [dcl.init]p16.6.2.2.
6039 // ...the object is initialized is follows. Let e1, ..., en be the
6040 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6041 // the elements of the expression-list...The element ei is
6042 // copy-initialized with xi for 1 <= i <= k.
6043 Expr *E = Args[EntityIndexToProcess];
6044 InitializationKind SubKind = InitializationKind::CreateForInit(
6045 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
6046 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6047 return;
6048 } else {
6049 // We've processed all of the args, but there are still base classes
6050 // that have to be initialized.
6051 // C++ [dcl.init]p17.6.2.2
6052 // The remaining elements...otherwise are value initialzed
6053 InitializationKind SubKind = InitializationKind::CreateValue(
6054 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(),
6055 /*IsImplicit=*/isImplicit: true);
6056 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6057 return;
6058 }
6059 EntityIndexToProcess++;
6060 }
6061 }
6062
6063 for (FieldDecl *FD : RD->fields()) {
6064 // Unnamed bitfields should not be initialized at all, either with an arg
6065 // or by default.
6066 if (FD->isUnnamedBitField())
6067 continue;
6068
6069 InitializedEntity SubEntity =
6070 InitializedEntity::InitializeMemberFromParenAggInit(Member: FD);
6071
6072 if (EntityIndexToProcess < Args.size()) {
6073 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6074 Expr *E = Args[EntityIndexToProcess];
6075
6076 // Incomplete array types indicate flexible array members. Do not allow
6077 // paren list initializations of structs with these members, as GCC
6078 // doesn't either.
6079 if (FD->getType()->isIncompleteArrayType()) {
6080 if (!VerifyOnly) {
6081 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_flexible_array_init)
6082 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6083 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_flexible_array_member) << FD;
6084 }
6085 Sequence.SetFailed(
6086 InitializationSequence::FK_ParenthesizedListInitFailed);
6087 return;
6088 }
6089
6090 InitializationKind SubKind = InitializationKind::CreateForInit(
6091 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
6092 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6093 return;
6094
6095 // Unions should have only one initializer expression, so we bail out
6096 // after processing the first field. If there are more initializers then
6097 // it will be caught when we later check whether EntityIndexToProcess is
6098 // less than Args.size();
6099 if (IsUnion) {
6100 InitializedFieldInUnion = FD;
6101 EntityIndexToProcess = 1;
6102 break;
6103 }
6104 } else {
6105 // We've processed all of the args, but there are still members that
6106 // have to be initialized.
6107 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6108 !S.isUnevaluatedContext()) {
6109 S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init)
6110 << /* Var-in-Record */ 0 << FD;
6111 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD;
6112 }
6113
6114 if (FD->hasInClassInitializer()) {
6115 if (!VerifyOnly) {
6116 // C++ [dcl.init]p16.6.2.2
6117 // The remaining elements are initialized with their default
6118 // member initializers, if any
6119 ExprResult DIE = S.BuildCXXDefaultInitExpr(
6120 Loc: Kind.getParenOrBraceRange().getEnd(), Field: FD);
6121 if (DIE.isInvalid())
6122 return;
6123 S.checkInitializerLifetime(Entity: SubEntity, Init: DIE.get());
6124 InitExprs.push_back(Elt: DIE.get());
6125 }
6126 } else {
6127 // C++ [dcl.init]p17.6.2.2
6128 // The remaining elements...otherwise are value initialzed
6129 if (FD->getType()->isReferenceType()) {
6130 Sequence.SetFailed(
6131 InitializationSequence::FK_ParenthesizedListInitFailed);
6132 if (!VerifyOnly) {
6133 SourceRange SR = Kind.getParenOrBraceRange();
6134 S.Diag(Loc: SR.getEnd(), DiagID: diag::err_init_reference_member_uninitialized)
6135 << FD->getType() << SR;
6136 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_uninit_reference_member);
6137 }
6138 return;
6139 }
6140 InitializationKind SubKind = InitializationKind::CreateValue(
6141 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true);
6142 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6143 return;
6144 }
6145 }
6146 EntityIndexToProcess++;
6147 }
6148 ResultType = Entity.getType();
6149 }
6150
6151 // Not all of the args have been processed, so there must've been more args
6152 // than were required to initialize the element.
6153 if (EntityIndexToProcess < Args.size()) {
6154 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
6155 if (!VerifyOnly) {
6156 QualType T = Entity.getType();
6157 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6158 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6159 Args.back()->getEndLoc());
6160 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers)
6161 << InitKind << ExcessInitSR;
6162 }
6163 return;
6164 }
6165
6166 if (VerifyOnly) {
6167 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
6168 Sequence.AddParenthesizedListInitStep(T: Entity.getType());
6169 } else if (Result) {
6170 SourceRange SR = Kind.getParenOrBraceRange();
6171 auto *CPLIE = CXXParenListInitExpr::Create(
6172 C&: S.getASTContext(), Args: InitExprs, T: ResultType, NumUserSpecifiedExprs: Args.size(),
6173 InitLoc: Kind.getLocation(), LParenLoc: SR.getBegin(), RParenLoc: SR.getEnd());
6174 if (ArrayFiller)
6175 CPLIE->setArrayFiller(ArrayFiller);
6176 if (InitializedFieldInUnion)
6177 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6178 *Result = CPLIE;
6179 S.Diag(Loc: Kind.getLocation(),
6180 DiagID: diag::warn_cxx17_compat_aggregate_init_paren_list)
6181 << Kind.getLocation() << SR << ResultType;
6182 }
6183}
6184
6185/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6186/// which enumerates all conversion functions and performs overload resolution
6187/// to select the best.
6188static void TryUserDefinedConversion(Sema &S,
6189 QualType DestType,
6190 const InitializationKind &Kind,
6191 Expr *Initializer,
6192 InitializationSequence &Sequence,
6193 bool TopLevelOfInitList) {
6194 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6195 QualType SourceType = Initializer->getType();
6196 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6197 "Must have a class type to perform a user-defined conversion");
6198
6199 // Build the candidate set directly in the initialization sequence
6200 // structure, so that it will persist if we fail.
6201 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6202 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
6203 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6204
6205 // Determine whether we are allowed to call explicit constructors or
6206 // explicit conversion operators.
6207 bool AllowExplicit = Kind.AllowExplicit();
6208
6209 if (DestType->isRecordType()) {
6210 // The type we're converting to is a class type. Enumerate its constructors
6211 // to see if there is a suitable conversion.
6212 // Try to complete the type we're converting to.
6213 if (S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) {
6214 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6215 for (NamedDecl *D : S.LookupConstructors(Class: DestRecordDecl)) {
6216 auto Info = getConstructorInfo(ND: D);
6217 if (!Info.Constructor)
6218 continue;
6219
6220 if (!Info.Constructor->isInvalidDecl() &&
6221 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6222 if (Info.ConstructorTmpl)
6223 S.AddTemplateOverloadCandidate(
6224 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
6225 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet,
6226 /*SuppressUserConversions=*/true,
6227 /*PartialOverloading*/ false, AllowExplicit);
6228 else
6229 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
6230 Args: Initializer, CandidateSet,
6231 /*SuppressUserConversions=*/true,
6232 /*PartialOverloading*/ false, AllowExplicit);
6233 }
6234 }
6235 }
6236 }
6237
6238 SourceLocation DeclLoc = Initializer->getBeginLoc();
6239
6240 if (SourceType->isRecordType()) {
6241 // The type we're converting from is a class type, enumerate its conversion
6242 // functions.
6243
6244 // We can only enumerate the conversion functions for a complete type; if
6245 // the type isn't complete, simply skip this step.
6246 if (S.isCompleteType(Loc: DeclLoc, T: SourceType)) {
6247 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6248 const auto &Conversions =
6249 SourceRecordDecl->getVisibleConversionFunctions();
6250 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6251 NamedDecl *D = *I;
6252 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
6253 if (isa<UsingShadowDecl>(Val: D))
6254 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6255
6256 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6257 CXXConversionDecl *Conv;
6258 if (ConvTemplate)
6259 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6260 else
6261 Conv = cast<CXXConversionDecl>(Val: D);
6262
6263 if (ConvTemplate)
6264 S.AddTemplateConversionCandidate(
6265 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
6266 CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit);
6267 else
6268 S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer,
6269 ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit,
6270 AllowExplicit);
6271 }
6272 }
6273 }
6274
6275 // Perform overload resolution. If it fails, return the failed result.
6276 OverloadCandidateSet::iterator Best;
6277 if (OverloadingResult Result
6278 = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
6279 Sequence.SetOverloadFailure(
6280 Failure: InitializationSequence::FK_UserConversionOverloadFailed, Result);
6281
6282 // [class.copy.elision]p3:
6283 // In some copy-initialization contexts, a two-stage overload resolution
6284 // is performed.
6285 // If the first overload resolution selects a deleted function, we also
6286 // need the initialization sequence to decide whether to perform the second
6287 // overload resolution.
6288 if (!(Result == OR_Deleted &&
6289 Kind.getKind() == InitializationKind::IK_Copy))
6290 return;
6291 }
6292
6293 FunctionDecl *Function = Best->Function;
6294 Function->setReferenced();
6295 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6296
6297 if (isa<CXXConstructorDecl>(Val: Function)) {
6298 // Add the user-defined conversion step. Any cv-qualification conversion is
6299 // subsumed by the initialization. Per DR5, the created temporary is of the
6300 // cv-unqualified type of the destination.
6301 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl,
6302 T: DestType.getUnqualifiedType(),
6303 HadMultipleCandidates);
6304
6305 // C++14 and before:
6306 // - if the function is a constructor, the call initializes a temporary
6307 // of the cv-unqualified version of the destination type. The [...]
6308 // temporary [...] is then used to direct-initialize, according to the
6309 // rules above, the object that is the destination of the
6310 // copy-initialization.
6311 // Note that this just performs a simple object copy from the temporary.
6312 //
6313 // C++17:
6314 // - if the function is a constructor, the call is a prvalue of the
6315 // cv-unqualified version of the destination type whose return object
6316 // is initialized by the constructor. The call is used to
6317 // direct-initialize, according to the rules above, the object that
6318 // is the destination of the copy-initialization.
6319 // Therefore we need to do nothing further.
6320 //
6321 // FIXME: Mark this copy as extraneous.
6322 if (!S.getLangOpts().CPlusPlus17)
6323 Sequence.AddFinalCopy(T: DestType);
6324 else if (DestType.hasQualifiers())
6325 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
6326 return;
6327 }
6328
6329 // Add the user-defined conversion step that calls the conversion function.
6330 QualType ConvType = Function->getCallResultType();
6331 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: ConvType,
6332 HadMultipleCandidates);
6333
6334 if (ConvType->isRecordType()) {
6335 // The call is used to direct-initialize [...] the object that is the
6336 // destination of the copy-initialization.
6337 //
6338 // In C++17, this does not call a constructor if we enter /17.6.1:
6339 // - If the initializer expression is a prvalue and the cv-unqualified
6340 // version of the source type is the same as the class of the
6341 // destination [... do not make an extra copy]
6342 //
6343 // FIXME: Mark this copy as extraneous.
6344 if (!S.getLangOpts().CPlusPlus17 ||
6345 Function->getReturnType()->isReferenceType() ||
6346 !S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType))
6347 Sequence.AddFinalCopy(T: DestType);
6348 else if (!S.Context.hasSameType(T1: ConvType, T2: DestType))
6349 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
6350 return;
6351 }
6352
6353 // If the conversion following the call to the conversion function
6354 // is interesting, add it as a separate step.
6355 assert(Best->HasFinalConversion);
6356 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6357 Best->FinalConversion.Third) {
6358 ImplicitConversionSequence ICS;
6359 ICS.setStandard();
6360 ICS.Standard = Best->FinalConversion;
6361 Sequence.AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList);
6362 }
6363}
6364
6365/// The non-zero enum values here are indexes into diagnostic alternatives.
6366enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
6367
6368/// Determines whether this expression is an acceptable ICR source.
6369static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
6370 bool isAddressOf, bool &isWeakAccess) {
6371 // Skip parens.
6372 e = e->IgnoreParens();
6373
6374 // Skip address-of nodes.
6375 if (UnaryOperator *op = dyn_cast<UnaryOperator>(Val: e)) {
6376 if (op->getOpcode() == UO_AddrOf)
6377 return isInvalidICRSource(C, e: op->getSubExpr(), /*addressof*/ isAddressOf: true,
6378 isWeakAccess);
6379
6380 // Skip certain casts.
6381 } else if (CastExpr *ce = dyn_cast<CastExpr>(Val: e)) {
6382 switch (ce->getCastKind()) {
6383 case CK_Dependent:
6384 case CK_BitCast:
6385 case CK_LValueBitCast:
6386 case CK_NoOp:
6387 return isInvalidICRSource(C, e: ce->getSubExpr(), isAddressOf, isWeakAccess);
6388
6389 case CK_ArrayToPointerDecay:
6390 return IIK_nonscalar;
6391
6392 case CK_NullToPointer:
6393 return IIK_okay;
6394
6395 default:
6396 break;
6397 }
6398
6399 // If we have a declaration reference, it had better be a local variable.
6400 } else if (isa<DeclRefExpr>(Val: e)) {
6401 // set isWeakAccess to true, to mean that there will be an implicit
6402 // load which requires a cleanup.
6403 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
6404 isWeakAccess = true;
6405
6406 if (!isAddressOf) return IIK_nonlocal;
6407
6408 VarDecl *var = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: e)->getDecl());
6409 if (!var) return IIK_nonlocal;
6410
6411 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6412
6413 // If we have a conditional operator, check both sides.
6414 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(Val: e)) {
6415 if (InvalidICRKind iik = isInvalidICRSource(C, e: cond->getLHS(), isAddressOf,
6416 isWeakAccess))
6417 return iik;
6418
6419 return isInvalidICRSource(C, e: cond->getRHS(), isAddressOf, isWeakAccess);
6420
6421 // These are never scalar.
6422 } else if (isa<ArraySubscriptExpr>(Val: e)) {
6423 return IIK_nonscalar;
6424
6425 // Otherwise, it needs to be a null pointer constant.
6426 } else {
6427 return (e->isNullPointerConstant(Ctx&: C, NPC: Expr::NPC_ValueDependentIsNull)
6428 ? IIK_okay : IIK_nonlocal);
6429 }
6430
6431 return IIK_nonlocal;
6432}
6433
6434/// Check whether the given expression is a valid operand for an
6435/// indirect copy/restore.
6436static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
6437 assert(src->isPRValue());
6438 bool isWeakAccess = false;
6439 InvalidICRKind iik = isInvalidICRSource(C&: S.Context, e: src, isAddressOf: false, isWeakAccess);
6440 // If isWeakAccess to true, there will be an implicit
6441 // load which requires a cleanup.
6442 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6443 S.Cleanup.setExprNeedsCleanups(true);
6444
6445 if (iik == IIK_okay) return;
6446
6447 S.Diag(Loc: src->getExprLoc(), DiagID: diag::err_arc_nonlocal_writeback)
6448 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6449 << src->getSourceRange();
6450}
6451
6452/// Determine whether we have compatible array types for the
6453/// purposes of GNU by-copy array initialization.
6454static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6455 const ArrayType *Source) {
6456 // If the source and destination array types are equivalent, we're
6457 // done.
6458 if (Context.hasSameType(T1: QualType(Dest, 0), T2: QualType(Source, 0)))
6459 return true;
6460
6461 // Make sure that the element types are the same.
6462 if (!Context.hasSameType(T1: Dest->getElementType(), T2: Source->getElementType()))
6463 return false;
6464
6465 // The only mismatch we allow is when the destination is an
6466 // incomplete array type and the source is a constant array type.
6467 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6468}
6469
6470static bool tryObjCWritebackConversion(Sema &S,
6471 InitializationSequence &Sequence,
6472 const InitializedEntity &Entity,
6473 Expr *Initializer) {
6474 bool ArrayDecay = false;
6475 QualType ArgType = Initializer->getType();
6476 QualType ArgPointee;
6477 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(T: ArgType)) {
6478 ArrayDecay = true;
6479 ArgPointee = ArgArrayType->getElementType();
6480 ArgType = S.Context.getPointerType(T: ArgPointee);
6481 }
6482
6483 // Handle write-back conversion.
6484 QualType ConvertedArgType;
6485 if (!S.ObjC().isObjCWritebackConversion(FromType: ArgType, ToType: Entity.getType(),
6486 ConvertedType&: ConvertedArgType))
6487 return false;
6488
6489 // We should copy unless we're passing to an argument explicitly
6490 // marked 'out'.
6491 bool ShouldCopy = true;
6492 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl()))
6493 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6494
6495 // Do we need an lvalue conversion?
6496 if (ArrayDecay || Initializer->isGLValue()) {
6497 ImplicitConversionSequence ICS;
6498 ICS.setStandard();
6499 ICS.Standard.setAsIdentityConversion();
6500
6501 QualType ResultType;
6502 if (ArrayDecay) {
6503 ICS.Standard.First = ICK_Array_To_Pointer;
6504 ResultType = S.Context.getPointerType(T: ArgPointee);
6505 } else {
6506 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
6507 ResultType = Initializer->getType().getNonLValueExprType(Context: S.Context);
6508 }
6509
6510 Sequence.AddConversionSequenceStep(ICS, T: ResultType);
6511 }
6512
6513 Sequence.AddPassByIndirectCopyRestoreStep(type: Entity.getType(), shouldCopy: ShouldCopy);
6514 return true;
6515}
6516
6517static bool TryOCLSamplerInitialization(Sema &S,
6518 InitializationSequence &Sequence,
6519 QualType DestType,
6520 Expr *Initializer) {
6521 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6522 (!Initializer->isIntegerConstantExpr(Ctx: S.Context) &&
6523 !Initializer->getType()->isSamplerT()))
6524 return false;
6525
6526 Sequence.AddOCLSamplerInitStep(T: DestType);
6527 return true;
6528}
6529
6530static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6531 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6532 return Value && Value->isZero();
6533}
6534
6535static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
6536 InitializationSequence &Sequence,
6537 QualType DestType,
6538 Expr *Initializer) {
6539 if (!S.getLangOpts().OpenCL)
6540 return false;
6541
6542 //
6543 // OpenCL 1.2 spec, s6.12.10
6544 //
6545 // The event argument can also be used to associate the
6546 // async_work_group_copy with a previous async copy allowing
6547 // an event to be shared by multiple async copies; otherwise
6548 // event should be zero.
6549 //
6550 if (DestType->isEventT() || DestType->isQueueT()) {
6551 if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext()))
6552 return false;
6553
6554 Sequence.AddOCLZeroOpaqueTypeStep(T: DestType);
6555 return true;
6556 }
6557
6558 // We should allow zero initialization for all types defined in the
6559 // cl_intel_device_side_avc_motion_estimation extension, except
6560 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6561 if (S.getOpenCLOptions().isAvailableOption(
6562 Ext: "cl_intel_device_side_avc_motion_estimation", LO: S.getLangOpts()) &&
6563 DestType->isOCLIntelSubgroupAVCType()) {
6564 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6565 DestType->isOCLIntelSubgroupAVCMceResultType())
6566 return false;
6567 if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext()))
6568 return false;
6569
6570 Sequence.AddOCLZeroOpaqueTypeStep(T: DestType);
6571 return true;
6572 }
6573
6574 return false;
6575}
6576
6577InitializationSequence::InitializationSequence(
6578 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6579 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6580 : FailedOverloadResult(OR_Success),
6581 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6582 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6583 TreatUnavailableAsInvalid);
6584}
6585
6586/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6587/// address of that function, this returns true. Otherwise, it returns false.
6588static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6589 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
6590 if (!DRE || !isa<FunctionDecl>(Val: DRE->getDecl()))
6591 return false;
6592
6593 return !S.checkAddressOfFunctionIsAvailable(
6594 Function: cast<FunctionDecl>(Val: DRE->getDecl()));
6595}
6596
6597/// Determine whether we can perform an elementwise array copy for this kind
6598/// of entity.
6599static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6600 switch (Entity.getKind()) {
6601 case InitializedEntity::EK_LambdaCapture:
6602 // C++ [expr.prim.lambda]p24:
6603 // For array members, the array elements are direct-initialized in
6604 // increasing subscript order.
6605 return true;
6606
6607 case InitializedEntity::EK_Variable:
6608 // C++ [dcl.decomp]p1:
6609 // [...] each element is copy-initialized or direct-initialized from the
6610 // corresponding element of the assignment-expression [...]
6611 return isa<DecompositionDecl>(Val: Entity.getDecl());
6612
6613 case InitializedEntity::EK_Member:
6614 // C++ [class.copy.ctor]p14:
6615 // - if the member is an array, each element is direct-initialized with
6616 // the corresponding subobject of x
6617 return Entity.isImplicitMemberInitializer();
6618
6619 case InitializedEntity::EK_ArrayElement:
6620 // All the above cases are intended to apply recursively, even though none
6621 // of them actually say that.
6622 if (auto *E = Entity.getParent())
6623 return canPerformArrayCopy(Entity: *E);
6624 break;
6625
6626 default:
6627 break;
6628 }
6629
6630 return false;
6631}
6632
6633static const FieldDecl *getConstField(const RecordDecl *RD) {
6634 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6635 for (const FieldDecl *FD : RD->fields()) {
6636 // If the field is a flexible array member, we don't want to consider it
6637 // as a const field because there's no way to initialize the FAM anyway.
6638 const ASTContext &Ctx = FD->getASTContext();
6639 if (Decl::isFlexibleArrayMemberLike(
6640 Context: Ctx, D: FD, Ty: FD->getType(),
6641 StrictFlexArraysLevel: Ctx.getLangOpts().getStrictFlexArraysLevel(),
6642 /*IgnoreTemplateOrMacroSubstitution=*/true))
6643 continue;
6644
6645 QualType QT = FD->getType();
6646 if (QT.isConstQualified())
6647 return FD;
6648 if (const auto *RD = QT->getAsRecordDecl()) {
6649 if (const FieldDecl *FD = getConstField(RD))
6650 return FD;
6651 }
6652 }
6653 return nullptr;
6654}
6655
6656void InitializationSequence::InitializeFrom(Sema &S,
6657 const InitializedEntity &Entity,
6658 const InitializationKind &Kind,
6659 MultiExprArg Args,
6660 bool TopLevelOfInitList,
6661 bool TreatUnavailableAsInvalid) {
6662 ASTContext &Context = S.Context;
6663
6664 // Eliminate non-overload placeholder types in the arguments. We
6665 // need to do this before checking whether types are dependent
6666 // because lowering a pseudo-object expression might well give us
6667 // something of dependent type.
6668 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6669 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6670 // FIXME: should we be doing this here?
6671 ExprResult result = S.CheckPlaceholderExpr(E: Args[I]);
6672 if (result.isInvalid()) {
6673 SetFailed(FK_PlaceholderType);
6674 return;
6675 }
6676 Args[I] = result.get();
6677 }
6678
6679 // C++0x [dcl.init]p16:
6680 // The semantics of initializers are as follows. The destination type is
6681 // the type of the object or reference being initialized and the source
6682 // type is the type of the initializer expression. The source type is not
6683 // defined when the initializer is a braced-init-list or when it is a
6684 // parenthesized list of expressions.
6685 QualType DestType = Entity.getType();
6686
6687 if (DestType->isDependentType() ||
6688 Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
6689 SequenceKind = DependentSequence;
6690 return;
6691 }
6692
6693 // Almost everything is a normal sequence.
6694 setSequenceKind(NormalSequence);
6695
6696 QualType SourceType;
6697 Expr *Initializer = nullptr;
6698 if (Args.size() == 1) {
6699 Initializer = Args[0];
6700 if (S.getLangOpts().ObjC) {
6701 if (S.ObjC().CheckObjCBridgeRelatedConversions(
6702 Loc: Initializer->getBeginLoc(), DestType, SrcType: Initializer->getType(),
6703 SrcExpr&: Initializer) ||
6704 S.ObjC().CheckConversionToObjCLiteral(DstType: DestType, SrcExpr&: Initializer))
6705 Args[0] = Initializer;
6706 }
6707 if (!isa<InitListExpr>(Val: Initializer))
6708 SourceType = Initializer->getType();
6709 }
6710
6711 // - If the initializer is a (non-parenthesized) braced-init-list, the
6712 // object is list-initialized (8.5.4).
6713 if (Kind.getKind() != InitializationKind::IK_Direct) {
6714 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Val: Initializer)) {
6715 TryListInitialization(S, Entity, Kind, InitList, Sequence&: *this,
6716 TreatUnavailableAsInvalid);
6717 return;
6718 }
6719 }
6720
6721 if (!S.getLangOpts().CPlusPlus &&
6722 Kind.getKind() == InitializationKind::IK_Default) {
6723 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6724 VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: Entity.getDecl());
6725 if (Rec->hasUninitializedExplicitInitFields()) {
6726 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6727 S.Diag(Loc: Var->getLocation(), DiagID: diag::warn_field_requires_explicit_init)
6728 << /* Var-in-Record */ 1 << Rec;
6729 emitUninitializedExplicitInitFields(S, R: Rec);
6730 }
6731 }
6732 // If the record has any members which are const (recursively checked),
6733 // then we want to diagnose those as being uninitialized if there is no
6734 // initializer present. However, we only do this for structure types, not
6735 // union types, because an unitialized field in a union is generally
6736 // reasonable, especially in C where unions can be used for type punning.
6737 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6738 if (const FieldDecl *FD = getConstField(RD: Rec)) {
6739 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6740 if (Var->getStorageDuration() == SD_Static ||
6741 Var->getStorageDuration() == SD_Thread)
6742 DiagID = diag::warn_default_init_const_field;
6743
6744 bool EmitCppCompat = !S.Diags.isIgnored(
6745 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6746 Loc: Var->getLocation());
6747
6748 S.Diag(Loc: Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6749 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_default_init_const_member) << FD;
6750 }
6751 }
6752 }
6753 }
6754
6755 // - If the destination type is a reference type, see 8.5.3.
6756 if (DestType->isReferenceType()) {
6757 // C++0x [dcl.init.ref]p1:
6758 // A variable declared to be a T& or T&&, that is, "reference to type T"
6759 // (8.3.2), shall be initialized by an object, or function, of type T or
6760 // by an object that can be converted into a T.
6761 // (Therefore, multiple arguments are not permitted.)
6762 if (Args.size() != 1)
6763 SetFailed(FK_TooManyInitsForReference);
6764 // C++17 [dcl.init.ref]p5:
6765 // A reference [...] is initialized by an expression [...] as follows:
6766 // If the initializer is not an expression, presumably we should reject,
6767 // but the standard fails to actually say so.
6768 else if (isa<InitListExpr>(Val: Args[0]))
6769 SetFailed(FK_ParenthesizedListInitForReference);
6770 else
6771 TryReferenceInitialization(S, Entity, Kind, Initializer: Args[0], Sequence&: *this,
6772 TopLevelOfInitList);
6773 return;
6774 }
6775
6776 // - If the initializer is (), the object is value-initialized.
6777 if (Kind.getKind() == InitializationKind::IK_Value ||
6778 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6779 TryValueInitialization(S, Entity, Kind, Sequence&: *this);
6780 return;
6781 }
6782
6783 // Handle default initialization.
6784 if (Kind.getKind() == InitializationKind::IK_Default) {
6785 TryDefaultInitialization(S, Entity, Kind, Sequence&: *this);
6786 return;
6787 }
6788
6789 // - If the destination type is an array of characters, an array of
6790 // char16_t, an array of char32_t, or an array of wchar_t, and the
6791 // initializer is a string literal, see 8.5.2.
6792 // - Otherwise, if the destination type is an array, the program is
6793 // ill-formed.
6794 // - Except in HLSL, where non-decaying array parameters behave like
6795 // non-array types for initialization.
6796 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6797 const ArrayType *DestAT = Context.getAsArrayType(T: DestType);
6798 if (Initializer && isa<VariableArrayType>(Val: DestAT)) {
6799 SetFailed(FK_VariableLengthArrayHasInitializer);
6800 return;
6801 }
6802
6803 if (Initializer) {
6804 switch (IsStringInit(Init: Initializer, AT: DestAT, Context)) {
6805 case SIF_None:
6806 TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence&: *this);
6807 return;
6808 case SIF_NarrowStringIntoWideChar:
6809 SetFailed(FK_NarrowStringIntoWideCharArray);
6810 return;
6811 case SIF_WideStringIntoChar:
6812 SetFailed(FK_WideStringIntoCharArray);
6813 return;
6814 case SIF_IncompatWideStringIntoWideChar:
6815 SetFailed(FK_IncompatWideStringIntoWideChar);
6816 return;
6817 case SIF_PlainStringIntoUTF8Char:
6818 SetFailed(FK_PlainStringIntoUTF8Char);
6819 return;
6820 case SIF_UTF8StringIntoPlainChar:
6821 SetFailed(FK_UTF8StringIntoPlainChar);
6822 return;
6823 case SIF_Other:
6824 break;
6825 }
6826 }
6827
6828 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(Val: DestAT)) {
6829 QualType SrcType = Entity.getType();
6830 if (SrcType->isArrayParameterType())
6831 SrcType =
6832 cast<ArrayParameterType>(Val&: SrcType)->getConstantArrayType(Ctx: Context);
6833 if (S.Context.hasSameUnqualifiedType(T1: DestType, T2: SrcType)) {
6834 TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this,
6835 TreatUnavailableAsInvalid);
6836 return;
6837 }
6838 }
6839
6840 // Some kinds of initialization permit an array to be initialized from
6841 // another array of the same type, and perform elementwise initialization.
6842 if (Initializer && isa<ConstantArrayType>(Val: DestAT) &&
6843 S.Context.hasSameUnqualifiedType(T1: Initializer->getType(),
6844 T2: Entity.getType()) &&
6845 canPerformArrayCopy(Entity)) {
6846 TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this,
6847 TreatUnavailableAsInvalid);
6848 return;
6849 }
6850
6851 // Note: as an GNU C extension, we allow initialization of an
6852 // array from a compound literal that creates an array of the same
6853 // type, so long as the initializer has no side effects.
6854 if (!S.getLangOpts().CPlusPlus && Initializer &&
6855 isa<CompoundLiteralExpr>(Val: Initializer->IgnoreParens()) &&
6856 Initializer->getType()->isArrayType()) {
6857 const ArrayType *SourceAT
6858 = Context.getAsArrayType(T: Initializer->getType());
6859 if (!hasCompatibleArrayTypes(Context&: S.Context, Dest: DestAT, Source: SourceAT))
6860 SetFailed(FK_ArrayTypeMismatch);
6861 else if (Initializer->HasSideEffects(Ctx: S.Context))
6862 SetFailed(FK_NonConstantArrayInit);
6863 else {
6864 AddArrayInitStep(T: DestType, /*IsGNUExtension*/true);
6865 }
6866 }
6867 // Note: as a GNU C++ extension, we allow list-initialization of a
6868 // class member of array type from a parenthesized initializer list.
6869 else if (S.getLangOpts().CPlusPlus &&
6870 Entity.getKind() == InitializedEntity::EK_Member &&
6871 isa_and_nonnull<InitListExpr>(Val: Initializer)) {
6872 TryListInitialization(S, Entity, Kind, InitList: cast<InitListExpr>(Val: Initializer),
6873 Sequence&: *this, TreatUnavailableAsInvalid);
6874 AddParenthesizedArrayInitStep(T: DestType);
6875 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6876 Kind.getKind() == InitializationKind::IK_Direct)
6877 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
6878 /*VerifyOnly=*/true);
6879 else if (DestAT->getElementType()->isCharType())
6880 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6881 else if (IsWideCharCompatible(T: DestAT->getElementType(), Context))
6882 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6883 else
6884 SetFailed(FK_ArrayNeedsInitList);
6885
6886 return;
6887 }
6888
6889 // Determine whether we should consider writeback conversions for
6890 // Objective-C ARC.
6891 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6892 Entity.isParameterKind();
6893
6894 if (TryOCLSamplerInitialization(S, Sequence&: *this, DestType, Initializer))
6895 return;
6896
6897 // We're at the end of the line for C: it's either a write-back conversion
6898 // or it's a C assignment. There's no need to check anything else.
6899 if (!S.getLangOpts().CPlusPlus) {
6900 assert(Initializer && "Initializer must be non-null");
6901 // If allowed, check whether this is an Objective-C writeback conversion.
6902 if (allowObjCWritebackConversion &&
6903 tryObjCWritebackConversion(S, Sequence&: *this, Entity, Initializer)) {
6904 return;
6905 }
6906
6907 if (TryOCLZeroOpaqueTypeInitialization(S, Sequence&: *this, DestType, Initializer))
6908 return;
6909
6910 // Handle initialization in C
6911 AddCAssignmentStep(T: DestType);
6912 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
6913 return;
6914 }
6915
6916 assert(S.getLangOpts().CPlusPlus);
6917
6918 // - If the destination type is a (possibly cv-qualified) class type:
6919 if (DestType->isRecordType()) {
6920 // - If the initialization is direct-initialization, or if it is
6921 // copy-initialization where the cv-unqualified version of the
6922 // source type is the same class as, or a derived class of, the
6923 // class of the destination, constructors are considered. [...]
6924 if (Kind.getKind() == InitializationKind::IK_Direct ||
6925 (Kind.getKind() == InitializationKind::IK_Copy &&
6926 (Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType) ||
6927 (Initializer && S.IsDerivedFrom(Loc: Initializer->getBeginLoc(),
6928 Derived: SourceType, Base: DestType))))) {
6929 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6930 Sequence&: *this, /*IsAggrListInit=*/false);
6931 } else {
6932 // - Otherwise (i.e., for the remaining copy-initialization cases),
6933 // user-defined conversion sequences that can convert from the
6934 // source type to the destination type or (when a conversion
6935 // function is used) to a derived class thereof are enumerated as
6936 // described in 13.3.1.4, and the best one is chosen through
6937 // overload resolution (13.3).
6938 assert(Initializer && "Initializer must be non-null");
6939 TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this,
6940 TopLevelOfInitList);
6941 }
6942 return;
6943 }
6944
6945 assert(Args.size() >= 1 && "Zero-argument case handled above");
6946
6947 // For HLSL ext vector types we allow list initialization behavior for C++
6948 // functional cast expressions which look like constructor syntax. This is
6949 // accomplished by converting initialization arguments to InitListExpr.
6950 auto ShouldTryListInitialization = [&]() -> bool {
6951 // Only try list initialization for HLSL.
6952 if (!S.getLangOpts().HLSL)
6953 return false;
6954
6955 bool DestIsVec = DestType->isExtVectorType();
6956 bool DestIsMat = DestType->isConstantMatrixType();
6957
6958 // If the destination type is neither a vector nor a matrix, then don't try
6959 // list initialization.
6960 if (!DestIsVec && !DestIsMat)
6961 return false;
6962
6963 // If there is only a single source argument, then only try list
6964 // initialization if initializing a matrix with a vector or vice versa.
6965 if (Args.size() == 1) {
6966 assert(!SourceType.isNull() &&
6967 "Source QualType should not be null when arg size is exactly 1");
6968 bool SourceIsVec = SourceType->isExtVectorType();
6969 bool SourceIsMat = SourceType->isConstantMatrixType();
6970
6971 if (DestIsMat && !SourceIsVec)
6972 return false;
6973 if (DestIsVec && !SourceIsMat)
6974 return false;
6975 }
6976
6977 // Try list initialization if the source type is null or if the
6978 // destination and source types differ.
6979 return SourceType.isNull() ||
6980 !Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType);
6981 };
6982 if (ShouldTryListInitialization()) {
6983 InitListExpr *ILE = new (Context)
6984 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
6985 Args.back()->getEndLoc());
6986 ILE->setType(DestType);
6987 Args[0] = ILE;
6988 TryListInitialization(S, Entity, Kind, InitList: ILE, Sequence&: *this,
6989 TreatUnavailableAsInvalid);
6990 return;
6991 }
6992
6993 // The remaining cases all need a source type.
6994 if (Args.size() > 1) {
6995 SetFailed(FK_TooManyInitsForScalar);
6996 return;
6997 } else if (isa<InitListExpr>(Val: Args[0])) {
6998 SetFailed(FK_ParenthesizedListInitForScalar);
6999 return;
7000 }
7001
7002 // - Otherwise, if the source type is a (possibly cv-qualified) class
7003 // type, conversion functions are considered.
7004 if (!SourceType.isNull() && SourceType->isRecordType()) {
7005 assert(Initializer && "Initializer must be non-null");
7006 // For a conversion to _Atomic(T) from either T or a class type derived
7007 // from T, initialize the T object then convert to _Atomic type.
7008 bool NeedAtomicConversion = false;
7009 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7010 if (Context.hasSameUnqualifiedType(T1: SourceType, T2: Atomic->getValueType()) ||
7011 S.IsDerivedFrom(Loc: Initializer->getBeginLoc(), Derived: SourceType,
7012 Base: Atomic->getValueType())) {
7013 DestType = Atomic->getValueType();
7014 NeedAtomicConversion = true;
7015 }
7016 }
7017
7018 TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this,
7019 TopLevelOfInitList);
7020 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
7021 if (!Failed() && NeedAtomicConversion)
7022 AddAtomicConversionStep(Ty: Entity.getType());
7023 return;
7024 }
7025
7026 // - Otherwise, if the initialization is direct-initialization, the source
7027 // type is std::nullptr_t, and the destination type is bool, the initial
7028 // value of the object being initialized is false.
7029 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7030 DestType->isBooleanType() &&
7031 Kind.getKind() == InitializationKind::IK_Direct) {
7032 AddConversionSequenceStep(
7033 ICS: ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
7034 NeedLValToRVal: Initializer->isGLValue()),
7035 T: DestType);
7036 return;
7037 }
7038
7039 // - Otherwise, the initial value of the object being initialized is the
7040 // (possibly converted) value of the initializer expression. Standard
7041 // conversions (Clause 4) will be used, if necessary, to convert the
7042 // initializer expression to the cv-unqualified version of the
7043 // destination type; no user-defined conversions are considered.
7044
7045 ImplicitConversionSequence ICS
7046 = S.TryImplicitConversion(From: Initializer, ToType: DestType,
7047 /*SuppressUserConversions*/true,
7048 AllowExplicit: Sema::AllowedExplicit::None,
7049 /*InOverloadResolution*/ false,
7050 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7051 AllowObjCWritebackConversion: allowObjCWritebackConversion);
7052
7053 if (ICS.isStandard() &&
7054 ICS.Standard.Second == ICK_Writeback_Conversion) {
7055 // Objective-C ARC writeback conversion.
7056
7057 // We should copy unless we're passing to an argument explicitly
7058 // marked 'out'.
7059 bool ShouldCopy = true;
7060 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl()))
7061 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7062
7063 // If there was an lvalue adjustment, add it as a separate conversion.
7064 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7065 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7066 ImplicitConversionSequence LvalueICS;
7067 LvalueICS.setStandard();
7068 LvalueICS.Standard.setAsIdentityConversion();
7069 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(Idx: 0));
7070 LvalueICS.Standard.First = ICS.Standard.First;
7071 AddConversionSequenceStep(ICS: LvalueICS, T: ICS.Standard.getToType(Idx: 0));
7072 }
7073
7074 AddPassByIndirectCopyRestoreStep(type: DestType, shouldCopy: ShouldCopy);
7075 } else if (ICS.isBad()) {
7076 if (DeclAccessPair Found;
7077 Initializer->getType() == Context.OverloadTy &&
7078 !S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, TargetType: DestType,
7079 /*Complain=*/false, Found))
7080 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
7081 else if (Initializer->getType()->isFunctionType() &&
7082 isExprAnUnaddressableFunction(S, E: Initializer))
7083 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
7084 else
7085 SetFailed(InitializationSequence::FK_ConversionFailed);
7086 } else {
7087 AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList);
7088
7089 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
7090 }
7091}
7092
7093InitializationSequence::~InitializationSequence() {
7094 for (auto &S : Steps)
7095 S.Destroy();
7096}
7097
7098//===----------------------------------------------------------------------===//
7099// Perform initialization
7100//===----------------------------------------------------------------------===//
7101static AssignmentAction getAssignmentAction(const InitializedEntity &Entity,
7102 bool Diagnose = false) {
7103 switch(Entity.getKind()) {
7104 case InitializedEntity::EK_Variable:
7105 case InitializedEntity::EK_New:
7106 case InitializedEntity::EK_Exception:
7107 case InitializedEntity::EK_Base:
7108 case InitializedEntity::EK_Delegating:
7109 return AssignmentAction::Initializing;
7110
7111 case InitializedEntity::EK_Parameter:
7112 if (Entity.getDecl() &&
7113 isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext()))
7114 return AssignmentAction::Sending;
7115
7116 return AssignmentAction::Passing;
7117
7118 case InitializedEntity::EK_Parameter_CF_Audited:
7119 if (Entity.getDecl() &&
7120 isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext()))
7121 return AssignmentAction::Sending;
7122
7123 return !Diagnose ? AssignmentAction::Passing
7124 : AssignmentAction::Passing_CFAudited;
7125
7126 case InitializedEntity::EK_Result:
7127 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7128 return AssignmentAction::Returning;
7129
7130 case InitializedEntity::EK_Temporary:
7131 case InitializedEntity::EK_RelatedResult:
7132 // FIXME: Can we tell apart casting vs. converting?
7133 return AssignmentAction::Casting;
7134
7135 case InitializedEntity::EK_TemplateParameter:
7136 // This is really initialization, but refer to it as conversion for
7137 // consistency with CheckConvertedConstantExpression.
7138 return AssignmentAction::Converting;
7139
7140 case InitializedEntity::EK_Member:
7141 case InitializedEntity::EK_ParenAggInitMember:
7142 case InitializedEntity::EK_Binding:
7143 case InitializedEntity::EK_ArrayElement:
7144 case InitializedEntity::EK_VectorElement:
7145 case InitializedEntity::EK_MatrixElement:
7146 case InitializedEntity::EK_ComplexElement:
7147 case InitializedEntity::EK_BlockElement:
7148 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7149 case InitializedEntity::EK_LambdaCapture:
7150 case InitializedEntity::EK_CompoundLiteralInit:
7151 return AssignmentAction::Initializing;
7152 }
7153
7154 llvm_unreachable("Invalid EntityKind!");
7155}
7156
7157/// Whether we should bind a created object as a temporary when
7158/// initializing the given entity.
7159static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
7160 switch (Entity.getKind()) {
7161 case InitializedEntity::EK_ArrayElement:
7162 case InitializedEntity::EK_Member:
7163 case InitializedEntity::EK_ParenAggInitMember:
7164 case InitializedEntity::EK_Result:
7165 case InitializedEntity::EK_StmtExprResult:
7166 case InitializedEntity::EK_New:
7167 case InitializedEntity::EK_Variable:
7168 case InitializedEntity::EK_Base:
7169 case InitializedEntity::EK_Delegating:
7170 case InitializedEntity::EK_VectorElement:
7171 case InitializedEntity::EK_MatrixElement:
7172 case InitializedEntity::EK_ComplexElement:
7173 case InitializedEntity::EK_Exception:
7174 case InitializedEntity::EK_BlockElement:
7175 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7176 case InitializedEntity::EK_LambdaCapture:
7177 case InitializedEntity::EK_CompoundLiteralInit:
7178 case InitializedEntity::EK_TemplateParameter:
7179 return false;
7180
7181 case InitializedEntity::EK_Parameter:
7182 case InitializedEntity::EK_Parameter_CF_Audited:
7183 case InitializedEntity::EK_Temporary:
7184 case InitializedEntity::EK_RelatedResult:
7185 case InitializedEntity::EK_Binding:
7186 return true;
7187 }
7188
7189 llvm_unreachable("missed an InitializedEntity kind?");
7190}
7191
7192/// Whether the given entity, when initialized with an object
7193/// created for that initialization, requires destruction.
7194static bool shouldDestroyEntity(const InitializedEntity &Entity) {
7195 switch (Entity.getKind()) {
7196 case InitializedEntity::EK_Result:
7197 case InitializedEntity::EK_StmtExprResult:
7198 case InitializedEntity::EK_New:
7199 case InitializedEntity::EK_Base:
7200 case InitializedEntity::EK_Delegating:
7201 case InitializedEntity::EK_VectorElement:
7202 case InitializedEntity::EK_MatrixElement:
7203 case InitializedEntity::EK_ComplexElement:
7204 case InitializedEntity::EK_BlockElement:
7205 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7206 case InitializedEntity::EK_LambdaCapture:
7207 return false;
7208
7209 case InitializedEntity::EK_Member:
7210 case InitializedEntity::EK_ParenAggInitMember:
7211 case InitializedEntity::EK_Binding:
7212 case InitializedEntity::EK_Variable:
7213 case InitializedEntity::EK_Parameter:
7214 case InitializedEntity::EK_Parameter_CF_Audited:
7215 case InitializedEntity::EK_TemplateParameter:
7216 case InitializedEntity::EK_Temporary:
7217 case InitializedEntity::EK_ArrayElement:
7218 case InitializedEntity::EK_Exception:
7219 case InitializedEntity::EK_CompoundLiteralInit:
7220 case InitializedEntity::EK_RelatedResult:
7221 return true;
7222 }
7223
7224 llvm_unreachable("missed an InitializedEntity kind?");
7225}
7226
7227/// Get the location at which initialization diagnostics should appear.
7228static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
7229 Expr *Initializer) {
7230 switch (Entity.getKind()) {
7231 case InitializedEntity::EK_Result:
7232 case InitializedEntity::EK_StmtExprResult:
7233 return Entity.getReturnLoc();
7234
7235 case InitializedEntity::EK_Exception:
7236 return Entity.getThrowLoc();
7237
7238 case InitializedEntity::EK_Variable:
7239 case InitializedEntity::EK_Binding:
7240 return Entity.getDecl()->getLocation();
7241
7242 case InitializedEntity::EK_LambdaCapture:
7243 return Entity.getCaptureLoc();
7244
7245 case InitializedEntity::EK_ArrayElement:
7246 case InitializedEntity::EK_Member:
7247 case InitializedEntity::EK_ParenAggInitMember:
7248 case InitializedEntity::EK_Parameter:
7249 case InitializedEntity::EK_Parameter_CF_Audited:
7250 case InitializedEntity::EK_TemplateParameter:
7251 case InitializedEntity::EK_Temporary:
7252 case InitializedEntity::EK_New:
7253 case InitializedEntity::EK_Base:
7254 case InitializedEntity::EK_Delegating:
7255 case InitializedEntity::EK_VectorElement:
7256 case InitializedEntity::EK_MatrixElement:
7257 case InitializedEntity::EK_ComplexElement:
7258 case InitializedEntity::EK_BlockElement:
7259 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7260 case InitializedEntity::EK_CompoundLiteralInit:
7261 case InitializedEntity::EK_RelatedResult:
7262 return Initializer->getBeginLoc();
7263 }
7264 llvm_unreachable("missed an InitializedEntity kind?");
7265}
7266
7267/// Make a (potentially elidable) temporary copy of the object
7268/// provided by the given initializer by calling the appropriate copy
7269/// constructor.
7270///
7271/// \param S The Sema object used for type-checking.
7272///
7273/// \param T The type of the temporary object, which must either be
7274/// the type of the initializer expression or a superclass thereof.
7275///
7276/// \param Entity The entity being initialized.
7277///
7278/// \param CurInit The initializer expression.
7279///
7280/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7281/// is permitted in C++03 (but not C++0x) when binding a reference to
7282/// an rvalue.
7283///
7284/// \returns An expression that copies the initializer expression into
7285/// a temporary object, or an error expression if a copy could not be
7286/// created.
7287static ExprResult CopyObject(Sema &S,
7288 QualType T,
7289 const InitializedEntity &Entity,
7290 ExprResult CurInit,
7291 bool IsExtraneousCopy) {
7292 if (CurInit.isInvalid())
7293 return CurInit;
7294 // Determine which class type we're copying to.
7295 Expr *CurInitExpr = (Expr *)CurInit.get();
7296 auto *Class = T->getAsCXXRecordDecl();
7297 if (!Class)
7298 return CurInit;
7299
7300 SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInit.get());
7301
7302 // Make sure that the type we are copying is complete.
7303 if (S.RequireCompleteType(Loc, T, DiagID: diag::err_temp_copy_incomplete))
7304 return CurInit;
7305
7306 // Perform overload resolution using the class's constructors. Per
7307 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7308 // is direct-initialization.
7309 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7310 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
7311
7312 OverloadCandidateSet::iterator Best;
7313 switch (ResolveConstructorOverload(
7314 S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: T, Ctors, Best,
7315 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7316 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7317 /*RequireActualConstructor=*/false,
7318 /*SecondStepOfCopyInit=*/true)) {
7319 case OR_Success:
7320 break;
7321
7322 case OR_No_Viable_Function:
7323 CandidateSet.NoteCandidates(
7324 PA: PartialDiagnosticAt(
7325 Loc, S.PDiag(DiagID: IsExtraneousCopy && !S.isSFINAEContext()
7326 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7327 : diag::err_temp_copy_no_viable)
7328 << (int)Entity.getKind() << CurInitExpr->getType()
7329 << CurInitExpr->getSourceRange()),
7330 S, OCD: OCD_AllCandidates, Args: CurInitExpr);
7331 if (!IsExtraneousCopy || S.isSFINAEContext())
7332 return ExprError();
7333 return CurInit;
7334
7335 case OR_Ambiguous:
7336 CandidateSet.NoteCandidates(
7337 PA: PartialDiagnosticAt(Loc, S.PDiag(DiagID: diag::err_temp_copy_ambiguous)
7338 << (int)Entity.getKind()
7339 << CurInitExpr->getType()
7340 << CurInitExpr->getSourceRange()),
7341 S, OCD: OCD_AmbiguousCandidates, Args: CurInitExpr);
7342 return ExprError();
7343
7344 case OR_Deleted:
7345 S.Diag(Loc, DiagID: diag::err_temp_copy_deleted)
7346 << (int)Entity.getKind() << CurInitExpr->getType()
7347 << CurInitExpr->getSourceRange();
7348 S.NoteDeletedFunction(FD: Best->Function);
7349 return ExprError();
7350 }
7351
7352 bool HadMultipleCandidates = CandidateSet.size() > 1;
7353
7354 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
7355 SmallVector<Expr*, 8> ConstructorArgs;
7356 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7357
7358 S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Best->FoundDecl, Entity,
7359 IsCopyBindingRefToTemp: IsExtraneousCopy);
7360
7361 if (IsExtraneousCopy) {
7362 // If this is a totally extraneous copy for C++03 reference
7363 // binding purposes, just return the original initialization
7364 // expression. We don't generate an (elided) copy operation here
7365 // because doing so would require us to pass down a flag to avoid
7366 // infinite recursion, where each step adds another extraneous,
7367 // elidable copy.
7368
7369 // Instantiate the default arguments of any extra parameters in
7370 // the selected copy constructor, as if we were going to create a
7371 // proper call to the copy constructor.
7372 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7373 ParmVarDecl *Parm = Constructor->getParamDecl(i: I);
7374 if (S.RequireCompleteType(Loc, T: Parm->getType(),
7375 DiagID: diag::err_call_incomplete_argument))
7376 break;
7377
7378 // Build the default argument expression; we don't actually care
7379 // if this succeeds or not, because this routine will complain
7380 // if there was a problem.
7381 S.BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Constructor, Param: Parm);
7382 }
7383
7384 return CurInitExpr;
7385 }
7386
7387 // Determine the arguments required to actually perform the
7388 // constructor call (we might have derived-to-base conversions, or
7389 // the copy constructor may have default arguments).
7390 if (S.CompleteConstructorCall(Constructor, DeclInitType: T, ArgsPtr: CurInitExpr, Loc,
7391 ConvertedArgs&: ConstructorArgs))
7392 return ExprError();
7393
7394 // C++0x [class.copy]p32:
7395 // When certain criteria are met, an implementation is allowed to
7396 // omit the copy/move construction of a class object, even if the
7397 // copy/move constructor and/or destructor for the object have
7398 // side effects. [...]
7399 // - when a temporary class object that has not been bound to a
7400 // reference (12.2) would be copied/moved to a class object
7401 // with the same cv-unqualified type, the copy/move operation
7402 // can be omitted by constructing the temporary object
7403 // directly into the target of the omitted copy/move
7404 //
7405 // Note that the other three bullets are handled elsewhere. Copy
7406 // elision for return statements and throw expressions are handled as part
7407 // of constructor initialization, while copy elision for exception handlers
7408 // is handled by the run-time.
7409 //
7410 // FIXME: If the function parameter is not the same type as the temporary, we
7411 // should still be able to elide the copy, but we don't have a way to
7412 // represent in the AST how much should be elided in this case.
7413 bool Elidable =
7414 CurInitExpr->isTemporaryObject(Ctx&: S.Context, TempTy: Class) &&
7415 S.Context.hasSameUnqualifiedType(
7416 T1: Best->Function->getParamDecl(i: 0)->getType().getNonReferenceType(),
7417 T2: CurInitExpr->getType());
7418
7419 // Actually perform the constructor call.
7420 CurInit = S.BuildCXXConstructExpr(
7421 ConstructLoc: Loc, DeclInitType: T, FoundDecl: Best->FoundDecl, Constructor, Elidable, Exprs: ConstructorArgs,
7422 HadMultipleCandidates,
7423 /*ListInit*/ IsListInitialization: false,
7424 /*StdInitListInit*/ IsStdInitListInitialization: false,
7425 /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
7426
7427 // If we're supposed to bind temporaries, do so.
7428 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7429 CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>());
7430 return CurInit;
7431}
7432
7433/// Check whether elidable copy construction for binding a reference to
7434/// a temporary would have succeeded if we were building in C++98 mode, for
7435/// -Wc++98-compat.
7436static void CheckCXX98CompatAccessibleCopy(Sema &S,
7437 const InitializedEntity &Entity,
7438 Expr *CurInitExpr) {
7439 assert(S.getLangOpts().CPlusPlus11);
7440
7441 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7442 if (!Record)
7443 return;
7444
7445 SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInitExpr);
7446 if (S.Diags.isIgnored(DiagID: diag::warn_cxx98_compat_temp_copy, Loc))
7447 return;
7448
7449 // Find constructors which would have been considered.
7450 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7451 DeclContext::lookup_result Ctors = S.LookupConstructors(Class: Record);
7452
7453 // Perform overload resolution.
7454 OverloadCandidateSet::iterator Best;
7455 OverloadingResult OR = ResolveConstructorOverload(
7456 S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: CurInitExpr->getType(), Ctors, Best,
7457 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7458 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7459 /*RequireActualConstructor=*/false,
7460 /*SecondStepOfCopyInit=*/true);
7461
7462 PartialDiagnostic Diag = S.PDiag(DiagID: diag::warn_cxx98_compat_temp_copy)
7463 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7464 << CurInitExpr->getSourceRange();
7465
7466 switch (OR) {
7467 case OR_Success:
7468 S.CheckConstructorAccess(Loc, D: cast<CXXConstructorDecl>(Val: Best->Function),
7469 FoundDecl: Best->FoundDecl, Entity, PDiag: Diag);
7470 // FIXME: Check default arguments as far as that's possible.
7471 break;
7472
7473 case OR_No_Viable_Function:
7474 CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S,
7475 OCD: OCD_AllCandidates, Args: CurInitExpr);
7476 break;
7477
7478 case OR_Ambiguous:
7479 CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S,
7480 OCD: OCD_AmbiguousCandidates, Args: CurInitExpr);
7481 break;
7482
7483 case OR_Deleted:
7484 S.Diag(Loc, PD: Diag);
7485 S.NoteDeletedFunction(FD: Best->Function);
7486 break;
7487 }
7488}
7489
7490void InitializationSequence::PrintInitLocationNote(Sema &S,
7491 const InitializedEntity &Entity) {
7492 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7493 if (Entity.getDecl()->getLocation().isInvalid())
7494 return;
7495
7496 if (Entity.getDecl()->getDeclName())
7497 S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_named_here)
7498 << Entity.getDecl()->getDeclName();
7499 else
7500 S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_here);
7501 }
7502 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7503 Entity.getMethodDecl())
7504 S.Diag(Loc: Entity.getMethodDecl()->getLocation(),
7505 DiagID: diag::note_method_return_type_change)
7506 << Entity.getMethodDecl()->getDeclName();
7507}
7508
7509/// Returns true if the parameters describe a constructor initialization of
7510/// an explicit temporary object, e.g. "Point(x, y)".
7511static bool isExplicitTemporary(const InitializedEntity &Entity,
7512 const InitializationKind &Kind,
7513 unsigned NumArgs) {
7514 switch (Entity.getKind()) {
7515 case InitializedEntity::EK_Temporary:
7516 case InitializedEntity::EK_CompoundLiteralInit:
7517 case InitializedEntity::EK_RelatedResult:
7518 break;
7519 default:
7520 return false;
7521 }
7522
7523 switch (Kind.getKind()) {
7524 case InitializationKind::IK_DirectList:
7525 return true;
7526 // FIXME: Hack to work around cast weirdness.
7527 case InitializationKind::IK_Direct:
7528 case InitializationKind::IK_Value:
7529 return NumArgs != 1;
7530 default:
7531 return false;
7532 }
7533}
7534
7535static ExprResult
7536PerformConstructorInitialization(Sema &S,
7537 const InitializedEntity &Entity,
7538 const InitializationKind &Kind,
7539 MultiExprArg Args,
7540 const InitializationSequence::Step& Step,
7541 bool &ConstructorInitRequiresZeroInit,
7542 bool IsListInitialization,
7543 bool IsStdInitListInitialization,
7544 SourceLocation LBraceLoc,
7545 SourceLocation RBraceLoc) {
7546 unsigned NumArgs = Args.size();
7547 CXXConstructorDecl *Constructor
7548 = cast<CXXConstructorDecl>(Val: Step.Function.Function);
7549 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7550
7551 // Build a call to the selected constructor.
7552 SmallVector<Expr*, 8> ConstructorArgs;
7553 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7554 ? Kind.getEqualLoc()
7555 : Kind.getLocation();
7556
7557 if (Kind.getKind() == InitializationKind::IK_Default) {
7558 // Force even a trivial, implicit default constructor to be
7559 // semantically checked. We do this explicitly because we don't build
7560 // the definition for completely trivial constructors.
7561 assert(Constructor->getParent() && "No parent class for constructor.");
7562 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7563 Constructor->isTrivial() && !Constructor->isUsed(CheckUsedAttr: false)) {
7564 S.runWithSufficientStackSpace(Loc, Fn: [&] {
7565 S.DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
7566 });
7567 }
7568 }
7569
7570 ExprResult CurInit((Expr *)nullptr);
7571
7572 // C++ [over.match.copy]p1:
7573 // - When initializing a temporary to be bound to the first parameter
7574 // of a constructor that takes a reference to possibly cv-qualified
7575 // T as its first argument, called with a single argument in the
7576 // context of direct-initialization, explicit conversion functions
7577 // are also considered.
7578 bool AllowExplicitConv =
7579 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7580 hasCopyOrMoveCtorParam(Ctx&: S.Context,
7581 Info: getConstructorInfo(ND: Step.Function.FoundDecl));
7582
7583 // A smart pointer constructed from a nullable pointer is nullable.
7584 if (NumArgs == 1 && !Kind.isExplicitCast())
7585 S.diagnoseNullableToNonnullConversion(
7586 DstType: Entity.getType(), SrcType: Args.front()->getType(), Loc: Kind.getLocation());
7587
7588 // Determine the arguments required to actually perform the constructor
7589 // call.
7590 if (S.CompleteConstructorCall(Constructor, DeclInitType: Step.Type, ArgsPtr: Args, Loc,
7591 ConvertedArgs&: ConstructorArgs, AllowExplicit: AllowExplicitConv,
7592 IsListInitialization))
7593 return ExprError();
7594
7595 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7596 // An explicitly-constructed temporary, e.g., X(1, 2).
7597 if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc))
7598 return ExprError();
7599
7600 if (Kind.getKind() == InitializationKind::IK_Value &&
7601 Constructor->isImplicit()) {
7602 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7603 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7604 unsigned I = 0;
7605 for (const FieldDecl *FD : RD->fields()) {
7606 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7607 !S.isUnevaluatedContext()) {
7608 S.Diag(Loc, DiagID: diag::warn_field_requires_explicit_init)
7609 << /* Var-in-Record */ 0 << FD;
7610 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD;
7611 }
7612 ++I;
7613 }
7614 }
7615 }
7616
7617 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7618 if (!TSInfo)
7619 TSInfo = S.Context.getTrivialTypeSourceInfo(T: Entity.getType(), Loc);
7620 SourceRange ParenOrBraceRange =
7621 (Kind.getKind() == InitializationKind::IK_DirectList)
7622 ? SourceRange(LBraceLoc, RBraceLoc)
7623 : Kind.getParenOrBraceRange();
7624
7625 CXXConstructorDecl *CalleeDecl = Constructor;
7626 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7627 Val: Step.Function.FoundDecl.getDecl())) {
7628 CalleeDecl = S.findInheritingConstructor(Loc, BaseCtor: Constructor, DerivedShadow: Shadow);
7629 }
7630 S.MarkFunctionReferenced(Loc, Func: CalleeDecl);
7631
7632 CurInit = S.CheckForImmediateInvocation(
7633 E: CXXTemporaryObjectExpr::Create(
7634 Ctx: S.Context, Cons: CalleeDecl,
7635 Ty: Entity.getType().getNonLValueExprType(Context: S.Context), TSI: TSInfo,
7636 Args: ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7637 ListInitialization: IsListInitialization, StdInitListInitialization: IsStdInitListInitialization,
7638 ZeroInitialization: ConstructorInitRequiresZeroInit),
7639 Decl: CalleeDecl);
7640 } else {
7641 CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;
7642
7643 if (Entity.getKind() == InitializedEntity::EK_Base) {
7644 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7645 ? CXXConstructionKind::VirtualBase
7646 : CXXConstructionKind::NonVirtualBase;
7647 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7648 ConstructKind = CXXConstructionKind::Delegating;
7649 }
7650
7651 // Only get the parenthesis or brace range if it is a list initialization or
7652 // direct construction.
7653 SourceRange ParenOrBraceRange;
7654 if (IsListInitialization)
7655 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7656 else if (Kind.getKind() == InitializationKind::IK_Direct)
7657 ParenOrBraceRange = Kind.getParenOrBraceRange();
7658
7659 // If the entity allows NRVO, mark the construction as elidable
7660 // unconditionally.
7661 if (Entity.allowsNRVO())
7662 CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type,
7663 FoundDecl: Step.Function.FoundDecl,
7664 Constructor, /*Elidable=*/true,
7665 Exprs: ConstructorArgs,
7666 HadMultipleCandidates,
7667 IsListInitialization,
7668 IsStdInitListInitialization,
7669 RequiresZeroInit: ConstructorInitRequiresZeroInit,
7670 ConstructKind,
7671 ParenRange: ParenOrBraceRange);
7672 else
7673 CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type,
7674 FoundDecl: Step.Function.FoundDecl,
7675 Constructor,
7676 Exprs: ConstructorArgs,
7677 HadMultipleCandidates,
7678 IsListInitialization,
7679 IsStdInitListInitialization,
7680 RequiresZeroInit: ConstructorInitRequiresZeroInit,
7681 ConstructKind,
7682 ParenRange: ParenOrBraceRange);
7683 }
7684 if (CurInit.isInvalid())
7685 return ExprError();
7686
7687 // Only check access if all of that succeeded.
7688 S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Step.Function.FoundDecl, Entity);
7689 if (S.DiagnoseUseOfOverloadedDecl(D: Constructor, Loc))
7690 return ExprError();
7691
7692 if (const ArrayType *AT = S.Context.getAsArrayType(T: Entity.getType()))
7693 if (checkDestructorReference(ElementType: S.Context.getBaseElementType(VAT: AT), Loc, SemaRef&: S))
7694 return ExprError();
7695
7696 if (shouldBindAsTemporary(Entity))
7697 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
7698
7699 return CurInit;
7700}
7701
7702void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7703 Expr *Init) {
7704 return sema::checkInitLifetime(SemaRef&: *this, Entity, Init);
7705}
7706
7707static void DiagnoseNarrowingInInitList(Sema &S,
7708 const ImplicitConversionSequence &ICS,
7709 QualType PreNarrowingType,
7710 QualType EntityType,
7711 const Expr *PostInit);
7712
7713static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7714 QualType ToType, Expr *Init);
7715
7716/// Provide warnings when std::move is used on construction.
7717static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7718 bool IsReturnStmt) {
7719 if (!InitExpr)
7720 return;
7721
7722 if (S.inTemplateInstantiation())
7723 return;
7724
7725 QualType DestType = InitExpr->getType();
7726 if (!DestType->isRecordType())
7727 return;
7728
7729 unsigned DiagID = 0;
7730 if (IsReturnStmt) {
7731 const CXXConstructExpr *CCE =
7732 dyn_cast<CXXConstructExpr>(Val: InitExpr->IgnoreParens());
7733 if (!CCE || CCE->getNumArgs() != 1)
7734 return;
7735
7736 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7737 return;
7738
7739 InitExpr = CCE->getArg(Arg: 0)->IgnoreImpCasts();
7740 }
7741
7742 // Find the std::move call and get the argument.
7743 const CallExpr *CE = dyn_cast<CallExpr>(Val: InitExpr->IgnoreParens());
7744 if (!CE || !CE->isCallToStdMove())
7745 return;
7746
7747 const Expr *Arg = CE->getArg(Arg: 0)->IgnoreImplicit();
7748
7749 if (IsReturnStmt) {
7750 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts());
7751 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7752 return;
7753
7754 const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
7755 if (!VD || !VD->hasLocalStorage())
7756 return;
7757
7758 // __block variables are not moved implicitly.
7759 if (VD->hasAttr<BlocksAttr>())
7760 return;
7761
7762 QualType SourceType = VD->getType();
7763 if (!SourceType->isRecordType())
7764 return;
7765
7766 if (!S.Context.hasSameUnqualifiedType(T1: DestType, T2: SourceType)) {
7767 return;
7768 }
7769
7770 // If we're returning a function parameter, copy elision
7771 // is not possible.
7772 if (isa<ParmVarDecl>(Val: VD))
7773 DiagID = diag::warn_redundant_move_on_return;
7774 else
7775 DiagID = diag::warn_pessimizing_move_on_return;
7776 } else {
7777 DiagID = diag::warn_pessimizing_move_on_initialization;
7778 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7779 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7780 return;
7781 }
7782
7783 S.Diag(Loc: CE->getBeginLoc(), DiagID);
7784
7785 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7786 // is within a macro.
7787 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7788 if (CallBegin.isMacroID())
7789 return;
7790 SourceLocation RParen = CE->getRParenLoc();
7791 if (RParen.isMacroID())
7792 return;
7793 SourceLocation LParen;
7794 SourceLocation ArgLoc = Arg->getBeginLoc();
7795
7796 // Special testing for the argument location. Since the fix-it needs the
7797 // location right before the argument, the argument location can be in a
7798 // macro only if it is at the beginning of the macro.
7799 while (ArgLoc.isMacroID() &&
7800 S.getSourceManager().isAtStartOfImmediateMacroExpansion(Loc: ArgLoc)) {
7801 ArgLoc = S.getSourceManager().getImmediateExpansionRange(Loc: ArgLoc).getBegin();
7802 }
7803
7804 if (LParen.isMacroID())
7805 return;
7806
7807 LParen = ArgLoc.getLocWithOffset(Offset: -1);
7808
7809 S.Diag(Loc: CE->getBeginLoc(), DiagID: diag::note_remove_move)
7810 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CallBegin, LParen))
7811 << FixItHint::CreateRemoval(RemoveRange: SourceRange(RParen, RParen));
7812}
7813
7814static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7815 // Check to see if we are dereferencing a null pointer. If so, this is
7816 // undefined behavior, so warn about it. This only handles the pattern
7817 // "*null", which is a very syntactic check.
7818 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts()))
7819 if (UO->getOpcode() == UO_Deref &&
7820 UO->getSubExpr()->IgnoreParenCasts()->
7821 isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
7822 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
7823 PD: S.PDiag(DiagID: diag::warn_binding_null_to_reference)
7824 << UO->getSubExpr()->getSourceRange());
7825 }
7826}
7827
7828MaterializeTemporaryExpr *
7829Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7830 bool BoundToLvalueReference) {
7831 auto MTE = new (Context)
7832 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7833
7834 // Order an ExprWithCleanups for lifetime marks.
7835 //
7836 // TODO: It'll be good to have a single place to check the access of the
7837 // destructor and generate ExprWithCleanups for various uses. Currently these
7838 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7839 // but there may be a chance to merge them.
7840 Cleanup.setExprNeedsCleanups(false);
7841 if (isInLifetimeExtendingContext())
7842 currentEvaluationContext().ForRangeLifetimeExtendTemps.push_back(Elt: MTE);
7843 return MTE;
7844}
7845
7846ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7847 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7848 // same rule, but C99 is broken without this behavior and so we treat the
7849 // change as applying to all C language modes.
7850 // FIXME: This means that AST consumers need to deal with "prvalues" that
7851 // denote materialized temporaries. Maybe we should add another ValueKind
7852 // for "xvalue pretending to be a prvalue" for C++98 support.
7853 if (!E->isPRValue() ||
7854 (!getLangOpts().CPlusPlus11 && getLangOpts().CPlusPlus))
7855 return E;
7856
7857 // C++1z [conv.rval]/1: T shall be a complete type.
7858 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7859 // If so, we should check for a non-abstract class type here too.
7860 QualType T = E->getType();
7861 if (RequireCompleteType(Loc: E->getExprLoc(), T, DiagID: diag::err_incomplete_type))
7862 return ExprError();
7863
7864 return CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: false);
7865}
7866
7867ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7868 ExprValueKind VK,
7869 CheckedConversionKind CCK) {
7870
7871 CastKind CK = CK_NoOp;
7872
7873 if (VK == VK_PRValue) {
7874 auto PointeeTy = Ty->getPointeeType();
7875 auto ExprPointeeTy = E->getType()->getPointeeType();
7876 if (!PointeeTy.isNull() &&
7877 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7878 CK = CK_AddressSpaceConversion;
7879 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7880 CK = CK_AddressSpaceConversion;
7881 }
7882
7883 return ImpCastExprToType(E, Type: Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7884}
7885
7886ExprResult InitializationSequence::Perform(Sema &S,
7887 const InitializedEntity &Entity,
7888 const InitializationKind &Kind,
7889 MultiExprArg Args,
7890 QualType *ResultType) {
7891 if (Failed()) {
7892 Diagnose(S, Entity, Kind, Args);
7893 return ExprError();
7894 }
7895 if (!ZeroInitializationFixit.empty()) {
7896 const Decl *D = Entity.getDecl();
7897 const auto *VD = dyn_cast_or_null<VarDecl>(Val: D);
7898 QualType DestType = Entity.getType();
7899
7900 // The initialization would have succeeded with this fixit. Since the fixit
7901 // is on the error, we need to build a valid AST in this case, so this isn't
7902 // handled in the Failed() branch above.
7903 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7904 // Use a more useful diagnostic for constexpr variables.
7905 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
7906 << VD
7907 << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc,
7908 Code: ZeroInitializationFixit);
7909 } else {
7910 unsigned DiagID = diag::err_default_init_const;
7911 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7912 DiagID = diag::ext_default_init_const;
7913
7914 S.Diag(Loc: Kind.getLocation(), DiagID)
7915 << DestType << DestType->isRecordType()
7916 << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc,
7917 Code: ZeroInitializationFixit);
7918 }
7919 }
7920
7921 if (getKind() == DependentSequence) {
7922 // If the declaration is a non-dependent, incomplete array type
7923 // that has an initializer, then its type will be completed once
7924 // the initializer is instantiated.
7925 if (ResultType && !Entity.getType()->isDependentType() &&
7926 Args.size() == 1) {
7927 QualType DeclType = Entity.getType();
7928 if (const IncompleteArrayType *ArrayT
7929 = S.Context.getAsIncompleteArrayType(T: DeclType)) {
7930 // FIXME: We don't currently have the ability to accurately
7931 // compute the length of an initializer list without
7932 // performing full type-checking of the initializer list
7933 // (since we have to determine where braces are implicitly
7934 // introduced and such). So, we fall back to making the array
7935 // type a dependently-sized array type with no specified
7936 // bound.
7937 if (isa<InitListExpr>(Val: (Expr *)Args[0]))
7938 *ResultType = S.Context.getDependentSizedArrayType(
7939 EltTy: ArrayT->getElementType(),
7940 /*NumElts=*/nullptr, ASM: ArrayT->getSizeModifier(),
7941 IndexTypeQuals: ArrayT->getIndexTypeCVRQualifiers());
7942 }
7943 }
7944 if (Kind.getKind() == InitializationKind::IK_Direct &&
7945 !Kind.isExplicitCast()) {
7946 // Rebuild the ParenListExpr.
7947 SourceRange ParenRange = Kind.getParenOrBraceRange();
7948 return S.ActOnParenListExpr(L: ParenRange.getBegin(), R: ParenRange.getEnd(),
7949 Val: Args);
7950 }
7951 assert(Kind.getKind() == InitializationKind::IK_Copy ||
7952 Kind.isExplicitCast() ||
7953 Kind.getKind() == InitializationKind::IK_DirectList);
7954 return ExprResult(Args[0]);
7955 }
7956
7957 // No steps means no initialization.
7958 if (Steps.empty())
7959 return ExprResult((Expr *)nullptr);
7960
7961 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
7962 Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) &&
7963 !Entity.isParamOrTemplateParamKind()) {
7964 // Produce a C++98 compatibility warning if we are initializing a reference
7965 // from an initializer list. For parameters, we produce a better warning
7966 // elsewhere.
7967 Expr *Init = Args[0];
7968 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::warn_cxx98_compat_reference_list_init)
7969 << Init->getSourceRange();
7970 }
7971
7972 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
7973 isa<PredefinedExpr>(Val: Args[0]) && Entity.getType()->isArrayType()) {
7974 // Produce a Microsoft compatibility warning when initializing from a
7975 // predefined expression since MSVC treats predefined expressions as string
7976 // literals.
7977 Expr *Init = Args[0];
7978 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::ext_init_from_predefined) << Init;
7979 }
7980
7981 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
7982 QualType ETy = Entity.getType();
7983 bool HasGlobalAS = ETy.hasAddressSpace() &&
7984 ETy.getAddressSpace() == LangAS::opencl_global;
7985
7986 if (S.getLangOpts().OpenCLVersion >= 200 &&
7987 ETy->isAtomicType() && !HasGlobalAS &&
7988 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
7989 S.Diag(Loc: Args[0]->getBeginLoc(), DiagID: diag::err_opencl_atomic_init)
7990 << 1
7991 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
7992 return ExprError();
7993 }
7994
7995 QualType DestType = Entity.getType().getNonReferenceType();
7996 // FIXME: Ugly hack around the fact that Entity.getType() is not
7997 // the same as Entity.getDecl()->getType() in cases involving type merging,
7998 // and we want latter when it makes sense.
7999 if (ResultType)
8000 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8001 Entity.getType();
8002
8003 ExprResult CurInit((Expr *)nullptr);
8004 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8005
8006 // HLSL allows vector/matrix initialization to function like list
8007 // initialization, but use the syntax of a C++-like constructor.
8008 bool IsHLSLVectorOrMatrixInit =
8009 S.getLangOpts().HLSL &&
8010 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8011 isa<InitListExpr>(Val: Args[0]);
8012 (void)IsHLSLVectorOrMatrixInit;
8013
8014 // For initialization steps that start with a single initializer,
8015 // grab the only argument out the Args and place it into the "current"
8016 // initializer.
8017 switch (Steps.front().Kind) {
8018 case SK_ResolveAddressOfOverloadedFunction:
8019 case SK_CastDerivedToBasePRValue:
8020 case SK_CastDerivedToBaseXValue:
8021 case SK_CastDerivedToBaseLValue:
8022 case SK_BindReference:
8023 case SK_BindReferenceToTemporary:
8024 case SK_FinalCopy:
8025 case SK_ExtraneousCopyToTemporary:
8026 case SK_UserConversion:
8027 case SK_QualificationConversionLValue:
8028 case SK_QualificationConversionXValue:
8029 case SK_QualificationConversionPRValue:
8030 case SK_FunctionReferenceConversion:
8031 case SK_AtomicConversion:
8032 case SK_ConversionSequence:
8033 case SK_ConversionSequenceNoNarrowing:
8034 case SK_ListInitialization:
8035 case SK_UnwrapInitList:
8036 case SK_RewrapInitList:
8037 case SK_CAssignment:
8038 case SK_StringInit:
8039 case SK_ObjCObjectConversion:
8040 case SK_ArrayLoopIndex:
8041 case SK_ArrayLoopInit:
8042 case SK_ArrayInit:
8043 case SK_GNUArrayInit:
8044 case SK_ParenthesizedArrayInit:
8045 case SK_PassByIndirectCopyRestore:
8046 case SK_PassByIndirectRestore:
8047 case SK_ProduceObjCObject:
8048 case SK_StdInitializerList:
8049 case SK_OCLSamplerInit:
8050 case SK_OCLZeroOpaqueType: {
8051 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8052 CurInit = Args[0];
8053 if (!CurInit.get()) return ExprError();
8054 break;
8055 }
8056
8057 case SK_ConstructorInitialization:
8058 case SK_ConstructorInitializationFromList:
8059 case SK_StdInitializerListConstructorCall:
8060 case SK_ZeroInitialization:
8061 case SK_ParenthesizedListInit:
8062 break;
8063 }
8064
8065 // Promote from an unevaluated context to an unevaluated list context in
8066 // C++11 list-initialization; we need to instantiate entities usable in
8067 // constant expressions here in order to perform narrowing checks =(
8068 EnterExpressionEvaluationContext Evaluated(
8069 S, EnterExpressionEvaluationContext::InitList,
8070 isa_and_nonnull<InitListExpr>(Val: CurInit.get()));
8071
8072 // C++ [class.abstract]p2:
8073 // no objects of an abstract class can be created except as subobjects
8074 // of a class derived from it
8075 auto checkAbstractType = [&](QualType T) -> bool {
8076 if (Entity.getKind() == InitializedEntity::EK_Base ||
8077 Entity.getKind() == InitializedEntity::EK_Delegating)
8078 return false;
8079 return S.RequireNonAbstractType(Loc: Kind.getLocation(), T,
8080 DiagID: diag::err_allocation_of_abstract_type);
8081 };
8082
8083 // Walk through the computed steps for the initialization sequence,
8084 // performing the specified conversions along the way.
8085 bool ConstructorInitRequiresZeroInit = false;
8086 for (step_iterator Step = step_begin(), StepEnd = step_end();
8087 Step != StepEnd; ++Step) {
8088 if (CurInit.isInvalid())
8089 return ExprError();
8090
8091 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8092
8093 switch (Step->Kind) {
8094 case SK_ResolveAddressOfOverloadedFunction:
8095 // Overload resolution determined which function invoke; update the
8096 // initializer to reflect that choice.
8097 S.CheckAddressOfMemberAccess(OvlExpr: CurInit.get(), FoundDecl: Step->Function.FoundDecl);
8098 if (S.DiagnoseUseOfDecl(D: Step->Function.FoundDecl, Locs: Kind.getLocation()))
8099 return ExprError();
8100 CurInit = S.FixOverloadedFunctionReference(CurInit,
8101 FoundDecl: Step->Function.FoundDecl,
8102 Fn: Step->Function.Function);
8103 // We might get back another placeholder expression if we resolved to a
8104 // builtin.
8105 if (!CurInit.isInvalid())
8106 CurInit = S.CheckPlaceholderExpr(E: CurInit.get());
8107 break;
8108
8109 case SK_CastDerivedToBasePRValue:
8110 case SK_CastDerivedToBaseXValue:
8111 case SK_CastDerivedToBaseLValue: {
8112 // We have a derived-to-base cast that produces either an rvalue or an
8113 // lvalue. Perform that cast.
8114
8115 CXXCastPath BasePath;
8116
8117 // Casts to inaccessible base classes are allowed with C-style casts.
8118 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8119 if (S.CheckDerivedToBaseConversion(
8120 Derived: SourceType, Base: Step->Type, Loc: CurInit.get()->getBeginLoc(),
8121 Range: CurInit.get()->getSourceRange(), BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
8122 return ExprError();
8123
8124 ExprValueKind VK =
8125 Step->Kind == SK_CastDerivedToBaseLValue
8126 ? VK_LValue
8127 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8128 : VK_PRValue);
8129 CurInit = ImplicitCastExpr::Create(Context: S.Context, T: Step->Type,
8130 Kind: CK_DerivedToBase, Operand: CurInit.get(),
8131 BasePath: &BasePath, Cat: VK, FPO: FPOptionsOverride());
8132 break;
8133 }
8134
8135 case SK_BindReference:
8136 // Reference binding does not have any corresponding ASTs.
8137
8138 // Check exception specifications
8139 if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType))
8140 return ExprError();
8141
8142 // We don't check for e.g. function pointers here, since address
8143 // availability checks should only occur when the function first decays
8144 // into a pointer or reference.
8145 if (CurInit.get()->getType()->isFunctionProtoType()) {
8146 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CurInit.get()->IgnoreParens())) {
8147 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) {
8148 if (!S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
8149 Loc: DRE->getBeginLoc()))
8150 return ExprError();
8151 }
8152 }
8153 }
8154
8155 CheckForNullPointerDereference(S, E: CurInit.get());
8156 break;
8157
8158 case SK_BindReferenceToTemporary: {
8159 // Make sure the "temporary" is actually an rvalue.
8160 assert(CurInit.get()->isPRValue() && "not a temporary");
8161
8162 // Check exception specifications
8163 if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType))
8164 return ExprError();
8165
8166 QualType MTETy = Step->Type;
8167
8168 // When this is an incomplete array type (such as when this is
8169 // initializing an array of unknown bounds from an init list), use THAT
8170 // type instead so that we propagate the array bounds.
8171 if (MTETy->isIncompleteArrayType() &&
8172 !CurInit.get()->getType()->isIncompleteArrayType() &&
8173 S.Context.hasSameType(
8174 T1: MTETy->getPointeeOrArrayElementType(),
8175 T2: CurInit.get()->getType()->getPointeeOrArrayElementType()))
8176 MTETy = CurInit.get()->getType();
8177
8178 // Materialize the temporary into memory.
8179 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8180 T: MTETy, Temporary: CurInit.get(), BoundToLvalueReference: Entity.getType()->isLValueReferenceType());
8181 CurInit = MTE;
8182
8183 // If we're extending this temporary to automatic storage duration -- we
8184 // need to register its cleanup during the full-expression's cleanups.
8185 if (MTE->getStorageDuration() == SD_Automatic &&
8186 MTE->getType().isDestructedType())
8187 S.Cleanup.setExprNeedsCleanups(true);
8188 break;
8189 }
8190
8191 case SK_FinalCopy:
8192 if (checkAbstractType(Step->Type))
8193 return ExprError();
8194
8195 // If the overall initialization is initializing a temporary, we already
8196 // bound our argument if it was necessary to do so. If not (if we're
8197 // ultimately initializing a non-temporary), our argument needs to be
8198 // bound since it's initializing a function parameter.
8199 // FIXME: This is a mess. Rationalize temporary destruction.
8200 if (!shouldBindAsTemporary(Entity))
8201 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8202 CurInit = CopyObject(S, T: Step->Type, Entity, CurInit,
8203 /*IsExtraneousCopy=*/false);
8204 break;
8205
8206 case SK_ExtraneousCopyToTemporary:
8207 CurInit = CopyObject(S, T: Step->Type, Entity, CurInit,
8208 /*IsExtraneousCopy=*/true);
8209 break;
8210
8211 case SK_UserConversion: {
8212 // We have a user-defined conversion that invokes either a constructor
8213 // or a conversion function.
8214 CastKind CastKind;
8215 FunctionDecl *Fn = Step->Function.Function;
8216 DeclAccessPair FoundFn = Step->Function.FoundDecl;
8217 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8218 bool CreatedObject = false;
8219 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
8220 // Build a call to the selected constructor.
8221 SmallVector<Expr*, 8> ConstructorArgs;
8222 SourceLocation Loc = CurInit.get()->getBeginLoc();
8223
8224 // Determine the arguments required to actually perform the constructor
8225 // call.
8226 Expr *Arg = CurInit.get();
8227 if (S.CompleteConstructorCall(Constructor, DeclInitType: Step->Type,
8228 ArgsPtr: MultiExprArg(&Arg, 1), Loc,
8229 ConvertedArgs&: ConstructorArgs))
8230 return ExprError();
8231
8232 // Build an expression that constructs a temporary.
8233 CurInit = S.BuildCXXConstructExpr(
8234 ConstructLoc: Loc, DeclInitType: Step->Type, FoundDecl: FoundFn, Constructor, Exprs: ConstructorArgs,
8235 HadMultipleCandidates,
8236 /*ListInit*/ IsListInitialization: false,
8237 /*StdInitListInit*/ IsStdInitListInitialization: false,
8238 /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
8239 if (CurInit.isInvalid())
8240 return ExprError();
8241
8242 S.CheckConstructorAccess(Loc: Kind.getLocation(), D: Constructor, FoundDecl: FoundFn,
8243 Entity);
8244 if (S.DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: Kind.getLocation()))
8245 return ExprError();
8246
8247 CastKind = CK_ConstructorConversion;
8248 CreatedObject = true;
8249 } else {
8250 // Build a call to the conversion function.
8251 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Val: Fn);
8252 S.CheckMemberOperatorAccess(Loc: Kind.getLocation(), ObjectExpr: CurInit.get(), ArgExpr: nullptr,
8253 FoundDecl: FoundFn);
8254 if (S.DiagnoseUseOfOverloadedDecl(D: Conversion, Loc: Kind.getLocation()))
8255 return ExprError();
8256
8257 CurInit = S.BuildCXXMemberCallExpr(Exp: CurInit.get(), FoundDecl: FoundFn, Method: Conversion,
8258 HadMultipleCandidates);
8259 if (CurInit.isInvalid())
8260 return ExprError();
8261
8262 CastKind = CK_UserDefinedConversion;
8263 CreatedObject = Conversion->getReturnType()->isRecordType();
8264 }
8265
8266 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8267 return ExprError();
8268
8269 CurInit = ImplicitCastExpr::Create(
8270 Context: S.Context, T: CurInit.get()->getType(), Kind: CastKind, Operand: CurInit.get(), BasePath: nullptr,
8271 Cat: CurInit.get()->getValueKind(), FPO: S.CurFPFeatureOverrides());
8272
8273 if (shouldBindAsTemporary(Entity))
8274 // The overall entity is temporary, so this expression should be
8275 // destroyed at the end of its full-expression.
8276 CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>());
8277 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8278 // The object outlasts the full-expression, but we need to prepare for
8279 // a destructor being run on it.
8280 // FIXME: It makes no sense to do this here. This should happen
8281 // regardless of how we initialized the entity.
8282 QualType T = CurInit.get()->getType();
8283 if (auto *Record = T->castAsCXXRecordDecl()) {
8284 CXXDestructorDecl *Destructor = S.LookupDestructor(Class: Record);
8285 S.CheckDestructorAccess(Loc: CurInit.get()->getBeginLoc(), Dtor: Destructor,
8286 PDiag: S.PDiag(DiagID: diag::err_access_dtor_temp) << T);
8287 S.MarkFunctionReferenced(Loc: CurInit.get()->getBeginLoc(), Func: Destructor);
8288 if (S.DiagnoseUseOfDecl(D: Destructor, Locs: CurInit.get()->getBeginLoc()))
8289 return ExprError();
8290 }
8291 }
8292 break;
8293 }
8294
8295 case SK_QualificationConversionLValue:
8296 case SK_QualificationConversionXValue:
8297 case SK_QualificationConversionPRValue: {
8298 // Perform a qualification conversion; these can never go wrong.
8299 ExprValueKind VK =
8300 Step->Kind == SK_QualificationConversionLValue
8301 ? VK_LValue
8302 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8303 : VK_PRValue);
8304 CurInit = S.PerformQualificationConversion(E: CurInit.get(), Ty: Step->Type, VK);
8305 break;
8306 }
8307
8308 case SK_FunctionReferenceConversion:
8309 assert(CurInit.get()->isLValue() &&
8310 "function reference should be lvalue");
8311 CurInit =
8312 S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, CK: CK_NoOp, VK: VK_LValue);
8313 break;
8314
8315 case SK_AtomicConversion: {
8316 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8317 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
8318 CK: CK_NonAtomicToAtomic, VK: VK_PRValue);
8319 break;
8320 }
8321
8322 case SK_ConversionSequence:
8323 case SK_ConversionSequenceNoNarrowing: {
8324 if (const auto *FromPtrType =
8325 CurInit.get()->getType()->getAs<PointerType>()) {
8326 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8327 if (FromPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
8328 !ToPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
8329 // Do not check static casts here because they are checked earlier
8330 // in Sema::ActOnCXXNamedCast()
8331 if (!Kind.isStaticCast()) {
8332 S.Diag(Loc: CurInit.get()->getExprLoc(),
8333 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
8334 << CurInit.get()->getSourceRange();
8335 }
8336 }
8337 }
8338 }
8339 Expr *Init = CurInit.get();
8340 CheckedConversionKind CCK =
8341 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8342 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8343 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8344 : CheckedConversionKind::Implicit;
8345 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8346 From: Init, ToType: Step->Type, ICS: *Step->ICS, Action: getAssignmentAction(Entity), CCK);
8347 if (CurInitExprRes.isInvalid())
8348 return ExprError();
8349
8350 S.DiscardMisalignedMemberAddress(T: Step->Type.getTypePtr(), E: Init);
8351
8352 CurInit = CurInitExprRes;
8353
8354 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
8355 S.getLangOpts().CPlusPlus)
8356 DiagnoseNarrowingInInitList(S, ICS: *Step->ICS, PreNarrowingType: SourceType, EntityType: Entity.getType(),
8357 PostInit: CurInit.get());
8358
8359 break;
8360 }
8361
8362 case SK_ListInitialization: {
8363 if (checkAbstractType(Step->Type))
8364 return ExprError();
8365
8366 InitListExpr *InitList = cast<InitListExpr>(Val: CurInit.get());
8367 // If we're not initializing the top-level entity, we need to create an
8368 // InitializeTemporary entity for our target type.
8369 QualType Ty = Step->Type;
8370 bool IsTemporary = !S.Context.hasSameType(T1: Entity.getType(), T2: Ty);
8371 InitializedEntity InitEntity =
8372 IsTemporary ? InitializedEntity::InitializeTemporary(Type: Ty) : Entity;
8373 InitListChecker PerformInitList(S, InitEntity,
8374 InitList, Ty, /*VerifyOnly=*/false,
8375 /*TreatUnavailableAsInvalid=*/false);
8376 if (PerformInitList.HadError())
8377 return ExprError();
8378
8379 // Hack: We must update *ResultType if available in order to set the
8380 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8381 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8382 if (ResultType &&
8383 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8384 if ((*ResultType)->isRValueReferenceType())
8385 Ty = S.Context.getRValueReferenceType(T: Ty);
8386 else if ((*ResultType)->isLValueReferenceType())
8387 Ty = S.Context.getLValueReferenceType(T: Ty,
8388 SpelledAsLValue: (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8389 *ResultType = Ty;
8390 }
8391
8392 InitListExpr *StructuredInitList =
8393 PerformInitList.getFullyStructuredList();
8394 CurInit = shouldBindAsTemporary(Entity: InitEntity)
8395 ? S.MaybeBindToTemporary(E: StructuredInitList)
8396 : StructuredInitList;
8397 break;
8398 }
8399
8400 case SK_ConstructorInitializationFromList: {
8401 if (checkAbstractType(Step->Type))
8402 return ExprError();
8403
8404 // When an initializer list is passed for a parameter of type "reference
8405 // to object", we don't get an EK_Temporary entity, but instead an
8406 // EK_Parameter entity with reference type.
8407 // FIXME: This is a hack. What we really should do is create a user
8408 // conversion step for this case, but this makes it considerably more
8409 // complicated. For now, this will do.
8410 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8411 Type: Entity.getType().getNonReferenceType());
8412 bool UseTemporary = Entity.getType()->isReferenceType();
8413 assert(Args.size() == 1 && "expected a single argument for list init");
8414 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
8415 S.Diag(Loc: InitList->getExprLoc(), DiagID: diag::warn_cxx98_compat_ctor_list_init)
8416 << InitList->getSourceRange();
8417 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8418 CurInit = PerformConstructorInitialization(S, Entity: UseTemporary ? TempEntity :
8419 Entity,
8420 Kind, Args: Arg, Step: *Step,
8421 ConstructorInitRequiresZeroInit,
8422 /*IsListInitialization*/true,
8423 /*IsStdInitListInit*/IsStdInitListInitialization: false,
8424 LBraceLoc: InitList->getLBraceLoc(),
8425 RBraceLoc: InitList->getRBraceLoc());
8426 break;
8427 }
8428
8429 case SK_UnwrapInitList:
8430 CurInit = cast<InitListExpr>(Val: CurInit.get())->getInit(Init: 0);
8431 break;
8432
8433 case SK_RewrapInitList: {
8434 Expr *E = CurInit.get();
8435 InitListExpr *Syntactic = Step->WrappingSyntacticList;
8436 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8437 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8438 ILE->setSyntacticForm(Syntactic);
8439 ILE->setType(E->getType());
8440 ILE->setValueKind(E->getValueKind());
8441 CurInit = ILE;
8442 break;
8443 }
8444
8445 case SK_ConstructorInitialization:
8446 case SK_StdInitializerListConstructorCall: {
8447 if (checkAbstractType(Step->Type))
8448 return ExprError();
8449
8450 // When an initializer list is passed for a parameter of type "reference
8451 // to object", we don't get an EK_Temporary entity, but instead an
8452 // EK_Parameter entity with reference type.
8453 // FIXME: This is a hack. What we really should do is create a user
8454 // conversion step for this case, but this makes it considerably more
8455 // complicated. For now, this will do.
8456 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8457 Type: Entity.getType().getNonReferenceType());
8458 bool UseTemporary = Entity.getType()->isReferenceType();
8459 bool IsStdInitListInit =
8460 Step->Kind == SK_StdInitializerListConstructorCall;
8461 Expr *Source = CurInit.get();
8462 SourceRange Range = Kind.hasParenOrBraceRange()
8463 ? Kind.getParenOrBraceRange()
8464 : SourceRange();
8465 CurInit = PerformConstructorInitialization(
8466 S, Entity: UseTemporary ? TempEntity : Entity, Kind,
8467 Args: Source ? MultiExprArg(Source) : Args, Step: *Step,
8468 ConstructorInitRequiresZeroInit,
8469 /*IsListInitialization*/ IsStdInitListInit,
8470 /*IsStdInitListInitialization*/ IsStdInitListInit,
8471 /*LBraceLoc*/ Range.getBegin(),
8472 /*RBraceLoc*/ Range.getEnd());
8473 break;
8474 }
8475
8476 case SK_ZeroInitialization: {
8477 step_iterator NextStep = Step;
8478 ++NextStep;
8479 if (NextStep != StepEnd &&
8480 (NextStep->Kind == SK_ConstructorInitialization ||
8481 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8482 // The need for zero-initialization is recorded directly into
8483 // the call to the object's constructor within the next step.
8484 ConstructorInitRequiresZeroInit = true;
8485 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8486 S.getLangOpts().CPlusPlus &&
8487 !Kind.isImplicitValueInit()) {
8488 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8489 if (!TSInfo)
8490 TSInfo = S.Context.getTrivialTypeSourceInfo(T: Step->Type,
8491 Loc: Kind.getRange().getBegin());
8492
8493 CurInit = new (S.Context) CXXScalarValueInitExpr(
8494 Entity.getType().getNonLValueExprType(Context: S.Context), TSInfo,
8495 Kind.getRange().getEnd());
8496 } else {
8497 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8498 // Note the return value isn't used to return a ExprError() when
8499 // initialization fails . For struct initialization allows all field
8500 // assignments to be checked rather than bailing on the first error.
8501 S.BoundsSafetyCheckInitialization(Entity, Kind,
8502 Action: AssignmentAction::Initializing,
8503 LHSType: Step->Type, RHSExpr: CurInit.get());
8504 }
8505 break;
8506 }
8507
8508 case SK_CAssignment: {
8509 QualType SourceType = CurInit.get()->getType();
8510 Expr *Init = CurInit.get();
8511
8512 // Save off the initial CurInit in case we need to emit a diagnostic
8513 ExprResult InitialCurInit = Init;
8514 ExprResult Result = Init;
8515 AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints(
8516 LHSType: Step->Type, RHS&: Result, Diagnose: true,
8517 DiagnoseCFAudited: Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
8518 if (Result.isInvalid())
8519 return ExprError();
8520 CurInit = Result;
8521
8522 // If this is a call, allow conversion to a transparent union.
8523 ExprResult CurInitExprRes = CurInit;
8524 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8525 S.CheckTransparentUnionArgumentConstraints(
8526 ArgType: Step->Type, RHS&: CurInitExprRes) == AssignConvertType::Compatible)
8527 ConvTy = AssignConvertType::Compatible;
8528 if (CurInitExprRes.isInvalid())
8529 return ExprError();
8530 CurInit = CurInitExprRes;
8531
8532 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8533 CheckC23ConstexprInitConversion(S, FromType: SourceType, ToType: Entity.getType(),
8534 Init: CurInit.get());
8535
8536 // C23 6.7.1p6: If an object or subobject declared with storage-class
8537 // specifier constexpr has pointer, integer, or arithmetic type, any
8538 // explicit initializer value for it shall be null, an integer
8539 // constant expression, or an arithmetic constant expression,
8540 // respectively.
8541 Expr::EvalResult ER;
8542 if (Entity.getType()->getAs<PointerType>() &&
8543 CurInit.get()->EvaluateAsRValue(Result&: ER, Ctx: S.Context) &&
8544 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8545 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_c23_constexpr_pointer_not_null);
8546 return ExprError();
8547 }
8548 }
8549
8550 // Note the return value isn't used to return a ExprError() when
8551 // initialization fails. For struct initialization this allows all field
8552 // assignments to be checked rather than bailing on the first error.
8553 S.BoundsSafetyCheckInitialization(Entity, Kind,
8554 Action: getAssignmentAction(Entity, Diagnose: true),
8555 LHSType: Step->Type, RHSExpr: InitialCurInit.get());
8556
8557 bool Complained;
8558 if (S.DiagnoseAssignmentResult(ConvTy, Loc: Kind.getLocation(),
8559 DstType: Step->Type, SrcType: SourceType,
8560 SrcExpr: InitialCurInit.get(),
8561 Action: getAssignmentAction(Entity, Diagnose: true),
8562 Complained: &Complained)) {
8563 PrintInitLocationNote(S, Entity);
8564 return ExprError();
8565 } else if (Complained)
8566 PrintInitLocationNote(S, Entity);
8567 break;
8568 }
8569
8570 case SK_StringInit: {
8571 QualType Ty = Step->Type;
8572 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8573 CheckStringInit(Str: CurInit.get(), DeclT&: UpdateType ? *ResultType : Ty,
8574 AT: S.Context.getAsArrayType(T: Ty), S, Entity,
8575 CheckC23ConstexprInit: S.getLangOpts().C23 &&
8576 initializingConstexprVariable(Entity));
8577 break;
8578 }
8579
8580 case SK_ObjCObjectConversion:
8581 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
8582 CK: CK_ObjCObjectLValueCast,
8583 VK: CurInit.get()->getValueKind());
8584 break;
8585
8586 case SK_ArrayLoopIndex: {
8587 Expr *Cur = CurInit.get();
8588 Expr *BaseExpr = new (S.Context)
8589 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8590 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8591 Expr *IndexExpr =
8592 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8593 CurInit = S.CreateBuiltinArraySubscriptExpr(
8594 Base: BaseExpr, LLoc: Kind.getLocation(), Idx: IndexExpr, RLoc: Kind.getLocation());
8595 ArrayLoopCommonExprs.push_back(Elt: BaseExpr);
8596 break;
8597 }
8598
8599 case SK_ArrayLoopInit: {
8600 assert(!ArrayLoopCommonExprs.empty() &&
8601 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8602 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8603 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8604 CurInit.get());
8605 break;
8606 }
8607
8608 case SK_GNUArrayInit:
8609 // Okay: we checked everything before creating this step. Note that
8610 // this is a GNU extension.
8611 S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_copy)
8612 << Step->Type << CurInit.get()->getType()
8613 << CurInit.get()->getSourceRange();
8614 updateGNUCompoundLiteralRValue(E: CurInit.get());
8615 [[fallthrough]];
8616 case SK_ArrayInit:
8617 // If the destination type is an incomplete array type, update the
8618 // type accordingly.
8619 if (ResultType) {
8620 if (const IncompleteArrayType *IncompleteDest
8621 = S.Context.getAsIncompleteArrayType(T: Step->Type)) {
8622 if (const ConstantArrayType *ConstantSource
8623 = S.Context.getAsConstantArrayType(T: CurInit.get()->getType())) {
8624 *ResultType = S.Context.getConstantArrayType(
8625 EltTy: IncompleteDest->getElementType(), ArySize: ConstantSource->getSize(),
8626 SizeExpr: ConstantSource->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
8627 }
8628 }
8629 }
8630 break;
8631
8632 case SK_ParenthesizedArrayInit:
8633 // Okay: we checked everything before creating this step. Note that
8634 // this is a GNU extension.
8635 S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_parens)
8636 << CurInit.get()->getSourceRange();
8637 break;
8638
8639 case SK_PassByIndirectCopyRestore:
8640 case SK_PassByIndirectRestore:
8641 checkIndirectCopyRestoreSource(S, src: CurInit.get());
8642 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8643 CurInit.get(), Step->Type,
8644 Step->Kind == SK_PassByIndirectCopyRestore);
8645 break;
8646
8647 case SK_ProduceObjCObject:
8648 CurInit = ImplicitCastExpr::Create(
8649 Context: S.Context, T: Step->Type, Kind: CK_ARCProduceObject, Operand: CurInit.get(), BasePath: nullptr,
8650 Cat: VK_PRValue, FPO: FPOptionsOverride());
8651 break;
8652
8653 case SK_StdInitializerList: {
8654 S.Diag(Loc: CurInit.get()->getExprLoc(),
8655 DiagID: diag::warn_cxx98_compat_initializer_list_init)
8656 << CurInit.get()->getSourceRange();
8657
8658 // Materialize the temporary into memory.
8659 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8660 T: CurInit.get()->getType(), Temporary: CurInit.get(),
8661 /*BoundToLvalueReference=*/false);
8662
8663 // Wrap it in a construction of a std::initializer_list<T>.
8664 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8665
8666 if (!Step->Type->isDependentType()) {
8667 QualType ElementType;
8668 [[maybe_unused]] bool IsStdInitializerList =
8669 S.isStdInitializerList(Ty: Step->Type, Element: &ElementType);
8670 assert(IsStdInitializerList &&
8671 "StdInitializerList step to non-std::initializer_list");
8672 const auto *Record = Step->Type->castAsCXXRecordDecl();
8673 assert(Record->isCompleteDefinition() &&
8674 "std::initializer_list should have already be "
8675 "complete/instantiated by this point");
8676
8677 auto InvalidType = [&] {
8678 S.Diag(Loc: Record->getLocation(),
8679 DiagID: diag::err_std_initializer_list_malformed)
8680 << Step->Type.getUnqualifiedType();
8681 return ExprError();
8682 };
8683
8684 if (Record->isUnion() || Record->getNumBases() != 0 ||
8685 Record->isPolymorphic())
8686 return InvalidType();
8687
8688 RecordDecl::field_iterator Field = Record->field_begin();
8689 if (Field == Record->field_end())
8690 return InvalidType();
8691
8692 // Start pointer
8693 if (!Field->getType()->isPointerType() ||
8694 !S.Context.hasSameType(T1: Field->getType()->getPointeeType(),
8695 T2: ElementType.withConst()))
8696 return InvalidType();
8697
8698 if (++Field == Record->field_end())
8699 return InvalidType();
8700
8701 // Size or end pointer
8702 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8703 if (!S.Context.hasSameType(T1: PT->getPointeeType(),
8704 T2: ElementType.withConst()))
8705 return InvalidType();
8706 } else {
8707 if (Field->isBitField() ||
8708 !S.Context.hasSameType(T1: Field->getType(), T2: S.Context.getSizeType()))
8709 return InvalidType();
8710 }
8711
8712 if (++Field != Record->field_end())
8713 return InvalidType();
8714 }
8715
8716 // Bind the result, in case the library has given initializer_list a
8717 // non-trivial destructor.
8718 if (shouldBindAsTemporary(Entity))
8719 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8720 break;
8721 }
8722
8723 case SK_OCLSamplerInit: {
8724 // Sampler initialization have 5 cases:
8725 // 1. function argument passing
8726 // 1a. argument is a file-scope variable
8727 // 1b. argument is a function-scope variable
8728 // 1c. argument is one of caller function's parameters
8729 // 2. variable initialization
8730 // 2a. initializing a file-scope variable
8731 // 2b. initializing a function-scope variable
8732 //
8733 // For file-scope variables, since they cannot be initialized by function
8734 // call of __translate_sampler_initializer in LLVM IR, their references
8735 // need to be replaced by a cast from their literal initializers to
8736 // sampler type. Since sampler variables can only be used in function
8737 // calls as arguments, we only need to replace them when handling the
8738 // argument passing.
8739 assert(Step->Type->isSamplerT() &&
8740 "Sampler initialization on non-sampler type.");
8741 Expr *Init = CurInit.get()->IgnoreParens();
8742 QualType SourceType = Init->getType();
8743 // Case 1
8744 if (Entity.isParameterKind()) {
8745 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8746 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_argument_required)
8747 << SourceType;
8748 break;
8749 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Init)) {
8750 auto Var = cast<VarDecl>(Val: DRE->getDecl());
8751 // Case 1b and 1c
8752 // No cast from integer to sampler is needed.
8753 if (!Var->hasGlobalStorage()) {
8754 CurInit = ImplicitCastExpr::Create(
8755 Context: S.Context, T: Step->Type, Kind: CK_LValueToRValue, Operand: Init,
8756 /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
8757 break;
8758 }
8759 // Case 1a
8760 // For function call with a file-scope sampler variable as argument,
8761 // get the integer literal.
8762 // Do not diagnose if the file-scope variable does not have initializer
8763 // since this has already been diagnosed when parsing the variable
8764 // declaration.
8765 if (!Var->getInit() || !isa<ImplicitCastExpr>(Val: Var->getInit()))
8766 break;
8767 Init = cast<ImplicitCastExpr>(Val: const_cast<Expr*>(
8768 Var->getInit()))->getSubExpr();
8769 SourceType = Init->getType();
8770 }
8771 } else {
8772 // Case 2
8773 // Check initializer is 32 bit integer constant.
8774 // If the initializer is taken from global variable, do not diagnose since
8775 // this has already been done when parsing the variable declaration.
8776 if (!Init->isConstantInitializer(Ctx&: S.Context, ForRef: false))
8777 break;
8778
8779 if (!SourceType->isIntegerType() ||
8780 32 != S.Context.getIntWidth(T: SourceType)) {
8781 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_initializer_not_integer)
8782 << SourceType;
8783 break;
8784 }
8785
8786 Expr::EvalResult EVResult;
8787 Init->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
8788 llvm::APSInt Result = EVResult.Val.getInt();
8789 const uint64_t SamplerValue = Result.getLimitedValue();
8790 // 32-bit value of sampler's initializer is interpreted as
8791 // bit-field with the following structure:
8792 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8793 // |31 6|5 4|3 1| 0|
8794 // This structure corresponds to enum values of sampler properties
8795 // defined in SPIR spec v1.2 and also opencl-c.h
8796 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8797 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8798 if (FilterMode != 1 && FilterMode != 2 &&
8799 !S.getOpenCLOptions().isAvailableOption(
8800 Ext: "cl_intel_device_side_avc_motion_estimation", LO: S.getLangOpts()))
8801 S.Diag(Loc: Kind.getLocation(),
8802 DiagID: diag::warn_sampler_initializer_invalid_bits)
8803 << "Filter Mode";
8804 if (AddressingMode > 4)
8805 S.Diag(Loc: Kind.getLocation(),
8806 DiagID: diag::warn_sampler_initializer_invalid_bits)
8807 << "Addressing Mode";
8808 }
8809
8810 // Cases 1a, 2a and 2b
8811 // Insert cast from integer to sampler.
8812 CurInit = S.ImpCastExprToType(E: Init, Type: S.Context.OCLSamplerTy,
8813 CK: CK_IntToOCLSampler);
8814 break;
8815 }
8816 case SK_OCLZeroOpaqueType: {
8817 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8818 Step->Type->isOCLIntelSubgroupAVCType()) &&
8819 "Wrong type for initialization of OpenCL opaque type.");
8820
8821 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
8822 CK: CK_ZeroToOCLOpaqueType,
8823 VK: CurInit.get()->getValueKind());
8824 break;
8825 }
8826 case SK_ParenthesizedListInit: {
8827 CurInit = nullptr;
8828 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
8829 /*VerifyOnly=*/false, Result: &CurInit);
8830 if (CurInit.get() && ResultType)
8831 *ResultType = CurInit.get()->getType();
8832 if (shouldBindAsTemporary(Entity))
8833 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8834 break;
8835 }
8836 }
8837 }
8838
8839 Expr *Init = CurInit.get();
8840 if (!Init)
8841 return ExprError();
8842
8843 // Check whether the initializer has a shorter lifetime than the initialized
8844 // entity, and if not, either lifetime-extend or warn as appropriate.
8845 S.checkInitializerLifetime(Entity, Init);
8846
8847 // Diagnose non-fatal problems with the completed initialization.
8848 if (InitializedEntity::EntityKind EK = Entity.getKind();
8849 (EK == InitializedEntity::EK_Member ||
8850 EK == InitializedEntity::EK_ParenAggInitMember) &&
8851 cast<FieldDecl>(Val: Entity.getDecl())->isBitField())
8852 S.CheckBitFieldInitialization(InitLoc: Kind.getLocation(),
8853 Field: cast<FieldDecl>(Val: Entity.getDecl()), Init);
8854
8855 // Check for std::move on construction.
8856 CheckMoveOnConstruction(S, InitExpr: Init,
8857 IsReturnStmt: Entity.getKind() == InitializedEntity::EK_Result);
8858
8859 return Init;
8860}
8861
8862/// Somewhere within T there is an uninitialized reference subobject.
8863/// Dig it out and diagnose it.
8864static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8865 QualType T) {
8866 if (T->isReferenceType()) {
8867 S.Diag(Loc, DiagID: diag::err_reference_without_init)
8868 << T.getNonReferenceType();
8869 return true;
8870 }
8871
8872 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8873 if (!RD || !RD->hasUninitializedReferenceMember())
8874 return false;
8875
8876 for (const auto *FI : RD->fields()) {
8877 if (FI->isUnnamedBitField())
8878 continue;
8879
8880 if (DiagnoseUninitializedReference(S, Loc: FI->getLocation(), T: FI->getType())) {
8881 S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD;
8882 return true;
8883 }
8884 }
8885
8886 for (const auto &BI : RD->bases()) {
8887 if (DiagnoseUninitializedReference(S, Loc: BI.getBeginLoc(), T: BI.getType())) {
8888 S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD;
8889 return true;
8890 }
8891 }
8892
8893 return false;
8894}
8895
8896
8897//===----------------------------------------------------------------------===//
8898// Diagnose initialization failures
8899//===----------------------------------------------------------------------===//
8900
8901/// Emit notes associated with an initialization that failed due to a
8902/// "simple" conversion failure.
8903static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8904 Expr *op) {
8905 QualType destType = entity.getType();
8906 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8907 op->getType()->isObjCObjectPointerType()) {
8908
8909 // Emit a possible note about the conversion failing because the
8910 // operand is a message send with a related result type.
8911 S.ObjC().EmitRelatedResultTypeNote(E: op);
8912
8913 // Emit a possible note about a return failing because we're
8914 // expecting a related result type.
8915 if (entity.getKind() == InitializedEntity::EK_Result)
8916 S.ObjC().EmitRelatedResultTypeNoteForReturn(destType);
8917 }
8918 QualType fromType = op->getType();
8919 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8920 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8921 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8922 auto *destDecl = destType->getPointeeCXXRecordDecl();
8923 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8924 destDecl->getDeclKind() == Decl::CXXRecord &&
8925 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8926 !fromDecl->hasDefinition() &&
8927 destPointeeType.getQualifiers().compatiblyIncludes(
8928 other: fromPointeeType.getQualifiers(), Ctx: S.getASTContext()))
8929 S.Diag(Loc: fromDecl->getLocation(), DiagID: diag::note_forward_class_conversion)
8930 << S.getASTContext().getCanonicalTagType(TD: fromDecl)
8931 << S.getASTContext().getCanonicalTagType(TD: destDecl);
8932}
8933
8934static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8935 InitListExpr *InitList) {
8936 QualType DestType = Entity.getType();
8937
8938 QualType E;
8939 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(Ty: DestType, Element: &E)) {
8940 QualType ArrayType = S.Context.getConstantArrayType(
8941 EltTy: E.withConst(),
8942 ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()),
8943 InitList->getNumInits()),
8944 SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0);
8945 InitializedEntity HiddenArray =
8946 InitializedEntity::InitializeTemporary(Type: ArrayType);
8947 return diagnoseListInit(S, Entity: HiddenArray, InitList);
8948 }
8949
8950 if (DestType->isReferenceType()) {
8951 // A list-initialization failure for a reference means that we tried to
8952 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
8953 // inner initialization failed.
8954 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
8955 diagnoseListInit(S, Entity: InitializedEntity::InitializeTemporary(Type: T), InitList);
8956 SourceLocation Loc = InitList->getBeginLoc();
8957 if (auto *D = Entity.getDecl())
8958 Loc = D->getLocation();
8959 S.Diag(Loc, DiagID: diag::note_in_reference_temporary_list_initializer) << T;
8960 return;
8961 }
8962
8963 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
8964 /*VerifyOnly=*/false,
8965 /*TreatUnavailableAsInvalid=*/false);
8966 assert(DiagnoseInitList.HadError() &&
8967 "Inconsistent init list check result.");
8968}
8969
8970bool InitializationSequence::Diagnose(Sema &S,
8971 const InitializedEntity &Entity,
8972 const InitializationKind &Kind,
8973 ArrayRef<Expr *> Args) {
8974 if (!Failed())
8975 return false;
8976
8977 QualType DestType = Entity.getType();
8978
8979 // When we want to diagnose only one element of a braced-init-list,
8980 // we need to factor it out.
8981 Expr *OnlyArg;
8982 if (Args.size() == 1) {
8983 auto *List = dyn_cast<InitListExpr>(Val: Args[0]);
8984 if (List && List->getNumInits() == 1)
8985 OnlyArg = List->getInit(Init: 0);
8986 else
8987 OnlyArg = Args[0];
8988
8989 if (OnlyArg->getType() == S.Context.OverloadTy) {
8990 DeclAccessPair Found;
8991 if (FunctionDecl *FD = S.ResolveAddressOfOverloadedFunction(
8992 AddressOfExpr: OnlyArg, TargetType: DestType.getNonReferenceType(), /*Complain=*/false,
8993 Found)) {
8994 if (Expr *Resolved =
8995 S.FixOverloadedFunctionReference(E: OnlyArg, FoundDecl: Found, Fn: FD).get())
8996 OnlyArg = Resolved;
8997 }
8998 }
8999 }
9000 else
9001 OnlyArg = nullptr;
9002
9003 switch (Failure) {
9004 case FK_TooManyInitsForReference:
9005 // FIXME: Customize for the initialized entity?
9006 if (Args.empty()) {
9007 // Dig out the reference subobject which is uninitialized and diagnose it.
9008 // If this is value-initialization, this could be nested some way within
9009 // the target type.
9010 assert(Kind.getKind() == InitializationKind::IK_Value ||
9011 DestType->isReferenceType());
9012 bool Diagnosed =
9013 DiagnoseUninitializedReference(S, Loc: Kind.getLocation(), T: DestType);
9014 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9015 (void)Diagnosed;
9016 } else // FIXME: diagnostic below could be better!
9017 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_has_multiple_inits)
9018 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9019 break;
9020 case FK_ParenthesizedListInitForReference:
9021 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens)
9022 << 1 << Entity.getType() << Args[0]->getSourceRange();
9023 break;
9024
9025 case FK_ArrayNeedsInitList:
9026 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 0;
9027 break;
9028 case FK_ArrayNeedsInitListOrStringLiteral:
9029 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 1;
9030 break;
9031 case FK_ArrayNeedsInitListOrWideStringLiteral:
9032 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 2;
9033 break;
9034 case FK_NarrowStringIntoWideCharArray:
9035 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_narrow_string_into_wchar);
9036 break;
9037 case FK_WideStringIntoCharArray:
9038 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_wide_string_into_char);
9039 break;
9040 case FK_IncompatWideStringIntoWideChar:
9041 S.Diag(Loc: Kind.getLocation(),
9042 DiagID: diag::err_array_init_incompat_wide_string_into_wchar);
9043 break;
9044 case FK_PlainStringIntoUTF8Char:
9045 S.Diag(Loc: Kind.getLocation(),
9046 DiagID: diag::err_array_init_plain_string_into_char8_t);
9047 S.Diag(Loc: Args.front()->getBeginLoc(),
9048 DiagID: diag::note_array_init_plain_string_into_char8_t)
9049 << FixItHint::CreateInsertion(InsertionLoc: Args.front()->getBeginLoc(), Code: "u8");
9050 break;
9051 case FK_UTF8StringIntoPlainChar:
9052 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_utf8_string_into_char)
9053 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9054 break;
9055 case FK_ArrayTypeMismatch:
9056 case FK_NonConstantArrayInit:
9057 S.Diag(Loc: Kind.getLocation(),
9058 DiagID: (Failure == FK_ArrayTypeMismatch
9059 ? diag::err_array_init_different_type
9060 : diag::err_array_init_non_constant_array))
9061 << DestType.getNonReferenceType()
9062 << OnlyArg->getType()
9063 << Args[0]->getSourceRange();
9064 break;
9065
9066 case FK_VariableLengthArrayHasInitializer:
9067 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_variable_object_no_init)
9068 << Args[0]->getSourceRange();
9069 break;
9070
9071 case FK_AddressOfOverloadFailed: {
9072 DeclAccessPair Found;
9073 S.ResolveAddressOfOverloadedFunction(AddressOfExpr: OnlyArg,
9074 TargetType: DestType.getNonReferenceType(),
9075 Complain: true,
9076 Found);
9077 break;
9078 }
9079
9080 case FK_AddressOfUnaddressableFunction: {
9081 auto *FD = cast<FunctionDecl>(Val: cast<DeclRefExpr>(Val: OnlyArg)->getDecl());
9082 S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
9083 Loc: OnlyArg->getBeginLoc());
9084 break;
9085 }
9086
9087 case FK_ReferenceInitOverloadFailed:
9088 case FK_UserConversionOverloadFailed:
9089 switch (FailedOverloadResult) {
9090 case OR_Ambiguous:
9091
9092 FailedCandidateSet.NoteCandidates(
9093 PA: PartialDiagnosticAt(
9094 Kind.getLocation(),
9095 Failure == FK_UserConversionOverloadFailed
9096 ? (S.PDiag(DiagID: diag::err_typecheck_ambiguous_condition)
9097 << OnlyArg->getType() << DestType
9098 << Args[0]->getSourceRange())
9099 : (S.PDiag(DiagID: diag::err_ref_init_ambiguous)
9100 << DestType << OnlyArg->getType()
9101 << Args[0]->getSourceRange())),
9102 S, OCD: OCD_AmbiguousCandidates, Args);
9103 break;
9104
9105 case OR_No_Viable_Function: {
9106 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args);
9107 if (!S.RequireCompleteType(Loc: Kind.getLocation(),
9108 T: DestType.getNonReferenceType(),
9109 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
9110 Args: OnlyArg->getType(), Args: Args[0]->getSourceRange()))
9111 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_nonviable_condition)
9112 << (Entity.getKind() == InitializedEntity::EK_Result)
9113 << OnlyArg->getType() << Args[0]->getSourceRange()
9114 << DestType.getNonReferenceType();
9115
9116 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9117 break;
9118 }
9119 case OR_Deleted: {
9120 OverloadCandidateSet::iterator Best;
9121 OverloadingResult Ovl
9122 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9123
9124 StringLiteral *Msg = Best->Function->getDeletedMessage();
9125 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_deleted_function)
9126 << OnlyArg->getType() << DestType.getNonReferenceType()
9127 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9128 << Args[0]->getSourceRange();
9129 if (Ovl == OR_Deleted) {
9130 S.NoteDeletedFunction(FD: Best->Function);
9131 } else {
9132 llvm_unreachable("Inconsistent overload resolution?");
9133 }
9134 break;
9135 }
9136
9137 case OR_Success:
9138 llvm_unreachable("Conversion did not fail!");
9139 }
9140 break;
9141
9142 case FK_NonConstLValueReferenceBindingToTemporary:
9143 if (isa<InitListExpr>(Val: Args[0])) {
9144 S.Diag(Loc: Kind.getLocation(),
9145 DiagID: diag::err_lvalue_reference_bind_to_initlist)
9146 << DestType.getNonReferenceType().isVolatileQualified()
9147 << DestType.getNonReferenceType()
9148 << Args[0]->getSourceRange();
9149 break;
9150 }
9151 [[fallthrough]];
9152
9153 case FK_NonConstLValueReferenceBindingToUnrelated:
9154 S.Diag(Loc: Kind.getLocation(),
9155 DiagID: Failure == FK_NonConstLValueReferenceBindingToTemporary
9156 ? diag::err_lvalue_reference_bind_to_temporary
9157 : diag::err_lvalue_reference_bind_to_unrelated)
9158 << DestType.getNonReferenceType().isVolatileQualified()
9159 << DestType.getNonReferenceType()
9160 << OnlyArg->getType()
9161 << Args[0]->getSourceRange();
9162 break;
9163
9164 case FK_NonConstLValueReferenceBindingToBitfield: {
9165 // We don't necessarily have an unambiguous source bit-field.
9166 FieldDecl *BitField = Args[0]->getSourceBitField();
9167 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_bitfield)
9168 << DestType.isVolatileQualified()
9169 << (BitField ? BitField->getDeclName() : DeclarationName())
9170 << (BitField != nullptr)
9171 << Args[0]->getSourceRange();
9172 if (BitField)
9173 S.Diag(Loc: BitField->getLocation(), DiagID: diag::note_bitfield_decl);
9174 break;
9175 }
9176
9177 case FK_NonConstLValueReferenceBindingToVectorElement:
9178 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_vector_element)
9179 << DestType.isVolatileQualified()
9180 << Args[0]->getSourceRange();
9181 break;
9182
9183 case FK_NonConstLValueReferenceBindingToMatrixElement:
9184 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_matrix_element)
9185 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9186 break;
9187
9188 case FK_RValueReferenceBindingToLValue:
9189 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_lvalue_to_rvalue_ref)
9190 << DestType.getNonReferenceType() << OnlyArg->getType()
9191 << Args[0]->getSourceRange();
9192 break;
9193
9194 case FK_ReferenceAddrspaceMismatchTemporary:
9195 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_temporary_addrspace)
9196 << DestType << Args[0]->getSourceRange();
9197 break;
9198
9199 case FK_ReferenceInitDropsQualifiers: {
9200 QualType SourceType = OnlyArg->getType();
9201 QualType NonRefType = DestType.getNonReferenceType();
9202 Qualifiers DroppedQualifiers =
9203 SourceType.getQualifiers() - NonRefType.getQualifiers();
9204
9205 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9206 other: SourceType.getQualifiers(), Ctx: S.getASTContext()))
9207 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals)
9208 << NonRefType << SourceType << 1 /*addr space*/
9209 << Args[0]->getSourceRange();
9210 else if (DroppedQualifiers.hasQualifiers())
9211 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals)
9212 << NonRefType << SourceType << 0 /*cv quals*/
9213 << Qualifiers::fromCVRMask(CVR: DroppedQualifiers.getCVRQualifiers())
9214 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9215 else
9216 // FIXME: Consider decomposing the type and explaining which qualifiers
9217 // were dropped where, or on which level a 'const' is missing, etc.
9218 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals)
9219 << NonRefType << SourceType << 2 /*incompatible quals*/
9220 << Args[0]->getSourceRange();
9221 break;
9222 }
9223
9224 case FK_ReferenceInitFailed:
9225 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_failed)
9226 << DestType.getNonReferenceType()
9227 << DestType.getNonReferenceType()->isIncompleteType()
9228 << OnlyArg->isLValue()
9229 << OnlyArg->getType()
9230 << Args[0]->getSourceRange();
9231 emitBadConversionNotes(S, entity: Entity, op: Args[0]);
9232 break;
9233
9234 case FK_ConversionFailed: {
9235 QualType FromType = OnlyArg->getType();
9236 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::err_init_conversion_failed)
9237 << (int)Entity.getKind()
9238 << DestType
9239 << OnlyArg->isLValue()
9240 << FromType
9241 << Args[0]->getSourceRange();
9242 S.HandleFunctionTypeMismatch(PDiag, FromType, ToType: DestType);
9243 S.Diag(Loc: Kind.getLocation(), PD: PDiag);
9244 emitBadConversionNotes(S, entity: Entity, op: Args[0]);
9245 break;
9246 }
9247
9248 case FK_ConversionFromPropertyFailed:
9249 // No-op. This error has already been reported.
9250 break;
9251
9252 case FK_TooManyInitsForScalar: {
9253 SourceRange R;
9254
9255 auto *InitList = dyn_cast<InitListExpr>(Val: Args[0]);
9256 if (InitList && InitList->getNumInits() >= 1) {
9257 R = SourceRange(InitList->getInit(Init: 0)->getEndLoc(), InitList->getEndLoc());
9258 } else {
9259 assert(Args.size() > 1 && "Expected multiple initializers!");
9260 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9261 }
9262
9263 R.setBegin(S.getLocForEndOfToken(Loc: R.getBegin()));
9264 if (Kind.isCStyleOrFunctionalCast())
9265 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_builtin_func_cast_more_than_one_arg)
9266 << R;
9267 else
9268 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers)
9269 << /*scalar=*/3 << R;
9270 break;
9271 }
9272
9273 case FK_ParenthesizedListInitForScalar:
9274 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens)
9275 << 0 << Entity.getType() << Args[0]->getSourceRange();
9276 break;
9277
9278 case FK_ReferenceBindingToInitList:
9279 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_init_list)
9280 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9281 break;
9282
9283 case FK_InitListBadDestinationType:
9284 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_init_list_bad_dest_type)
9285 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9286 break;
9287
9288 case FK_ListConstructorOverloadFailed:
9289 case FK_ConstructorOverloadFailed: {
9290 SourceRange ArgsRange;
9291 if (Args.size())
9292 ArgsRange =
9293 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9294
9295 if (Failure == FK_ListConstructorOverloadFailed) {
9296 assert(Args.size() == 1 &&
9297 "List construction from other than 1 argument.");
9298 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9299 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9300 }
9301
9302 // FIXME: Using "DestType" for the entity we're printing is probably
9303 // bad.
9304 switch (FailedOverloadResult) {
9305 case OR_Ambiguous:
9306 FailedCandidateSet.NoteCandidates(
9307 PA: PartialDiagnosticAt(Kind.getLocation(),
9308 S.PDiag(DiagID: diag::err_ovl_ambiguous_init)
9309 << DestType << ArgsRange),
9310 S, OCD: OCD_AmbiguousCandidates, Args);
9311 break;
9312
9313 case OR_No_Viable_Function:
9314 if (Kind.getKind() == InitializationKind::IK_Default &&
9315 (Entity.getKind() == InitializedEntity::EK_Base ||
9316 Entity.getKind() == InitializedEntity::EK_Member ||
9317 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9318 isa<CXXConstructorDecl>(Val: S.CurContext)) {
9319 // This is implicit default initialization of a member or
9320 // base within a constructor. If no viable function was
9321 // found, notify the user that they need to explicitly
9322 // initialize this base/member.
9323 CXXConstructorDecl *Constructor
9324 = cast<CXXConstructorDecl>(Val: S.CurContext);
9325 const CXXRecordDecl *InheritedFrom = nullptr;
9326 if (auto Inherited = Constructor->getInheritedConstructor())
9327 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9328 if (Entity.getKind() == InitializedEntity::EK_Base) {
9329 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor)
9330 << (InheritedFrom ? 2
9331 : Constructor->isImplicit() ? 1
9332 : 0)
9333 << S.Context.getCanonicalTagType(TD: Constructor->getParent())
9334 << /*base=*/0 << Entity.getType() << InheritedFrom;
9335
9336 auto *BaseDecl =
9337 Entity.getBaseSpecifier()->getType()->castAsRecordDecl();
9338 S.Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_previous_decl)
9339 << S.Context.getCanonicalTagType(TD: BaseDecl);
9340 } else {
9341 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor)
9342 << (InheritedFrom ? 2
9343 : Constructor->isImplicit() ? 1
9344 : 0)
9345 << S.Context.getCanonicalTagType(TD: Constructor->getParent())
9346 << /*member=*/1 << Entity.getName() << InheritedFrom;
9347 S.Diag(Loc: Entity.getDecl()->getLocation(),
9348 DiagID: diag::note_member_declared_at);
9349
9350 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9351 S.Diag(Loc: Record->getDecl()->getLocation(), DiagID: diag::note_previous_decl)
9352 << S.Context.getCanonicalTagType(TD: Record->getDecl());
9353 }
9354 break;
9355 }
9356
9357 FailedCandidateSet.NoteCandidates(
9358 PA: PartialDiagnosticAt(
9359 Kind.getLocation(),
9360 S.PDiag(DiagID: diag::err_ovl_no_viable_function_in_init)
9361 << DestType << ArgsRange),
9362 S, OCD: OCD_AllCandidates, Args);
9363 break;
9364
9365 case OR_Deleted: {
9366 OverloadCandidateSet::iterator Best;
9367 OverloadingResult Ovl
9368 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9369 if (Ovl != OR_Deleted) {
9370 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init)
9371 << DestType << ArgsRange;
9372 llvm_unreachable("Inconsistent overload resolution?");
9373 break;
9374 }
9375
9376 // If this is a defaulted or implicitly-declared function, then
9377 // it was implicitly deleted. Make it clear that the deletion was
9378 // implicit.
9379 if (S.isImplicitlyDeleted(FD: Best->Function))
9380 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_special_init)
9381 << S.getSpecialMember(MD: cast<CXXMethodDecl>(Val: Best->Function))
9382 << DestType << ArgsRange;
9383 else {
9384 StringLiteral *Msg = Best->Function->getDeletedMessage();
9385 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init)
9386 << DestType << (Msg != nullptr)
9387 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9388 }
9389
9390 // If it's a default constructed member, but it's not in the
9391 // constructor's initializer list, explicitly note where the member is
9392 // declared so the user can see which member is erroneously initialized
9393 // with a deleted default constructor.
9394 if (Kind.getKind() == InitializationKind::IK_Default &&
9395 (Entity.getKind() == InitializedEntity::EK_Member ||
9396 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember)) {
9397 S.Diag(Loc: Entity.getDecl()->getLocation(),
9398 DiagID: diag::note_default_constructed_field)
9399 << Entity.getDecl();
9400 }
9401 S.NoteDeletedFunction(FD: Best->Function);
9402 break;
9403 }
9404
9405 case OR_Success:
9406 llvm_unreachable("Conversion did not fail!");
9407 }
9408 }
9409 break;
9410
9411 case FK_DefaultInitOfConst:
9412 if (Entity.getKind() == InitializedEntity::EK_Member &&
9413 isa<CXXConstructorDecl>(Val: S.CurContext)) {
9414 // This is implicit default-initialization of a const member in
9415 // a constructor. Complain that it needs to be explicitly
9416 // initialized.
9417 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: S.CurContext);
9418 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_uninitialized_member_in_ctor)
9419 << (Constructor->getInheritedConstructor() ? 2
9420 : Constructor->isImplicit() ? 1
9421 : 0)
9422 << S.Context.getCanonicalTagType(TD: Constructor->getParent())
9423 << /*const=*/1 << Entity.getName();
9424 S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_previous_decl)
9425 << Entity.getName();
9426 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: Entity.getDecl());
9427 VD && VD->isConstexpr()) {
9428 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
9429 << VD;
9430 } else {
9431 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_default_init_const)
9432 << DestType << DestType->isRecordType();
9433 }
9434 break;
9435
9436 case FK_Incomplete:
9437 S.RequireCompleteType(Loc: Kind.getLocation(), T: FailedIncompleteType,
9438 DiagID: diag::err_init_incomplete_type);
9439 break;
9440
9441 case FK_ListInitializationFailed: {
9442 // Run the init list checker again to emit diagnostics.
9443 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9444 diagnoseListInit(S, Entity, InitList);
9445 break;
9446 }
9447
9448 case FK_PlaceholderType: {
9449 // FIXME: Already diagnosed!
9450 break;
9451 }
9452
9453 case InitializationSequence::FK_HLSLInitListFlatteningFailed: {
9454 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9455 // allows us to diagnose the failure when it happens in the
9456 // TryListInitialization call instead of delaying the diagnosis, which is
9457 // beneficial because the flattening is also expensive.
9458 break;
9459 }
9460
9461 case FK_ExplicitConstructor: {
9462 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_selected_explicit_constructor)
9463 << Args[0]->getSourceRange();
9464 OverloadCandidateSet::iterator Best;
9465 OverloadingResult Ovl
9466 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9467 (void)Ovl;
9468 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9469 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
9470 S.Diag(Loc: CtorDecl->getLocation(),
9471 DiagID: diag::note_explicit_ctor_deduction_guide_here) << false;
9472 break;
9473 }
9474
9475 case FK_ParenthesizedListInitFailed:
9476 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
9477 /*VerifyOnly=*/false);
9478 break;
9479
9480 case FK_DesignatedInitForNonAggregate:
9481 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9482 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_designated_init_for_non_aggregate)
9483 << Entity.getType() << InitList->getSourceRange();
9484 break;
9485 }
9486
9487 PrintInitLocationNote(S, Entity);
9488 return true;
9489}
9490
9491void InitializationSequence::dump(raw_ostream &OS) const {
9492 switch (SequenceKind) {
9493 case FailedSequence: {
9494 OS << "Failed sequence: ";
9495 switch (Failure) {
9496 case FK_TooManyInitsForReference:
9497 OS << "too many initializers for reference";
9498 break;
9499
9500 case FK_ParenthesizedListInitForReference:
9501 OS << "parenthesized list init for reference";
9502 break;
9503
9504 case FK_ArrayNeedsInitList:
9505 OS << "array requires initializer list";
9506 break;
9507
9508 case FK_AddressOfUnaddressableFunction:
9509 OS << "address of unaddressable function was taken";
9510 break;
9511
9512 case FK_ArrayNeedsInitListOrStringLiteral:
9513 OS << "array requires initializer list or string literal";
9514 break;
9515
9516 case FK_ArrayNeedsInitListOrWideStringLiteral:
9517 OS << "array requires initializer list or wide string literal";
9518 break;
9519
9520 case FK_NarrowStringIntoWideCharArray:
9521 OS << "narrow string into wide char array";
9522 break;
9523
9524 case FK_WideStringIntoCharArray:
9525 OS << "wide string into char array";
9526 break;
9527
9528 case FK_IncompatWideStringIntoWideChar:
9529 OS << "incompatible wide string into wide char array";
9530 break;
9531
9532 case FK_PlainStringIntoUTF8Char:
9533 OS << "plain string literal into char8_t array";
9534 break;
9535
9536 case FK_UTF8StringIntoPlainChar:
9537 OS << "u8 string literal into char array";
9538 break;
9539
9540 case FK_ArrayTypeMismatch:
9541 OS << "array type mismatch";
9542 break;
9543
9544 case FK_NonConstantArrayInit:
9545 OS << "non-constant array initializer";
9546 break;
9547
9548 case FK_AddressOfOverloadFailed:
9549 OS << "address of overloaded function failed";
9550 break;
9551
9552 case FK_ReferenceInitOverloadFailed:
9553 OS << "overload resolution for reference initialization failed";
9554 break;
9555
9556 case FK_NonConstLValueReferenceBindingToTemporary:
9557 OS << "non-const lvalue reference bound to temporary";
9558 break;
9559
9560 case FK_NonConstLValueReferenceBindingToBitfield:
9561 OS << "non-const lvalue reference bound to bit-field";
9562 break;
9563
9564 case FK_NonConstLValueReferenceBindingToVectorElement:
9565 OS << "non-const lvalue reference bound to vector element";
9566 break;
9567
9568 case FK_NonConstLValueReferenceBindingToMatrixElement:
9569 OS << "non-const lvalue reference bound to matrix element";
9570 break;
9571
9572 case FK_NonConstLValueReferenceBindingToUnrelated:
9573 OS << "non-const lvalue reference bound to unrelated type";
9574 break;
9575
9576 case FK_RValueReferenceBindingToLValue:
9577 OS << "rvalue reference bound to an lvalue";
9578 break;
9579
9580 case FK_ReferenceInitDropsQualifiers:
9581 OS << "reference initialization drops qualifiers";
9582 break;
9583
9584 case FK_ReferenceAddrspaceMismatchTemporary:
9585 OS << "reference with mismatching address space bound to temporary";
9586 break;
9587
9588 case FK_ReferenceInitFailed:
9589 OS << "reference initialization failed";
9590 break;
9591
9592 case FK_ConversionFailed:
9593 OS << "conversion failed";
9594 break;
9595
9596 case FK_ConversionFromPropertyFailed:
9597 OS << "conversion from property failed";
9598 break;
9599
9600 case FK_TooManyInitsForScalar:
9601 OS << "too many initializers for scalar";
9602 break;
9603
9604 case FK_ParenthesizedListInitForScalar:
9605 OS << "parenthesized list init for reference";
9606 break;
9607
9608 case FK_ReferenceBindingToInitList:
9609 OS << "referencing binding to initializer list";
9610 break;
9611
9612 case FK_InitListBadDestinationType:
9613 OS << "initializer list for non-aggregate, non-scalar type";
9614 break;
9615
9616 case FK_UserConversionOverloadFailed:
9617 OS << "overloading failed for user-defined conversion";
9618 break;
9619
9620 case FK_ConstructorOverloadFailed:
9621 OS << "constructor overloading failed";
9622 break;
9623
9624 case FK_DefaultInitOfConst:
9625 OS << "default initialization of a const variable";
9626 break;
9627
9628 case FK_Incomplete:
9629 OS << "initialization of incomplete type";
9630 break;
9631
9632 case FK_ListInitializationFailed:
9633 OS << "list initialization checker failure";
9634 break;
9635
9636 case FK_VariableLengthArrayHasInitializer:
9637 OS << "variable length array has an initializer";
9638 break;
9639
9640 case FK_PlaceholderType:
9641 OS << "initializer expression isn't contextually valid";
9642 break;
9643
9644 case FK_ListConstructorOverloadFailed:
9645 OS << "list constructor overloading failed";
9646 break;
9647
9648 case FK_ExplicitConstructor:
9649 OS << "list copy initialization chose explicit constructor";
9650 break;
9651
9652 case FK_ParenthesizedListInitFailed:
9653 OS << "parenthesized list initialization failed";
9654 break;
9655
9656 case FK_DesignatedInitForNonAggregate:
9657 OS << "designated initializer for non-aggregate type";
9658 break;
9659
9660 case FK_HLSLInitListFlatteningFailed:
9661 OS << "HLSL initialization list flattening failed";
9662 break;
9663 }
9664 OS << '\n';
9665 return;
9666 }
9667
9668 case DependentSequence:
9669 OS << "Dependent sequence\n";
9670 return;
9671
9672 case NormalSequence:
9673 OS << "Normal sequence: ";
9674 break;
9675 }
9676
9677 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9678 if (S != step_begin()) {
9679 OS << " -> ";
9680 }
9681
9682 switch (S->Kind) {
9683 case SK_ResolveAddressOfOverloadedFunction:
9684 OS << "resolve address of overloaded function";
9685 break;
9686
9687 case SK_CastDerivedToBasePRValue:
9688 OS << "derived-to-base (prvalue)";
9689 break;
9690
9691 case SK_CastDerivedToBaseXValue:
9692 OS << "derived-to-base (xvalue)";
9693 break;
9694
9695 case SK_CastDerivedToBaseLValue:
9696 OS << "derived-to-base (lvalue)";
9697 break;
9698
9699 case SK_BindReference:
9700 OS << "bind reference to lvalue";
9701 break;
9702
9703 case SK_BindReferenceToTemporary:
9704 OS << "bind reference to a temporary";
9705 break;
9706
9707 case SK_FinalCopy:
9708 OS << "final copy in class direct-initialization";
9709 break;
9710
9711 case SK_ExtraneousCopyToTemporary:
9712 OS << "extraneous C++03 copy to temporary";
9713 break;
9714
9715 case SK_UserConversion:
9716 OS << "user-defined conversion via " << *S->Function.Function;
9717 break;
9718
9719 case SK_QualificationConversionPRValue:
9720 OS << "qualification conversion (prvalue)";
9721 break;
9722
9723 case SK_QualificationConversionXValue:
9724 OS << "qualification conversion (xvalue)";
9725 break;
9726
9727 case SK_QualificationConversionLValue:
9728 OS << "qualification conversion (lvalue)";
9729 break;
9730
9731 case SK_FunctionReferenceConversion:
9732 OS << "function reference conversion";
9733 break;
9734
9735 case SK_AtomicConversion:
9736 OS << "non-atomic-to-atomic conversion";
9737 break;
9738
9739 case SK_ConversionSequence:
9740 OS << "implicit conversion sequence (";
9741 S->ICS->dump(); // FIXME: use OS
9742 OS << ")";
9743 break;
9744
9745 case SK_ConversionSequenceNoNarrowing:
9746 OS << "implicit conversion sequence with narrowing prohibited (";
9747 S->ICS->dump(); // FIXME: use OS
9748 OS << ")";
9749 break;
9750
9751 case SK_ListInitialization:
9752 OS << "list aggregate initialization";
9753 break;
9754
9755 case SK_UnwrapInitList:
9756 OS << "unwrap reference initializer list";
9757 break;
9758
9759 case SK_RewrapInitList:
9760 OS << "rewrap reference initializer list";
9761 break;
9762
9763 case SK_ConstructorInitialization:
9764 OS << "constructor initialization";
9765 break;
9766
9767 case SK_ConstructorInitializationFromList:
9768 OS << "list initialization via constructor";
9769 break;
9770
9771 case SK_ZeroInitialization:
9772 OS << "zero initialization";
9773 break;
9774
9775 case SK_CAssignment:
9776 OS << "C assignment";
9777 break;
9778
9779 case SK_StringInit:
9780 OS << "string initialization";
9781 break;
9782
9783 case SK_ObjCObjectConversion:
9784 OS << "Objective-C object conversion";
9785 break;
9786
9787 case SK_ArrayLoopIndex:
9788 OS << "indexing for array initialization loop";
9789 break;
9790
9791 case SK_ArrayLoopInit:
9792 OS << "array initialization loop";
9793 break;
9794
9795 case SK_ArrayInit:
9796 OS << "array initialization";
9797 break;
9798
9799 case SK_GNUArrayInit:
9800 OS << "array initialization (GNU extension)";
9801 break;
9802
9803 case SK_ParenthesizedArrayInit:
9804 OS << "parenthesized array initialization";
9805 break;
9806
9807 case SK_PassByIndirectCopyRestore:
9808 OS << "pass by indirect copy and restore";
9809 break;
9810
9811 case SK_PassByIndirectRestore:
9812 OS << "pass by indirect restore";
9813 break;
9814
9815 case SK_ProduceObjCObject:
9816 OS << "Objective-C object retension";
9817 break;
9818
9819 case SK_StdInitializerList:
9820 OS << "std::initializer_list from initializer list";
9821 break;
9822
9823 case SK_StdInitializerListConstructorCall:
9824 OS << "list initialization from std::initializer_list";
9825 break;
9826
9827 case SK_OCLSamplerInit:
9828 OS << "OpenCL sampler_t from integer constant";
9829 break;
9830
9831 case SK_OCLZeroOpaqueType:
9832 OS << "OpenCL opaque type from zero";
9833 break;
9834 case SK_ParenthesizedListInit:
9835 OS << "initialization from a parenthesized list of values";
9836 break;
9837 }
9838
9839 OS << " [" << S->Type << ']';
9840 }
9841
9842 OS << '\n';
9843}
9844
9845void InitializationSequence::dump() const {
9846 dump(OS&: llvm::errs());
9847}
9848
9849static void DiagnoseNarrowingInInitList(Sema &S,
9850 const ImplicitConversionSequence &ICS,
9851 QualType PreNarrowingType,
9852 QualType EntityType,
9853 const Expr *PostInit) {
9854 const StandardConversionSequence *SCS = nullptr;
9855 switch (ICS.getKind()) {
9856 case ImplicitConversionSequence::StandardConversion:
9857 SCS = &ICS.Standard;
9858 break;
9859 case ImplicitConversionSequence::UserDefinedConversion:
9860 SCS = &ICS.UserDefined.After;
9861 break;
9862 case ImplicitConversionSequence::AmbiguousConversion:
9863 case ImplicitConversionSequence::StaticObjectArgumentConversion:
9864 case ImplicitConversionSequence::EllipsisConversion:
9865 case ImplicitConversionSequence::BadConversion:
9866 return;
9867 }
9868
9869 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9870 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9871 unsigned DiagID;
9872 auto &L = S.getLangOpts();
9873 if (L.CPlusPlus11 && !L.HLSL &&
9874 (!L.MicrosoftExt || L.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)))
9875 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9876 else
9877 DiagID = WarnDiagID;
9878 return S.Diag(Loc: PostInit->getBeginLoc(), DiagID)
9879 << PostInit->getSourceRange();
9880 };
9881
9882 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9883 APValue ConstantValue;
9884 QualType ConstantType;
9885 switch (SCS->getNarrowingKind(Context&: S.Context, Converted: PostInit, ConstantValue,
9886 ConstantType)) {
9887 case NK_Not_Narrowing:
9888 case NK_Dependent_Narrowing:
9889 // No narrowing occurred.
9890 return;
9891
9892 case NK_Type_Narrowing: {
9893 // This was a floating-to-integer conversion, which is always considered a
9894 // narrowing conversion even if the value is a constant and can be
9895 // represented exactly as an integer.
9896 QualType T = EntityType.getNonReferenceType();
9897 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9898 diag::ext_init_list_type_narrowing_const_reference,
9899 diag::warn_init_list_type_narrowing)
9900 << PreNarrowingType.getLocalUnqualifiedType()
9901 << T.getLocalUnqualifiedType();
9902 break;
9903 }
9904
9905 case NK_Constant_Narrowing: {
9906 // A constant value was narrowed.
9907 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9908 diag::ext_init_list_constant_narrowing,
9909 diag::ext_init_list_constant_narrowing_const_reference,
9910 diag::warn_init_list_constant_narrowing)
9911 << ConstantValue.getAsString(Ctx: S.getASTContext(), Ty: ConstantType)
9912 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
9913 break;
9914 }
9915
9916 case NK_Variable_Narrowing: {
9917 // A variable's value may have been narrowed.
9918 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9919 diag::ext_init_list_variable_narrowing,
9920 diag::ext_init_list_variable_narrowing_const_reference,
9921 diag::warn_init_list_variable_narrowing)
9922 << PreNarrowingType.getLocalUnqualifiedType()
9923 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
9924 break;
9925 }
9926 }
9927
9928 SmallString<128> StaticCast;
9929 llvm::raw_svector_ostream OS(StaticCast);
9930 OS << "static_cast<";
9931 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
9932 // It's important to use the typedef's name if there is one so that the
9933 // fixit doesn't break code using types like int64_t.
9934 //
9935 // FIXME: This will break if the typedef requires qualification. But
9936 // getQualifiedNameAsString() includes non-machine-parsable components.
9937 OS << *TT->getDecl();
9938 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
9939 OS << BT->getName(Policy: S.getLangOpts());
9940 else {
9941 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
9942 // with a broken cast.
9943 return;
9944 }
9945 OS << ">(";
9946 S.Diag(Loc: PostInit->getBeginLoc(), DiagID: diag::note_init_list_narrowing_silence)
9947 << PostInit->getSourceRange()
9948 << FixItHint::CreateInsertion(InsertionLoc: PostInit->getBeginLoc(), Code: OS.str())
9949 << FixItHint::CreateInsertion(
9950 InsertionLoc: S.getLocForEndOfToken(Loc: PostInit->getEndLoc()), Code: ")");
9951}
9952
9953static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
9954 QualType ToType, Expr *Init) {
9955 assert(S.getLangOpts().C23);
9956 ImplicitConversionSequence ICS = S.TryImplicitConversion(
9957 From: Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
9958 AllowExplicit: Sema::AllowedExplicit::None,
9959 /*InOverloadResolution*/ false,
9960 /*CStyle*/ false,
9961 /*AllowObjCWritebackConversion=*/false);
9962
9963 if (!ICS.isStandard())
9964 return;
9965
9966 APValue Value;
9967 QualType PreNarrowingType;
9968 // Reuse C++ narrowing check.
9969 switch (ICS.Standard.getNarrowingKind(
9970 Context&: S.Context, Converted: Init, ConstantValue&: Value, ConstantType&: PreNarrowingType,
9971 /*IgnoreFloatToIntegralConversion*/ false)) {
9972 // The value doesn't fit.
9973 case NK_Constant_Narrowing:
9974 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_not_representable)
9975 << Value.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
9976 return;
9977
9978 // Conversion to a narrower type.
9979 case NK_Type_Narrowing:
9980 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_type_mismatch)
9981 << ToType << FromType;
9982 return;
9983
9984 // Since we only reuse narrowing check for C23 constexpr variables here, we're
9985 // not really interested in these cases.
9986 case NK_Dependent_Narrowing:
9987 case NK_Variable_Narrowing:
9988 case NK_Not_Narrowing:
9989 return;
9990 }
9991 llvm_unreachable("unhandled case in switch");
9992}
9993
9994static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
9995 Sema &SemaRef, QualType &TT) {
9996 assert(SemaRef.getLangOpts().C23);
9997 // character that string literal contains fits into TT - target type.
9998 const ArrayType *AT = SemaRef.Context.getAsArrayType(T: TT);
9999 QualType CharType = AT->getElementType();
10000 uint32_t BitWidth = SemaRef.Context.getTypeSize(T: CharType);
10001 bool isUnsigned = CharType->isUnsignedIntegerType();
10002 llvm::APSInt Value(BitWidth, isUnsigned);
10003 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10004 int64_t C = SE->getCodeUnitS(I, BitWidth: SemaRef.Context.getCharWidth());
10005 Value = C;
10006 if (Value != C) {
10007 SemaRef.Diag(Loc: SemaRef.getLocationOfStringLiteralByte(SL: SE, ByteNo: I),
10008 DiagID: diag::err_c23_constexpr_init_not_representable)
10009 << C << CharType;
10010 return;
10011 }
10012 }
10013}
10014
10015//===----------------------------------------------------------------------===//
10016// Initialization helper functions
10017//===----------------------------------------------------------------------===//
10018bool
10019Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10020 ExprResult Init) {
10021 if (Init.isInvalid())
10022 return false;
10023
10024 Expr *InitE = Init.get();
10025 assert(InitE && "No initialization expression");
10026
10027 InitializationKind Kind =
10028 InitializationKind::CreateCopy(InitLoc: InitE->getBeginLoc(), EqualLoc: SourceLocation());
10029 InitializationSequence Seq(*this, Entity, Kind, InitE);
10030 return !Seq.Failed();
10031}
10032
10033ExprResult
10034Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10035 SourceLocation EqualLoc,
10036 ExprResult Init,
10037 bool TopLevelOfInitList,
10038 bool AllowExplicit) {
10039 if (Init.isInvalid())
10040 return ExprError();
10041
10042 Expr *InitE = Init.get();
10043 assert(InitE && "No initialization expression?");
10044
10045 if (EqualLoc.isInvalid())
10046 EqualLoc = InitE->getBeginLoc();
10047
10048 InitializationKind Kind = InitializationKind::CreateCopy(
10049 InitLoc: InitE->getBeginLoc(), EqualLoc, AllowExplicitConvs: AllowExplicit);
10050 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10051
10052 // Prevent infinite recursion when performing parameter copy-initialization.
10053 const bool ShouldTrackCopy =
10054 Entity.isParameterKind() && Seq.isConstructorInitialization();
10055 if (ShouldTrackCopy) {
10056 if (llvm::is_contained(Range&: CurrentParameterCopyTypes, Element: Entity.getType())) {
10057 Seq.SetOverloadFailure(
10058 Failure: InitializationSequence::FK_ConstructorOverloadFailed,
10059 Result: OR_No_Viable_Function);
10060
10061 // Try to give a meaningful diagnostic note for the problematic
10062 // constructor.
10063 const auto LastStep = Seq.step_end() - 1;
10064 assert(LastStep->Kind ==
10065 InitializationSequence::SK_ConstructorInitialization);
10066 const FunctionDecl *Function = LastStep->Function.Function;
10067 auto Candidate =
10068 llvm::find_if(Range&: Seq.getFailedCandidateSet(),
10069 P: [Function](const OverloadCandidate &Candidate) -> bool {
10070 return Candidate.Viable &&
10071 Candidate.Function == Function &&
10072 Candidate.Conversions.size() > 0;
10073 });
10074 if (Candidate != Seq.getFailedCandidateSet().end() &&
10075 Function->getNumParams() > 0) {
10076 Candidate->Viable = false;
10077 Candidate->FailureKind = ovl_fail_bad_conversion;
10078 Candidate->Conversions[0].setBad(Failure: BadConversionSequence::no_conversion,
10079 FromExpr: InitE,
10080 ToType: Function->getParamDecl(i: 0)->getType());
10081 }
10082 }
10083 CurrentParameterCopyTypes.push_back(Elt: Entity.getType());
10084 }
10085
10086 ExprResult Result = Seq.Perform(S&: *this, Entity, Kind, Args: InitE);
10087
10088 if (ShouldTrackCopy)
10089 CurrentParameterCopyTypes.pop_back();
10090
10091 return Result;
10092}
10093
10094/// Determine whether RD is, or is derived from, a specialization of CTD.
10095static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10096 ClassTemplateDecl *CTD) {
10097 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10098 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Candidate);
10099 return !CTSD || !declaresSameEntity(D1: CTSD->getSpecializedTemplate(), D2: CTD);
10100 };
10101 return !(NotSpecialization(RD) && RD->forallBases(BaseMatches: NotSpecialization));
10102}
10103
10104QualType Sema::DeduceTemplateSpecializationFromInitializer(
10105 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10106 const InitializationKind &Kind, MultiExprArg Inits) {
10107 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10108 Val: TSInfo->getType()->getContainedDeducedType());
10109 assert(DeducedTST && "not a deduced template specialization type");
10110
10111 auto TemplateName = DeducedTST->getTemplateName();
10112 if (TemplateName.isDependent())
10113 return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType();
10114
10115 // We can only perform deduction for class templates or alias templates.
10116 auto *Template =
10117 dyn_cast_or_null<ClassTemplateDecl>(Val: TemplateName.getAsTemplateDecl());
10118 TemplateDecl *LookupTemplateDecl = Template;
10119 if (!Template) {
10120 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10121 Val: TemplateName.getAsTemplateDecl())) {
10122 DiagCompat(Loc: Kind.getLocation(), CompatDiagId: diag_compat::ctad_for_alias_templates);
10123 LookupTemplateDecl = AliasTemplate;
10124 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10125 ->getUnderlyingType()
10126 .getCanonicalType();
10127 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10128 // of the form
10129 // [typename] [nested-name-specifier] [template] simple-template-id
10130 if (const auto *TST =
10131 UnderlyingType->getAs<TemplateSpecializationType>()) {
10132 Template = dyn_cast_or_null<ClassTemplateDecl>(
10133 Val: TST->getTemplateName().getAsTemplateDecl());
10134 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10135 // Cases where template arguments in the RHS of the alias are not
10136 // dependent. e.g.
10137 // using AliasFoo = Foo<bool>;
10138 if (const auto *CTSD =
10139 llvm::dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl()))
10140 Template = CTSD->getSpecializedTemplate();
10141 }
10142 }
10143 }
10144 if (!Template) {
10145 Diag(Loc: Kind.getLocation(),
10146 DiagID: diag::err_deduced_non_class_or_alias_template_specialization_type)
10147 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName) << TemplateName;
10148 if (auto *TD = TemplateName.getAsTemplateDecl())
10149 NoteTemplateLocation(Decl: *TD);
10150 return QualType();
10151 }
10152
10153 // Can't deduce from dependent arguments.
10154 if (Expr::hasAnyTypeDependentArguments(Exprs: Inits)) {
10155 Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(),
10156 DiagID: diag::warn_cxx14_compat_class_template_argument_deduction)
10157 << TSInfo->getTypeLoc().getSourceRange() << 0;
10158 return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType();
10159 }
10160
10161 // FIXME: Perform "exact type" matching first, per CWG discussion?
10162 // Or implement this via an implied 'T(T) -> T' deduction guide?
10163
10164 // Look up deduction guides, including those synthesized from constructors.
10165 //
10166 // C++1z [over.match.class.deduct]p1:
10167 // A set of functions and function templates is formed comprising:
10168 // - For each constructor of the class template designated by the
10169 // template-name, a function template [...]
10170 // - For each deduction-guide, a function or function template [...]
10171 DeclarationNameInfo NameInfo(
10172 Context.DeclarationNames.getCXXDeductionGuideName(TD: LookupTemplateDecl),
10173 TSInfo->getTypeLoc().getEndLoc());
10174 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10175 LookupQualifiedName(R&: Guides, LookupCtx: LookupTemplateDecl->getDeclContext());
10176
10177 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10178 // clear on this, but they're not found by name so access does not apply.
10179 Guides.suppressDiagnostics();
10180
10181 // Figure out if this is list-initialization.
10182 InitListExpr *ListInit =
10183 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10184 ? dyn_cast<InitListExpr>(Val: Inits[0])
10185 : nullptr;
10186
10187 // C++1z [over.match.class.deduct]p1:
10188 // Initialization and overload resolution are performed as described in
10189 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10190 // (as appropriate for the type of initialization performed) for an object
10191 // of a hypothetical class type, where the selected functions and function
10192 // templates are considered to be the constructors of that class type
10193 //
10194 // Since we know we're initializing a class type of a type unrelated to that
10195 // of the initializer, this reduces to something fairly reasonable.
10196 OverloadCandidateSet Candidates(Kind.getLocation(),
10197 OverloadCandidateSet::CSK_Normal);
10198 OverloadCandidateSet::iterator Best;
10199
10200 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10201
10202 // Return true if the candidate is added successfully, false otherwise.
10203 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10204 CXXDeductionGuideDecl *GD,
10205 DeclAccessPair FoundDecl,
10206 bool OnlyListConstructors,
10207 bool AllowAggregateDeductionCandidate) {
10208 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10209 // For copy-initialization, the candidate functions are all the
10210 // converting constructors (12.3.1) of that class.
10211 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10212 // The converting constructors of T are candidate functions.
10213 if (!AllowExplicit) {
10214 // Overload resolution checks whether the deduction guide is declared
10215 // explicit for us.
10216
10217 // When looking for a converting constructor, deduction guides that
10218 // could never be called with one argument are not interesting to
10219 // check or note.
10220 if (GD->getMinRequiredArguments() > 1 ||
10221 (GD->getNumParams() == 0 && !GD->isVariadic()))
10222 return;
10223 }
10224
10225 // C++ [over.match.list]p1.1: (first phase list initialization)
10226 // Initially, the candidate functions are the initializer-list
10227 // constructors of the class T
10228 if (OnlyListConstructors && !isInitListConstructor(Ctor: GD))
10229 return;
10230
10231 if (!AllowAggregateDeductionCandidate &&
10232 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10233 return;
10234
10235 // C++ [over.match.list]p1.2: (second phase list initialization)
10236 // the candidate functions are all the constructors of the class T
10237 // C++ [over.match.ctor]p1: (all other cases)
10238 // the candidate functions are all the constructors of the class of
10239 // the object being initialized
10240
10241 // C++ [over.best.ics]p4:
10242 // When [...] the constructor [...] is a candidate by
10243 // - [over.match.copy] (in all cases)
10244 if (TD) {
10245
10246 // As template candidates are not deduced immediately,
10247 // persist the array in the overload set.
10248 MutableArrayRef<Expr *> TmpInits =
10249 Candidates.getPersistentArgsArray(N: Inits.size());
10250
10251 for (auto [I, E] : llvm::enumerate(First&: Inits)) {
10252 if (auto *DI = dyn_cast<DesignatedInitExpr>(Val: E))
10253 TmpInits[I] = DI->getInit();
10254 else
10255 TmpInits[I] = E;
10256 }
10257
10258 AddTemplateOverloadCandidate(
10259 FunctionTemplate: TD, FoundDecl, /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, Args: TmpInits, CandidateSet&: Candidates,
10260 /*SuppressUserConversions=*/false,
10261 /*PartialOverloading=*/false, AllowExplicit, IsADLCandidate: ADLCallKind::NotADL,
10262 /*PO=*/{}, AggregateCandidateDeduction: AllowAggregateDeductionCandidate);
10263 } else {
10264 AddOverloadCandidate(Function: GD, FoundDecl, Args: Inits, CandidateSet&: Candidates,
10265 /*SuppressUserConversions=*/false,
10266 /*PartialOverloading=*/false, AllowExplicit);
10267 }
10268 };
10269
10270 bool FoundDeductionGuide = false;
10271
10272 auto TryToResolveOverload =
10273 [&](bool OnlyListConstructors) -> OverloadingResult {
10274 Candidates.clear(CSK: OverloadCandidateSet::CSK_Normal);
10275 bool HasAnyDeductionGuide = false;
10276
10277 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10278 auto *Pattern = Template;
10279 while (Pattern->getInstantiatedFromMemberTemplate()) {
10280 if (Pattern->isMemberSpecialization())
10281 break;
10282 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10283 }
10284
10285 auto *RD = cast<CXXRecordDecl>(Val: Pattern->getTemplatedDecl());
10286 if (!(RD->getDefinition() && RD->isAggregate()))
10287 return;
10288 QualType Ty = Context.getCanonicalTagType(TD: RD);
10289 SmallVector<QualType, 8> ElementTypes;
10290
10291 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10292 if (!CheckInitList.HadError()) {
10293 // C++ [over.match.class.deduct]p1.8:
10294 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10295 // rvalue reference to the declared type of e_i and
10296 // C++ [over.match.class.deduct]p1.9:
10297 // if e_i is of array type and x_i is a string-literal, T_i is an
10298 // lvalue reference to the const-qualified declared type of e_i and
10299 // C++ [over.match.class.deduct]p1.10:
10300 // otherwise, T_i is the declared type of e_i
10301 for (int I = 0, E = ListInit->getNumInits();
10302 I < E && !isa<PackExpansionType>(Val: ElementTypes[I]); ++I)
10303 if (ElementTypes[I]->isArrayType()) {
10304 if (isa<InitListExpr, DesignatedInitExpr>(Val: ListInit->getInit(Init: I)))
10305 ElementTypes[I] = Context.getRValueReferenceType(T: ElementTypes[I]);
10306 else if (isa<StringLiteral>(
10307 Val: ListInit->getInit(Init: I)->IgnoreParenImpCasts()))
10308 ElementTypes[I] =
10309 Context.getLValueReferenceType(T: ElementTypes[I].withConst());
10310 }
10311
10312 if (FunctionTemplateDecl *TD =
10313 DeclareAggregateDeductionGuideFromInitList(
10314 Template: LookupTemplateDecl, ParamTypes: ElementTypes,
10315 Loc: TSInfo->getTypeLoc().getEndLoc())) {
10316 auto *GD = cast<CXXDeductionGuideDecl>(Val: TD->getTemplatedDecl());
10317 addDeductionCandidate(TD, GD, DeclAccessPair::make(D: TD, AS: AS_public),
10318 OnlyListConstructors,
10319 /*AllowAggregateDeductionCandidate=*/true);
10320 HasAnyDeductionGuide = true;
10321 }
10322 }
10323 };
10324
10325 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10326 NamedDecl *D = (*I)->getUnderlyingDecl();
10327 if (D->isInvalidDecl())
10328 continue;
10329
10330 auto *TD = dyn_cast<FunctionTemplateDecl>(Val: D);
10331 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10332 Val: TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(Val: D));
10333 if (!GD)
10334 continue;
10335
10336 if (!GD->isImplicit())
10337 HasAnyDeductionGuide = true;
10338
10339 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10340 /*AllowAggregateDeductionCandidate=*/false);
10341 }
10342
10343 // C++ [over.match.class.deduct]p1.4:
10344 // if C is defined and its definition satisfies the conditions for an
10345 // aggregate class ([dcl.init.aggr]) with the assumption that any
10346 // dependent base class has no virtual functions and no virtual base
10347 // classes, and the initializer is a non-empty braced-init-list or
10348 // parenthesized expression-list, and there are no deduction-guides for
10349 // C, the set contains an additional function template, called the
10350 // aggregate deduction candidate, defined as follows.
10351 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10352 if (ListInit && ListInit->getNumInits()) {
10353 SynthesizeAggrGuide(ListInit);
10354 } else if (Inits.size()) { // parenthesized expression-list
10355 // Inits are expressions inside the parentheses. We don't have
10356 // the parentheses source locations, use the begin/end of Inits as the
10357 // best heuristic.
10358 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10359 Inits, Inits.back()->getEndLoc());
10360 SynthesizeAggrGuide(&TempListInit);
10361 }
10362 }
10363
10364 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10365
10366 return Candidates.BestViableFunction(S&: *this, Loc: Kind.getLocation(), Best);
10367 };
10368
10369 OverloadingResult Result = OR_No_Viable_Function;
10370
10371 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10372 // try initializer-list constructors.
10373 if (ListInit) {
10374 bool TryListConstructors = true;
10375
10376 // Try list constructors unless the list is empty and the class has one or
10377 // more default constructors, in which case those constructors win.
10378 if (!ListInit->getNumInits()) {
10379 for (NamedDecl *D : Guides) {
10380 auto *FD = dyn_cast<FunctionDecl>(Val: D->getUnderlyingDecl());
10381 if (FD && FD->getMinRequiredArguments() == 0) {
10382 TryListConstructors = false;
10383 break;
10384 }
10385 }
10386 } else if (ListInit->getNumInits() == 1) {
10387 // C++ [over.match.class.deduct]:
10388 // As an exception, the first phase in [over.match.list] (considering
10389 // initializer-list constructors) is omitted if the initializer list
10390 // consists of a single expression of type cv U, where U is a
10391 // specialization of C or a class derived from a specialization of C.
10392 Expr *E = ListInit->getInit(Init: 0);
10393 auto *RD = E->getType()->getAsCXXRecordDecl();
10394 if (!isa<InitListExpr>(Val: E) && RD &&
10395 isCompleteType(Loc: Kind.getLocation(), T: E->getType()) &&
10396 isOrIsDerivedFromSpecializationOf(RD, CTD: Template))
10397 TryListConstructors = false;
10398 }
10399
10400 if (TryListConstructors)
10401 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10402 // Then unwrap the initializer list and try again considering all
10403 // constructors.
10404 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10405 }
10406
10407 // If list-initialization fails, or if we're doing any other kind of
10408 // initialization, we (eventually) consider constructors.
10409 if (Result == OR_No_Viable_Function)
10410 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10411
10412 switch (Result) {
10413 case OR_Ambiguous:
10414 // FIXME: For list-initialization candidates, it'd usually be better to
10415 // list why they were not viable when given the initializer list itself as
10416 // an argument.
10417 Candidates.NoteCandidates(
10418 PA: PartialDiagnosticAt(
10419 Kind.getLocation(),
10420 PDiag(DiagID: diag::err_deduced_class_template_ctor_ambiguous)
10421 << TemplateName),
10422 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Inits);
10423 return QualType();
10424
10425 case OR_No_Viable_Function: {
10426 CXXRecordDecl *Primary =
10427 cast<ClassTemplateDecl>(Val: Template)->getTemplatedDecl();
10428 bool Complete = isCompleteType(Loc: Kind.getLocation(),
10429 T: Context.getCanonicalTagType(TD: Primary));
10430 Candidates.NoteCandidates(
10431 PA: PartialDiagnosticAt(
10432 Kind.getLocation(),
10433 PDiag(DiagID: Complete ? diag::err_deduced_class_template_ctor_no_viable
10434 : diag::err_deduced_class_template_incomplete)
10435 << TemplateName << !Guides.empty()),
10436 S&: *this, OCD: OCD_AllCandidates, Args: Inits);
10437 return QualType();
10438 }
10439
10440 case OR_Deleted: {
10441 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10442 // like we ever get here; attempts to trigger this seem to yield a
10443 // generic c'all to deleted function' diagnostic instead.
10444 Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_deleted)
10445 << TemplateName;
10446 NoteDeletedFunction(FD: Best->Function);
10447 return QualType();
10448 }
10449
10450 case OR_Success:
10451 // C++ [over.match.list]p1:
10452 // In copy-list-initialization, if an explicit constructor is chosen, the
10453 // initialization is ill-formed.
10454 if (Kind.isCopyInit() && ListInit &&
10455 cast<CXXDeductionGuideDecl>(Val: Best->Function)->isExplicit()) {
10456 bool IsDeductionGuide = !Best->Function->isImplicit();
10457 Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_explicit)
10458 << TemplateName << IsDeductionGuide;
10459 Diag(Loc: Best->Function->getLocation(),
10460 DiagID: diag::note_explicit_ctor_deduction_guide_here)
10461 << IsDeductionGuide;
10462 return QualType();
10463 }
10464
10465 // Make sure we didn't select an unusable deduction guide, and mark it
10466 // as referenced.
10467 DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: Kind.getLocation());
10468 MarkFunctionReferenced(Loc: Kind.getLocation(), Func: Best->Function);
10469 break;
10470 }
10471
10472 // C++ [dcl.type.class.deduct]p1:
10473 // The placeholder is replaced by the return type of the function selected
10474 // by overload resolution for class template deduction.
10475 QualType DeducedType =
10476 SubstAutoTypeSourceInfo(TypeWithAuto: TSInfo, Replacement: Best->Function->getReturnType())
10477 ->getType();
10478 Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(),
10479 DiagID: diag::warn_cxx14_compat_class_template_argument_deduction)
10480 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10481
10482 // Warn if CTAD was used on a type that does not have any user-defined
10483 // deduction guides.
10484 if (!FoundDeductionGuide) {
10485 Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(),
10486 DiagID: diag::warn_ctad_maybe_unsupported)
10487 << TemplateName;
10488 Diag(Loc: Template->getLocation(), DiagID: diag::note_suppress_ctad_maybe_unsupported);
10489 }
10490
10491 return DeducedType;
10492}
10493