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