clang 20.0.0git
SemaInit.cpp
Go to the documentation of this file.
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"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeLoc.h"
27#include "clang/Sema/Lookup.h"
29#include "clang/Sema/SemaObjC.h"
30#include "llvm/ADT/APInt.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/PointerIntPair.h"
33#include "llvm/ADT/STLForwardCompat.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// Sema Initialization Checking
43//===----------------------------------------------------------------------===//
44
45/// Check whether T is compatible with a wide character type (wchar_t,
46/// char16_t or char32_t).
47static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
48 if (Context.typesAreCompatible(Context.getWideCharType(), T))
49 return true;
50 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
51 return Context.typesAreCompatible(Context.Char16Ty, T) ||
52 Context.typesAreCompatible(Context.Char32Ty, T);
53 }
54 return false;
55}
56
65};
66
67/// Check whether the array of type AT can be initialized by the Init
68/// expression by means of string initialization. Returns SIF_None if so,
69/// otherwise returns a StringInitFailureKind that describes why the
70/// initialization would not work.
72 ASTContext &Context) {
73 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
74 return SIF_Other;
75
76 // See if this is a string literal or @encode.
77 Init = Init->IgnoreParens();
78
79 // Handle @encode, which is a narrow string.
80 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
81 return SIF_None;
82
83 // Otherwise we can only handle string literals.
84 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
85 if (!SL)
86 return SIF_Other;
87
88 const QualType ElemTy =
90
91 auto IsCharOrUnsignedChar = [](const QualType &T) {
92 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
93 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
94 };
95
96 switch (SL->getKind()) {
97 case StringLiteralKind::UTF8:
98 // char8_t array can be initialized with a UTF-8 string.
99 // - C++20 [dcl.init.string] (DR)
100 // Additionally, an array of char or unsigned char may be initialized
101 // by a UTF-8 string literal.
102 if (ElemTy->isChar8Type() ||
103 (Context.getLangOpts().Char8 &&
104 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
105 return SIF_None;
106 [[fallthrough]];
107 case StringLiteralKind::Ordinary:
108 // char array can be initialized with a narrow string.
109 // Only allow char x[] = "foo"; not char x[] = L"foo";
110 if (ElemTy->isCharType())
111 return (SL->getKind() == StringLiteralKind::UTF8 &&
112 Context.getLangOpts().Char8)
114 : SIF_None;
115 if (ElemTy->isChar8Type())
117 if (IsWideCharCompatible(ElemTy, Context))
119 return SIF_Other;
120 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
121 // "An array with element type compatible with a qualified or unqualified
122 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
123 // string literal with the corresponding encoding prefix (L, u, or U,
124 // respectively), optionally enclosed in braces.
125 case StringLiteralKind::UTF16:
126 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
127 return SIF_None;
128 if (ElemTy->isCharType() || ElemTy->isChar8Type())
130 if (IsWideCharCompatible(ElemTy, Context))
132 return SIF_Other;
133 case StringLiteralKind::UTF32:
134 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
135 return SIF_None;
136 if (ElemTy->isCharType() || ElemTy->isChar8Type())
138 if (IsWideCharCompatible(ElemTy, Context))
140 return SIF_Other;
141 case StringLiteralKind::Wide:
142 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
143 return SIF_None;
144 if (ElemTy->isCharType() || ElemTy->isChar8Type())
146 if (IsWideCharCompatible(ElemTy, Context))
148 return SIF_Other;
149 case StringLiteralKind::Unevaluated:
150 assert(false && "Unevaluated string literal in initialization");
151 break;
152 }
153
154 llvm_unreachable("missed a StringLiteral kind?");
155}
156
158 ASTContext &Context) {
159 const ArrayType *arrayType = Context.getAsArrayType(declType);
160 if (!arrayType)
161 return SIF_Other;
162 return IsStringInit(init, arrayType, Context);
163}
164
166 return ::IsStringInit(Init, AT, Context) == SIF_None;
167}
168
169/// Update the type of a string literal, including any surrounding parentheses,
170/// to match the type of the object which it is initializing.
172 while (true) {
173 E->setType(Ty);
175 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
176 break;
178 }
179}
180
181/// Fix a compound literal initializing an array so it's correctly marked
182/// as an rvalue.
184 while (true) {
186 if (isa<CompoundLiteralExpr>(E))
187 break;
189 }
190}
191
193 Decl *D = Entity.getDecl();
194 const InitializedEntity *Parent = &Entity;
195
196 while (Parent) {
197 D = Parent->getDecl();
198 Parent = Parent->getParent();
199 }
200
201 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
202 return true;
203
204 return false;
205}
206
208 Sema &SemaRef, QualType &TT);
209
210static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
211 Sema &S, bool CheckC23ConstexprInit = false) {
212 // Get the length of the string as parsed.
213 auto *ConstantArrayTy =
214 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
215 uint64_t StrLength = ConstantArrayTy->getZExtSize();
216
217 if (CheckC23ConstexprInit)
218 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
220
221 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
222 // C99 6.7.8p14. We have an array of character type with unknown size
223 // being initialized to a string literal.
224 llvm::APInt ConstVal(32, StrLength);
225 // Return a new array type (C99 6.7.8p22).
227 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
228 updateStringLiteralType(Str, DeclT);
229 return;
230 }
231
232 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
233
234 // We have an array of character type with known size. However,
235 // the size may be smaller or larger than the string we are initializing.
236 // FIXME: Avoid truncation for 64-bit length strings.
237 if (S.getLangOpts().CPlusPlus) {
238 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
239 // For Pascal strings it's OK to strip off the terminating null character,
240 // so the example below is valid:
241 //
242 // unsigned char a[2] = "\pa";
243 if (SL->isPascal())
244 StrLength--;
245 }
246
247 // [dcl.init.string]p2
248 if (StrLength > CAT->getZExtSize())
249 S.Diag(Str->getBeginLoc(),
250 diag::err_initializer_string_for_char_array_too_long)
251 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
252 } else {
253 // C99 6.7.8p14.
254 if (StrLength - 1 > CAT->getZExtSize())
255 S.Diag(Str->getBeginLoc(),
256 diag::ext_initializer_string_for_char_array_too_long)
257 << Str->getSourceRange();
258 }
259
260 // Set the type to the actual size that we are initializing. If we have
261 // something like:
262 // char x[1] = "foo";
263 // then this will set the string literal's type to char[1].
264 updateStringLiteralType(Str, DeclT);
265}
266
267//===----------------------------------------------------------------------===//
268// Semantic checking for initializer lists.
269//===----------------------------------------------------------------------===//
270
271namespace {
272
273/// Semantic checking for initializer lists.
274///
275/// The InitListChecker class contains a set of routines that each
276/// handle the initialization of a certain kind of entity, e.g.,
277/// arrays, vectors, struct/union types, scalars, etc. The
278/// InitListChecker itself performs a recursive walk of the subobject
279/// structure of the type to be initialized, while stepping through
280/// the initializer list one element at a time. The IList and Index
281/// parameters to each of the Check* routines contain the active
282/// (syntactic) initializer list and the index into that initializer
283/// list that represents the current initializer. Each routine is
284/// responsible for moving that Index forward as it consumes elements.
285///
286/// Each Check* routine also has a StructuredList/StructuredIndex
287/// arguments, which contains the current "structured" (semantic)
288/// initializer list and the index into that initializer list where we
289/// are copying initializers as we map them over to the semantic
290/// list. Once we have completed our recursive walk of the subobject
291/// structure, we will have constructed a full semantic initializer
292/// list.
293///
294/// C99 designators cause changes in the initializer list traversal,
295/// because they make the initialization "jump" into a specific
296/// subobject and then continue the initialization from that
297/// point. CheckDesignatedInitializer() recursively steps into the
298/// designated subobject and manages backing out the recursion to
299/// initialize the subobjects after the one designated.
300///
301/// If an initializer list contains any designators, we build a placeholder
302/// structured list even in 'verify only' mode, so that we can track which
303/// elements need 'empty' initializtion.
304class InitListChecker {
305 Sema &SemaRef;
306 bool hadError = false;
307 bool VerifyOnly; // No diagnostics.
308 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
309 bool InOverloadResolution;
310 InitListExpr *FullyStructuredList = nullptr;
311 NoInitExpr *DummyExpr = nullptr;
312 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
313 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
314 unsigned CurEmbedIndex = 0;
315
316 NoInitExpr *getDummyInit() {
317 if (!DummyExpr)
318 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
319 return DummyExpr;
320 }
321
322 void CheckImplicitInitList(const InitializedEntity &Entity,
323 InitListExpr *ParentIList, QualType T,
324 unsigned &Index, InitListExpr *StructuredList,
325 unsigned &StructuredIndex);
326 void CheckExplicitInitList(const InitializedEntity &Entity,
327 InitListExpr *IList, QualType &T,
328 InitListExpr *StructuredList,
329 bool TopLevelObject = false);
330 void CheckListElementTypes(const InitializedEntity &Entity,
331 InitListExpr *IList, QualType &DeclType,
332 bool SubobjectIsDesignatorContext,
333 unsigned &Index,
334 InitListExpr *StructuredList,
335 unsigned &StructuredIndex,
336 bool TopLevelObject = false);
337 void CheckSubElementType(const InitializedEntity &Entity,
338 InitListExpr *IList, QualType ElemType,
339 unsigned &Index,
340 InitListExpr *StructuredList,
341 unsigned &StructuredIndex,
342 bool DirectlyDesignated = false);
343 void CheckComplexType(const InitializedEntity &Entity,
344 InitListExpr *IList, QualType DeclType,
345 unsigned &Index,
346 InitListExpr *StructuredList,
347 unsigned &StructuredIndex);
348 void CheckScalarType(const InitializedEntity &Entity,
349 InitListExpr *IList, QualType DeclType,
350 unsigned &Index,
351 InitListExpr *StructuredList,
352 unsigned &StructuredIndex);
353 void CheckReferenceType(const InitializedEntity &Entity,
354 InitListExpr *IList, QualType DeclType,
355 unsigned &Index,
356 InitListExpr *StructuredList,
357 unsigned &StructuredIndex);
358 void CheckVectorType(const InitializedEntity &Entity,
359 InitListExpr *IList, QualType DeclType, unsigned &Index,
360 InitListExpr *StructuredList,
361 unsigned &StructuredIndex);
362 void CheckStructUnionTypes(const InitializedEntity &Entity,
363 InitListExpr *IList, QualType DeclType,
366 bool SubobjectIsDesignatorContext, unsigned &Index,
367 InitListExpr *StructuredList,
368 unsigned &StructuredIndex,
369 bool TopLevelObject = false);
370 void CheckArrayType(const InitializedEntity &Entity,
371 InitListExpr *IList, QualType &DeclType,
372 llvm::APSInt elementIndex,
373 bool SubobjectIsDesignatorContext, unsigned &Index,
374 InitListExpr *StructuredList,
375 unsigned &StructuredIndex);
376 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
377 InitListExpr *IList, DesignatedInitExpr *DIE,
378 unsigned DesigIdx,
379 QualType &CurrentObjectType,
381 llvm::APSInt *NextElementIndex,
382 unsigned &Index,
383 InitListExpr *StructuredList,
384 unsigned &StructuredIndex,
385 bool FinishSubobjectInit,
386 bool TopLevelObject);
387 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
388 QualType CurrentObjectType,
389 InitListExpr *StructuredList,
390 unsigned StructuredIndex,
391 SourceRange InitRange,
392 bool IsFullyOverwritten = false);
393 void UpdateStructuredListElement(InitListExpr *StructuredList,
394 unsigned &StructuredIndex,
395 Expr *expr);
396 InitListExpr *createInitListExpr(QualType CurrentObjectType,
397 SourceRange InitRange,
398 unsigned ExpectedNumInits);
399 int numArrayElements(QualType DeclType);
400 int numStructUnionElements(QualType DeclType);
401 static RecordDecl *getRecordDecl(QualType DeclType);
402
403 ExprResult PerformEmptyInit(SourceLocation Loc,
404 const InitializedEntity &Entity);
405
406 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
407 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
408 bool UnionOverride = false,
409 bool FullyOverwritten = true) {
410 // Overriding an initializer via a designator is valid with C99 designated
411 // initializers, but ill-formed with C++20 designated initializers.
412 unsigned DiagID =
413 SemaRef.getLangOpts().CPlusPlus
414 ? (UnionOverride ? diag::ext_initializer_union_overrides
415 : diag::ext_initializer_overrides)
416 : diag::warn_initializer_overrides;
417
418 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
419 // In overload resolution, we have to strictly enforce the rules, and so
420 // don't allow any overriding of prior initializers. This matters for a
421 // case such as:
422 //
423 // union U { int a, b; };
424 // struct S { int a, b; };
425 // void f(U), f(S);
426 //
427 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
428 // consistency, we disallow all overriding of prior initializers in
429 // overload resolution, not only overriding of union members.
430 hadError = true;
431 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
432 // If we'll be keeping around the old initializer but overwriting part of
433 // the object it initialized, and that object is not trivially
434 // destructible, this can leak. Don't allow that, not even as an
435 // extension.
436 //
437 // FIXME: It might be reasonable to allow this in cases where the part of
438 // the initializer that we're overriding has trivial destruction.
439 DiagID = diag::err_initializer_overrides_destructed;
440 } else if (!OldInit->getSourceRange().isValid()) {
441 // We need to check on source range validity because the previous
442 // initializer does not have to be an explicit initializer. e.g.,
443 //
444 // struct P { int a, b; };
445 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
446 //
447 // There is an overwrite taking place because the first braced initializer
448 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
449 //
450 // Such overwrites are harmless, so we don't diagnose them. (Note that in
451 // C++, this cannot be reached unless we've already seen and diagnosed a
452 // different conformance issue, such as a mixture of designated and
453 // non-designated initializers or a multi-level designator.)
454 return;
455 }
456
457 if (!VerifyOnly) {
458 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
459 << NewInitRange << FullyOverwritten << OldInit->getType();
460 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
461 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
462 << OldInit->getSourceRange();
463 }
464 }
465
466 // Explanation on the "FillWithNoInit" mode:
467 //
468 // Assume we have the following definitions (Case#1):
469 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
470 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
471 //
472 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
473 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
474 //
475 // But if we have (Case#2):
476 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
477 //
478 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
479 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
480 //
481 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
482 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
483 // initializers but with special "NoInitExpr" place holders, which tells the
484 // CodeGen not to generate any initializers for these parts.
485 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
486 const InitializedEntity &ParentEntity,
487 InitListExpr *ILE, bool &RequiresSecondPass,
488 bool FillWithNoInit);
489 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
490 const InitializedEntity &ParentEntity,
491 InitListExpr *ILE, bool &RequiresSecondPass,
492 bool FillWithNoInit = false);
493 void FillInEmptyInitializations(const InitializedEntity &Entity,
494 InitListExpr *ILE, bool &RequiresSecondPass,
495 InitListExpr *OuterILE, unsigned OuterIndex,
496 bool FillWithNoInit = false);
497 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
498 Expr *InitExpr, FieldDecl *Field,
499 bool TopLevelObject);
500 void CheckEmptyInitializable(const InitializedEntity &Entity,
502
503 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
504 Expr *Result = nullptr;
505 // Undrestand which part of embed we'd like to reference.
506 if (!CurEmbed) {
507 CurEmbed = Embed;
508 CurEmbedIndex = 0;
509 }
510 // Reference just one if we're initializing a single scalar.
511 uint64_t ElsCount = 1;
512 // Otherwise try to fill whole array with embed data.
514 auto *AType =
515 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
516 assert(AType && "expected array type when initializing array");
517 ElsCount = Embed->getDataElementCount();
518 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
519 ElsCount = std::min(CAType->getSize().getZExtValue(),
520 ElsCount - CurEmbedIndex);
521 if (ElsCount == Embed->getDataElementCount()) {
522 CurEmbed = nullptr;
523 CurEmbedIndex = 0;
524 return Embed;
525 }
526 }
527
528 Result = new (SemaRef.Context)
529 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
530 CurEmbedIndex, ElsCount);
531 CurEmbedIndex += ElsCount;
532 if (CurEmbedIndex >= Embed->getDataElementCount()) {
533 CurEmbed = nullptr;
534 CurEmbedIndex = 0;
535 }
536 return Result;
537 }
538
539public:
540 InitListChecker(
541 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
542 bool VerifyOnly, bool TreatUnavailableAsInvalid,
543 bool InOverloadResolution = false,
544 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
545 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
546 QualType &T,
547 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
548 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
549 /*TreatUnavailableAsInvalid=*/false,
550 /*InOverloadResolution=*/false,
551 &AggrDeductionCandidateParamTypes) {}
552
553 bool HadError() { return hadError; }
554
555 // Retrieves the fully-structured initializer list used for
556 // semantic analysis and code generation.
557 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
558};
559
560} // end anonymous namespace
561
562ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
563 const InitializedEntity &Entity) {
565 true);
566 MultiExprArg SubInit;
567 Expr *InitExpr;
568 InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc);
569
570 // C++ [dcl.init.aggr]p7:
571 // If there are fewer initializer-clauses in the list than there are
572 // members in the aggregate, then each member not explicitly initialized
573 // ...
574 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
576 if (EmptyInitList) {
577 // C++1y / DR1070:
578 // shall be initialized [...] from an empty initializer list.
579 //
580 // We apply the resolution of this DR to C++11 but not C++98, since C++98
581 // does not have useful semantics for initialization from an init list.
582 // We treat this as copy-initialization, because aggregate initialization
583 // always performs copy-initialization on its elements.
584 //
585 // Only do this if we're initializing a class type, to avoid filling in
586 // the initializer list where possible.
587 InitExpr = VerifyOnly ? &DummyInitList
588 : new (SemaRef.Context)
589 InitListExpr(SemaRef.Context, Loc, {}, Loc);
590 InitExpr->setType(SemaRef.Context.VoidTy);
591 SubInit = InitExpr;
593 } else {
594 // C++03:
595 // shall be value-initialized.
596 }
597
598 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
599 // libstdc++4.6 marks the vector default constructor as explicit in
600 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
601 // stlport does so too. Look for std::__debug for libstdc++, and for
602 // std:: for stlport. This is effectively a compiler-side implementation of
603 // LWG2193.
604 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
608 InitSeq.getFailedCandidateSet()
609 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
610 (void)O;
611 assert(O == OR_Success && "Inconsistent overload resolution");
612 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
613 CXXRecordDecl *R = CtorDecl->getParent();
614
615 if (CtorDecl->getMinRequiredArguments() == 0 &&
616 CtorDecl->isExplicit() && R->getDeclName() &&
617 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
618 bool IsInStd = false;
619 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
620 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
622 IsInStd = true;
623 }
624
625 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
626 .Cases("basic_string", "deque", "forward_list", true)
627 .Cases("list", "map", "multimap", "multiset", true)
628 .Cases("priority_queue", "queue", "set", "stack", true)
629 .Cases("unordered_map", "unordered_set", "vector", true)
630 .Default(false)) {
631 InitSeq.InitializeFrom(
632 SemaRef, Entity,
634 MultiExprArg(), /*TopLevelOfInitList=*/false,
635 TreatUnavailableAsInvalid);
636 // Emit a warning for this. System header warnings aren't shown
637 // by default, but people working on system headers should see it.
638 if (!VerifyOnly) {
639 SemaRef.Diag(CtorDecl->getLocation(),
640 diag::warn_invalid_initializer_from_system_header);
642 SemaRef.Diag(Entity.getDecl()->getLocation(),
643 diag::note_used_in_initialization_here);
644 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
645 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
646 }
647 }
648 }
649 }
650 if (!InitSeq) {
651 if (!VerifyOnly) {
652 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
654 SemaRef.Diag(Entity.getDecl()->getLocation(),
655 diag::note_in_omitted_aggregate_initializer)
656 << /*field*/1 << Entity.getDecl();
657 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
658 bool IsTrailingArrayNewMember =
659 Entity.getParent() &&
661 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
662 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
663 << Entity.getElementIndex();
664 }
665 }
666 hadError = true;
667 return ExprError();
668 }
669
670 return VerifyOnly ? ExprResult()
671 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
672}
673
674void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
676 // If we're building a fully-structured list, we'll check this at the end
677 // once we know which elements are actually initialized. Otherwise, we know
678 // that there are no designators so we can just check now.
679 if (FullyStructuredList)
680 return;
681 PerformEmptyInit(Loc, Entity);
682}
683
684void InitListChecker::FillInEmptyInitForBase(
685 unsigned Init, const CXXBaseSpecifier &Base,
686 const InitializedEntity &ParentEntity, InitListExpr *ILE,
687 bool &RequiresSecondPass, bool FillWithNoInit) {
689 SemaRef.Context, &Base, false, &ParentEntity);
690
691 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
692 ExprResult BaseInit = FillWithNoInit
693 ? new (SemaRef.Context) NoInitExpr(Base.getType())
694 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
695 if (BaseInit.isInvalid()) {
696 hadError = true;
697 return;
698 }
699
700 if (!VerifyOnly) {
701 assert(Init < ILE->getNumInits() && "should have been expanded");
702 ILE->setInit(Init, BaseInit.getAs<Expr>());
703 }
704 } else if (InitListExpr *InnerILE =
705 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
706 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
707 ILE, Init, FillWithNoInit);
708 } else if (DesignatedInitUpdateExpr *InnerDIUE =
709 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
710 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
711 RequiresSecondPass, ILE, Init,
712 /*FillWithNoInit =*/true);
713 }
714}
715
716void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
717 const InitializedEntity &ParentEntity,
718 InitListExpr *ILE,
719 bool &RequiresSecondPass,
720 bool FillWithNoInit) {
722 unsigned NumInits = ILE->getNumInits();
723 InitializedEntity MemberEntity
724 = InitializedEntity::InitializeMember(Field, &ParentEntity);
725
726 if (Init >= NumInits || !ILE->getInit(Init)) {
727 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
728 if (!RType->getDecl()->isUnion())
729 assert((Init < NumInits || VerifyOnly) &&
730 "This ILE should have been expanded");
731
732 if (FillWithNoInit) {
733 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
734 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
735 if (Init < NumInits)
736 ILE->setInit(Init, Filler);
737 else
738 ILE->updateInit(SemaRef.Context, Init, Filler);
739 return;
740 }
741 // C++1y [dcl.init.aggr]p7:
742 // If there are fewer initializer-clauses in the list than there are
743 // members in the aggregate, then each member not explicitly initialized
744 // shall be initialized from its brace-or-equal-initializer [...]
745 if (Field->hasInClassInitializer()) {
746 if (VerifyOnly)
747 return;
748
749 ExprResult DIE;
750 {
751 // Enter a default initializer rebuild context, then we can support
752 // lifetime extension of temporary created by aggregate initialization
753 // using a default member initializer.
754 // CWG1815 (https://wg21.link/CWG1815).
755 EnterExpressionEvaluationContext RebuildDefaultInit(
758 true;
764 DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
765 }
766 if (DIE.isInvalid()) {
767 hadError = true;
768 return;
769 }
770 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
771 if (Init < NumInits)
772 ILE->setInit(Init, DIE.get());
773 else {
774 ILE->updateInit(SemaRef.Context, Init, DIE.get());
775 RequiresSecondPass = true;
776 }
777 return;
778 }
779
780 if (Field->getType()->isReferenceType()) {
781 if (!VerifyOnly) {
782 // C++ [dcl.init.aggr]p9:
783 // If an incomplete or empty initializer-list leaves a
784 // member of reference type uninitialized, the program is
785 // ill-formed.
786 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
787 << Field->getType()
788 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
789 ->getSourceRange();
790 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
791 }
792 hadError = true;
793 return;
794 }
795
796 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
797 if (MemberInit.isInvalid()) {
798 hadError = true;
799 return;
800 }
801
802 if (hadError || VerifyOnly) {
803 // Do nothing
804 } else if (Init < NumInits) {
805 ILE->setInit(Init, MemberInit.getAs<Expr>());
806 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
807 // Empty initialization requires a constructor call, so
808 // extend the initializer list to include the constructor
809 // call and make a note that we'll need to take another pass
810 // through the initializer list.
811 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
812 RequiresSecondPass = true;
813 }
814 } else if (InitListExpr *InnerILE
815 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
816 FillInEmptyInitializations(MemberEntity, InnerILE,
817 RequiresSecondPass, ILE, Init, FillWithNoInit);
818 } else if (DesignatedInitUpdateExpr *InnerDIUE =
819 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
820 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
821 RequiresSecondPass, ILE, Init,
822 /*FillWithNoInit =*/true);
823 }
824}
825
826/// Recursively replaces NULL values within the given initializer list
827/// with expressions that perform value-initialization of the
828/// appropriate type, and finish off the InitListExpr formation.
829void
830InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
831 InitListExpr *ILE,
832 bool &RequiresSecondPass,
833 InitListExpr *OuterILE,
834 unsigned OuterIndex,
835 bool FillWithNoInit) {
836 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
837 "Should not have void type");
838
839 // We don't need to do any checks when just filling NoInitExprs; that can't
840 // fail.
841 if (FillWithNoInit && VerifyOnly)
842 return;
843
844 // If this is a nested initializer list, we might have changed its contents
845 // (and therefore some of its properties, such as instantiation-dependence)
846 // while filling it in. Inform the outer initializer list so that its state
847 // can be updated to match.
848 // FIXME: We should fully build the inner initializers before constructing
849 // the outer InitListExpr instead of mutating AST nodes after they have
850 // been used as subexpressions of other nodes.
851 struct UpdateOuterILEWithUpdatedInit {
852 InitListExpr *Outer;
853 unsigned OuterIndex;
854 ~UpdateOuterILEWithUpdatedInit() {
855 if (Outer)
856 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
857 }
858 } UpdateOuterRAII = {OuterILE, OuterIndex};
859
860 // A transparent ILE is not performing aggregate initialization and should
861 // not be filled in.
862 if (ILE->isTransparent())
863 return;
864
865 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
866 const RecordDecl *RDecl = RType->getDecl();
867 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
868 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
869 RequiresSecondPass, FillWithNoInit);
870 } else {
871 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
872 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
873 "We should have computed initialized fields already");
874 // The fields beyond ILE->getNumInits() are default initialized, so in
875 // order to leave them uninitialized, the ILE is expanded and the extra
876 // fields are then filled with NoInitExpr.
877 unsigned NumElems = numStructUnionElements(ILE->getType());
878 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
879 ++NumElems;
880 if (!VerifyOnly && ILE->getNumInits() < NumElems)
881 ILE->resizeInits(SemaRef.Context, NumElems);
882
883 unsigned Init = 0;
884
885 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
886 for (auto &Base : CXXRD->bases()) {
887 if (hadError)
888 return;
889
890 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
891 FillWithNoInit);
892 ++Init;
893 }
894 }
895
896 for (auto *Field : RDecl->fields()) {
897 if (Field->isUnnamedBitField())
898 continue;
899
900 if (hadError)
901 return;
902
903 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
904 FillWithNoInit);
905 if (hadError)
906 return;
907
908 ++Init;
909
910 // Only look at the first initialization of a union.
911 if (RDecl->isUnion())
912 break;
913 }
914 }
915
916 return;
917 }
918
919 QualType ElementType;
920
921 InitializedEntity ElementEntity = Entity;
922 unsigned NumInits = ILE->getNumInits();
923 uint64_t NumElements = NumInits;
924 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
925 ElementType = AType->getElementType();
926 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
927 NumElements = CAType->getZExtSize();
928 // For an array new with an unknown bound, ask for one additional element
929 // in order to populate the array filler.
930 if (Entity.isVariableLengthArrayNew())
931 ++NumElements;
932 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
933 0, Entity);
934 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
935 ElementType = VType->getElementType();
936 NumElements = VType->getNumElements();
937 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
938 0, Entity);
939 } else
940 ElementType = ILE->getType();
941
942 bool SkipEmptyInitChecks = false;
943 for (uint64_t Init = 0; Init != NumElements; ++Init) {
944 if (hadError)
945 return;
946
947 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
949 ElementEntity.setElementIndex(Init);
950
951 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
952 return;
953
954 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
955 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
956 ILE->setInit(Init, ILE->getArrayFiller());
957 else if (!InitExpr && !ILE->hasArrayFiller()) {
958 // In VerifyOnly mode, there's no point performing empty initialization
959 // more than once.
960 if (SkipEmptyInitChecks)
961 continue;
962
963 Expr *Filler = nullptr;
964
965 if (FillWithNoInit)
966 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
967 else {
968 ExprResult ElementInit =
969 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
970 if (ElementInit.isInvalid()) {
971 hadError = true;
972 return;
973 }
974
975 Filler = ElementInit.getAs<Expr>();
976 }
977
978 if (hadError) {
979 // Do nothing
980 } else if (VerifyOnly) {
981 SkipEmptyInitChecks = true;
982 } else if (Init < NumInits) {
983 // For arrays, just set the expression used for value-initialization
984 // of the "holes" in the array.
985 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
986 ILE->setArrayFiller(Filler);
987 else
988 ILE->setInit(Init, Filler);
989 } else {
990 // For arrays, just set the expression used for value-initialization
991 // of the rest of elements and exit.
992 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
993 ILE->setArrayFiller(Filler);
994 return;
995 }
996
997 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
998 // Empty initialization requires a constructor call, so
999 // extend the initializer list to include the constructor
1000 // call and make a note that we'll need to take another pass
1001 // through the initializer list.
1002 ILE->updateInit(SemaRef.Context, Init, Filler);
1003 RequiresSecondPass = true;
1004 }
1005 }
1006 } else if (InitListExpr *InnerILE
1007 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
1008 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
1009 ILE, Init, FillWithNoInit);
1010 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1011 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1012 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1013 RequiresSecondPass, ILE, Init,
1014 /*FillWithNoInit =*/true);
1015 }
1016 }
1017}
1018
1019static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1020 for (const Stmt *Init : *IL)
1021 if (isa_and_nonnull<DesignatedInitExpr>(Init))
1022 return true;
1023 return false;
1024}
1025
1026InitListChecker::InitListChecker(
1027 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1028 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1029 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1030 : SemaRef(S), VerifyOnly(VerifyOnly),
1031 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1032 InOverloadResolution(InOverloadResolution),
1033 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1034 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1035 FullyStructuredList =
1036 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
1037
1038 // FIXME: Check that IL isn't already the semantic form of some other
1039 // InitListExpr. If it is, we'd create a broken AST.
1040 if (!VerifyOnly)
1041 FullyStructuredList->setSyntacticForm(IL);
1042 }
1043
1044 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1045 /*TopLevelObject=*/true);
1046
1047 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1048 bool RequiresSecondPass = false;
1049 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1050 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1051 if (RequiresSecondPass && !hadError)
1052 FillInEmptyInitializations(Entity, FullyStructuredList,
1053 RequiresSecondPass, nullptr, 0);
1054 }
1055 if (hadError && FullyStructuredList)
1056 FullyStructuredList->markError();
1057}
1058
1059int InitListChecker::numArrayElements(QualType DeclType) {
1060 // FIXME: use a proper constant
1061 int maxElements = 0x7FFFFFFF;
1062 if (const ConstantArrayType *CAT =
1063 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1064 maxElements = static_cast<int>(CAT->getZExtSize());
1065 }
1066 return maxElements;
1067}
1068
1069int InitListChecker::numStructUnionElements(QualType DeclType) {
1070 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1071 int InitializableMembers = 0;
1072 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1073 InitializableMembers += CXXRD->getNumBases();
1074 for (const auto *Field : structDecl->fields())
1075 if (!Field->isUnnamedBitField())
1076 ++InitializableMembers;
1077
1078 if (structDecl->isUnion())
1079 return std::min(InitializableMembers, 1);
1080 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1081}
1082
1083RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1084 if (const auto *RT = DeclType->getAs<RecordType>())
1085 return RT->getDecl();
1086 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1087 return Inject->getDecl();
1088 return nullptr;
1089}
1090
1091/// Determine whether Entity is an entity for which it is idiomatic to elide
1092/// the braces in aggregate initialization.
1094 // Recursive initialization of the one and only field within an aggregate
1095 // class is considered idiomatic. This case arises in particular for
1096 // initialization of std::array, where the C++ standard suggests the idiom of
1097 //
1098 // std::array<T, N> arr = {1, 2, 3};
1099 //
1100 // (where std::array is an aggregate struct containing a single array field.
1101
1102 if (!Entity.getParent())
1103 return false;
1104
1105 // Allows elide brace initialization for aggregates with empty base.
1106 if (Entity.getKind() == InitializedEntity::EK_Base) {
1107 auto *ParentRD =
1108 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1109 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1110 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1111 }
1112
1113 // Allow brace elision if the only subobject is a field.
1114 if (Entity.getKind() == InitializedEntity::EK_Member) {
1115 auto *ParentRD =
1116 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1117 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1118 if (CXXRD->getNumBases()) {
1119 return false;
1120 }
1121 }
1122 auto FieldIt = ParentRD->field_begin();
1123 assert(FieldIt != ParentRD->field_end() &&
1124 "no fields but have initializer for member?");
1125 return ++FieldIt == ParentRD->field_end();
1126 }
1127
1128 return false;
1129}
1130
1131/// Check whether the range of the initializer \p ParentIList from element
1132/// \p Index onwards can be used to initialize an object of type \p T. Update
1133/// \p Index to indicate how many elements of the list were consumed.
1134///
1135/// This also fills in \p StructuredList, from element \p StructuredIndex
1136/// onwards, with the fully-braced, desugared form of the initialization.
1137void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1138 InitListExpr *ParentIList,
1139 QualType T, unsigned &Index,
1140 InitListExpr *StructuredList,
1141 unsigned &StructuredIndex) {
1142 int maxElements = 0;
1143
1144 if (T->isArrayType())
1145 maxElements = numArrayElements(T);
1146 else if (T->isRecordType())
1147 maxElements = numStructUnionElements(T);
1148 else if (T->isVectorType())
1149 maxElements = T->castAs<VectorType>()->getNumElements();
1150 else
1151 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1152
1153 if (maxElements == 0) {
1154 if (!VerifyOnly)
1155 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1156 diag::err_implicit_empty_initializer);
1157 ++Index;
1158 hadError = true;
1159 return;
1160 }
1161
1162 // Build a structured initializer list corresponding to this subobject.
1163 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1164 ParentIList, Index, T, StructuredList, StructuredIndex,
1165 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1166 ParentIList->getSourceRange().getEnd()));
1167 unsigned StructuredSubobjectInitIndex = 0;
1168
1169 // Check the element types and build the structural subobject.
1170 unsigned StartIndex = Index;
1171 CheckListElementTypes(Entity, ParentIList, T,
1172 /*SubobjectIsDesignatorContext=*/false, Index,
1173 StructuredSubobjectInitList,
1174 StructuredSubobjectInitIndex);
1175
1176 if (StructuredSubobjectInitList) {
1177 StructuredSubobjectInitList->setType(T);
1178
1179 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1180 // Update the structured sub-object initializer so that it's ending
1181 // range corresponds with the end of the last initializer it used.
1182 if (EndIndex < ParentIList->getNumInits() &&
1183 ParentIList->getInit(EndIndex)) {
1184 SourceLocation EndLoc
1185 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1186 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1187 }
1188
1189 // Complain about missing braces.
1190 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1191 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1193 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1194 diag::warn_missing_braces)
1195 << StructuredSubobjectInitList->getSourceRange()
1197 StructuredSubobjectInitList->getBeginLoc(), "{")
1199 SemaRef.getLocForEndOfToken(
1200 StructuredSubobjectInitList->getEndLoc()),
1201 "}");
1202 }
1203
1204 // Warn if this type won't be an aggregate in future versions of C++.
1205 auto *CXXRD = T->getAsCXXRecordDecl();
1206 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1207 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1208 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1209 << StructuredSubobjectInitList->getSourceRange() << T;
1210 }
1211 }
1212}
1213
1214/// Warn that \p Entity was of scalar type and was initialized by a
1215/// single-element braced initializer list.
1216static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1218 // Don't warn during template instantiation. If the initialization was
1219 // non-dependent, we warned during the initial parse; otherwise, the
1220 // type might not be scalar in some uses of the template.
1222 return;
1223
1224 unsigned DiagID = 0;
1225
1226 switch (Entity.getKind()) {
1235 // Extra braces here are suspicious.
1236 DiagID = diag::warn_braces_around_init;
1237 break;
1238
1240 // Warn on aggregate initialization but not on ctor init list or
1241 // default member initializer.
1242 if (Entity.getParent())
1243 DiagID = diag::warn_braces_around_init;
1244 break;
1245
1248 // No warning, might be direct-list-initialization.
1249 // FIXME: Should we warn for copy-list-initialization in these cases?
1250 break;
1251
1255 // No warning, braces are part of the syntax of the underlying construct.
1256 break;
1257
1259 // No warning, we already warned when initializing the result.
1260 break;
1261
1269 llvm_unreachable("unexpected braced scalar init");
1270 }
1271
1272 if (DiagID) {
1273 S.Diag(Braces.getBegin(), DiagID)
1274 << Entity.getType()->isSizelessBuiltinType() << Braces
1275 << FixItHint::CreateRemoval(Braces.getBegin())
1276 << FixItHint::CreateRemoval(Braces.getEnd());
1277 }
1278}
1279
1280/// Check whether the initializer \p IList (that was written with explicit
1281/// braces) can be used to initialize an object of type \p T.
1282///
1283/// This also fills in \p StructuredList with the fully-braced, desugared
1284/// form of the initialization.
1285void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1286 InitListExpr *IList, QualType &T,
1287 InitListExpr *StructuredList,
1288 bool TopLevelObject) {
1289 unsigned Index = 0, StructuredIndex = 0;
1290 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1291 Index, StructuredList, StructuredIndex, TopLevelObject);
1292 if (StructuredList) {
1293 QualType ExprTy = T;
1294 if (!ExprTy->isArrayType())
1295 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1296 if (!VerifyOnly)
1297 IList->setType(ExprTy);
1298 StructuredList->setType(ExprTy);
1299 }
1300 if (hadError)
1301 return;
1302
1303 // Don't complain for incomplete types, since we'll get an error elsewhere.
1304 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1305 // We have leftover initializers
1306 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1307 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1308 hadError = ExtraInitsIsError;
1309 if (VerifyOnly) {
1310 return;
1311 } else if (StructuredIndex == 1 &&
1312 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1313 SIF_None) {
1314 unsigned DK =
1315 ExtraInitsIsError
1316 ? diag::err_excess_initializers_in_char_array_initializer
1317 : diag::ext_excess_initializers_in_char_array_initializer;
1318 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1319 << IList->getInit(Index)->getSourceRange();
1320 } else if (T->isSizelessBuiltinType()) {
1321 unsigned DK = ExtraInitsIsError
1322 ? diag::err_excess_initializers_for_sizeless_type
1323 : diag::ext_excess_initializers_for_sizeless_type;
1324 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1325 << T << IList->getInit(Index)->getSourceRange();
1326 } else {
1327 int initKind = T->isArrayType() ? 0 :
1328 T->isVectorType() ? 1 :
1329 T->isScalarType() ? 2 :
1330 T->isUnionType() ? 3 :
1331 4;
1332
1333 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1334 : diag::ext_excess_initializers;
1335 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1336 << initKind << IList->getInit(Index)->getSourceRange();
1337 }
1338 }
1339
1340 if (!VerifyOnly) {
1341 if (T->isScalarType() && IList->getNumInits() == 1 &&
1342 !isa<InitListExpr>(IList->getInit(0)))
1343 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1344
1345 // Warn if this is a class type that won't be an aggregate in future
1346 // versions of C++.
1347 auto *CXXRD = T->getAsCXXRecordDecl();
1348 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1349 // Don't warn if there's an equivalent default constructor that would be
1350 // used instead.
1351 bool HasEquivCtor = false;
1352 if (IList->getNumInits() == 0) {
1353 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1354 HasEquivCtor = CD && !CD->isDeleted();
1355 }
1356
1357 if (!HasEquivCtor) {
1358 SemaRef.Diag(IList->getBeginLoc(),
1359 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1360 << IList->getSourceRange() << T;
1361 }
1362 }
1363 }
1364}
1365
1366void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1367 InitListExpr *IList,
1368 QualType &DeclType,
1369 bool SubobjectIsDesignatorContext,
1370 unsigned &Index,
1371 InitListExpr *StructuredList,
1372 unsigned &StructuredIndex,
1373 bool TopLevelObject) {
1374 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1375 // Explicitly braced initializer for complex type can be real+imaginary
1376 // parts.
1377 CheckComplexType(Entity, IList, DeclType, Index,
1378 StructuredList, StructuredIndex);
1379 } else if (DeclType->isScalarType()) {
1380 CheckScalarType(Entity, IList, DeclType, Index,
1381 StructuredList, StructuredIndex);
1382 } else if (DeclType->isVectorType()) {
1383 CheckVectorType(Entity, IList, DeclType, Index,
1384 StructuredList, StructuredIndex);
1385 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1386 auto Bases =
1389 if (DeclType->isRecordType()) {
1390 assert(DeclType->isAggregateType() &&
1391 "non-aggregate records should be handed in CheckSubElementType");
1392 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1393 Bases = CXXRD->bases();
1394 } else {
1395 Bases = cast<CXXRecordDecl>(RD)->bases();
1396 }
1397 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1398 SubobjectIsDesignatorContext, Index, StructuredList,
1399 StructuredIndex, TopLevelObject);
1400 } else if (DeclType->isArrayType()) {
1401 llvm::APSInt Zero(
1402 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1403 false);
1404 CheckArrayType(Entity, IList, DeclType, Zero,
1405 SubobjectIsDesignatorContext, Index,
1406 StructuredList, StructuredIndex);
1407 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1408 // This type is invalid, issue a diagnostic.
1409 ++Index;
1410 if (!VerifyOnly)
1411 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1412 << DeclType;
1413 hadError = true;
1414 } else if (DeclType->isReferenceType()) {
1415 CheckReferenceType(Entity, IList, DeclType, Index,
1416 StructuredList, StructuredIndex);
1417 } else if (DeclType->isObjCObjectType()) {
1418 if (!VerifyOnly)
1419 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1420 hadError = true;
1421 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1422 DeclType->isSizelessBuiltinType()) {
1423 // Checks for scalar type are sufficient for these types too.
1424 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1425 StructuredIndex);
1426 } else if (DeclType->isDependentType()) {
1427 // C++ [over.match.class.deduct]p1.5:
1428 // brace elision is not considered for any aggregate element that has a
1429 // dependent non-array type or an array type with a value-dependent bound
1430 ++Index;
1431 assert(AggrDeductionCandidateParamTypes);
1432 AggrDeductionCandidateParamTypes->push_back(DeclType);
1433 } else {
1434 if (!VerifyOnly)
1435 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1436 << DeclType;
1437 hadError = true;
1438 }
1439}
1440
1441void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1442 InitListExpr *IList,
1443 QualType ElemType,
1444 unsigned &Index,
1445 InitListExpr *StructuredList,
1446 unsigned &StructuredIndex,
1447 bool DirectlyDesignated) {
1448 Expr *expr = IList->getInit(Index);
1449
1450 if (ElemType->isReferenceType())
1451 return CheckReferenceType(Entity, IList, ElemType, Index,
1452 StructuredList, StructuredIndex);
1453
1454 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1455 if (SubInitList->getNumInits() == 1 &&
1456 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1457 SIF_None) {
1458 // FIXME: It would be more faithful and no less correct to include an
1459 // InitListExpr in the semantic form of the initializer list in this case.
1460 expr = SubInitList->getInit(0);
1461 }
1462 // Nested aggregate initialization and C++ initialization are handled later.
1463 } else if (isa<ImplicitValueInitExpr>(expr)) {
1464 // This happens during template instantiation when we see an InitListExpr
1465 // that we've already checked once.
1466 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1467 "found implicit initialization for the wrong type");
1468 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1469 ++Index;
1470 return;
1471 }
1472
1473 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1474 // C++ [dcl.init.aggr]p2:
1475 // Each member is copy-initialized from the corresponding
1476 // initializer-clause.
1477
1478 // FIXME: Better EqualLoc?
1481
1482 // Vector elements can be initialized from other vectors in which case
1483 // we need initialization entity with a type of a vector (and not a vector
1484 // element!) initializing multiple vector elements.
1485 auto TmpEntity =
1486 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1488 : Entity;
1489
1490 if (TmpEntity.getType()->isDependentType()) {
1491 // C++ [over.match.class.deduct]p1.5:
1492 // brace elision is not considered for any aggregate element that has a
1493 // dependent non-array type or an array type with a value-dependent
1494 // bound
1495 assert(AggrDeductionCandidateParamTypes);
1496
1497 // In the presence of a braced-init-list within the initializer, we should
1498 // not perform brace-elision, even if brace elision would otherwise be
1499 // applicable. For example, given:
1500 //
1501 // template <class T> struct Foo {
1502 // T t[2];
1503 // };
1504 //
1505 // Foo t = {{1, 2}};
1506 //
1507 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1508 // {{1, 2}}.
1509 if (isa<InitListExpr, DesignatedInitExpr>(expr) ||
1510 !isa_and_present<ConstantArrayType>(
1511 SemaRef.Context.getAsArrayType(ElemType))) {
1512 ++Index;
1513 AggrDeductionCandidateParamTypes->push_back(ElemType);
1514 return;
1515 }
1516 } else {
1517 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1518 /*TopLevelOfInitList*/ true);
1519 // C++14 [dcl.init.aggr]p13:
1520 // If the assignment-expression can initialize a member, the member is
1521 // initialized. Otherwise [...] brace elision is assumed
1522 //
1523 // Brace elision is never performed if the element is not an
1524 // assignment-expression.
1525 if (Seq || isa<InitListExpr>(expr)) {
1526 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1527 expr = HandleEmbed(Embed, Entity);
1528 }
1529 if (!VerifyOnly) {
1530 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1531 if (Result.isInvalid())
1532 hadError = true;
1533
1534 UpdateStructuredListElement(StructuredList, StructuredIndex,
1535 Result.getAs<Expr>());
1536 } else if (!Seq) {
1537 hadError = true;
1538 } else if (StructuredList) {
1539 UpdateStructuredListElement(StructuredList, StructuredIndex,
1540 getDummyInit());
1541 }
1542 if (!CurEmbed)
1543 ++Index;
1544 if (AggrDeductionCandidateParamTypes)
1545 AggrDeductionCandidateParamTypes->push_back(ElemType);
1546 return;
1547 }
1548 }
1549
1550 // Fall through for subaggregate initialization
1551 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1552 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1553 return CheckScalarType(Entity, IList, ElemType, Index,
1554 StructuredList, StructuredIndex);
1555 } else if (const ArrayType *arrayType =
1556 SemaRef.Context.getAsArrayType(ElemType)) {
1557 // arrayType can be incomplete if we're initializing a flexible
1558 // array member. There's nothing we can do with the completed
1559 // type here, though.
1560
1561 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1562 // FIXME: Should we do this checking in verify-only mode?
1563 if (!VerifyOnly)
1564 CheckStringInit(expr, ElemType, arrayType, SemaRef,
1565 SemaRef.getLangOpts().C23 &&
1567 if (StructuredList)
1568 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1569 ++Index;
1570 return;
1571 }
1572
1573 // Fall through for subaggregate initialization.
1574
1575 } else {
1576 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1577 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1578
1579 // C99 6.7.8p13:
1580 //
1581 // The initializer for a structure or union object that has
1582 // automatic storage duration shall be either an initializer
1583 // list as described below, or a single expression that has
1584 // compatible structure or union type. In the latter case, the
1585 // initial value of the object, including unnamed members, is
1586 // that of the expression.
1587 ExprResult ExprRes = expr;
1589 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1590 if (ExprRes.isInvalid())
1591 hadError = true;
1592 else {
1593 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1594 if (ExprRes.isInvalid())
1595 hadError = true;
1596 }
1597 UpdateStructuredListElement(StructuredList, StructuredIndex,
1598 ExprRes.getAs<Expr>());
1599 ++Index;
1600 return;
1601 }
1602 ExprRes.get();
1603 // Fall through for subaggregate initialization
1604 }
1605
1606 // C++ [dcl.init.aggr]p12:
1607 //
1608 // [...] Otherwise, if the member is itself a non-empty
1609 // subaggregate, brace elision is assumed and the initializer is
1610 // considered for the initialization of the first member of
1611 // the subaggregate.
1612 // OpenCL vector initializer is handled elsewhere.
1613 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1614 ElemType->isAggregateType()) {
1615 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1616 StructuredIndex);
1617 ++StructuredIndex;
1618
1619 // In C++20, brace elision is not permitted for a designated initializer.
1620 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1621 if (InOverloadResolution)
1622 hadError = true;
1623 if (!VerifyOnly) {
1624 SemaRef.Diag(expr->getBeginLoc(),
1625 diag::ext_designated_init_brace_elision)
1626 << expr->getSourceRange()
1627 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1629 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1630 }
1631 }
1632 } else {
1633 if (!VerifyOnly) {
1634 // We cannot initialize this element, so let PerformCopyInitialization
1635 // produce the appropriate diagnostic. We already checked that this
1636 // initialization will fail.
1639 /*TopLevelOfInitList=*/true);
1640 (void)Copy;
1641 assert(Copy.isInvalid() &&
1642 "expected non-aggregate initialization to fail");
1643 }
1644 hadError = true;
1645 ++Index;
1646 ++StructuredIndex;
1647 }
1648}
1649
1650void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1651 InitListExpr *IList, QualType DeclType,
1652 unsigned &Index,
1653 InitListExpr *StructuredList,
1654 unsigned &StructuredIndex) {
1655 assert(Index == 0 && "Index in explicit init list must be zero");
1656
1657 // As an extension, clang supports complex initializers, which initialize
1658 // a complex number component-wise. When an explicit initializer list for
1659 // a complex number contains two initializers, this extension kicks in:
1660 // it expects the initializer list to contain two elements convertible to
1661 // the element type of the complex type. The first element initializes
1662 // the real part, and the second element intitializes the imaginary part.
1663
1664 if (IList->getNumInits() < 2)
1665 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1666 StructuredIndex);
1667
1668 // This is an extension in C. (The builtin _Complex type does not exist
1669 // in the C++ standard.)
1670 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1671 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1672 << IList->getSourceRange();
1673
1674 // Initialize the complex number.
1675 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1676 InitializedEntity ElementEntity =
1678
1679 for (unsigned i = 0; i < 2; ++i) {
1680 ElementEntity.setElementIndex(Index);
1681 CheckSubElementType(ElementEntity, IList, elementType, Index,
1682 StructuredList, StructuredIndex);
1683 }
1684}
1685
1686void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1687 InitListExpr *IList, QualType DeclType,
1688 unsigned &Index,
1689 InitListExpr *StructuredList,
1690 unsigned &StructuredIndex) {
1691 if (Index >= IList->getNumInits()) {
1692 if (!VerifyOnly) {
1693 if (SemaRef.getLangOpts().CPlusPlus) {
1694 if (DeclType->isSizelessBuiltinType())
1695 SemaRef.Diag(IList->getBeginLoc(),
1696 SemaRef.getLangOpts().CPlusPlus11
1697 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1698 : diag::err_empty_sizeless_initializer)
1699 << DeclType << IList->getSourceRange();
1700 else
1701 SemaRef.Diag(IList->getBeginLoc(),
1702 SemaRef.getLangOpts().CPlusPlus11
1703 ? diag::warn_cxx98_compat_empty_scalar_initializer
1704 : diag::err_empty_scalar_initializer)
1705 << IList->getSourceRange();
1706 }
1707 }
1708 hadError =
1709 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1710 ++Index;
1711 ++StructuredIndex;
1712 return;
1713 }
1714
1715 Expr *expr = IList->getInit(Index);
1716 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1717 // FIXME: This is invalid, and accepting it causes overload resolution
1718 // to pick the wrong overload in some corner cases.
1719 if (!VerifyOnly)
1720 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1721 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1722
1723 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1724 StructuredIndex);
1725 return;
1726 } else if (isa<DesignatedInitExpr>(expr)) {
1727 if (!VerifyOnly)
1728 SemaRef.Diag(expr->getBeginLoc(),
1729 diag::err_designator_for_scalar_or_sizeless_init)
1730 << DeclType->isSizelessBuiltinType() << DeclType
1731 << expr->getSourceRange();
1732 hadError = true;
1733 ++Index;
1734 ++StructuredIndex;
1735 return;
1736 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1737 expr = HandleEmbed(Embed, Entity);
1738 }
1739
1740 ExprResult Result;
1741 if (VerifyOnly) {
1742 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1743 Result = getDummyInit();
1744 else
1745 Result = ExprError();
1746 } else {
1747 Result =
1748 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1749 /*TopLevelOfInitList=*/true);
1750 }
1751
1752 Expr *ResultExpr = nullptr;
1753
1754 if (Result.isInvalid())
1755 hadError = true; // types weren't compatible.
1756 else {
1757 ResultExpr = Result.getAs<Expr>();
1758
1759 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1760 // The type was promoted, update initializer list.
1761 // FIXME: Why are we updating the syntactic init list?
1762 IList->setInit(Index, ResultExpr);
1763 }
1764 }
1765
1766 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1767 if (!CurEmbed)
1768 ++Index;
1769 if (AggrDeductionCandidateParamTypes)
1770 AggrDeductionCandidateParamTypes->push_back(DeclType);
1771}
1772
1773void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1774 InitListExpr *IList, QualType DeclType,
1775 unsigned &Index,
1776 InitListExpr *StructuredList,
1777 unsigned &StructuredIndex) {
1778 if (Index >= IList->getNumInits()) {
1779 // FIXME: It would be wonderful if we could point at the actual member. In
1780 // general, it would be useful to pass location information down the stack,
1781 // so that we know the location (or decl) of the "current object" being
1782 // initialized.
1783 if (!VerifyOnly)
1784 SemaRef.Diag(IList->getBeginLoc(),
1785 diag::err_init_reference_member_uninitialized)
1786 << DeclType << IList->getSourceRange();
1787 hadError = true;
1788 ++Index;
1789 ++StructuredIndex;
1790 return;
1791 }
1792
1793 Expr *expr = IList->getInit(Index);
1794 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1795 if (!VerifyOnly)
1796 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1797 << DeclType << IList->getSourceRange();
1798 hadError = true;
1799 ++Index;
1800 ++StructuredIndex;
1801 return;
1802 }
1803
1804 ExprResult Result;
1805 if (VerifyOnly) {
1806 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1807 Result = getDummyInit();
1808 else
1809 Result = ExprError();
1810 } else {
1811 Result =
1812 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1813 /*TopLevelOfInitList=*/true);
1814 }
1815
1816 if (Result.isInvalid())
1817 hadError = true;
1818
1819 expr = Result.getAs<Expr>();
1820 // FIXME: Why are we updating the syntactic init list?
1821 if (!VerifyOnly && expr)
1822 IList->setInit(Index, expr);
1823
1824 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1825 ++Index;
1826 if (AggrDeductionCandidateParamTypes)
1827 AggrDeductionCandidateParamTypes->push_back(DeclType);
1828}
1829
1830void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1831 InitListExpr *IList, QualType DeclType,
1832 unsigned &Index,
1833 InitListExpr *StructuredList,
1834 unsigned &StructuredIndex) {
1835 const VectorType *VT = DeclType->castAs<VectorType>();
1836 unsigned maxElements = VT->getNumElements();
1837 unsigned numEltsInit = 0;
1838 QualType elementType = VT->getElementType();
1839
1840 if (Index >= IList->getNumInits()) {
1841 // Make sure the element type can be value-initialized.
1842 CheckEmptyInitializable(
1844 IList->getEndLoc());
1845 return;
1846 }
1847
1848 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1849 // If the initializing element is a vector, try to copy-initialize
1850 // instead of breaking it apart (which is doomed to failure anyway).
1851 Expr *Init = IList->getInit(Index);
1852 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1853 ExprResult Result;
1854 if (VerifyOnly) {
1855 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1856 Result = getDummyInit();
1857 else
1858 Result = ExprError();
1859 } else {
1860 Result =
1861 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1862 /*TopLevelOfInitList=*/true);
1863 }
1864
1865 Expr *ResultExpr = nullptr;
1866 if (Result.isInvalid())
1867 hadError = true; // types weren't compatible.
1868 else {
1869 ResultExpr = Result.getAs<Expr>();
1870
1871 if (ResultExpr != Init && !VerifyOnly) {
1872 // The type was promoted, update initializer list.
1873 // FIXME: Why are we updating the syntactic init list?
1874 IList->setInit(Index, ResultExpr);
1875 }
1876 }
1877 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1878 ++Index;
1879 if (AggrDeductionCandidateParamTypes)
1880 AggrDeductionCandidateParamTypes->push_back(elementType);
1881 return;
1882 }
1883
1884 InitializedEntity ElementEntity =
1886
1887 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1888 // Don't attempt to go past the end of the init list
1889 if (Index >= IList->getNumInits()) {
1890 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1891 break;
1892 }
1893
1894 ElementEntity.setElementIndex(Index);
1895 CheckSubElementType(ElementEntity, IList, elementType, Index,
1896 StructuredList, StructuredIndex);
1897 }
1898
1899 if (VerifyOnly)
1900 return;
1901
1902 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1903 const VectorType *T = Entity.getType()->castAs<VectorType>();
1904 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1905 T->getVectorKind() == VectorKind::NeonPoly)) {
1906 // The ability to use vector initializer lists is a GNU vector extension
1907 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1908 // endian machines it works fine, however on big endian machines it
1909 // exhibits surprising behaviour:
1910 //
1911 // uint32x2_t x = {42, 64};
1912 // return vget_lane_u32(x, 0); // Will return 64.
1913 //
1914 // Because of this, explicitly call out that it is non-portable.
1915 //
1916 SemaRef.Diag(IList->getBeginLoc(),
1917 diag::warn_neon_vector_initializer_non_portable);
1918
1919 const char *typeCode;
1920 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1921
1922 if (elementType->isFloatingType())
1923 typeCode = "f";
1924 else if (elementType->isSignedIntegerType())
1925 typeCode = "s";
1926 else if (elementType->isUnsignedIntegerType())
1927 typeCode = "u";
1928 else
1929 llvm_unreachable("Invalid element type!");
1930
1931 SemaRef.Diag(IList->getBeginLoc(),
1932 SemaRef.Context.getTypeSize(VT) > 64
1933 ? diag::note_neon_vector_initializer_non_portable_q
1934 : diag::note_neon_vector_initializer_non_portable)
1935 << typeCode << typeSize;
1936 }
1937
1938 return;
1939 }
1940
1941 InitializedEntity ElementEntity =
1943
1944 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1945 for (unsigned i = 0; i < maxElements; ++i) {
1946 // Don't attempt to go past the end of the init list
1947 if (Index >= IList->getNumInits())
1948 break;
1949
1950 ElementEntity.setElementIndex(Index);
1951
1952 QualType IType = IList->getInit(Index)->getType();
1953 if (!IType->isVectorType()) {
1954 CheckSubElementType(ElementEntity, IList, elementType, Index,
1955 StructuredList, StructuredIndex);
1956 ++numEltsInit;
1957 } else {
1958 QualType VecType;
1959 const VectorType *IVT = IType->castAs<VectorType>();
1960 unsigned numIElts = IVT->getNumElements();
1961
1962 if (IType->isExtVectorType())
1963 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1964 else
1965 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1966 IVT->getVectorKind());
1967 CheckSubElementType(ElementEntity, IList, VecType, Index,
1968 StructuredList, StructuredIndex);
1969 numEltsInit += numIElts;
1970 }
1971 }
1972
1973 // OpenCL and HLSL require all elements to be initialized.
1974 if (numEltsInit != maxElements) {
1975 if (!VerifyOnly)
1976 SemaRef.Diag(IList->getBeginLoc(),
1977 diag::err_vector_incorrect_num_elements)
1978 << (numEltsInit < maxElements) << maxElements << numEltsInit
1979 << /*initialization*/ 0;
1980 hadError = true;
1981 }
1982}
1983
1984/// Check if the type of a class element has an accessible destructor, and marks
1985/// it referenced. Returns true if we shouldn't form a reference to the
1986/// destructor.
1987///
1988/// Aggregate initialization requires a class element's destructor be
1989/// accessible per 11.6.1 [dcl.init.aggr]:
1990///
1991/// The destructor for each element of class type is potentially invoked
1992/// (15.4 [class.dtor]) from the context where the aggregate initialization
1993/// occurs.
1995 Sema &SemaRef) {
1996 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1997 if (!CXXRD)
1998 return false;
1999
2001 if (!Destructor)
2002 return false;
2003
2005 SemaRef.PDiag(diag::err_access_dtor_temp)
2006 << ElementType);
2008 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
2009}
2010
2011static bool
2013 const InitializedEntity &Entity,
2014 ASTContext &Context) {
2015 QualType InitType = Entity.getType();
2016 const InitializedEntity *Parent = &Entity;
2017
2018 while (Parent) {
2019 InitType = Parent->getType();
2020 Parent = Parent->getParent();
2021 }
2022
2023 // Only one initializer, it's an embed and the types match;
2024 EmbedExpr *EE =
2025 ExprList.size() == 1
2026 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2027 : nullptr;
2028 if (!EE)
2029 return false;
2030
2031 if (InitType->isArrayType()) {
2032 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2033 QualType InitElementTy = InitArrayType->getElementType();
2034 QualType EmbedExprElementTy = EE->getDataStringLiteral()->getType();
2035 const bool TypesMatch =
2036 Context.typesAreCompatible(InitElementTy, EmbedExprElementTy) ||
2037 (InitElementTy->isCharType() && EmbedExprElementTy->isCharType());
2038 if (TypesMatch)
2039 return true;
2040 }
2041 return false;
2042}
2043
2044void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2045 InitListExpr *IList, QualType &DeclType,
2046 llvm::APSInt elementIndex,
2047 bool SubobjectIsDesignatorContext,
2048 unsigned &Index,
2049 InitListExpr *StructuredList,
2050 unsigned &StructuredIndex) {
2051 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2052
2053 if (!VerifyOnly) {
2054 if (checkDestructorReference(arrayType->getElementType(),
2055 IList->getEndLoc(), SemaRef)) {
2056 hadError = true;
2057 return;
2058 }
2059 }
2060
2061 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2062 SemaRef.Context)) {
2063 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2064 IList->setInit(0, Embed->getDataStringLiteral());
2065 }
2066
2067 // Check for the special-case of initializing an array with a string.
2068 if (Index < IList->getNumInits()) {
2069 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2070 SIF_None) {
2071 // We place the string literal directly into the resulting
2072 // initializer list. This is the only place where the structure
2073 // of the structured initializer list doesn't match exactly,
2074 // because doing so would involve allocating one character
2075 // constant for each string.
2076 // FIXME: Should we do these checks in verify-only mode too?
2077 if (!VerifyOnly)
2078 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
2079 SemaRef.getLangOpts().C23 &&
2081 if (StructuredList) {
2082 UpdateStructuredListElement(StructuredList, StructuredIndex,
2083 IList->getInit(Index));
2084 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2085 }
2086 ++Index;
2087 if (AggrDeductionCandidateParamTypes)
2088 AggrDeductionCandidateParamTypes->push_back(DeclType);
2089 return;
2090 }
2091 }
2092 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2093 // Check for VLAs; in standard C it would be possible to check this
2094 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2095 // them in all sorts of strange places).
2096 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2097 if (!VerifyOnly) {
2098 // C23 6.7.10p4: An entity of variable length array type shall not be
2099 // initialized except by an empty initializer.
2100 //
2101 // The C extension warnings are issued from ParseBraceInitializer() and
2102 // do not need to be issued here. However, we continue to issue an error
2103 // in the case there are initializers or we are compiling C++. We allow
2104 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2105 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2106 // FIXME: should we allow this construct in C++ when it makes sense to do
2107 // so?
2108 if (HasErr)
2109 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2110 diag::err_variable_object_no_init)
2111 << VAT->getSizeExpr()->getSourceRange();
2112 }
2113 hadError = HasErr;
2114 ++Index;
2115 ++StructuredIndex;
2116 return;
2117 }
2118
2119 // We might know the maximum number of elements in advance.
2120 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2121 elementIndex.isUnsigned());
2122 bool maxElementsKnown = false;
2123 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2124 maxElements = CAT->getSize();
2125 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2126 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2127 maxElementsKnown = true;
2128 }
2129
2130 QualType elementType = arrayType->getElementType();
2131 while (Index < IList->getNumInits()) {
2132 Expr *Init = IList->getInit(Index);
2133 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2134 // If we're not the subobject that matches up with the '{' for
2135 // the designator, we shouldn't be handling the
2136 // designator. Return immediately.
2137 if (!SubobjectIsDesignatorContext)
2138 return;
2139
2140 // Handle this designated initializer. elementIndex will be
2141 // updated to be the next array element we'll initialize.
2142 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2143 DeclType, nullptr, &elementIndex, Index,
2144 StructuredList, StructuredIndex, true,
2145 false)) {
2146 hadError = true;
2147 continue;
2148 }
2149
2150 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2151 maxElements = maxElements.extend(elementIndex.getBitWidth());
2152 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2153 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2154 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2155
2156 // If the array is of incomplete type, keep track of the number of
2157 // elements in the initializer.
2158 if (!maxElementsKnown && elementIndex > maxElements)
2159 maxElements = elementIndex;
2160
2161 continue;
2162 }
2163
2164 // If we know the maximum number of elements, and we've already
2165 // hit it, stop consuming elements in the initializer list.
2166 if (maxElementsKnown && elementIndex == maxElements)
2167 break;
2168
2170 SemaRef.Context, StructuredIndex, Entity);
2171
2172 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2173 // Check this element.
2174 CheckSubElementType(ElementEntity, IList, elementType, Index,
2175 StructuredList, StructuredIndex);
2176 ++elementIndex;
2177 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2178 if (CurEmbed) {
2179 elementIndex =
2180 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2181 } else {
2182 auto Embed = cast<EmbedExpr>(Init);
2183 elementIndex = elementIndex + Embed->getDataElementCount() -
2184 EmbedElementIndexBeforeInit - 1;
2185 }
2186 }
2187
2188 // If the array is of incomplete type, keep track of the number of
2189 // elements in the initializer.
2190 if (!maxElementsKnown && elementIndex > maxElements)
2191 maxElements = elementIndex;
2192 }
2193 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2194 // If this is an incomplete array type, the actual type needs to
2195 // be calculated here.
2196 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2197 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2198 // Sizing an array implicitly to zero is not allowed by ISO C,
2199 // but is supported by GNU.
2200 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2201 }
2202
2203 DeclType = SemaRef.Context.getConstantArrayType(
2204 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2205 }
2206 if (!hadError) {
2207 // If there are any members of the array that get value-initialized, check
2208 // that is possible. That happens if we know the bound and don't have
2209 // enough elements, or if we're performing an array new with an unknown
2210 // bound.
2211 if ((maxElementsKnown && elementIndex < maxElements) ||
2212 Entity.isVariableLengthArrayNew())
2213 CheckEmptyInitializable(
2215 IList->getEndLoc());
2216 }
2217}
2218
2219bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2220 Expr *InitExpr,
2221 FieldDecl *Field,
2222 bool TopLevelObject) {
2223 // Handle GNU flexible array initializers.
2224 unsigned FlexArrayDiag;
2225 if (isa<InitListExpr>(InitExpr) &&
2226 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2227 // Empty flexible array init always allowed as an extension
2228 FlexArrayDiag = diag::ext_flexible_array_init;
2229 } else if (!TopLevelObject) {
2230 // Disallow flexible array init on non-top-level object
2231 FlexArrayDiag = diag::err_flexible_array_init;
2232 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2233 // Disallow flexible array init on anything which is not a variable.
2234 FlexArrayDiag = diag::err_flexible_array_init;
2235 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2236 // Disallow flexible array init on local variables.
2237 FlexArrayDiag = diag::err_flexible_array_init;
2238 } else {
2239 // Allow other cases.
2240 FlexArrayDiag = diag::ext_flexible_array_init;
2241 }
2242
2243 if (!VerifyOnly) {
2244 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2245 << InitExpr->getBeginLoc();
2246 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2247 << Field;
2248 }
2249
2250 return FlexArrayDiag != diag::ext_flexible_array_init;
2251}
2252
2253static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2254 return StructuredList && StructuredList->getNumInits() == 1U;
2255}
2256
2257void InitListChecker::CheckStructUnionTypes(
2258 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2260 bool SubobjectIsDesignatorContext, unsigned &Index,
2261 InitListExpr *StructuredList, unsigned &StructuredIndex,
2262 bool TopLevelObject) {
2263 const RecordDecl *RD = getRecordDecl(DeclType);
2264
2265 // If the record is invalid, some of it's members are invalid. To avoid
2266 // confusion, we forgo checking the initializer for the entire record.
2267 if (RD->isInvalidDecl()) {
2268 // Assume it was supposed to consume a single initializer.
2269 ++Index;
2270 hadError = true;
2271 return;
2272 }
2273
2274 if (RD->isUnion() && IList->getNumInits() == 0) {
2275 if (!VerifyOnly)
2276 for (FieldDecl *FD : RD->fields()) {
2277 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2278 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2279 hadError = true;
2280 return;
2281 }
2282 }
2283
2284 // If there's a default initializer, use it.
2285 if (isa<CXXRecordDecl>(RD) &&
2286 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2287 if (!StructuredList)
2288 return;
2289 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2290 Field != FieldEnd; ++Field) {
2291 if (Field->hasInClassInitializer() ||
2292 (Field->isAnonymousStructOrUnion() &&
2293 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
2294 StructuredList->setInitializedFieldInUnion(*Field);
2295 // FIXME: Actually build a CXXDefaultInitExpr?
2296 return;
2297 }
2298 }
2299 llvm_unreachable("Couldn't find in-class initializer");
2300 }
2301
2302 // Value-initialize the first member of the union that isn't an unnamed
2303 // bitfield.
2304 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2305 Field != FieldEnd; ++Field) {
2306 if (!Field->isUnnamedBitField()) {
2307 CheckEmptyInitializable(
2308 InitializedEntity::InitializeMember(*Field, &Entity),
2309 IList->getEndLoc());
2310 if (StructuredList)
2311 StructuredList->setInitializedFieldInUnion(*Field);
2312 break;
2313 }
2314 }
2315 return;
2316 }
2317
2318 bool InitializedSomething = false;
2319
2320 // If we have any base classes, they are initialized prior to the fields.
2321 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2322 auto &Base = *I;
2323 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2324
2325 // Designated inits always initialize fields, so if we see one, all
2326 // remaining base classes have no explicit initializer.
2327 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2328 Init = nullptr;
2329
2330 // C++ [over.match.class.deduct]p1.6:
2331 // each non-trailing aggregate element that is a pack expansion is assumed
2332 // to correspond to no elements of the initializer list, and (1.7) a
2333 // trailing aggregate element that is a pack expansion is assumed to
2334 // correspond to all remaining elements of the initializer list (if any).
2335
2336 // C++ [over.match.class.deduct]p1.9:
2337 // ... except that additional parameter packs of the form P_j... are
2338 // inserted into the parameter list in their original aggregate element
2339 // position corresponding to each non-trailing aggregate element of
2340 // type P_j that was skipped because it was a parameter pack, and the
2341 // trailing sequence of parameters corresponding to a trailing
2342 // aggregate element that is a pack expansion (if any) is replaced
2343 // by a single parameter of the form T_n....
2344 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2345 AggrDeductionCandidateParamTypes->push_back(
2346 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2347
2348 // Trailing pack expansion
2349 if (I + 1 == E && RD->field_empty()) {
2350 if (Index < IList->getNumInits())
2351 Index = IList->getNumInits();
2352 return;
2353 }
2354
2355 continue;
2356 }
2357
2358 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2360 SemaRef.Context, &Base, false, &Entity);
2361 if (Init) {
2362 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2363 StructuredList, StructuredIndex);
2364 InitializedSomething = true;
2365 } else {
2366 CheckEmptyInitializable(BaseEntity, InitLoc);
2367 }
2368
2369 if (!VerifyOnly)
2370 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2371 hadError = true;
2372 return;
2373 }
2374 }
2375
2376 // If structDecl is a forward declaration, this loop won't do
2377 // anything except look at designated initializers; That's okay,
2378 // because an error should get printed out elsewhere. It might be
2379 // worthwhile to skip over the rest of the initializer, though.
2380 RecordDecl::field_iterator FieldEnd = RD->field_end();
2381 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2382 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2383 });
2384 bool HasDesignatedInit = false;
2385
2386 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2387
2388 while (Index < IList->getNumInits()) {
2389 Expr *Init = IList->getInit(Index);
2390 SourceLocation InitLoc = Init->getBeginLoc();
2391
2392 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2393 // If we're not the subobject that matches up with the '{' for
2394 // the designator, we shouldn't be handling the
2395 // designator. Return immediately.
2396 if (!SubobjectIsDesignatorContext)
2397 return;
2398
2399 HasDesignatedInit = true;
2400
2401 // Handle this designated initializer. Field will be updated to
2402 // the next field that we'll be initializing.
2403 bool DesignatedInitFailed = CheckDesignatedInitializer(
2404 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2405 StructuredList, StructuredIndex, true, TopLevelObject);
2406 if (DesignatedInitFailed)
2407 hadError = true;
2408
2409 // Find the field named by the designated initializer.
2410 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2411 if (!VerifyOnly && D->isFieldDesignator()) {
2412 FieldDecl *F = D->getFieldDecl();
2413 InitializedFields.insert(F);
2414 if (!DesignatedInitFailed) {
2415 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2416 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2417 hadError = true;
2418 return;
2419 }
2420 }
2421 }
2422
2423 InitializedSomething = true;
2424 continue;
2425 }
2426
2427 // Check if this is an initializer of forms:
2428 //
2429 // struct foo f = {};
2430 // struct foo g = {0};
2431 //
2432 // These are okay for randomized structures. [C99 6.7.8p19]
2433 //
2434 // Also, if there is only one element in the structure, we allow something
2435 // like this, because it's really not randomized in the traditional sense.
2436 //
2437 // struct foo h = {bar};
2438 auto IsZeroInitializer = [&](const Expr *I) {
2439 if (IList->getNumInits() == 1) {
2440 if (NumRecordDecls == 1)
2441 return true;
2442 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2443 return IL->getValue().isZero();
2444 }
2445 return false;
2446 };
2447
2448 // Don't allow non-designated initializers on randomized structures.
2449 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2450 if (!VerifyOnly)
2451 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2452 hadError = true;
2453 break;
2454 }
2455
2456 if (Field == FieldEnd) {
2457 // We've run out of fields. We're done.
2458 break;
2459 }
2460
2461 // We've already initialized a member of a union. We can stop entirely.
2462 if (InitializedSomething && RD->isUnion())
2463 return;
2464
2465 // Stop if we've hit a flexible array member.
2466 if (Field->getType()->isIncompleteArrayType())
2467 break;
2468
2469 if (Field->isUnnamedBitField()) {
2470 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2471 ++Field;
2472 continue;
2473 }
2474
2475 // Make sure we can use this declaration.
2476 bool InvalidUse;
2477 if (VerifyOnly)
2478 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2479 else
2480 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2481 *Field, IList->getInit(Index)->getBeginLoc());
2482 if (InvalidUse) {
2483 ++Index;
2484 ++Field;
2485 hadError = true;
2486 continue;
2487 }
2488
2489 if (!VerifyOnly) {
2490 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2491 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2492 hadError = true;
2493 return;
2494 }
2495 }
2496
2497 InitializedEntity MemberEntity =
2498 InitializedEntity::InitializeMember(*Field, &Entity);
2499 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2500 StructuredList, StructuredIndex);
2501 InitializedSomething = true;
2502 InitializedFields.insert(*Field);
2503 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2504 // Initialize the first field within the union.
2505 StructuredList->setInitializedFieldInUnion(*Field);
2506 }
2507
2508 ++Field;
2509 }
2510
2511 // Emit warnings for missing struct field initializers.
2512 // This check is disabled for designated initializers in C.
2513 // This matches gcc behaviour.
2514 bool IsCDesignatedInitializer =
2515 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2516 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2517 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2518 !IsCDesignatedInitializer) {
2519 // It is possible we have one or more unnamed bitfields remaining.
2520 // Find first (if any) named field and emit warning.
2521 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2522 : Field,
2523 end = RD->field_end();
2524 it != end; ++it) {
2525 if (HasDesignatedInit && InitializedFields.count(*it))
2526 continue;
2527
2528 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2529 !it->getType()->isIncompleteArrayType()) {
2530 auto Diag = HasDesignatedInit
2531 ? diag::warn_missing_designated_field_initializers
2532 : diag::warn_missing_field_initializers;
2533 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2534 break;
2535 }
2536 }
2537 }
2538
2539 // Check that any remaining fields can be value-initialized if we're not
2540 // building a structured list. (If we are, we'll check this later.)
2541 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2542 !Field->getType()->isIncompleteArrayType()) {
2543 for (; Field != FieldEnd && !hadError; ++Field) {
2544 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2545 CheckEmptyInitializable(
2546 InitializedEntity::InitializeMember(*Field, &Entity),
2547 IList->getEndLoc());
2548 }
2549 }
2550
2551 // Check that the types of the remaining fields have accessible destructors.
2552 if (!VerifyOnly) {
2553 // If the initializer expression has a designated initializer, check the
2554 // elements for which a designated initializer is not provided too.
2555 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2556 : Field;
2557 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2558 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2559 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2560 hadError = true;
2561 return;
2562 }
2563 }
2564 }
2565
2566 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2567 Index >= IList->getNumInits())
2568 return;
2569
2570 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2571 TopLevelObject)) {
2572 hadError = true;
2573 ++Index;
2574 return;
2575 }
2576
2577 InitializedEntity MemberEntity =
2578 InitializedEntity::InitializeMember(*Field, &Entity);
2579
2580 if (isa<InitListExpr>(IList->getInit(Index)) ||
2581 AggrDeductionCandidateParamTypes)
2582 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2583 StructuredList, StructuredIndex);
2584 else
2585 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2586 StructuredList, StructuredIndex);
2587
2588 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2589 // Initialize the first field within the union.
2590 StructuredList->setInitializedFieldInUnion(*Field);
2591 }
2592}
2593
2594/// Expand a field designator that refers to a member of an
2595/// anonymous struct or union into a series of field designators that
2596/// refers to the field within the appropriate subobject.
2597///
2599 DesignatedInitExpr *DIE,
2600 unsigned DesigIdx,
2601 IndirectFieldDecl *IndirectField) {
2603
2604 // Build the replacement designators.
2605 SmallVector<Designator, 4> Replacements;
2606 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2607 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2608 if (PI + 1 == PE)
2609 Replacements.push_back(Designator::CreateFieldDesignator(
2610 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2611 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2612 else
2613 Replacements.push_back(Designator::CreateFieldDesignator(
2614 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2615 assert(isa<FieldDecl>(*PI));
2616 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2617 }
2618
2619 // Expand the current designator into the set of replacement
2620 // designators, so we have a full subobject path down to where the
2621 // member of the anonymous struct/union is actually stored.
2622 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2623 &Replacements[0] + Replacements.size());
2624}
2625
2627 DesignatedInitExpr *DIE) {
2628 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2629 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2630 for (unsigned I = 0; I < NumIndexExprs; ++I)
2631 IndexExprs[I] = DIE->getSubExpr(I + 1);
2632 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2633 IndexExprs,
2634 DIE->getEqualOrColonLoc(),
2635 DIE->usesGNUSyntax(), DIE->getInit());
2636}
2637
2638namespace {
2639
2640// Callback to only accept typo corrections that are for field members of
2641// the given struct or union.
2642class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2643 public:
2644 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2645 : Record(RD) {}
2646
2647 bool ValidateCandidate(const TypoCorrection &candidate) override {
2648 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2649 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2650 }
2651
2652 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2653 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2654 }
2655
2656 private:
2657 const RecordDecl *Record;
2658};
2659
2660} // end anonymous namespace
2661
2662/// Check the well-formedness of a C99 designated initializer.
2663///
2664/// Determines whether the designated initializer @p DIE, which
2665/// resides at the given @p Index within the initializer list @p
2666/// IList, is well-formed for a current object of type @p DeclType
2667/// (C99 6.7.8). The actual subobject that this designator refers to
2668/// within the current subobject is returned in either
2669/// @p NextField or @p NextElementIndex (whichever is appropriate).
2670///
2671/// @param IList The initializer list in which this designated
2672/// initializer occurs.
2673///
2674/// @param DIE The designated initializer expression.
2675///
2676/// @param DesigIdx The index of the current designator.
2677///
2678/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2679/// into which the designation in @p DIE should refer.
2680///
2681/// @param NextField If non-NULL and the first designator in @p DIE is
2682/// a field, this will be set to the field declaration corresponding
2683/// to the field named by the designator. On input, this is expected to be
2684/// the next field that would be initialized in the absence of designation,
2685/// if the complete object being initialized is a struct.
2686///
2687/// @param NextElementIndex If non-NULL and the first designator in @p
2688/// DIE is an array designator or GNU array-range designator, this
2689/// will be set to the last index initialized by this designator.
2690///
2691/// @param Index Index into @p IList where the designated initializer
2692/// @p DIE occurs.
2693///
2694/// @param StructuredList The initializer list expression that
2695/// describes all of the subobject initializers in the order they'll
2696/// actually be initialized.
2697///
2698/// @returns true if there was an error, false otherwise.
2699bool
2700InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2701 InitListExpr *IList,
2702 DesignatedInitExpr *DIE,
2703 unsigned DesigIdx,
2704 QualType &CurrentObjectType,
2705 RecordDecl::field_iterator *NextField,
2706 llvm::APSInt *NextElementIndex,
2707 unsigned &Index,
2708 InitListExpr *StructuredList,
2709 unsigned &StructuredIndex,
2710 bool FinishSubobjectInit,
2711 bool TopLevelObject) {
2712 if (DesigIdx == DIE->size()) {
2713 // C++20 designated initialization can result in direct-list-initialization
2714 // of the designated subobject. This is the only way that we can end up
2715 // performing direct initialization as part of aggregate initialization, so
2716 // it needs special handling.
2717 if (DIE->isDirectInit()) {
2718 Expr *Init = DIE->getInit();
2719 assert(isa<InitListExpr>(Init) &&
2720 "designator result in direct non-list initialization?");
2722 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2723 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2724 /*TopLevelOfInitList*/ true);
2725 if (StructuredList) {
2726 ExprResult Result = VerifyOnly
2727 ? getDummyInit()
2728 : Seq.Perform(SemaRef, Entity, Kind, Init);
2729 UpdateStructuredListElement(StructuredList, StructuredIndex,
2730 Result.get());
2731 }
2732 ++Index;
2733 if (AggrDeductionCandidateParamTypes)
2734 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2735 return !Seq;
2736 }
2737
2738 // Check the actual initialization for the designated object type.
2739 bool prevHadError = hadError;
2740
2741 // Temporarily remove the designator expression from the
2742 // initializer list that the child calls see, so that we don't try
2743 // to re-process the designator.
2744 unsigned OldIndex = Index;
2745 IList->setInit(OldIndex, DIE->getInit());
2746
2747 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2748 StructuredIndex, /*DirectlyDesignated=*/true);
2749
2750 // Restore the designated initializer expression in the syntactic
2751 // form of the initializer list.
2752 if (IList->getInit(OldIndex) != DIE->getInit())
2753 DIE->setInit(IList->getInit(OldIndex));
2754 IList->setInit(OldIndex, DIE);
2755
2756 return hadError && !prevHadError;
2757 }
2758
2760 bool IsFirstDesignator = (DesigIdx == 0);
2761 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2762 // Determine the structural initializer list that corresponds to the
2763 // current subobject.
2764 if (IsFirstDesignator)
2765 StructuredList = FullyStructuredList;
2766 else {
2767 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2768 StructuredList->getInit(StructuredIndex) : nullptr;
2769 if (!ExistingInit && StructuredList->hasArrayFiller())
2770 ExistingInit = StructuredList->getArrayFiller();
2771
2772 if (!ExistingInit)
2773 StructuredList = getStructuredSubobjectInit(
2774 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2775 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2776 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2777 StructuredList = Result;
2778 else {
2779 // We are creating an initializer list that initializes the
2780 // subobjects of the current object, but there was already an
2781 // initialization that completely initialized the current
2782 // subobject, e.g., by a compound literal:
2783 //
2784 // struct X { int a, b; };
2785 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2786 //
2787 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2788 // designated initializer re-initializes only its current object
2789 // subobject [0].b.
2790 diagnoseInitOverride(ExistingInit,
2791 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2792 /*UnionOverride=*/false,
2793 /*FullyOverwritten=*/false);
2794
2795 if (!VerifyOnly) {
2797 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2798 StructuredList = E->getUpdater();
2799 else {
2800 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2802 ExistingInit, DIE->getEndLoc());
2803 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2804 StructuredList = DIUE->getUpdater();
2805 }
2806 } else {
2807 // We don't need to track the structured representation of a
2808 // designated init update of an already-fully-initialized object in
2809 // verify-only mode. The only reason we would need the structure is
2810 // to determine where the uninitialized "holes" are, and in this
2811 // case, we know there aren't any and we can't introduce any.
2812 StructuredList = nullptr;
2813 }
2814 }
2815 }
2816 }
2817
2818 if (D->isFieldDesignator()) {
2819 // C99 6.7.8p7:
2820 //
2821 // If a designator has the form
2822 //
2823 // . identifier
2824 //
2825 // then the current object (defined below) shall have
2826 // structure or union type and the identifier shall be the
2827 // name of a member of that type.
2828 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2829 if (!RD) {
2830 SourceLocation Loc = D->getDotLoc();
2831 if (Loc.isInvalid())
2832 Loc = D->getFieldLoc();
2833 if (!VerifyOnly)
2834 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2835 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2836 ++Index;
2837 return true;
2838 }
2839
2840 FieldDecl *KnownField = D->getFieldDecl();
2841 if (!KnownField) {
2842 const IdentifierInfo *FieldName = D->getFieldName();
2843 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2844 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2845 KnownField = FD;
2846 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2847 // In verify mode, don't modify the original.
2848 if (VerifyOnly)
2849 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2850 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2851 D = DIE->getDesignator(DesigIdx);
2852 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2853 }
2854 if (!KnownField) {
2855 if (VerifyOnly) {
2856 ++Index;
2857 return true; // No typo correction when just trying this out.
2858 }
2859
2860 // We found a placeholder variable
2861 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2862 FieldName)) {
2863 ++Index;
2864 return true;
2865 }
2866 // Name lookup found something, but it wasn't a field.
2867 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2868 !Lookup.empty()) {
2869 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2870 << FieldName;
2871 SemaRef.Diag(Lookup.front()->getLocation(),
2872 diag::note_field_designator_found);
2873 ++Index;
2874 return true;
2875 }
2876
2877 // Name lookup didn't find anything.
2878 // Determine whether this was a typo for another field name.
2879 FieldInitializerValidatorCCC CCC(RD);
2880 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2881 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2882 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2884 SemaRef.diagnoseTypo(
2885 Corrected,
2886 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2887 << FieldName << CurrentObjectType);
2888 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2889 hadError = true;
2890 } else {
2891 // Typo correction didn't find anything.
2892 SourceLocation Loc = D->getFieldLoc();
2893
2894 // The loc can be invalid with a "null" designator (i.e. an anonymous
2895 // union/struct). Do our best to approximate the location.
2896 if (Loc.isInvalid())
2897 Loc = IList->getBeginLoc();
2898
2899 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2900 << FieldName << CurrentObjectType << DIE->getSourceRange();
2901 ++Index;
2902 return true;
2903 }
2904 }
2905 }
2906
2907 unsigned NumBases = 0;
2908 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2909 NumBases = CXXRD->getNumBases();
2910
2911 unsigned FieldIndex = NumBases;
2912
2913 for (auto *FI : RD->fields()) {
2914 if (FI->isUnnamedBitField())
2915 continue;
2916 if (declaresSameEntity(KnownField, FI)) {
2917 KnownField = FI;
2918 break;
2919 }
2920 ++FieldIndex;
2921 }
2922
2925
2926 // All of the fields of a union are located at the same place in
2927 // the initializer list.
2928 if (RD->isUnion()) {
2929 FieldIndex = 0;
2930 if (StructuredList) {
2931 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2932 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2933 assert(StructuredList->getNumInits() == 1
2934 && "A union should never have more than one initializer!");
2935
2936 Expr *ExistingInit = StructuredList->getInit(0);
2937 if (ExistingInit) {
2938 // We're about to throw away an initializer, emit warning.
2939 diagnoseInitOverride(
2940 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2941 /*UnionOverride=*/true,
2942 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2943 : true);
2944 }
2945
2946 // remove existing initializer
2947 StructuredList->resizeInits(SemaRef.Context, 0);
2948 StructuredList->setInitializedFieldInUnion(nullptr);
2949 }
2950
2951 StructuredList->setInitializedFieldInUnion(*Field);
2952 }
2953 }
2954
2955 // Make sure we can use this declaration.
2956 bool InvalidUse;
2957 if (VerifyOnly)
2958 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2959 else
2960 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2961 if (InvalidUse) {
2962 ++Index;
2963 return true;
2964 }
2965
2966 // C++20 [dcl.init.list]p3:
2967 // The ordered identifiers in the designators of the designated-
2968 // initializer-list shall form a subsequence of the ordered identifiers
2969 // in the direct non-static data members of T.
2970 //
2971 // Note that this is not a condition on forming the aggregate
2972 // initialization, only on actually performing initialization,
2973 // so it is not checked in VerifyOnly mode.
2974 //
2975 // FIXME: This is the only reordering diagnostic we produce, and it only
2976 // catches cases where we have a top-level field designator that jumps
2977 // backwards. This is the only such case that is reachable in an
2978 // otherwise-valid C++20 program, so is the only case that's required for
2979 // conformance, but for consistency, we should diagnose all the other
2980 // cases where a designator takes us backwards too.
2981 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2982 NextField &&
2983 (*NextField == RD->field_end() ||
2984 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2985 // Find the field that we just initialized.
2986 FieldDecl *PrevField = nullptr;
2987 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2988 if (FI->isUnnamedBitField())
2989 continue;
2990 if (*NextField != RD->field_end() &&
2991 declaresSameEntity(*FI, **NextField))
2992 break;
2993 PrevField = *FI;
2994 }
2995
2996 if (PrevField &&
2997 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2998 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2999 diag::ext_designated_init_reordered)
3000 << KnownField << PrevField << DIE->getSourceRange();
3001
3002 unsigned OldIndex = StructuredIndex - 1;
3003 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3004 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
3005 SemaRef.Diag(PrevInit->getBeginLoc(),
3006 diag::note_previous_field_init)
3007 << PrevField << PrevInit->getSourceRange();
3008 }
3009 }
3010 }
3011 }
3012
3013
3014 // Update the designator with the field declaration.
3015 if (!VerifyOnly)
3016 D->setFieldDecl(*Field);
3017
3018 // Make sure that our non-designated initializer list has space
3019 // for a subobject corresponding to this field.
3020 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3021 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3022
3023 // This designator names a flexible array member.
3024 if (Field->getType()->isIncompleteArrayType()) {
3025 bool Invalid = false;
3026 if ((DesigIdx + 1) != DIE->size()) {
3027 // We can't designate an object within the flexible array
3028 // member (because GCC doesn't allow it).
3029 if (!VerifyOnly) {
3031 = DIE->getDesignator(DesigIdx + 1);
3032 SemaRef.Diag(NextD->getBeginLoc(),
3033 diag::err_designator_into_flexible_array_member)
3034 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3035 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3036 << *Field;
3037 }
3038 Invalid = true;
3039 }
3040
3041 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3042 !isa<StringLiteral>(DIE->getInit())) {
3043 // The initializer is not an initializer list.
3044 if (!VerifyOnly) {
3045 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3046 diag::err_flexible_array_init_needs_braces)
3047 << DIE->getInit()->getSourceRange();
3048 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3049 << *Field;
3050 }
3051 Invalid = true;
3052 }
3053
3054 // Check GNU flexible array initializer.
3055 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3056 TopLevelObject))
3057 Invalid = true;
3058
3059 if (Invalid) {
3060 ++Index;
3061 return true;
3062 }
3063
3064 // Initialize the array.
3065 bool prevHadError = hadError;
3066 unsigned newStructuredIndex = FieldIndex;
3067 unsigned OldIndex = Index;
3068 IList->setInit(Index, DIE->getInit());
3069
3070 InitializedEntity MemberEntity =
3071 InitializedEntity::InitializeMember(*Field, &Entity);
3072 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3073 StructuredList, newStructuredIndex);
3074
3075 IList->setInit(OldIndex, DIE);
3076 if (hadError && !prevHadError) {
3077 ++Field;
3078 ++FieldIndex;
3079 if (NextField)
3080 *NextField = Field;
3081 StructuredIndex = FieldIndex;
3082 return true;
3083 }
3084 } else {
3085 // Recurse to check later designated subobjects.
3086 QualType FieldType = Field->getType();
3087 unsigned newStructuredIndex = FieldIndex;
3088
3089 InitializedEntity MemberEntity =
3090 InitializedEntity::InitializeMember(*Field, &Entity);
3091 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3092 FieldType, nullptr, nullptr, Index,
3093 StructuredList, newStructuredIndex,
3094 FinishSubobjectInit, false))
3095 return true;
3096 }
3097
3098 // Find the position of the next field to be initialized in this
3099 // subobject.
3100 ++Field;
3101 ++FieldIndex;
3102
3103 // If this the first designator, our caller will continue checking
3104 // the rest of this struct/class/union subobject.
3105 if (IsFirstDesignator) {
3106 if (Field != RD->field_end() && Field->isUnnamedBitField())
3107 ++Field;
3108
3109 if (NextField)
3110 *NextField = Field;
3111
3112 StructuredIndex = FieldIndex;
3113 return false;
3114 }
3115
3116 if (!FinishSubobjectInit)
3117 return false;
3118
3119 // We've already initialized something in the union; we're done.
3120 if (RD->isUnion())
3121 return hadError;
3122
3123 // Check the remaining fields within this class/struct/union subobject.
3124 bool prevHadError = hadError;
3125
3126 auto NoBases =
3129 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3130 false, Index, StructuredList, FieldIndex);
3131 return hadError && !prevHadError;
3132 }
3133
3134 // C99 6.7.8p6:
3135 //
3136 // If a designator has the form
3137 //
3138 // [ constant-expression ]
3139 //
3140 // then the current object (defined below) shall have array
3141 // type and the expression shall be an integer constant
3142 // expression. If the array is of unknown size, any
3143 // nonnegative value is valid.
3144 //
3145 // Additionally, cope with the GNU extension that permits
3146 // designators of the form
3147 //
3148 // [ constant-expression ... constant-expression ]
3149 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3150 if (!AT) {
3151 if (!VerifyOnly)
3152 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3153 << CurrentObjectType;
3154 ++Index;
3155 return true;
3156 }
3157
3158 Expr *IndexExpr = nullptr;
3159 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3160 if (D->isArrayDesignator()) {
3161 IndexExpr = DIE->getArrayIndex(*D);
3162 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3163 DesignatedEndIndex = DesignatedStartIndex;
3164 } else {
3165 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3166
3167 DesignatedStartIndex =
3169 DesignatedEndIndex =
3171 IndexExpr = DIE->getArrayRangeEnd(*D);
3172
3173 // Codegen can't handle evaluating array range designators that have side
3174 // effects, because we replicate the AST value for each initialized element.
3175 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3176 // elements with something that has a side effect, so codegen can emit an
3177 // "error unsupported" error instead of miscompiling the app.
3178 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3179 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3180 FullyStructuredList->sawArrayRangeDesignator();
3181 }
3182
3183 if (isa<ConstantArrayType>(AT)) {
3184 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3185 DesignatedStartIndex
3186 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3187 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3188 DesignatedEndIndex
3189 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3190 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3191 if (DesignatedEndIndex >= MaxElements) {
3192 if (!VerifyOnly)
3193 SemaRef.Diag(IndexExpr->getBeginLoc(),
3194 diag::err_array_designator_too_large)
3195 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3196 << IndexExpr->getSourceRange();
3197 ++Index;
3198 return true;
3199 }
3200 } else {
3201 unsigned DesignatedIndexBitWidth =
3203 DesignatedStartIndex =
3204 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3205 DesignatedEndIndex =
3206 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3207 DesignatedStartIndex.setIsUnsigned(true);
3208 DesignatedEndIndex.setIsUnsigned(true);
3209 }
3210
3211 bool IsStringLiteralInitUpdate =
3212 StructuredList && StructuredList->isStringLiteralInit();
3213 if (IsStringLiteralInitUpdate && VerifyOnly) {
3214 // We're just verifying an update to a string literal init. We don't need
3215 // to split the string up into individual characters to do that.
3216 StructuredList = nullptr;
3217 } else if (IsStringLiteralInitUpdate) {
3218 // We're modifying a string literal init; we have to decompose the string
3219 // so we can modify the individual characters.
3220 ASTContext &Context = SemaRef.Context;
3221 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3222
3223 // Compute the character type
3224 QualType CharTy = AT->getElementType();
3225
3226 // Compute the type of the integer literals.
3227 QualType PromotedCharTy = CharTy;
3228 if (Context.isPromotableIntegerType(CharTy))
3229 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3230 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3231
3232 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3233 // Get the length of the string.
3234 uint64_t StrLen = SL->getLength();
3235 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3236 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3237 StructuredList->resizeInits(Context, StrLen);
3238
3239 // Build a literal for each character in the string, and put them into
3240 // the init list.
3241 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3242 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3243 Expr *Init = new (Context) IntegerLiteral(
3244 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3245 if (CharTy != PromotedCharTy)
3246 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3247 Init, nullptr, VK_PRValue,
3249 StructuredList->updateInit(Context, i, Init);
3250 }
3251 } else {
3252 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3253 std::string Str;
3254 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3255
3256 // Get the length of the string.
3257 uint64_t StrLen = Str.size();
3258 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3259 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3260 StructuredList->resizeInits(Context, StrLen);
3261
3262 // Build a literal for each character in the string, and put them into
3263 // the init list.
3264 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3265 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3266 Expr *Init = new (Context) IntegerLiteral(
3267 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3268 if (CharTy != PromotedCharTy)
3269 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3270 Init, nullptr, VK_PRValue,
3272 StructuredList->updateInit(Context, i, Init);
3273 }
3274 }
3275 }
3276
3277 // Make sure that our non-designated initializer list has space
3278 // for a subobject corresponding to this array element.
3279 if (StructuredList &&
3280 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3281 StructuredList->resizeInits(SemaRef.Context,
3282 DesignatedEndIndex.getZExtValue() + 1);
3283
3284 // Repeatedly perform subobject initializations in the range
3285 // [DesignatedStartIndex, DesignatedEndIndex].
3286
3287 // Move to the next designator
3288 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3289 unsigned OldIndex = Index;
3290
3291 InitializedEntity ElementEntity =
3293
3294 while (DesignatedStartIndex <= DesignatedEndIndex) {
3295 // Recurse to check later designated subobjects.
3296 QualType ElementType = AT->getElementType();
3297 Index = OldIndex;
3298
3299 ElementEntity.setElementIndex(ElementIndex);
3300 if (CheckDesignatedInitializer(
3301 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3302 nullptr, Index, StructuredList, ElementIndex,
3303 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3304 false))
3305 return true;
3306
3307 // Move to the next index in the array that we'll be initializing.
3308 ++DesignatedStartIndex;
3309 ElementIndex = DesignatedStartIndex.getZExtValue();
3310 }
3311
3312 // If this the first designator, our caller will continue checking
3313 // the rest of this array subobject.
3314 if (IsFirstDesignator) {
3315 if (NextElementIndex)
3316 *NextElementIndex = DesignatedStartIndex;
3317 StructuredIndex = ElementIndex;
3318 return false;
3319 }
3320
3321 if (!FinishSubobjectInit)
3322 return false;
3323
3324 // Check the remaining elements within this array subobject.
3325 bool prevHadError = hadError;
3326 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3327 /*SubobjectIsDesignatorContext=*/false, Index,
3328 StructuredList, ElementIndex);
3329 return hadError && !prevHadError;
3330}
3331
3332// Get the structured initializer list for a subobject of type
3333// @p CurrentObjectType.
3335InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3336 QualType CurrentObjectType,
3337 InitListExpr *StructuredList,
3338 unsigned StructuredIndex,
3339 SourceRange InitRange,
3340 bool IsFullyOverwritten) {
3341 if (!StructuredList)
3342 return nullptr;
3343
3344 Expr *ExistingInit = nullptr;
3345 if (StructuredIndex < StructuredList->getNumInits())
3346 ExistingInit = StructuredList->getInit(StructuredIndex);
3347
3348 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3349 // There might have already been initializers for subobjects of the current
3350 // object, but a subsequent initializer list will overwrite the entirety
3351 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3352 //
3353 // struct P { char x[6]; };
3354 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3355 //
3356 // The first designated initializer is ignored, and l.x is just "f".
3357 if (!IsFullyOverwritten)
3358 return Result;
3359
3360 if (ExistingInit) {
3361 // We are creating an initializer list that initializes the
3362 // subobjects of the current object, but there was already an
3363 // initialization that completely initialized the current
3364 // subobject:
3365 //
3366 // struct X { int a, b; };
3367 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3368 //
3369 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3370 // designated initializer overwrites the [0].b initializer
3371 // from the prior initialization.
3372 //
3373 // When the existing initializer is an expression rather than an
3374 // initializer list, we cannot decompose and update it in this way.
3375 // For example:
3376 //
3377 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3378 //
3379 // This case is handled by CheckDesignatedInitializer.
3380 diagnoseInitOverride(ExistingInit, InitRange);
3381 }
3382
3383 unsigned ExpectedNumInits = 0;
3384 if (Index < IList->getNumInits()) {
3385 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3386 ExpectedNumInits = Init->getNumInits();
3387 else
3388 ExpectedNumInits = IList->getNumInits() - Index;
3389 }
3390
3391 InitListExpr *Result =
3392 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3393
3394 // Link this new initializer list into the structured initializer
3395 // lists.
3396 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3397 return Result;
3398}
3399
3401InitListChecker::createInitListExpr(QualType CurrentObjectType,
3402 SourceRange InitRange,
3403 unsigned ExpectedNumInits) {
3404 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3405 SemaRef.Context, InitRange.getBegin(), {}, InitRange.getEnd());
3406
3407 QualType ResultType = CurrentObjectType;
3408 if (!ResultType->isArrayType())
3409 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3410 Result->setType(ResultType);
3411
3412 // Pre-allocate storage for the structured initializer list.
3413 unsigned NumElements = 0;
3414
3415 if (const ArrayType *AType
3416 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3417 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3418 NumElements = CAType->getZExtSize();
3419 // Simple heuristic so that we don't allocate a very large
3420 // initializer with many empty entries at the end.
3421 if (NumElements > ExpectedNumInits)
3422 NumElements = 0;
3423 }
3424 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3425 NumElements = VType->getNumElements();
3426 } else if (CurrentObjectType->isRecordType()) {
3427 NumElements = numStructUnionElements(CurrentObjectType);
3428 } else if (CurrentObjectType->isDependentType()) {
3429 NumElements = 1;
3430 }
3431
3432 Result->reserveInits(SemaRef.Context, NumElements);
3433
3434 return Result;
3435}
3436
3437/// Update the initializer at index @p StructuredIndex within the
3438/// structured initializer list to the value @p expr.
3439void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3440 unsigned &StructuredIndex,
3441 Expr *expr) {
3442 // No structured initializer list to update
3443 if (!StructuredList)
3444 return;
3445
3446 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3447 StructuredIndex, expr)) {
3448 // This initializer overwrites a previous initializer.
3449 // No need to diagnose when `expr` is nullptr because a more relevant
3450 // diagnostic has already been issued and this diagnostic is potentially
3451 // noise.
3452 if (expr)
3453 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3454 }
3455
3456 ++StructuredIndex;
3457}
3458
3460 const InitializedEntity &Entity, InitListExpr *From) {
3461 QualType Type = Entity.getType();
3462 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3463 /*TreatUnavailableAsInvalid=*/false,
3464 /*InOverloadResolution=*/true);
3465 return !Check.HadError();
3466}
3467
3468/// Check that the given Index expression is a valid array designator
3469/// value. This is essentially just a wrapper around
3470/// VerifyIntegerConstantExpression that also checks for negative values
3471/// and produces a reasonable diagnostic if there is a
3472/// failure. Returns the index expression, possibly with an implicit cast
3473/// added, on success. If everything went okay, Value will receive the
3474/// value of the constant expression.
3475static ExprResult
3476CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3477 SourceLocation Loc = Index->getBeginLoc();
3478
3479 // Make sure this is an integer constant expression.
3482 if (Result.isInvalid())
3483 return Result;
3484
3485 if (Value.isSigned() && Value.isNegative())
3486 return S.Diag(Loc, diag::err_array_designator_negative)
3487 << toString(Value, 10) << Index->getSourceRange();
3488
3489 Value.setIsUnsigned(true);
3490 return Result;
3491}
3492
3494 SourceLocation EqualOrColonLoc,
3495 bool GNUSyntax,
3496 ExprResult Init) {
3497 typedef DesignatedInitExpr::Designator ASTDesignator;
3498
3499 bool Invalid = false;
3501 SmallVector<Expr *, 32> InitExpressions;
3502
3503 // Build designators and check array designator expressions.
3504 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3505 const Designator &D = Desig.getDesignator(Idx);
3506
3507 if (D.isFieldDesignator()) {
3508 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3509 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3510 } else if (D.isArrayDesignator()) {
3511 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3512 llvm::APSInt IndexValue;
3513 if (!Index->isTypeDependent() && !Index->isValueDependent())
3514 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3515 if (!Index)
3516 Invalid = true;
3517 else {
3518 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3519 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3520 InitExpressions.push_back(Index);
3521 }
3522 } else if (D.isArrayRangeDesignator()) {
3523 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3524 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3525 llvm::APSInt StartValue;
3526 llvm::APSInt EndValue;
3527 bool StartDependent = StartIndex->isTypeDependent() ||
3528 StartIndex->isValueDependent();
3529 bool EndDependent = EndIndex->isTypeDependent() ||
3530 EndIndex->isValueDependent();
3531 if (!StartDependent)
3532 StartIndex =
3533 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3534 if (!EndDependent)
3535 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3536
3537 if (!StartIndex || !EndIndex)
3538 Invalid = true;
3539 else {
3540 // Make sure we're comparing values with the same bit width.
3541 if (StartDependent || EndDependent) {
3542 // Nothing to compute.
3543 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3544 EndValue = EndValue.extend(StartValue.getBitWidth());
3545 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3546 StartValue = StartValue.extend(EndValue.getBitWidth());
3547
3548 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3549 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3550 << toString(StartValue, 10) << toString(EndValue, 10)
3551 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3552 Invalid = true;
3553 } else {
3554 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3555 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3556 D.getRBracketLoc()));
3557 InitExpressions.push_back(StartIndex);
3558 InitExpressions.push_back(EndIndex);
3559 }
3560 }
3561 }
3562 }
3563
3564 if (Invalid || Init.isInvalid())
3565 return ExprError();
3566
3567 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3568 EqualOrColonLoc, GNUSyntax,
3569 Init.getAs<Expr>());
3570}
3571
3572//===----------------------------------------------------------------------===//
3573// Initialization entity
3574//===----------------------------------------------------------------------===//
3575
3576InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3578 : Parent(&Parent), Index(Index)
3579{
3580 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3581 Kind = EK_ArrayElement;
3582 Type = AT->getElementType();
3583 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3584 Kind = EK_VectorElement;
3585 Type = VT->getElementType();
3586 } else {
3587 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3588 assert(CT && "Unexpected type");
3589 Kind = EK_ComplexElement;
3590 Type = CT->getElementType();
3591 }
3592}
3593
3596 const CXXBaseSpecifier *Base,
3597 bool IsInheritedVirtualBase,
3598 const InitializedEntity *Parent) {
3600 Result.Kind = EK_Base;
3601 Result.Parent = Parent;
3602 Result.Base = {Base, IsInheritedVirtualBase};
3603 Result.Type = Base->getType();
3604 return Result;
3605}
3606
3608 switch (getKind()) {
3609 case EK_Parameter:
3611 ParmVarDecl *D = Parameter.getPointer();
3612 return (D ? D->getDeclName() : DeclarationName());
3613 }
3614
3615 case EK_Variable:
3616 case EK_Member:
3618 case EK_Binding:
3620 return Variable.VariableOrMember->getDeclName();
3621
3622 case EK_LambdaCapture:
3623 return DeclarationName(Capture.VarID);
3624
3625 case EK_Result:
3626 case EK_StmtExprResult:
3627 case EK_Exception:
3628 case EK_New:
3629 case EK_Temporary:
3630 case EK_Base:
3631 case EK_Delegating:
3632 case EK_ArrayElement:
3633 case EK_VectorElement:
3634 case EK_ComplexElement:
3635 case EK_BlockElement:
3638 case EK_RelatedResult:
3639 return DeclarationName();
3640 }
3641
3642 llvm_unreachable("Invalid EntityKind!");
3643}
3644
3646 switch (getKind()) {
3647 case EK_Variable:
3648 case EK_Member:
3650 case EK_Binding:
3652 return Variable.VariableOrMember;
3653
3654 case EK_Parameter:
3656 return Parameter.getPointer();
3657
3658 case EK_Result:
3659 case EK_StmtExprResult:
3660 case EK_Exception:
3661 case EK_New:
3662 case EK_Temporary:
3663 case EK_Base:
3664 case EK_Delegating:
3665 case EK_ArrayElement:
3666 case EK_VectorElement:
3667 case EK_ComplexElement:
3668 case EK_BlockElement:
3670 case EK_LambdaCapture:
3672 case EK_RelatedResult:
3673 return nullptr;
3674 }
3675
3676 llvm_unreachable("Invalid EntityKind!");
3677}
3678
3680 switch (getKind()) {
3681 case EK_Result:
3682 case EK_Exception:
3683 return LocAndNRVO.NRVO;
3684
3685 case EK_StmtExprResult:
3686 case EK_Variable:
3687 case EK_Parameter:
3690 case EK_Member:
3692 case EK_Binding:
3693 case EK_New:
3694 case EK_Temporary:
3696 case EK_Base:
3697 case EK_Delegating:
3698 case EK_ArrayElement:
3699 case EK_VectorElement:
3700 case EK_ComplexElement:
3701 case EK_BlockElement:
3703 case EK_LambdaCapture:
3704 case EK_RelatedResult:
3705 break;
3706 }
3707
3708 return false;
3709}
3710
3711unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3712 assert(getParent() != this);
3713 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3714 for (unsigned I = 0; I != Depth; ++I)
3715 OS << "`-";
3716
3717 switch (getKind()) {
3718 case EK_Variable: OS << "Variable"; break;
3719 case EK_Parameter: OS << "Parameter"; break;
3720 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3721 break;
3722 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3723 case EK_Result: OS << "Result"; break;
3724 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3725 case EK_Exception: OS << "Exception"; break;
3726 case EK_Member:
3728 OS << "Member";
3729 break;
3730 case EK_Binding: OS << "Binding"; break;
3731 case EK_New: OS << "New"; break;
3732 case EK_Temporary: OS << "Temporary"; break;
3733 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3734 case EK_RelatedResult: OS << "RelatedResult"; break;
3735 case EK_Base: OS << "Base"; break;
3736 case EK_Delegating: OS << "Delegating"; break;
3737 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3738 case EK_VectorElement: OS << "VectorElement " << Index; break;
3739 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3740 case EK_BlockElement: OS << "Block"; break;
3742 OS << "Block (lambda)";
3743 break;
3744 case EK_LambdaCapture:
3745 OS << "LambdaCapture ";
3746 OS << DeclarationName(Capture.VarID);
3747 break;
3748 }
3749
3750 if (auto *D = getDecl()) {
3751 OS << " ";
3752 D->printQualifiedName(OS);
3753 }
3754
3755 OS << " '" << getType() << "'\n";
3756
3757 return Depth + 1;
3758}
3759
3760LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3761 dumpImpl(llvm::errs());
3762}
3763
3764//===----------------------------------------------------------------------===//
3765// Initialization sequence
3766//===----------------------------------------------------------------------===//
3767
3769 switch (Kind) {
3774 case SK_BindReference:
3776 case SK_FinalCopy:
3778 case SK_UserConversion:
3785 case SK_UnwrapInitList:
3786 case SK_RewrapInitList:
3790 case SK_CAssignment:
3791 case SK_StringInit:
3793 case SK_ArrayLoopIndex:
3794 case SK_ArrayLoopInit:
3795 case SK_ArrayInit:
3796 case SK_GNUArrayInit:
3803 case SK_OCLSamplerInit:
3806 break;
3807
3810 delete ICS;
3811 }
3812}
3813
3815 // There can be some lvalue adjustments after the SK_BindReference step.
3816 for (const Step &S : llvm::reverse(Steps)) {
3817 if (S.Kind == SK_BindReference)
3818 return true;
3819 if (S.Kind == SK_BindReferenceToTemporary)
3820 return false;
3821 }
3822 return false;
3823}
3824
3826 if (!Failed())
3827 return false;
3828
3829 switch (getFailureKind()) {
3840 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3857 case FK_Incomplete:
3862 case FK_PlaceholderType:
3867 return false;
3868
3873 return FailedOverloadResult == OR_Ambiguous;
3874 }
3875
3876 llvm_unreachable("Invalid EntityKind!");
3877}
3878
3880 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3881}
3882
3883void
3884InitializationSequence
3885::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3887 bool HadMultipleCandidates) {
3888 Step S;
3890 S.Type = Function->getType();
3891 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3892 S.Function.Function = Function;
3893 S.Function.FoundDecl = Found;
3894 Steps.push_back(S);
3895}
3896
3898 ExprValueKind VK) {
3899 Step S;
3900 switch (VK) {
3901 case VK_PRValue:
3903 break;
3904 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3905 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3906 }
3907 S.Type = BaseType;
3908 Steps.push_back(S);
3909}
3910
3912 bool BindingTemporary) {
3913 Step S;
3914 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3915 S.Type = T;
3916 Steps.push_back(S);
3917}
3918
3920 Step S;
3921 S.Kind = SK_FinalCopy;
3922 S.Type = T;
3923 Steps.push_back(S);
3924}
3925
3927 Step S;
3929 S.Type = T;
3930 Steps.push_back(S);
3931}
3932
3933void
3935 DeclAccessPair FoundDecl,
3936 QualType T,
3937 bool HadMultipleCandidates) {
3938 Step S;
3939 S.Kind = SK_UserConversion;
3940 S.Type = T;
3941 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3942 S.Function.Function = Function;
3943 S.Function.FoundDecl = FoundDecl;
3944 Steps.push_back(S);
3945}
3946
3948 ExprValueKind VK) {
3949 Step S;
3950 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3951 switch (VK) {
3952 case VK_PRValue:
3954 break;
3955 case VK_XValue:
3957 break;
3958 case VK_LValue:
3960 break;
3961 }
3962 S.Type = Ty;
3963 Steps.push_back(S);
3964}
3965
3967 Step S;
3969 S.Type = Ty;
3970 Steps.push_back(S);
3971}
3972
3974 Step S;
3975 S.Kind = SK_AtomicConversion;
3976 S.Type = Ty;
3977 Steps.push_back(S);
3978}
3979
3982 bool TopLevelOfInitList) {
3983 Step S;
3984 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3986 S.Type = T;
3987 S.ICS = new ImplicitConversionSequence(ICS);
3988 Steps.push_back(S);
3989}
3990
3992 Step S;
3993 S.Kind = SK_ListInitialization;
3994 S.Type = T;
3995 Steps.push_back(S);
3996}
3997
3999 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
4000 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4001 Step S;
4002 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4005 S.Type = T;
4006 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4007 S.Function.Function = Constructor;
4008 S.Function.FoundDecl = FoundDecl;
4009 Steps.push_back(S);
4010}
4011
4013 Step S;
4014 S.Kind = SK_ZeroInitialization;
4015 S.Type = T;
4016 Steps.push_back(S);
4017}
4018
4020 Step S;
4021 S.Kind = SK_CAssignment;
4022 S.Type = T;
4023 Steps.push_back(S);
4024}
4025
4027 Step S;
4028 S.Kind = SK_StringInit;
4029 S.Type = T;
4030 Steps.push_back(S);
4031}
4032
4034 Step S;
4035 S.Kind = SK_ObjCObjectConversion;
4036 S.Type = T;
4037 Steps.push_back(S);
4038}
4039
4041 Step S;
4042 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4043 S.Type = T;
4044 Steps.push_back(S);
4045}
4046
4048 Step S;
4049 S.Kind = SK_ArrayLoopIndex;
4050 S.Type = EltT;
4051 Steps.insert(Steps.begin(), S);
4052
4053 S.Kind = SK_ArrayLoopInit;
4054 S.Type = T;
4055 Steps.push_back(S);
4056}
4057
4059 Step S;
4061 S.Type = T;
4062 Steps.push_back(S);
4063}
4064
4066 bool shouldCopy) {
4067 Step s;
4068 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4070 s.Type = type;
4071 Steps.push_back(s);
4072}
4073
4075 Step S;
4076 S.Kind = SK_ProduceObjCObject;
4077 S.Type = T;
4078 Steps.push_back(S);
4079}
4080
4082 Step S;
4083 S.Kind = SK_StdInitializerList;
4084 S.Type = T;
4085 Steps.push_back(S);
4086}
4087
4089 Step S;
4090 S.Kind = SK_OCLSamplerInit;
4091 S.Type = T;
4092 Steps.push_back(S);
4093}
4094
4096 Step S;
4097 S.Kind = SK_OCLZeroOpaqueType;
4098 S.Type = T;
4099 Steps.push_back(S);
4100}
4101
4103 Step S;
4104 S.Kind = SK_ParenthesizedListInit;
4105 S.Type = T;
4106 Steps.push_back(S);
4107}
4108
4110 InitListExpr *Syntactic) {
4111 assert(Syntactic->getNumInits() == 1 &&
4112 "Can only unwrap trivial init lists.");
4113 Step S;
4114 S.Kind = SK_UnwrapInitList;
4115 S.Type = Syntactic->getInit(0)->getType();
4116 Steps.insert(Steps.begin(), S);
4117}
4118
4120 InitListExpr *Syntactic) {
4121 assert(Syntactic->getNumInits() == 1 &&
4122 "Can only rewrap trivial init lists.");
4123 Step S;
4124 S.Kind = SK_UnwrapInitList;
4125 S.Type = Syntactic->getInit(0)->getType();
4126 Steps.insert(Steps.begin(), S);
4127
4128 S.Kind = SK_RewrapInitList;
4129 S.Type = T;
4130 S.WrappingSyntacticList = Syntactic;
4131 Steps.push_back(S);
4132}
4133
4137 this->Failure = Failure;
4138 this->FailedOverloadResult = Result;
4139}
4140
4141//===----------------------------------------------------------------------===//
4142// Attempt initialization
4143//===----------------------------------------------------------------------===//
4144
4145/// Tries to add a zero initializer. Returns true if that worked.
4146static bool
4148 const InitializedEntity &Entity) {
4150 return false;
4151
4152 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4153 if (VD->getInit() || VD->getEndLoc().isMacroID())
4154 return false;
4155
4156 QualType VariableTy = VD->getType().getCanonicalType();
4158 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4159 if (!Init.empty()) {
4160 Sequence.AddZeroInitializationStep(Entity.getType());
4162 return true;
4163 }
4164 return false;
4165}
4166
4168 InitializationSequence &Sequence,
4169 const InitializedEntity &Entity) {
4170 if (!S.getLangOpts().ObjCAutoRefCount) return;
4171
4172 /// When initializing a parameter, produce the value if it's marked
4173 /// __attribute__((ns_consumed)).
4174 if (Entity.isParameterKind()) {
4175 if (!Entity.isParameterConsumed())
4176 return;
4177
4178 assert(Entity.getType()->isObjCRetainableType() &&
4179 "consuming an object of unretainable type?");
4180 Sequence.AddProduceObjCObjectStep(Entity.getType());
4181
4182 /// When initializing a return value, if the return type is a
4183 /// retainable type, then returns need to immediately retain the
4184 /// object. If an autorelease is required, it will be done at the
4185 /// last instant.
4186 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4188 if (!Entity.getType()->isObjCRetainableType())
4189 return;
4190
4191 Sequence.AddProduceObjCObjectStep(Entity.getType());
4192 }
4193}
4194
4195/// Initialize an array from another array
4196static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4197 const InitializedEntity &Entity, Expr *Initializer,
4198 QualType DestType, InitializationSequence &Sequence,
4199 bool TreatUnavailableAsInvalid) {
4200 // If source is a prvalue, use it directly.
4201 if (Initializer->isPRValue()) {
4202 Sequence.AddArrayInitStep(DestType, /*IsGNUExtension*/ false);
4203 return;
4204 }
4205
4206 // Emit element-at-a-time copy loop.
4207 InitializedEntity Element =
4209 QualType InitEltT =
4211 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
4212 Initializer->getValueKind(),
4213 Initializer->getObjectKind());
4214 Expr *OVEAsExpr = &OVE;
4215 Sequence.InitializeFrom(S, Element, Kind, OVEAsExpr,
4216 /*TopLevelOfInitList*/ false,
4217 TreatUnavailableAsInvalid);
4218 if (Sequence)
4219 Sequence.AddArrayInitLoopStep(Entity.getType(), InitEltT);
4220}
4221
4222static void TryListInitialization(Sema &S,
4223 const InitializedEntity &Entity,
4224 const InitializationKind &Kind,
4225 InitListExpr *InitList,
4226 InitializationSequence &Sequence,
4227 bool TreatUnavailableAsInvalid);
4228
4229/// When initializing from init list via constructor, handle
4230/// initialization of an object of type std::initializer_list<T>.
4231///
4232/// \return true if we have handled initialization of an object of type
4233/// std::initializer_list<T>, false otherwise.
4235 InitListExpr *List,
4236 QualType DestType,
4237 InitializationSequence &Sequence,
4238 bool TreatUnavailableAsInvalid) {
4239 QualType E;
4240 if (!S.isStdInitializerList(DestType, &E))
4241 return false;
4242
4243 if (!S.isCompleteType(List->getExprLoc(), E)) {
4244 Sequence.setIncompleteTypeFailure(E);
4245 return true;
4246 }
4247
4248 // Try initializing a temporary array from the init list.
4250 E.withConst(),
4251 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4252 List->getNumInits()),
4254 InitializedEntity HiddenArray =
4257 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4258 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4259 TreatUnavailableAsInvalid);
4260 if (Sequence)
4261 Sequence.AddStdInitializerListConstructionStep(DestType);
4262 return true;
4263}
4264
4265/// Determine if the constructor has the signature of a copy or move
4266/// constructor for the type T of the class in which it was found. That is,
4267/// determine if its first parameter is of type T or reference to (possibly
4268/// cv-qualified) T.
4270 const ConstructorInfo &Info) {
4271 if (Info.Constructor->getNumParams() == 0)
4272 return false;
4273
4274 QualType ParmT =
4276 QualType ClassT =
4277 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4278
4279 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4280}
4281
4283 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4284 OverloadCandidateSet &CandidateSet, QualType DestType,
4286 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4287 bool IsListInit, bool RequireActualConstructor,
4288 bool SecondStepOfCopyInit = false) {
4290 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4291
4292 for (NamedDecl *D : Ctors) {
4293 auto Info = getConstructorInfo(D);
4294 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4295 continue;
4296
4297 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4298 continue;
4299
4300 // C++11 [over.best.ics]p4:
4301 // ... and the constructor or user-defined conversion function is a
4302 // candidate by
4303 // - 13.3.1.3, when the argument is the temporary in the second step
4304 // of a class copy-initialization, or
4305 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4306 // - the second phase of 13.3.1.7 when the initializer list has exactly
4307 // one element that is itself an initializer list, and the target is
4308 // the first parameter of a constructor of class X, and the conversion
4309 // is to X or reference to (possibly cv-qualified X),
4310 // user-defined conversion sequences are not considered.
4311 bool SuppressUserConversions =
4312 SecondStepOfCopyInit ||
4313 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4315
4316 if (Info.ConstructorTmpl)
4318 Info.ConstructorTmpl, Info.FoundDecl,
4319 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4320 /*PartialOverloading=*/false, AllowExplicit);
4321 else {
4322 // C++ [over.match.copy]p1:
4323 // - When initializing a temporary to be bound to the first parameter
4324 // of a constructor [for type T] that takes a reference to possibly
4325 // cv-qualified T as its first argument, called with a single
4326 // argument in the context of direct-initialization, explicit
4327 // conversion functions are also considered.
4328 // FIXME: What if a constructor template instantiates to such a signature?
4329 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4330 Args.size() == 1 &&
4332 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4333 CandidateSet, SuppressUserConversions,
4334 /*PartialOverloading=*/false, AllowExplicit,
4335 AllowExplicitConv);
4336 }
4337 }
4338
4339 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4340 //
4341 // When initializing an object of class type T by constructor
4342 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4343 // from a single expression of class type U, conversion functions of
4344 // U that convert to the non-reference type cv T are candidates.
4345 // Explicit conversion functions are only candidates during
4346 // direct-initialization.
4347 //
4348 // Note: SecondStepOfCopyInit is only ever true in this case when
4349 // evaluating whether to produce a C++98 compatibility warning.
4350 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4351 !RequireActualConstructor && !SecondStepOfCopyInit) {
4352 Expr *Initializer = Args[0];
4353 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4354 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4355 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4356 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4357 NamedDecl *D = *I;
4358 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4359 D = D->getUnderlyingDecl();
4360
4361 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4362 CXXConversionDecl *Conv;
4363 if (ConvTemplate)
4364 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4365 else
4366 Conv = cast<CXXConversionDecl>(D);
4367
4368 if (ConvTemplate)
4370 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4371 CandidateSet, AllowExplicit, AllowExplicit,
4372 /*AllowResultConversion*/ false);
4373 else
4374 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4375 DestType, CandidateSet, AllowExplicit,
4376 AllowExplicit,
4377 /*AllowResultConversion*/ false);
4378 }
4379 }
4380 }
4381
4382 // Perform overload resolution and return the result.
4383 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4384}
4385
4386/// Attempt initialization by constructor (C++ [dcl.init]), which
4387/// enumerates the constructors of the initialized entity and performs overload
4388/// resolution to select the best.
4389/// \param DestType The destination class type.
4390/// \param DestArrayType The destination type, which is either DestType or
4391/// a (possibly multidimensional) array of DestType.
4392/// \param IsListInit Is this list-initialization?
4393/// \param IsInitListCopy Is this non-list-initialization resulting from a
4394/// list-initialization from {x} where x is the same
4395/// aggregate type as the entity?
4397 const InitializedEntity &Entity,
4398 const InitializationKind &Kind,
4399 MultiExprArg Args, QualType DestType,
4400 QualType DestArrayType,
4401 InitializationSequence &Sequence,
4402 bool IsListInit = false,
4403 bool IsInitListCopy = false) {
4404 assert(((!IsListInit && !IsInitListCopy) ||
4405 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4406 "IsListInit/IsInitListCopy must come with a single initializer list "
4407 "argument.");
4408 InitListExpr *ILE =
4409 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4410 MultiExprArg UnwrappedArgs =
4411 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4412
4413 // The type we're constructing needs to be complete.
4414 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4415 Sequence.setIncompleteTypeFailure(DestType);
4416 return;
4417 }
4418
4419 bool RequireActualConstructor =
4420 !(Entity.getKind() != InitializedEntity::EK_Base &&
4422 Entity.getKind() !=
4424
4425 bool CopyElisionPossible = false;
4426 auto ElideConstructor = [&] {
4427 // Convert qualifications if necessary.
4428 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4429 if (ILE)
4430 Sequence.RewrapReferenceInitList(DestType, ILE);
4431 };
4432
4433 // C++17 [dcl.init]p17:
4434 // - If the initializer expression is a prvalue and the cv-unqualified
4435 // version of the source type is the same class as the class of the
4436 // destination, the initializer expression is used to initialize the
4437 // destination object.
4438 // Per DR (no number yet), this does not apply when initializing a base
4439 // class or delegating to another constructor from a mem-initializer.
4440 // ObjC++: Lambda captured by the block in the lambda to block conversion
4441 // should avoid copy elision.
4442 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4443 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4444 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4445 if (ILE && !DestType->isAggregateType()) {
4446 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4447 // Make this an elision if this won't call an initializer-list
4448 // constructor. (Always on an aggregate type or check constructors first.)
4449
4450 // This effectively makes our resolution as follows. The parts in angle
4451 // brackets are additions.
4452 // C++17 [over.match.list]p(1.2):
4453 // - If no viable initializer-list constructor is found <and the
4454 // initializer list does not consist of exactly a single element with
4455 // the same cv-unqualified class type as T>, [...]
4456 // C++17 [dcl.init.list]p(3.6):
4457 // - Otherwise, if T is a class type, constructors are considered. The
4458 // applicable constructors are enumerated and the best one is chosen
4459 // through overload resolution. <If no constructor is found and the
4460 // initializer list consists of exactly a single element with the same
4461 // cv-unqualified class type as T, the object is initialized from that
4462 // element (by copy-initialization for copy-list-initialization, or by
4463 // direct-initialization for direct-list-initialization). Otherwise, >
4464 // if a narrowing conversion [...]
4465 assert(!IsInitListCopy &&
4466 "IsInitListCopy only possible with aggregate types");
4467 CopyElisionPossible = true;
4468 } else {
4469 ElideConstructor();
4470 return;
4471 }
4472 }
4473
4474 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4475 assert(DestRecordType && "Constructor initialization requires record type");
4476 CXXRecordDecl *DestRecordDecl
4477 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4478
4479 // Build the candidate set directly in the initialization sequence
4480 // structure, so that it will persist if we fail.
4481 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4482
4483 // Determine whether we are allowed to call explicit constructors or
4484 // explicit conversion operators.
4485 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4486 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4487
4488 // - Otherwise, if T is a class type, constructors are considered. The
4489 // applicable constructors are enumerated, and the best one is chosen
4490 // through overload resolution.
4491 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4492
4495 bool AsInitializerList = false;
4496
4497 // C++11 [over.match.list]p1, per DR1467:
4498 // When objects of non-aggregate type T are list-initialized, such that
4499 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4500 // according to the rules in this section, overload resolution selects
4501 // the constructor in two phases:
4502 //
4503 // - Initially, the candidate functions are the initializer-list
4504 // constructors of the class T and the argument list consists of the
4505 // initializer list as a single argument.
4506 if (IsListInit) {
4507 AsInitializerList = true;
4508
4509 // If the initializer list has no elements and T has a default constructor,
4510 // the first phase is omitted.
4511 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4513 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4514 CopyInitialization, AllowExplicit,
4515 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4516
4517 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4518 // No initializer list candidate
4519 ElideConstructor();
4520 return;
4521 }
4522 }
4523
4524 // C++11 [over.match.list]p1:
4525 // - If no viable initializer-list constructor is found, overload resolution
4526 // is performed again, where the candidate functions are all the
4527 // constructors of the class T and the argument list consists of the
4528 // elements of the initializer list.
4530 AsInitializerList = false;
4532 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4533 Best, CopyInitialization, AllowExplicit,
4534 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4535 }
4536 if (Result) {
4537 Sequence.SetOverloadFailure(
4540 Result);
4541
4542 if (Result != OR_Deleted)
4543 return;
4544 }
4545
4546 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4547
4548 // In C++17, ResolveConstructorOverload can select a conversion function
4549 // instead of a constructor.
4550 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4551 // Add the user-defined conversion step that calls the conversion function.
4552 QualType ConvType = CD->getConversionType();
4553 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4554 "should not have selected this conversion function");
4555 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4556 HadMultipleCandidates);
4557 if (!S.Context.hasSameType(ConvType, DestType))
4558 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4559 if (IsListInit)
4560 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4561 return;
4562 }
4563
4564 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4565 if (Result != OR_Deleted) {
4566 // C++11 [dcl.init]p6:
4567 // If a program calls for the default initialization of an object
4568 // of a const-qualified type T, T shall be a class type with a
4569 // user-provided default constructor.
4570 // C++ core issue 253 proposal:
4571 // If the implicit default constructor initializes all subobjects, no
4572 // initializer should be required.
4573 // The 253 proposal is for example needed to process libstdc++ headers
4574 // in 5.x.
4575 if (Kind.getKind() == InitializationKind::IK_Default &&
4576 Entity.getType().isConstQualified()) {
4577 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4578 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4580 return;
4581 }
4582 }
4583
4584 // C++11 [over.match.list]p1:
4585 // In copy-list-initialization, if an explicit constructor is chosen, the
4586 // initializer is ill-formed.
4587 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4589 return;
4590 }
4591 }
4592
4593 // [class.copy.elision]p3:
4594 // In some copy-initialization contexts, a two-stage overload resolution
4595 // is performed.
4596 // If the first overload resolution selects a deleted function, we also
4597 // need the initialization sequence to decide whether to perform the second
4598 // overload resolution.
4599 // For deleted functions in other contexts, there is no need to get the
4600 // initialization sequence.
4601 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4602 return;
4603
4604 // Add the constructor initialization step. Any cv-qualification conversion is
4605 // subsumed by the initialization.
4607 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4608 IsListInit | IsInitListCopy, AsInitializerList);
4609}
4610
4611static bool
4614 QualType &SourceType,
4615 QualType &UnqualifiedSourceType,
4616 QualType UnqualifiedTargetType,
4617 InitializationSequence &Sequence) {
4618 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4619 S.Context.OverloadTy) {
4621 bool HadMultipleCandidates = false;
4622 if (FunctionDecl *Fn
4624 UnqualifiedTargetType,
4625 false, Found,
4626 &HadMultipleCandidates)) {
4628 HadMultipleCandidates);
4629 SourceType = Fn->getType();
4630 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4631 } else if (!UnqualifiedTargetType->isRecordType()) {
4633 return true;
4634 }
4635 }
4636 return false;
4637}
4638
4640 const InitializedEntity &Entity,
4641 const InitializationKind &Kind,
4643 QualType cv1T1, QualType T1,
4644 Qualifiers T1Quals,
4645 QualType cv2T2, QualType T2,
4646 Qualifiers T2Quals,
4647 InitializationSequence &Sequence,
4648 bool TopLevelOfInitList);
4649
4650static void TryValueInitialization(Sema &S,
4651 const InitializedEntity &Entity,
4652 const InitializationKind &Kind,
4653 InitializationSequence &Sequence,
4654 InitListExpr *InitList = nullptr);
4655
4656/// Attempt list initialization of a reference.
4658 const InitializedEntity &Entity,
4659 const InitializationKind &Kind,
4660 InitListExpr *InitList,
4661 InitializationSequence &Sequence,
4662 bool TreatUnavailableAsInvalid) {
4663 // First, catch C++03 where this isn't possible.
4664 if (!S.getLangOpts().CPlusPlus11) {
4666 return;
4667 }
4668 // Can't reference initialize a compound literal.
4671 return;
4672 }
4673
4674 QualType DestType = Entity.getType();
4675 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4676 Qualifiers T1Quals;
4677 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4678
4679 // Reference initialization via an initializer list works thus:
4680 // If the initializer list consists of a single element that is
4681 // reference-related to the referenced type, bind directly to that element
4682 // (possibly creating temporaries).
4683 // Otherwise, initialize a temporary with the initializer list and
4684 // bind to that.
4685 if (InitList->getNumInits() == 1) {
4686 Expr *Initializer = InitList->getInit(0);
4688 Qualifiers T2Quals;
4689 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4690
4691 // If this fails, creating a temporary wouldn't work either.
4693 T1, Sequence))
4694 return;
4695
4696 SourceLocation DeclLoc = Initializer->getBeginLoc();
4697 Sema::ReferenceCompareResult RefRelationship
4698 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4699 if (RefRelationship >= Sema::Ref_Related) {
4700 // Try to bind the reference here.
4701 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4702 T1Quals, cv2T2, T2, T2Quals, Sequence,
4703 /*TopLevelOfInitList=*/true);
4704 if (Sequence)
4705 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4706 return;
4707 }
4708
4709 // Update the initializer if we've resolved an overloaded function.
4710 if (Sequence.step_begin() != Sequence.step_end())
4711 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4712 }
4713 // Perform address space compatibility check.
4714 QualType cv1T1IgnoreAS = cv1T1;
4715 if (T1Quals.hasAddressSpace()) {
4716 Qualifiers T2Quals;
4717 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4718 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals, S.getASTContext())) {
4719 Sequence.SetFailed(
4721 return;
4722 }
4723 // Ignore address space of reference type at this point and perform address
4724 // space conversion after the reference binding step.
4725 cv1T1IgnoreAS =
4727 }
4728 // Not reference-related. Create a temporary and bind to that.
4729 InitializedEntity TempEntity =
4731
4732 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4733 TreatUnavailableAsInvalid);
4734 if (Sequence) {
4735 if (DestType->isRValueReferenceType() ||
4736 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4737 if (S.getLangOpts().CPlusPlus20 &&
4738 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4739 DestType->isRValueReferenceType()) {
4740 // C++20 [dcl.init.list]p3.10:
4741 // List-initialization of an object or reference of type T is defined as
4742 // follows:
4743 // ..., unless T is “reference to array of unknown bound of U”, in which
4744 // case the type of the prvalue is the type of x in the declaration U
4745 // x[] H, where H is the initializer list.
4747 }
4748 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4749 /*BindingTemporary=*/true);
4750 if (T1Quals.hasAddressSpace())
4752 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4753 } else
4754 Sequence.SetFailed(
4756 }
4757}
4758
4759/// Attempt list initialization (C++0x [dcl.init.list])
4761 const InitializedEntity &Entity,
4762 const InitializationKind &Kind,
4763 InitListExpr *InitList,
4764 InitializationSequence &Sequence,
4765 bool TreatUnavailableAsInvalid) {
4766 QualType DestType = Entity.getType();
4767
4768 // C++ doesn't allow scalar initialization with more than one argument.
4769 // But C99 complex numbers are scalars and it makes sense there.
4770 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4771 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4773 return;
4774 }
4775 if (DestType->isReferenceType()) {
4776 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4777 TreatUnavailableAsInvalid);
4778 return;
4779 }
4780
4781 if (DestType->isRecordType() &&
4782 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4783 Sequence.setIncompleteTypeFailure(DestType);
4784 return;
4785 }
4786
4787 // C++20 [dcl.init.list]p3:
4788 // - If the braced-init-list contains a designated-initializer-list, T shall
4789 // be an aggregate class. [...] Aggregate initialization is performed.
4790 //
4791 // We allow arrays here too in order to support array designators.
4792 //
4793 // FIXME: This check should precede the handling of reference initialization.
4794 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4795 // as a tentative DR resolution.
4796 bool IsDesignatedInit = InitList->hasDesignatedInit();
4797 if (!DestType->isAggregateType() && IsDesignatedInit) {
4798 Sequence.SetFailed(
4800 return;
4801 }
4802
4803 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4804 // - If T is an aggregate class and the initializer list has a single element
4805 // of type cv U, where U is T or a class derived from T, the object is
4806 // initialized from that element (by copy-initialization for
4807 // copy-list-initialization, or by direct-initialization for
4808 // direct-list-initialization).
4809 // - Otherwise, if T is a character array and the initializer list has a
4810 // single element that is an appropriately-typed string literal
4811 // (8.5.2 [dcl.init.string]), initialization is performed as described
4812 // in that section.
4813 // - Otherwise, if T is an aggregate, [...] (continue below).
4814 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4815 !IsDesignatedInit) {
4816 if (DestType->isRecordType() && DestType->isAggregateType()) {
4817 QualType InitType = InitList->getInit(0)->getType();
4818 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4819 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4820 Expr *InitListAsExpr = InitList;
4821 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4822 DestType, Sequence,
4823 /*InitListSyntax*/false,
4824 /*IsInitListCopy*/true);
4825 return;
4826 }
4827 }
4828 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4829 Expr *SubInit[1] = {InitList->getInit(0)};
4830
4831 // C++17 [dcl.struct.bind]p1:
4832 // ... If the assignment-expression in the initializer has array type A
4833 // and no ref-qualifier is present, e has type cv A and each element is
4834 // copy-initialized or direct-initialized from the corresponding element
4835 // of the assignment-expression as specified by the form of the
4836 // initializer. ...
4837 //
4838 // This is a special case not following list-initialization.
4839 if (isa<ConstantArrayType>(DestAT) &&
4841 isa<DecompositionDecl>(Entity.getDecl())) {
4842 assert(
4843 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
4844 "Deduced to other type?");
4845 TryArrayCopy(S,
4846 InitializationKind::CreateCopy(Kind.getLocation(),
4847 InitList->getLBraceLoc()),
4848 Entity, SubInit[0], DestType, Sequence,
4849 TreatUnavailableAsInvalid);
4850 if (Sequence)
4851 Sequence.AddUnwrapInitListInitStep(InitList);
4852 return;
4853 }
4854
4855 if (!isa<VariableArrayType>(DestAT) &&
4856 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4857 InitializationKind SubKind =
4858 Kind.getKind() == InitializationKind::IK_DirectList
4859 ? InitializationKind::CreateDirect(Kind.getLocation(),
4860 InitList->getLBraceLoc(),
4861 InitList->getRBraceLoc())
4862 : Kind;
4863 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4864 /*TopLevelOfInitList*/ true,
4865 TreatUnavailableAsInvalid);
4866
4867 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4868 // the element is not an appropriately-typed string literal, in which
4869 // case we should proceed as in C++11 (below).
4870 if (Sequence) {
4871 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4872 return;
4873 }
4874 }
4875 }
4876 }
4877
4878 // C++11 [dcl.init.list]p3:
4879 // - If T is an aggregate, aggregate initialization is performed.
4880 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4881 (S.getLangOpts().CPlusPlus11 &&
4882 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4883 if (S.getLangOpts().CPlusPlus11) {
4884 // - Otherwise, if the initializer list has no elements and T is a
4885 // class type with a default constructor, the object is
4886 // value-initialized.
4887 if (InitList->getNumInits() == 0) {
4888 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4889 if (S.LookupDefaultConstructor(RD)) {
4890 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4891 return;
4892 }
4893 }
4894
4895 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4896 // an initializer_list object constructed [...]
4897 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4898 TreatUnavailableAsInvalid))
4899 return;
4900
4901 // - Otherwise, if T is a class type, constructors are considered.
4902 Expr *InitListAsExpr = InitList;
4903 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4904 DestType, Sequence, /*InitListSyntax*/true);
4905 } else
4907 return;
4908 }
4909
4910 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4911 InitList->getNumInits() == 1) {
4912 Expr *E = InitList->getInit(0);
4913
4914 // - Otherwise, if T is an enumeration with a fixed underlying type,
4915 // the initializer-list has a single element v, and the initialization
4916 // is direct-list-initialization, the object is initialized with the
4917 // value T(v); if a narrowing conversion is required to convert v to
4918 // the underlying type of T, the program is ill-formed.
4919 auto *ET = DestType->getAs<EnumType>();
4920 if (S.getLangOpts().CPlusPlus17 &&
4921 Kind.getKind() == InitializationKind::IK_DirectList &&
4922 ET && ET->getDecl()->isFixed() &&
4923 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4925 E->getType()->isFloatingType())) {
4926 // There are two ways that T(v) can work when T is an enumeration type.
4927 // If there is either an implicit conversion sequence from v to T or
4928 // a conversion function that can convert from v to T, then we use that.
4929 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4930 // type, it is converted to the enumeration type via its underlying type.
4931 // There is no overlap possible between these two cases (except when the
4932 // source value is already of the destination type), and the first
4933 // case is handled by the general case for single-element lists below.
4935 ICS.setStandard();
4937 if (!E->isPRValue())
4939 // If E is of a floating-point type, then the conversion is ill-formed
4940 // due to narrowing, but go through the motions in order to produce the
4941 // right diagnostic.
4945 ICS.Standard.setFromType(E->getType());
4946 ICS.Standard.setToType(0, E->getType());
4947 ICS.Standard.setToType(1, DestType);
4948 ICS.Standard.setToType(2, DestType);
4949 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4950 /*TopLevelOfInitList*/true);
4951 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4952 return;
4953 }
4954
4955 // - Otherwise, if the initializer list has a single element of type E
4956 // [...references are handled above...], the object or reference is
4957 // initialized from that element (by copy-initialization for
4958 // copy-list-initialization, or by direct-initialization for
4959 // direct-list-initialization); if a narrowing conversion is required
4960 // to convert the element to T, the program is ill-formed.
4961 //
4962 // Per core-24034, this is direct-initialization if we were performing
4963 // direct-list-initialization and copy-initialization otherwise.
4964 // We can't use InitListChecker for this, because it always performs
4965 // copy-initialization. This only m