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