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