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