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