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

source code of clang/lib/Sema/SemaInit.cpp