Bug Summary

File:build/source/clang/lib/Sema/SemaInit.cpp
Warning:line 9503, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaInit.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaInit.cpp
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/AST/ExprOpenMP.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Basic/CharInfo.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Sema/Designator.h"
23#include "clang/Sema/EnterExpressionEvaluationContext.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/PointerIntPair.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// Sema Initialization Checking
37//===----------------------------------------------------------------------===//
38
39/// Check whether T is compatible with a wide character type (wchar_t,
40/// char16_t or char32_t).
41static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
42 if (Context.typesAreCompatible(Context.getWideCharType(), T))
43 return true;
44 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
45 return Context.typesAreCompatible(Context.Char16Ty, T) ||
46 Context.typesAreCompatible(Context.Char32Ty, T);
47 }
48 return false;
49}
50
51enum StringInitFailureKind {
52 SIF_None,
53 SIF_NarrowStringIntoWideChar,
54 SIF_WideStringIntoChar,
55 SIF_IncompatWideStringIntoWideChar,
56 SIF_UTF8StringIntoPlainChar,
57 SIF_PlainStringIntoUTF8Char,
58 SIF_Other
59};
60
61/// Check whether the array of type AT can be initialized by the Init
62/// expression by means of string initialization. Returns SIF_None if so,
63/// otherwise returns a StringInitFailureKind that describes why the
64/// initialization would not work.
65static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
66 ASTContext &Context) {
67 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
68 return SIF_Other;
69
70 // See if this is a string literal or @encode.
71 Init = Init->IgnoreParens();
72
73 // Handle @encode, which is a narrow string.
74 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
75 return SIF_None;
76
77 // Otherwise we can only handle string literals.
78 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
79 if (!SL)
80 return SIF_Other;
81
82 const QualType ElemTy =
83 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
84
85 auto IsCharOrUnsignedChar = [](const QualType &T) {
86 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
87 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
88 };
89
90 switch (SL->getKind()) {
91 case StringLiteral::UTF8:
92 // char8_t array can be initialized with a UTF-8 string.
93 // - C++20 [dcl.init.string] (DR)
94 // Additionally, an array of char or unsigned char may be initialized
95 // by a UTF-8 string literal.
96 if (ElemTy->isChar8Type() ||
97 (Context.getLangOpts().Char8 &&
98 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
99 return SIF_None;
100 [[fallthrough]];
101 case StringLiteral::Ordinary:
102 // char array can be initialized with a narrow string.
103 // Only allow char x[] = "foo"; not char x[] = L"foo";
104 if (ElemTy->isCharType())
105 return (SL->getKind() == StringLiteral::UTF8 &&
106 Context.getLangOpts().Char8)
107 ? SIF_UTF8StringIntoPlainChar
108 : SIF_None;
109 if (ElemTy->isChar8Type())
110 return SIF_PlainStringIntoUTF8Char;
111 if (IsWideCharCompatible(ElemTy, Context))
112 return SIF_NarrowStringIntoWideChar;
113 return SIF_Other;
114 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
115 // "An array with element type compatible with a qualified or unqualified
116 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
117 // string literal with the corresponding encoding prefix (L, u, or U,
118 // respectively), optionally enclosed in braces.
119 case StringLiteral::UTF16:
120 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
121 return SIF_None;
122 if (ElemTy->isCharType() || ElemTy->isChar8Type())
123 return SIF_WideStringIntoChar;
124 if (IsWideCharCompatible(ElemTy, Context))
125 return SIF_IncompatWideStringIntoWideChar;
126 return SIF_Other;
127 case StringLiteral::UTF32:
128 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
129 return SIF_None;
130 if (ElemTy->isCharType() || ElemTy->isChar8Type())
131 return SIF_WideStringIntoChar;
132 if (IsWideCharCompatible(ElemTy, Context))
133 return SIF_IncompatWideStringIntoWideChar;
134 return SIF_Other;
135 case StringLiteral::Wide:
136 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
137 return SIF_None;
138 if (ElemTy->isCharType() || ElemTy->isChar8Type())
139 return SIF_WideStringIntoChar;
140 if (IsWideCharCompatible(ElemTy, Context))
141 return SIF_IncompatWideStringIntoWideChar;
142 return SIF_Other;
143 }
144
145 llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?"
, "clang/lib/Sema/SemaInit.cpp", 145)
;
146}
147
148static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
149 ASTContext &Context) {
150 const ArrayType *arrayType = Context.getAsArrayType(declType);
151 if (!arrayType)
152 return SIF_Other;
153 return IsStringInit(init, arrayType, Context);
154}
155
156bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
157 return ::IsStringInit(Init, AT, Context) == SIF_None;
158}
159
160/// Update the type of a string literal, including any surrounding parentheses,
161/// to match the type of the object which it is initializing.
162static void updateStringLiteralType(Expr *E, QualType Ty) {
163 while (true) {
164 E->setType(Ty);
165 E->setValueKind(VK_PRValue);
166 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
167 break;
168 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
169 E = PE->getSubExpr();
170 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
171 assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension
) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension"
, "clang/lib/Sema/SemaInit.cpp", 171, __extension__ __PRETTY_FUNCTION__
))
;
172 E = UO->getSubExpr();
173 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
174 E = GSE->getResultExpr();
175 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
176 E = CE->getChosenSubExpr();
177 } else {
178 llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init"
, "clang/lib/Sema/SemaInit.cpp", 178)
;
179 }
180 }
181}
182
183/// Fix a compound literal initializing an array so it's correctly marked
184/// as an rvalue.
185static void updateGNUCompoundLiteralRValue(Expr *E) {
186 while (true) {
187 E->setValueKind(VK_PRValue);
188 if (isa<CompoundLiteralExpr>(E)) {
189 break;
190 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
191 E = PE->getSubExpr();
192 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
193 assert(UO->getOpcode() == UO_Extension)(static_cast <bool> (UO->getOpcode() == UO_Extension
) ? void (0) : __assert_fail ("UO->getOpcode() == UO_Extension"
, "clang/lib/Sema/SemaInit.cpp", 193, __extension__ __PRETTY_FUNCTION__
))
;
194 E = UO->getSubExpr();
195 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
196 E = GSE->getResultExpr();
197 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
198 E = CE->getChosenSubExpr();
199 } else {
200 llvm_unreachable("unexpected expr in array compound literal init")::llvm::llvm_unreachable_internal("unexpected expr in array compound literal init"
, "clang/lib/Sema/SemaInit.cpp", 200)
;
201 }
202 }
203}
204
205static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
206 Sema &S) {
207 // Get the length of the string as parsed.
208 auto *ConstantArrayTy =
209 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
210 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
211
212 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
213 // C99 6.7.8p14. We have an array of character type with unknown size
214 // being initialized to a string literal.
215 llvm::APInt ConstVal(32, StrLength);
216 // Return a new array type (C99 6.7.8p22).
217 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
218 ConstVal, nullptr,
219 ArrayType::Normal, 0);
220 updateStringLiteralType(Str, DeclT);
221 return;
222 }
223
224 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
225
226 // We have an array of character type with known size. However,
227 // the size may be smaller or larger than the string we are initializing.
228 // FIXME: Avoid truncation for 64-bit length strings.
229 if (S.getLangOpts().CPlusPlus) {
230 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
231 // For Pascal strings it's OK to strip off the terminating null character,
232 // so the example below is valid:
233 //
234 // unsigned char a[2] = "\pa";
235 if (SL->isPascal())
236 StrLength--;
237 }
238
239 // [dcl.init.string]p2
240 if (StrLength > CAT->getSize().getZExtValue())
241 S.Diag(Str->getBeginLoc(),
242 diag::err_initializer_string_for_char_array_too_long)
243 << CAT->getSize().getZExtValue() << StrLength
244 << Str->getSourceRange();
245 } else {
246 // C99 6.7.8p14.
247 if (StrLength-1 > CAT->getSize().getZExtValue())
248 S.Diag(Str->getBeginLoc(),
249 diag::ext_initializer_string_for_char_array_too_long)
250 << Str->getSourceRange();
251 }
252
253 // Set the type to the actual size that we are initializing. If we have
254 // something like:
255 // char x[1] = "foo";
256 // then this will set the string literal's type to char[1].
257 updateStringLiteralType(Str, DeclT);
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic checking for initializer lists.
262//===----------------------------------------------------------------------===//
263
264namespace {
265
266/// Semantic checking for initializer lists.
267///
268/// The InitListChecker class contains a set of routines that each
269/// handle the initialization of a certain kind of entity, e.g.,
270/// arrays, vectors, struct/union types, scalars, etc. The
271/// InitListChecker itself performs a recursive walk of the subobject
272/// structure of the type to be initialized, while stepping through
273/// the initializer list one element at a time. The IList and Index
274/// parameters to each of the Check* routines contain the active
275/// (syntactic) initializer list and the index into that initializer
276/// list that represents the current initializer. Each routine is
277/// responsible for moving that Index forward as it consumes elements.
278///
279/// Each Check* routine also has a StructuredList/StructuredIndex
280/// arguments, which contains the current "structured" (semantic)
281/// initializer list and the index into that initializer list where we
282/// are copying initializers as we map them over to the semantic
283/// list. Once we have completed our recursive walk of the subobject
284/// structure, we will have constructed a full semantic initializer
285/// list.
286///
287/// C99 designators cause changes in the initializer list traversal,
288/// because they make the initialization "jump" into a specific
289/// subobject and then continue the initialization from that
290/// point. CheckDesignatedInitializer() recursively steps into the
291/// designated subobject and manages backing out the recursion to
292/// initialize the subobjects after the one designated.
293///
294/// If an initializer list contains any designators, we build a placeholder
295/// structured list even in 'verify only' mode, so that we can track which
296/// elements need 'empty' initializtion.
297class InitListChecker {
298 Sema &SemaRef;
299 bool hadError = false;
300 bool VerifyOnly; // No diagnostics.
301 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
302 bool InOverloadResolution;
303 InitListExpr *FullyStructuredList = nullptr;
304 NoInitExpr *DummyExpr = nullptr;
305
306 NoInitExpr *getDummyInit() {
307 if (!DummyExpr)
308 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
309 return DummyExpr;
310 }
311
312 void CheckImplicitInitList(const InitializedEntity &Entity,
313 InitListExpr *ParentIList, QualType T,
314 unsigned &Index, InitListExpr *StructuredList,
315 unsigned &StructuredIndex);
316 void CheckExplicitInitList(const InitializedEntity &Entity,
317 InitListExpr *IList, QualType &T,
318 InitListExpr *StructuredList,
319 bool TopLevelObject = false);
320 void CheckListElementTypes(const InitializedEntity &Entity,
321 InitListExpr *IList, QualType &DeclType,
322 bool SubobjectIsDesignatorContext,
323 unsigned &Index,
324 InitListExpr *StructuredList,
325 unsigned &StructuredIndex,
326 bool TopLevelObject = false);
327 void CheckSubElementType(const InitializedEntity &Entity,
328 InitListExpr *IList, QualType ElemType,
329 unsigned &Index,
330 InitListExpr *StructuredList,
331 unsigned &StructuredIndex,
332 bool DirectlyDesignated = false);
333 void CheckComplexType(const InitializedEntity &Entity,
334 InitListExpr *IList, QualType DeclType,
335 unsigned &Index,
336 InitListExpr *StructuredList,
337 unsigned &StructuredIndex);
338 void CheckScalarType(const InitializedEntity &Entity,
339 InitListExpr *IList, QualType DeclType,
340 unsigned &Index,
341 InitListExpr *StructuredList,
342 unsigned &StructuredIndex);
343 void CheckReferenceType(const InitializedEntity &Entity,
344 InitListExpr *IList, QualType DeclType,
345 unsigned &Index,
346 InitListExpr *StructuredList,
347 unsigned &StructuredIndex);
348 void CheckVectorType(const InitializedEntity &Entity,
349 InitListExpr *IList, QualType DeclType, unsigned &Index,
350 InitListExpr *StructuredList,
351 unsigned &StructuredIndex);
352 void CheckStructUnionTypes(const InitializedEntity &Entity,
353 InitListExpr *IList, QualType DeclType,
354 CXXRecordDecl::base_class_range Bases,
355 RecordDecl::field_iterator Field,
356 bool SubobjectIsDesignatorContext, unsigned &Index,
357 InitListExpr *StructuredList,
358 unsigned &StructuredIndex,
359 bool TopLevelObject = false);
360 void CheckArrayType(const InitializedEntity &Entity,
361 InitListExpr *IList, QualType &DeclType,
362 llvm::APSInt elementIndex,
363 bool SubobjectIsDesignatorContext, unsigned &Index,
364 InitListExpr *StructuredList,
365 unsigned &StructuredIndex);
366 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
367 InitListExpr *IList, DesignatedInitExpr *DIE,
368 unsigned DesigIdx,
369 QualType &CurrentObjectType,
370 RecordDecl::field_iterator *NextField,
371 llvm::APSInt *NextElementIndex,
372 unsigned &Index,
373 InitListExpr *StructuredList,
374 unsigned &StructuredIndex,
375 bool FinishSubobjectInit,
376 bool TopLevelObject);
377 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
378 QualType CurrentObjectType,
379 InitListExpr *StructuredList,
380 unsigned StructuredIndex,
381 SourceRange InitRange,
382 bool IsFullyOverwritten = false);
383 void UpdateStructuredListElement(InitListExpr *StructuredList,
384 unsigned &StructuredIndex,
385 Expr *expr);
386 InitListExpr *createInitListExpr(QualType CurrentObjectType,
387 SourceRange InitRange,
388 unsigned ExpectedNumInits);
389 int numArrayElements(QualType DeclType);
390 int numStructUnionElements(QualType DeclType);
391
392 ExprResult PerformEmptyInit(SourceLocation Loc,
393 const InitializedEntity &Entity);
394
395 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
396 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
397 bool UnionOverride = false,
398 bool FullyOverwritten = true) {
399 // Overriding an initializer via a designator is valid with C99 designated
400 // initializers, but ill-formed with C++20 designated initializers.
401 unsigned DiagID =
402 SemaRef.getLangOpts().CPlusPlus
403 ? (UnionOverride ? diag::ext_initializer_union_overrides
404 : diag::ext_initializer_overrides)
405 : diag::warn_initializer_overrides;
406
407 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
408 // In overload resolution, we have to strictly enforce the rules, and so
409 // don't allow any overriding of prior initializers. This matters for a
410 // case such as:
411 //
412 // union U { int a, b; };
413 // struct S { int a, b; };
414 // void f(U), f(S);
415 //
416 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
417 // consistency, we disallow all overriding of prior initializers in
418 // overload resolution, not only overriding of union members.
419 hadError = true;
420 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
421 // If we'll be keeping around the old initializer but overwriting part of
422 // the object it initialized, and that object is not trivially
423 // destructible, this can leak. Don't allow that, not even as an
424 // extension.
425 //
426 // FIXME: It might be reasonable to allow this in cases where the part of
427 // the initializer that we're overriding has trivial destruction.
428 DiagID = diag::err_initializer_overrides_destructed;
429 } else if (!OldInit->getSourceRange().isValid()) {
430 // We need to check on source range validity because the previous
431 // initializer does not have to be an explicit initializer. e.g.,
432 //
433 // struct P { int a, b; };
434 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
435 //
436 // There is an overwrite taking place because the first braced initializer
437 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
438 //
439 // Such overwrites are harmless, so we don't diagnose them. (Note that in
440 // C++, this cannot be reached unless we've already seen and diagnosed a
441 // different conformance issue, such as a mixture of designated and
442 // non-designated initializers or a multi-level designator.)
443 return;
444 }
445
446 if (!VerifyOnly) {
447 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
448 << NewInitRange << FullyOverwritten << OldInit->getType();
449 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
450 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
451 << OldInit->getSourceRange();
452 }
453 }
454
455 // Explanation on the "FillWithNoInit" mode:
456 //
457 // Assume we have the following definitions (Case#1):
458 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
459 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
460 //
461 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
462 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
463 //
464 // But if we have (Case#2):
465 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
466 //
467 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
468 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
469 //
470 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
471 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
472 // initializers but with special "NoInitExpr" place holders, which tells the
473 // CodeGen not to generate any initializers for these parts.
474 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
475 const InitializedEntity &ParentEntity,
476 InitListExpr *ILE, bool &RequiresSecondPass,
477 bool FillWithNoInit);
478 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
479 const InitializedEntity &ParentEntity,
480 InitListExpr *ILE, bool &RequiresSecondPass,
481 bool FillWithNoInit = false);
482 void FillInEmptyInitializations(const InitializedEntity &Entity,
483 InitListExpr *ILE, bool &RequiresSecondPass,
484 InitListExpr *OuterILE, unsigned OuterIndex,
485 bool FillWithNoInit = false);
486 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
487 Expr *InitExpr, FieldDecl *Field,
488 bool TopLevelObject);
489 void CheckEmptyInitializable(const InitializedEntity &Entity,
490 SourceLocation Loc);
491
492public:
493 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
494 QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
495 bool InOverloadResolution = false);
496 bool HadError() { return hadError; }
497
498 // Retrieves the fully-structured initializer list used for
499 // semantic analysis and code generation.
500 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
501};
502
503} // end anonymous namespace
504
505ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
506 const InitializedEntity &Entity) {
507 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
508 true);
509 MultiExprArg SubInit;
510 Expr *InitExpr;
511 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
512
513 // C++ [dcl.init.aggr]p7:
514 // If there are fewer initializer-clauses in the list than there are
515 // members in the aggregate, then each member not explicitly initialized
516 // ...
517 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
518 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
519 if (EmptyInitList) {
520 // C++1y / DR1070:
521 // shall be initialized [...] from an empty initializer list.
522 //
523 // We apply the resolution of this DR to C++11 but not C++98, since C++98
524 // does not have useful semantics for initialization from an init list.
525 // We treat this as copy-initialization, because aggregate initialization
526 // always performs copy-initialization on its elements.
527 //
528 // Only do this if we're initializing a class type, to avoid filling in
529 // the initializer list where possible.
530 InitExpr = VerifyOnly
531 ? &DummyInitList
532 : new (SemaRef.Context)
533 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
534 InitExpr->setType(SemaRef.Context.VoidTy);
535 SubInit = InitExpr;
536 Kind = InitializationKind::CreateCopy(Loc, Loc);
537 } else {
538 // C++03:
539 // shall be value-initialized.
540 }
541
542 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
543 // libstdc++4.6 marks the vector default constructor as explicit in
544 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
545 // stlport does so too. Look for std::__debug for libstdc++, and for
546 // std:: for stlport. This is effectively a compiler-side implementation of
547 // LWG2193.
548 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
549 InitializationSequence::FK_ExplicitConstructor) {
550 OverloadCandidateSet::iterator Best;
551 OverloadingResult O =
552 InitSeq.getFailedCandidateSet()
553 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
554 (void)O;
555 assert(O == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (O == OR_Success && "Inconsistent overload resolution"
) ? void (0) : __assert_fail ("O == OR_Success && \"Inconsistent overload resolution\""
, "clang/lib/Sema/SemaInit.cpp", 555, __extension__ __PRETTY_FUNCTION__
))
;
556 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
557 CXXRecordDecl *R = CtorDecl->getParent();
558
559 if (CtorDecl->getMinRequiredArguments() == 0 &&
560 CtorDecl->isExplicit() && R->getDeclName() &&
561 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
562 bool IsInStd = false;
563 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
564 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
565 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
566 IsInStd = true;
567 }
568
569 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
570 .Cases("basic_string", "deque", "forward_list", true)
571 .Cases("list", "map", "multimap", "multiset", true)
572 .Cases("priority_queue", "queue", "set", "stack", true)
573 .Cases("unordered_map", "unordered_set", "vector", true)
574 .Default(false)) {
575 InitSeq.InitializeFrom(
576 SemaRef, Entity,
577 InitializationKind::CreateValue(Loc, Loc, Loc, true),
578 MultiExprArg(), /*TopLevelOfInitList=*/false,
579 TreatUnavailableAsInvalid);
580 // Emit a warning for this. System header warnings aren't shown
581 // by default, but people working on system headers should see it.
582 if (!VerifyOnly) {
583 SemaRef.Diag(CtorDecl->getLocation(),
584 diag::warn_invalid_initializer_from_system_header);
585 if (Entity.getKind() == InitializedEntity::EK_Member)
586 SemaRef.Diag(Entity.getDecl()->getLocation(),
587 diag::note_used_in_initialization_here);
588 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
589 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
590 }
591 }
592 }
593 }
594 if (!InitSeq) {
595 if (!VerifyOnly) {
596 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
597 if (Entity.getKind() == InitializedEntity::EK_Member)
598 SemaRef.Diag(Entity.getDecl()->getLocation(),
599 diag::note_in_omitted_aggregate_initializer)
600 << /*field*/1 << Entity.getDecl();
601 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
602 bool IsTrailingArrayNewMember =
603 Entity.getParent() &&
604 Entity.getParent()->isVariableLengthArrayNew();
605 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
606 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
607 << Entity.getElementIndex();
608 }
609 }
610 hadError = true;
611 return ExprError();
612 }
613
614 return VerifyOnly ? ExprResult()
615 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
616}
617
618void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
619 SourceLocation Loc) {
620 // If we're building a fully-structured list, we'll check this at the end
621 // once we know which elements are actually initialized. Otherwise, we know
622 // that there are no designators so we can just check now.
623 if (FullyStructuredList)
624 return;
625 PerformEmptyInit(Loc, Entity);
626}
627
628void InitListChecker::FillInEmptyInitForBase(
629 unsigned Init, const CXXBaseSpecifier &Base,
630 const InitializedEntity &ParentEntity, InitListExpr *ILE,
631 bool &RequiresSecondPass, bool FillWithNoInit) {
632 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
633 SemaRef.Context, &Base, false, &ParentEntity);
634
635 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
636 ExprResult BaseInit = FillWithNoInit
637 ? new (SemaRef.Context) NoInitExpr(Base.getType())
638 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
639 if (BaseInit.isInvalid()) {
640 hadError = true;
641 return;
642 }
643
644 if (!VerifyOnly) {
645 assert(Init < ILE->getNumInits() && "should have been expanded")(static_cast <bool> (Init < ILE->getNumInits() &&
"should have been expanded") ? void (0) : __assert_fail ("Init < ILE->getNumInits() && \"should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 645, __extension__ __PRETTY_FUNCTION__
))
;
646 ILE->setInit(Init, BaseInit.getAs<Expr>());
647 }
648 } else if (InitListExpr *InnerILE =
649 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
650 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
651 ILE, Init, FillWithNoInit);
652 } else if (DesignatedInitUpdateExpr *InnerDIUE =
653 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
654 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
655 RequiresSecondPass, ILE, Init,
656 /*FillWithNoInit =*/true);
657 }
658}
659
660void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
661 const InitializedEntity &ParentEntity,
662 InitListExpr *ILE,
663 bool &RequiresSecondPass,
664 bool FillWithNoInit) {
665 SourceLocation Loc = ILE->getEndLoc();
666 unsigned NumInits = ILE->getNumInits();
667 InitializedEntity MemberEntity
668 = InitializedEntity::InitializeMember(Field, &ParentEntity);
669
670 if (Init >= NumInits || !ILE->getInit(Init)) {
671 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
672 if (!RType->getDecl()->isUnion())
673 assert((Init < NumInits || VerifyOnly) &&(static_cast <bool> ((Init < NumInits || VerifyOnly)
&& "This ILE should have been expanded") ? void (0) :
__assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 674, __extension__ __PRETTY_FUNCTION__
))
674 "This ILE should have been expanded")(static_cast <bool> ((Init < NumInits || VerifyOnly)
&& "This ILE should have been expanded") ? void (0) :
__assert_fail ("(Init < NumInits || VerifyOnly) && \"This ILE should have been expanded\""
, "clang/lib/Sema/SemaInit.cpp", 674, __extension__ __PRETTY_FUNCTION__
))
;
675
676 if (FillWithNoInit) {
677 assert(!VerifyOnly && "should not fill with no-init in verify-only mode")(static_cast <bool> (!VerifyOnly && "should not fill with no-init in verify-only mode"
) ? void (0) : __assert_fail ("!VerifyOnly && \"should not fill with no-init in verify-only mode\""
, "clang/lib/Sema/SemaInit.cpp", 677, __extension__ __PRETTY_FUNCTION__
))
;
678 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
679 if (Init < NumInits)
680 ILE->setInit(Init, Filler);
681 else
682 ILE->updateInit(SemaRef.Context, Init, Filler);
683 return;
684 }
685 // C++1y [dcl.init.aggr]p7:
686 // If there are fewer initializer-clauses in the list than there are
687 // members in the aggregate, then each member not explicitly initialized
688 // shall be initialized from its brace-or-equal-initializer [...]
689 if (Field->hasInClassInitializer()) {
690 if (VerifyOnly)
691 return;
692
693 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
694 if (DIE.isInvalid()) {
695 hadError = true;
696 return;
697 }
698 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
699 if (Init < NumInits)
700 ILE->setInit(Init, DIE.get());
701 else {
702 ILE->updateInit(SemaRef.Context, Init, DIE.get());
703 RequiresSecondPass = true;
704 }
705 return;
706 }
707
708 if (Field->getType()->isReferenceType()) {
709 if (!VerifyOnly) {
710 // C++ [dcl.init.aggr]p9:
711 // If an incomplete or empty initializer-list leaves a
712 // member of reference type uninitialized, the program is
713 // ill-formed.
714 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
715 << Field->getType()
716 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
717 ->getSourceRange();
718 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
719 }
720 hadError = true;
721 return;
722 }
723
724 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
725 if (MemberInit.isInvalid()) {
726 hadError = true;
727 return;
728 }
729
730 if (hadError || VerifyOnly) {
731 // Do nothing
732 } else if (Init < NumInits) {
733 ILE->setInit(Init, MemberInit.getAs<Expr>());
734 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
735 // Empty initialization requires a constructor call, so
736 // extend the initializer list to include the constructor
737 // call and make a note that we'll need to take another pass
738 // through the initializer list.
739 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
740 RequiresSecondPass = true;
741 }
742 } else if (InitListExpr *InnerILE
743 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
744 FillInEmptyInitializations(MemberEntity, InnerILE,
745 RequiresSecondPass, ILE, Init, FillWithNoInit);
746 } else if (DesignatedInitUpdateExpr *InnerDIUE =
747 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
748 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
749 RequiresSecondPass, ILE, Init,
750 /*FillWithNoInit =*/true);
751 }
752}
753
754/// Recursively replaces NULL values within the given initializer list
755/// with expressions that perform value-initialization of the
756/// appropriate type, and finish off the InitListExpr formation.
757void
758InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
759 InitListExpr *ILE,
760 bool &RequiresSecondPass,
761 InitListExpr *OuterILE,
762 unsigned OuterIndex,
763 bool FillWithNoInit) {
764 assert((ILE->getType() != SemaRef.Context.VoidTy) &&(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "clang/lib/Sema/SemaInit.cpp", 765, __extension__ __PRETTY_FUNCTION__
))
765 "Should not have void type")(static_cast <bool> ((ILE->getType() != SemaRef.Context
.VoidTy) && "Should not have void type") ? void (0) :
__assert_fail ("(ILE->getType() != SemaRef.Context.VoidTy) && \"Should not have void type\""
, "clang/lib/Sema/SemaInit.cpp", 765, __extension__ __PRETTY_FUNCTION__
))
;
766
767 // We don't need to do any checks when just filling NoInitExprs; that can't
768 // fail.
769 if (FillWithNoInit && VerifyOnly)
770 return;
771
772 // If this is a nested initializer list, we might have changed its contents
773 // (and therefore some of its properties, such as instantiation-dependence)
774 // while filling it in. Inform the outer initializer list so that its state
775 // can be updated to match.
776 // FIXME: We should fully build the inner initializers before constructing
777 // the outer InitListExpr instead of mutating AST nodes after they have
778 // been used as subexpressions of other nodes.
779 struct UpdateOuterILEWithUpdatedInit {
780 InitListExpr *Outer;
781 unsigned OuterIndex;
782 ~UpdateOuterILEWithUpdatedInit() {
783 if (Outer)
784 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
785 }
786 } UpdateOuterRAII = {OuterILE, OuterIndex};
787
788 // A transparent ILE is not performing aggregate initialization and should
789 // not be filled in.
790 if (ILE->isTransparent())
791 return;
792
793 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
794 const RecordDecl *RDecl = RType->getDecl();
795 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
796 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
797 Entity, ILE, RequiresSecondPass, FillWithNoInit);
798 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
799 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
800 for (auto *Field : RDecl->fields()) {
801 if (Field->hasInClassInitializer()) {
802 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
803 FillWithNoInit);
804 break;
805 }
806 }
807 } else {
808 // The fields beyond ILE->getNumInits() are default initialized, so in
809 // order to leave them uninitialized, the ILE is expanded and the extra
810 // fields are then filled with NoInitExpr.
811 unsigned NumElems = numStructUnionElements(ILE->getType());
812 if (RDecl->hasFlexibleArrayMember())
813 ++NumElems;
814 if (!VerifyOnly && ILE->getNumInits() < NumElems)
815 ILE->resizeInits(SemaRef.Context, NumElems);
816
817 unsigned Init = 0;
818
819 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
820 for (auto &Base : CXXRD->bases()) {
821 if (hadError)
822 return;
823
824 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
825 FillWithNoInit);
826 ++Init;
827 }
828 }
829
830 for (auto *Field : RDecl->fields()) {
831 if (Field->isUnnamedBitfield())
832 continue;
833
834 if (hadError)
835 return;
836
837 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
838 FillWithNoInit);
839 if (hadError)
840 return;
841
842 ++Init;
843
844 // Only look at the first initialization of a union.
845 if (RDecl->isUnion())
846 break;
847 }
848 }
849
850 return;
851 }
852
853 QualType ElementType;
854
855 InitializedEntity ElementEntity = Entity;
856 unsigned NumInits = ILE->getNumInits();
857 unsigned NumElements = NumInits;
858 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
859 ElementType = AType->getElementType();
860 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
861 NumElements = CAType->getSize().getZExtValue();
862 // For an array new with an unknown bound, ask for one additional element
863 // in order to populate the array filler.
864 if (Entity.isVariableLengthArrayNew())
865 ++NumElements;
866 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
867 0, Entity);
868 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
869 ElementType = VType->getElementType();
870 NumElements = VType->getNumElements();
871 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
872 0, Entity);
873 } else
874 ElementType = ILE->getType();
875
876 bool SkipEmptyInitChecks = false;
877 for (unsigned Init = 0; Init != NumElements; ++Init) {
878 if (hadError)
879 return;
880
881 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
882 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
883 ElementEntity.setElementIndex(Init);
884
885 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
886 return;
887
888 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
889 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
890 ILE->setInit(Init, ILE->getArrayFiller());
891 else if (!InitExpr && !ILE->hasArrayFiller()) {
892 // In VerifyOnly mode, there's no point performing empty initialization
893 // more than once.
894 if (SkipEmptyInitChecks)
895 continue;
896
897 Expr *Filler = nullptr;
898
899 if (FillWithNoInit)
900 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
901 else {
902 ExprResult ElementInit =
903 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
904 if (ElementInit.isInvalid()) {
905 hadError = true;
906 return;
907 }
908
909 Filler = ElementInit.getAs<Expr>();
910 }
911
912 if (hadError) {
913 // Do nothing
914 } else if (VerifyOnly) {
915 SkipEmptyInitChecks = true;
916 } else if (Init < NumInits) {
917 // For arrays, just set the expression used for value-initialization
918 // of the "holes" in the array.
919 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
920 ILE->setArrayFiller(Filler);
921 else
922 ILE->setInit(Init, Filler);
923 } else {
924 // For arrays, just set the expression used for value-initialization
925 // of the rest of elements and exit.
926 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
927 ILE->setArrayFiller(Filler);
928 return;
929 }
930
931 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
932 // Empty initialization requires a constructor call, so
933 // extend the initializer list to include the constructor
934 // call and make a note that we'll need to take another pass
935 // through the initializer list.
936 ILE->updateInit(SemaRef.Context, Init, Filler);
937 RequiresSecondPass = true;
938 }
939 }
940 } else if (InitListExpr *InnerILE
941 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
942 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
943 ILE, Init, FillWithNoInit);
944 } else if (DesignatedInitUpdateExpr *InnerDIUE =
945 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
946 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
947 RequiresSecondPass, ILE, Init,
948 /*FillWithNoInit =*/true);
949 }
950 }
951}
952
953static bool hasAnyDesignatedInits(const InitListExpr *IL) {
954 for (const Stmt *Init : *IL)
955 if (Init && isa<DesignatedInitExpr>(Init))
956 return true;
957 return false;
958}
959
960InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
961 InitListExpr *IL, QualType &T, bool VerifyOnly,
962 bool TreatUnavailableAsInvalid,
963 bool InOverloadResolution)
964 : SemaRef(S), VerifyOnly(VerifyOnly),
965 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
966 InOverloadResolution(InOverloadResolution) {
967 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
968 FullyStructuredList =
969 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
970
971 // FIXME: Check that IL isn't already the semantic form of some other
972 // InitListExpr. If it is, we'd create a broken AST.
973 if (!VerifyOnly)
974 FullyStructuredList->setSyntacticForm(IL);
975 }
976
977 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
978 /*TopLevelObject=*/true);
979
980 if (!hadError && FullyStructuredList) {
981 bool RequiresSecondPass = false;
982 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
983 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
984 if (RequiresSecondPass && !hadError)
985 FillInEmptyInitializations(Entity, FullyStructuredList,
986 RequiresSecondPass, nullptr, 0);
987 }
988 if (hadError && FullyStructuredList)
989 FullyStructuredList->markError();
990}
991
992int InitListChecker::numArrayElements(QualType DeclType) {
993 // FIXME: use a proper constant
994 int maxElements = 0x7FFFFFFF;
995 if (const ConstantArrayType *CAT =
996 SemaRef.Context.getAsConstantArrayType(DeclType)) {
997 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
998 }
999 return maxElements;
1000}
1001
1002int InitListChecker::numStructUnionElements(QualType DeclType) {
1003 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1004 int InitializableMembers = 0;
1005 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1006 InitializableMembers += CXXRD->getNumBases();
1007 for (const auto *Field : structDecl->fields())
1008 if (!Field->isUnnamedBitfield())
1009 ++InitializableMembers;
1010
1011 if (structDecl->isUnion())
1012 return std::min(InitializableMembers, 1);
1013 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1014}
1015
1016/// Determine whether Entity is an entity for which it is idiomatic to elide
1017/// the braces in aggregate initialization.
1018static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1019 // Recursive initialization of the one and only field within an aggregate
1020 // class is considered idiomatic. This case arises in particular for
1021 // initialization of std::array, where the C++ standard suggests the idiom of
1022 //
1023 // std::array<T, N> arr = {1, 2, 3};
1024 //
1025 // (where std::array is an aggregate struct containing a single array field.
1026
1027 if (!Entity.getParent())
1028 return false;
1029
1030 // Allows elide brace initialization for aggregates with empty base.
1031 if (Entity.getKind() == InitializedEntity::EK_Base) {
1032 auto *ParentRD =
1033 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1034 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1035 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1036 }
1037
1038 // Allow brace elision if the only subobject is a field.
1039 if (Entity.getKind() == InitializedEntity::EK_Member) {
1040 auto *ParentRD =
1041 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1042 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1043 if (CXXRD->getNumBases()) {
1044 return false;
1045 }
1046 }
1047 auto FieldIt = ParentRD->field_begin();
1048 assert(FieldIt != ParentRD->field_end() &&(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "clang/lib/Sema/SemaInit.cpp", 1049, __extension__ __PRETTY_FUNCTION__
))
1049 "no fields but have initializer for member?")(static_cast <bool> (FieldIt != ParentRD->field_end(
) && "no fields but have initializer for member?") ? void
(0) : __assert_fail ("FieldIt != ParentRD->field_end() && \"no fields but have initializer for member?\""
, "clang/lib/Sema/SemaInit.cpp", 1049, __extension__ __PRETTY_FUNCTION__
))
;
1050 return ++FieldIt == ParentRD->field_end();
1051 }
1052
1053 return false;
1054}
1055
1056/// Check whether the range of the initializer \p ParentIList from element
1057/// \p Index onwards can be used to initialize an object of type \p T. Update
1058/// \p Index to indicate how many elements of the list were consumed.
1059///
1060/// This also fills in \p StructuredList, from element \p StructuredIndex
1061/// onwards, with the fully-braced, desugared form of the initialization.
1062void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1063 InitListExpr *ParentIList,
1064 QualType T, unsigned &Index,
1065 InitListExpr *StructuredList,
1066 unsigned &StructuredIndex) {
1067 int maxElements = 0;
1068
1069 if (T->isArrayType())
1070 maxElements = numArrayElements(T);
1071 else if (T->isRecordType())
1072 maxElements = numStructUnionElements(T);
1073 else if (T->isVectorType())
1074 maxElements = T->castAs<VectorType>()->getNumElements();
1075 else
1076 llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type"
, "clang/lib/Sema/SemaInit.cpp", 1076)
;
1077
1078 if (maxElements == 0) {
1079 if (!VerifyOnly)
1080 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1081 diag::err_implicit_empty_initializer);
1082 ++Index;
1083 hadError = true;
1084 return;
1085 }
1086
1087 // Build a structured initializer list corresponding to this subobject.
1088 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1089 ParentIList, Index, T, StructuredList, StructuredIndex,
1090 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1091 ParentIList->getSourceRange().getEnd()));
1092 unsigned StructuredSubobjectInitIndex = 0;
1093
1094 // Check the element types and build the structural subobject.
1095 unsigned StartIndex = Index;
1096 CheckListElementTypes(Entity, ParentIList, T,
1097 /*SubobjectIsDesignatorContext=*/false, Index,
1098 StructuredSubobjectInitList,
1099 StructuredSubobjectInitIndex);
1100
1101 if (StructuredSubobjectInitList) {
1102 StructuredSubobjectInitList->setType(T);
1103
1104 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1105 // Update the structured sub-object initializer so that it's ending
1106 // range corresponds with the end of the last initializer it used.
1107 if (EndIndex < ParentIList->getNumInits() &&
1108 ParentIList->getInit(EndIndex)) {
1109 SourceLocation EndLoc
1110 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1111 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1112 }
1113
1114 // Complain about missing braces.
1115 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1116 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1117 !isIdiomaticBraceElisionEntity(Entity)) {
1118 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1119 diag::warn_missing_braces)
1120 << StructuredSubobjectInitList->getSourceRange()
1121 << FixItHint::CreateInsertion(
1122 StructuredSubobjectInitList->getBeginLoc(), "{")
1123 << FixItHint::CreateInsertion(
1124 SemaRef.getLocForEndOfToken(
1125 StructuredSubobjectInitList->getEndLoc()),
1126 "}");
1127 }
1128
1129 // Warn if this type won't be an aggregate in future versions of C++.
1130 auto *CXXRD = T->getAsCXXRecordDecl();
1131 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1132 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1133 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1134 << StructuredSubobjectInitList->getSourceRange() << T;
1135 }
1136 }
1137}
1138
1139/// Warn that \p Entity was of scalar type and was initialized by a
1140/// single-element braced initializer list.
1141static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1142 SourceRange Braces) {
1143 // Don't warn during template instantiation. If the initialization was
1144 // non-dependent, we warned during the initial parse; otherwise, the
1145 // type might not be scalar in some uses of the template.
1146 if (S.inTemplateInstantiation())
1147 return;
1148
1149 unsigned DiagID = 0;
1150
1151 switch (Entity.getKind()) {
1152 case InitializedEntity::EK_VectorElement:
1153 case InitializedEntity::EK_ComplexElement:
1154 case InitializedEntity::EK_ArrayElement:
1155 case InitializedEntity::EK_Parameter:
1156 case InitializedEntity::EK_Parameter_CF_Audited:
1157 case InitializedEntity::EK_TemplateParameter:
1158 case InitializedEntity::EK_Result:
1159 // Extra braces here are suspicious.
1160 DiagID = diag::warn_braces_around_init;
1161 break;
1162
1163 case InitializedEntity::EK_Member:
1164 // Warn on aggregate initialization but not on ctor init list or
1165 // default member initializer.
1166 if (Entity.getParent())
1167 DiagID = diag::warn_braces_around_init;
1168 break;
1169
1170 case InitializedEntity::EK_Variable:
1171 case InitializedEntity::EK_LambdaCapture:
1172 // No warning, might be direct-list-initialization.
1173 // FIXME: Should we warn for copy-list-initialization in these cases?
1174 break;
1175
1176 case InitializedEntity::EK_New:
1177 case InitializedEntity::EK_Temporary:
1178 case InitializedEntity::EK_CompoundLiteralInit:
1179 // No warning, braces are part of the syntax of the underlying construct.
1180 break;
1181
1182 case InitializedEntity::EK_RelatedResult:
1183 // No warning, we already warned when initializing the result.
1184 break;
1185
1186 case InitializedEntity::EK_Exception:
1187 case InitializedEntity::EK_Base:
1188 case InitializedEntity::EK_Delegating:
1189 case InitializedEntity::EK_BlockElement:
1190 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1191 case InitializedEntity::EK_Binding:
1192 case InitializedEntity::EK_StmtExprResult:
1193 case InitializedEntity::EK_ParenAggInitMember:
1194 llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init"
, "clang/lib/Sema/SemaInit.cpp", 1194)
;
1195 }
1196
1197 if (DiagID) {
1198 S.Diag(Braces.getBegin(), DiagID)
1199 << Entity.getType()->isSizelessBuiltinType() << Braces
1200 << FixItHint::CreateRemoval(Braces.getBegin())
1201 << FixItHint::CreateRemoval(Braces.getEnd());
1202 }
1203}
1204
1205/// Check whether the initializer \p IList (that was written with explicit
1206/// braces) can be used to initialize an object of type \p T.
1207///
1208/// This also fills in \p StructuredList with the fully-braced, desugared
1209/// form of the initialization.
1210void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1211 InitListExpr *IList, QualType &T,
1212 InitListExpr *StructuredList,
1213 bool TopLevelObject) {
1214 unsigned Index = 0, StructuredIndex = 0;
1215 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1216 Index, StructuredList, StructuredIndex, TopLevelObject);
1217 if (StructuredList) {
1218 QualType ExprTy = T;
1219 if (!ExprTy->isArrayType())
1220 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1221 if (!VerifyOnly)
1222 IList->setType(ExprTy);
1223 StructuredList->setType(ExprTy);
1224 }
1225 if (hadError)
1226 return;
1227
1228 // Don't complain for incomplete types, since we'll get an error elsewhere.
1229 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1230 // We have leftover initializers
1231 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1232 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1233 hadError = ExtraInitsIsError;
1234 if (VerifyOnly) {
1235 return;
1236 } else if (StructuredIndex == 1 &&
1237 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1238 SIF_None) {
1239 unsigned DK =
1240 ExtraInitsIsError
1241 ? diag::err_excess_initializers_in_char_array_initializer
1242 : diag::ext_excess_initializers_in_char_array_initializer;
1243 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1244 << IList->getInit(Index)->getSourceRange();
1245 } else if (T->isSizelessBuiltinType()) {
1246 unsigned DK = ExtraInitsIsError
1247 ? diag::err_excess_initializers_for_sizeless_type
1248 : diag::ext_excess_initializers_for_sizeless_type;
1249 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1250 << T << IList->getInit(Index)->getSourceRange();
1251 } else {
1252 int initKind = T->isArrayType() ? 0 :
1253 T->isVectorType() ? 1 :
1254 T->isScalarType() ? 2 :
1255 T->isUnionType() ? 3 :
1256 4;
1257
1258 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1259 : diag::ext_excess_initializers;
1260 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1261 << initKind << IList->getInit(Index)->getSourceRange();
1262 }
1263 }
1264
1265 if (!VerifyOnly) {
1266 if (T->isScalarType() && IList->getNumInits() == 1 &&
1267 !isa<InitListExpr>(IList->getInit(0)))
1268 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1269
1270 // Warn if this is a class type that won't be an aggregate in future
1271 // versions of C++.
1272 auto *CXXRD = T->getAsCXXRecordDecl();
1273 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1274 // Don't warn if there's an equivalent default constructor that would be
1275 // used instead.
1276 bool HasEquivCtor = false;
1277 if (IList->getNumInits() == 0) {
1278 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1279 HasEquivCtor = CD && !CD->isDeleted();
1280 }
1281
1282 if (!HasEquivCtor) {
1283 SemaRef.Diag(IList->getBeginLoc(),
1284 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1285 << IList->getSourceRange() << T;
1286 }
1287 }
1288 }
1289}
1290
1291void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1292 InitListExpr *IList,
1293 QualType &DeclType,
1294 bool SubobjectIsDesignatorContext,
1295 unsigned &Index,
1296 InitListExpr *StructuredList,
1297 unsigned &StructuredIndex,
1298 bool TopLevelObject) {
1299 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1300 // Explicitly braced initializer for complex type can be real+imaginary
1301 // parts.
1302 CheckComplexType(Entity, IList, DeclType, Index,
1303 StructuredList, StructuredIndex);
1304 } else if (DeclType->isScalarType()) {
1305 CheckScalarType(Entity, IList, DeclType, Index,
1306 StructuredList, StructuredIndex);
1307 } else if (DeclType->isVectorType()) {
1308 CheckVectorType(Entity, IList, DeclType, Index,
1309 StructuredList, StructuredIndex);
1310 } else if (DeclType->isRecordType()) {
1311 assert(DeclType->isAggregateType() &&(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "clang/lib/Sema/SemaInit.cpp", 1312, __extension__ __PRETTY_FUNCTION__
))
1312 "non-aggregate records should be handed in CheckSubElementType")(static_cast <bool> (DeclType->isAggregateType() &&
"non-aggregate records should be handed in CheckSubElementType"
) ? void (0) : __assert_fail ("DeclType->isAggregateType() && \"non-aggregate records should be handed in CheckSubElementType\""
, "clang/lib/Sema/SemaInit.cpp", 1312, __extension__ __PRETTY_FUNCTION__
))
;
1313 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
1314 auto Bases =
1315 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1316 CXXRecordDecl::base_class_iterator());
1317 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1318 Bases = CXXRD->bases();
1319 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1320 SubobjectIsDesignatorContext, Index, StructuredList,
1321 StructuredIndex, TopLevelObject);
1322 } else if (DeclType->isArrayType()) {
1323 llvm::APSInt Zero(
1324 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1325 false);
1326 CheckArrayType(Entity, IList, DeclType, Zero,
1327 SubobjectIsDesignatorContext, Index,
1328 StructuredList, StructuredIndex);
1329 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1330 // This type is invalid, issue a diagnostic.
1331 ++Index;
1332 if (!VerifyOnly)
1333 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1334 << DeclType;
1335 hadError = true;
1336 } else if (DeclType->isReferenceType()) {
1337 CheckReferenceType(Entity, IList, DeclType, Index,
1338 StructuredList, StructuredIndex);
1339 } else if (DeclType->isObjCObjectType()) {
1340 if (!VerifyOnly)
1341 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1342 hadError = true;
1343 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1344 DeclType->isSizelessBuiltinType()) {
1345 // Checks for scalar type are sufficient for these types too.
1346 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1347 StructuredIndex);
1348 } else {
1349 if (!VerifyOnly)
1350 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1351 << DeclType;
1352 hadError = true;
1353 }
1354}
1355
1356void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1357 InitListExpr *IList,
1358 QualType ElemType,
1359 unsigned &Index,
1360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex,
1362 bool DirectlyDesignated) {
1363 Expr *expr = IList->getInit(Index);
1364
1365 if (ElemType->isReferenceType())
1366 return CheckReferenceType(Entity, IList, ElemType, Index,
1367 StructuredList, StructuredIndex);
1368
1369 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1370 if (SubInitList->getNumInits() == 1 &&
1371 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1372 SIF_None) {
1373 // FIXME: It would be more faithful and no less correct to include an
1374 // InitListExpr in the semantic form of the initializer list in this case.
1375 expr = SubInitList->getInit(0);
1376 }
1377 // Nested aggregate initialization and C++ initialization are handled later.
1378 } else if (isa<ImplicitValueInitExpr>(expr)) {
1379 // This happens during template instantiation when we see an InitListExpr
1380 // that we've already checked once.
1381 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "clang/lib/Sema/SemaInit.cpp", 1382, __extension__ __PRETTY_FUNCTION__
))
1382 "found implicit initialization for the wrong type")(static_cast <bool> (SemaRef.Context.hasSameType(expr->
getType(), ElemType) && "found implicit initialization for the wrong type"
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(expr->getType(), ElemType) && \"found implicit initialization for the wrong type\""
, "clang/lib/Sema/SemaInit.cpp", 1382, __extension__ __PRETTY_FUNCTION__
))
;
1383 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1384 ++Index;
1385 return;
1386 }
1387
1388 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1389 // C++ [dcl.init.aggr]p2:
1390 // Each member is copy-initialized from the corresponding
1391 // initializer-clause.
1392
1393 // FIXME: Better EqualLoc?
1394 InitializationKind Kind =
1395 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1396
1397 // Vector elements can be initialized from other vectors in which case
1398 // we need initialization entity with a type of a vector (and not a vector
1399 // element!) initializing multiple vector elements.
1400 auto TmpEntity =
1401 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1402 ? InitializedEntity::InitializeTemporary(ElemType)
1403 : Entity;
1404
1405 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1406 /*TopLevelOfInitList*/ true);
1407
1408 // C++14 [dcl.init.aggr]p13:
1409 // If the assignment-expression can initialize a member, the member is
1410 // initialized. Otherwise [...] brace elision is assumed
1411 //
1412 // Brace elision is never performed if the element is not an
1413 // assignment-expression.
1414 if (Seq || isa<InitListExpr>(expr)) {
1415 if (!VerifyOnly) {
1416 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1417 if (Result.isInvalid())
1418 hadError = true;
1419
1420 UpdateStructuredListElement(StructuredList, StructuredIndex,
1421 Result.getAs<Expr>());
1422 } else if (!Seq) {
1423 hadError = true;
1424 } else if (StructuredList) {
1425 UpdateStructuredListElement(StructuredList, StructuredIndex,
1426 getDummyInit());
1427 }
1428 ++Index;
1429 return;
1430 }
1431
1432 // Fall through for subaggregate initialization
1433 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1434 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1435 return CheckScalarType(Entity, IList, ElemType, Index,
1436 StructuredList, StructuredIndex);
1437 } else if (const ArrayType *arrayType =
1438 SemaRef.Context.getAsArrayType(ElemType)) {
1439 // arrayType can be incomplete if we're initializing a flexible
1440 // array member. There's nothing we can do with the completed
1441 // type here, though.
1442
1443 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1444 // FIXME: Should we do this checking in verify-only mode?
1445 if (!VerifyOnly)
1446 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1447 if (StructuredList)
1448 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1449 ++Index;
1450 return;
1451 }
1452
1453 // Fall through for subaggregate initialization.
1454
1455 } else {
1456 assert((ElemType->isRecordType() || ElemType->isVectorType() ||(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 1457, __extension__ __PRETTY_FUNCTION__
))
1457 ElemType->isOpenCLSpecificType()) && "Unexpected type")(static_cast <bool> ((ElemType->isRecordType() || ElemType
->isVectorType() || ElemType->isOpenCLSpecificType()) &&
"Unexpected type") ? void (0) : __assert_fail ("(ElemType->isRecordType() || ElemType->isVectorType() || ElemType->isOpenCLSpecificType()) && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 1457, __extension__ __PRETTY_FUNCTION__
))
;
1458
1459 // C99 6.7.8p13:
1460 //
1461 // The initializer for a structure or union object that has
1462 // automatic storage duration shall be either an initializer
1463 // list as described below, or a single expression that has
1464 // compatible structure or union type. In the latter case, the
1465 // initial value of the object, including unnamed members, is
1466 // that of the expression.
1467 ExprResult ExprRes = expr;
1468 if (SemaRef.CheckSingleAssignmentConstraints(
1469 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1470 if (ExprRes.isInvalid())
1471 hadError = true;
1472 else {
1473 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1474 if (ExprRes.isInvalid())
1475 hadError = true;
1476 }
1477 UpdateStructuredListElement(StructuredList, StructuredIndex,
1478 ExprRes.getAs<Expr>());
1479 ++Index;
1480 return;
1481 }
1482 ExprRes.get();
1483 // Fall through for subaggregate initialization
1484 }
1485
1486 // C++ [dcl.init.aggr]p12:
1487 //
1488 // [...] Otherwise, if the member is itself a non-empty
1489 // subaggregate, brace elision is assumed and the initializer is
1490 // considered for the initialization of the first member of
1491 // the subaggregate.
1492 // OpenCL vector initializer is handled elsewhere.
1493 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1494 ElemType->isAggregateType()) {
1495 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1496 StructuredIndex);
1497 ++StructuredIndex;
1498
1499 // In C++20, brace elision is not permitted for a designated initializer.
1500 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1501 if (InOverloadResolution)
1502 hadError = true;
1503 if (!VerifyOnly) {
1504 SemaRef.Diag(expr->getBeginLoc(),
1505 diag::ext_designated_init_brace_elision)
1506 << expr->getSourceRange()
1507 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1508 << FixItHint::CreateInsertion(
1509 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1510 }
1511 }
1512 } else {
1513 if (!VerifyOnly) {
1514 // We cannot initialize this element, so let PerformCopyInitialization
1515 // produce the appropriate diagnostic. We already checked that this
1516 // initialization will fail.
1517 ExprResult Copy =
1518 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1519 /*TopLevelOfInitList=*/true);
1520 (void)Copy;
1521 assert(Copy.isInvalid() &&(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail"
) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\""
, "clang/lib/Sema/SemaInit.cpp", 1522, __extension__ __PRETTY_FUNCTION__
))
1522 "expected non-aggregate initialization to fail")(static_cast <bool> (Copy.isInvalid() && "expected non-aggregate initialization to fail"
) ? void (0) : __assert_fail ("Copy.isInvalid() && \"expected non-aggregate initialization to fail\""
, "clang/lib/Sema/SemaInit.cpp", 1522, __extension__ __PRETTY_FUNCTION__
))
;
1523 }
1524 hadError = true;
1525 ++Index;
1526 ++StructuredIndex;
1527 }
1528}
1529
1530void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1531 InitListExpr *IList, QualType DeclType,
1532 unsigned &Index,
1533 InitListExpr *StructuredList,
1534 unsigned &StructuredIndex) {
1535 assert(Index == 0 && "Index in explicit init list must be zero")(static_cast <bool> (Index == 0 && "Index in explicit init list must be zero"
) ? void (0) : __assert_fail ("Index == 0 && \"Index in explicit init list must be zero\""
, "clang/lib/Sema/SemaInit.cpp", 1535, __extension__ __PRETTY_FUNCTION__
))
;
1536
1537 // As an extension, clang supports complex initializers, which initialize
1538 // a complex number component-wise. When an explicit initializer list for
1539 // a complex number contains two initializers, this extension kicks in:
1540 // it expects the initializer list to contain two elements convertible to
1541 // the element type of the complex type. The first element initializes
1542 // the real part, and the second element intitializes the imaginary part.
1543
1544 if (IList->getNumInits() < 2)
1545 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1546 StructuredIndex);
1547
1548 // This is an extension in C. (The builtin _Complex type does not exist
1549 // in the C++ standard.)
1550 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1551 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1552 << IList->getSourceRange();
1553
1554 // Initialize the complex number.
1555 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1556 InitializedEntity ElementEntity =
1557 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1558
1559 for (unsigned i = 0; i < 2; ++i) {
1560 ElementEntity.setElementIndex(Index);
1561 CheckSubElementType(ElementEntity, IList, elementType, Index,
1562 StructuredList, StructuredIndex);
1563 }
1564}
1565
1566void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1567 InitListExpr *IList, QualType DeclType,
1568 unsigned &Index,
1569 InitListExpr *StructuredList,
1570 unsigned &StructuredIndex) {
1571 if (Index >= IList->getNumInits()) {
1572 if (!VerifyOnly) {
1573 if (SemaRef.getLangOpts().CPlusPlus) {
1574 if (DeclType->isSizelessBuiltinType())
1575 SemaRef.Diag(IList->getBeginLoc(),
1576 SemaRef.getLangOpts().CPlusPlus11
1577 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1578 : diag::err_empty_sizeless_initializer)
1579 << DeclType << IList->getSourceRange();
1580 else
1581 SemaRef.Diag(IList->getBeginLoc(),
1582 SemaRef.getLangOpts().CPlusPlus11
1583 ? diag::warn_cxx98_compat_empty_scalar_initializer
1584 : diag::err_empty_scalar_initializer)
1585 << IList->getSourceRange();
1586 }
1587 }
1588 hadError =
1589 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1590 ++Index;
1591 ++StructuredIndex;
1592 return;
1593 }
1594
1595 Expr *expr = IList->getInit(Index);
1596 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1597 // FIXME: This is invalid, and accepting it causes overload resolution
1598 // to pick the wrong overload in some corner cases.
1599 if (!VerifyOnly)
1600 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1601 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1602
1603 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1604 StructuredIndex);
1605 return;
1606 } else if (isa<DesignatedInitExpr>(expr)) {
1607 if (!VerifyOnly)
1608 SemaRef.Diag(expr->getBeginLoc(),
1609 diag::err_designator_for_scalar_or_sizeless_init)
1610 << DeclType->isSizelessBuiltinType() << DeclType
1611 << expr->getSourceRange();
1612 hadError = true;
1613 ++Index;
1614 ++StructuredIndex;
1615 return;
1616 }
1617
1618 ExprResult Result;
1619 if (VerifyOnly) {
1620 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1621 Result = getDummyInit();
1622 else
1623 Result = ExprError();
1624 } else {
1625 Result =
1626 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1627 /*TopLevelOfInitList=*/true);
1628 }
1629
1630 Expr *ResultExpr = nullptr;
1631
1632 if (Result.isInvalid())
1633 hadError = true; // types weren't compatible.
1634 else {
1635 ResultExpr = Result.getAs<Expr>();
1636
1637 if (ResultExpr != expr && !VerifyOnly) {
1638 // The type was promoted, update initializer list.
1639 // FIXME: Why are we updating the syntactic init list?
1640 IList->setInit(Index, ResultExpr);
1641 }
1642 }
1643 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1644 ++Index;
1645}
1646
1647void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1648 InitListExpr *IList, QualType DeclType,
1649 unsigned &Index,
1650 InitListExpr *StructuredList,
1651 unsigned &StructuredIndex) {
1652 if (Index >= IList->getNumInits()) {
1653 // FIXME: It would be wonderful if we could point at the actual member. In
1654 // general, it would be useful to pass location information down the stack,
1655 // so that we know the location (or decl) of the "current object" being
1656 // initialized.
1657 if (!VerifyOnly)
1658 SemaRef.Diag(IList->getBeginLoc(),
1659 diag::err_init_reference_member_uninitialized)
1660 << DeclType << IList->getSourceRange();
1661 hadError = true;
1662 ++Index;
1663 ++StructuredIndex;
1664 return;
1665 }
1666
1667 Expr *expr = IList->getInit(Index);
1668 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1669 if (!VerifyOnly)
1670 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1671 << DeclType << IList->getSourceRange();
1672 hadError = true;
1673 ++Index;
1674 ++StructuredIndex;
1675 return;
1676 }
1677
1678 ExprResult Result;
1679 if (VerifyOnly) {
1680 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1681 Result = getDummyInit();
1682 else
1683 Result = ExprError();
1684 } else {
1685 Result =
1686 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1687 /*TopLevelOfInitList=*/true);
1688 }
1689
1690 if (Result.isInvalid())
1691 hadError = true;
1692
1693 expr = Result.getAs<Expr>();
1694 // FIXME: Why are we updating the syntactic init list?
1695 if (!VerifyOnly && expr)
1696 IList->setInit(Index, expr);
1697
1698 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1699 ++Index;
1700}
1701
1702void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1703 InitListExpr *IList, QualType DeclType,
1704 unsigned &Index,
1705 InitListExpr *StructuredList,
1706 unsigned &StructuredIndex) {
1707 const VectorType *VT = DeclType->castAs<VectorType>();
1708 unsigned maxElements = VT->getNumElements();
1709 unsigned numEltsInit = 0;
1710 QualType elementType = VT->getElementType();
1711
1712 if (Index >= IList->getNumInits()) {
1713 // Make sure the element type can be value-initialized.
1714 CheckEmptyInitializable(
1715 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1716 IList->getEndLoc());
1717 return;
1718 }
1719
1720 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1721 // If the initializing element is a vector, try to copy-initialize
1722 // instead of breaking it apart (which is doomed to failure anyway).
1723 Expr *Init = IList->getInit(Index);
1724 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1725 ExprResult Result;
1726 if (VerifyOnly) {
1727 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1728 Result = getDummyInit();
1729 else
1730 Result = ExprError();
1731 } else {
1732 Result =
1733 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1734 /*TopLevelOfInitList=*/true);
1735 }
1736
1737 Expr *ResultExpr = nullptr;
1738 if (Result.isInvalid())
1739 hadError = true; // types weren't compatible.
1740 else {
1741 ResultExpr = Result.getAs<Expr>();
1742
1743 if (ResultExpr != Init && !VerifyOnly) {
1744 // The type was promoted, update initializer list.
1745 // FIXME: Why are we updating the syntactic init list?
1746 IList->setInit(Index, ResultExpr);
1747 }
1748 }
1749 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1750 ++Index;
1751 return;
1752 }
1753
1754 InitializedEntity ElementEntity =
1755 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1756
1757 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1758 // Don't attempt to go past the end of the init list
1759 if (Index >= IList->getNumInits()) {
1760 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1761 break;
1762 }
1763
1764 ElementEntity.setElementIndex(Index);
1765 CheckSubElementType(ElementEntity, IList, elementType, Index,
1766 StructuredList, StructuredIndex);
1767 }
1768
1769 if (VerifyOnly)
1770 return;
1771
1772 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1773 const VectorType *T = Entity.getType()->castAs<VectorType>();
1774 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1775 T->getVectorKind() == VectorType::NeonPolyVector)) {
1776 // The ability to use vector initializer lists is a GNU vector extension
1777 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1778 // endian machines it works fine, however on big endian machines it
1779 // exhibits surprising behaviour:
1780 //
1781 // uint32x2_t x = {42, 64};
1782 // return vget_lane_u32(x, 0); // Will return 64.
1783 //
1784 // Because of this, explicitly call out that it is non-portable.
1785 //
1786 SemaRef.Diag(IList->getBeginLoc(),
1787 diag::warn_neon_vector_initializer_non_portable);
1788
1789 const char *typeCode;
1790 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1791
1792 if (elementType->isFloatingType())
1793 typeCode = "f";
1794 else if (elementType->isSignedIntegerType())
1795 typeCode = "s";
1796 else if (elementType->isUnsignedIntegerType())
1797 typeCode = "u";
1798 else
1799 llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "clang/lib/Sema/SemaInit.cpp"
, 1799)
;
1800
1801 SemaRef.Diag(IList->getBeginLoc(),
1802 SemaRef.Context.getTypeSize(VT) > 64
1803 ? diag::note_neon_vector_initializer_non_portable_q
1804 : diag::note_neon_vector_initializer_non_portable)
1805 << typeCode << typeSize;
1806 }
1807
1808 return;
1809 }
1810
1811 InitializedEntity ElementEntity =
1812 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1813
1814 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1815 for (unsigned i = 0; i < maxElements; ++i) {
1816 // Don't attempt to go past the end of the init list
1817 if (Index >= IList->getNumInits())
1818 break;
1819
1820 ElementEntity.setElementIndex(Index);
1821
1822 QualType IType = IList->getInit(Index)->getType();
1823 if (!IType->isVectorType()) {
1824 CheckSubElementType(ElementEntity, IList, elementType, Index,
1825 StructuredList, StructuredIndex);
1826 ++numEltsInit;
1827 } else {
1828 QualType VecType;
1829 const VectorType *IVT = IType->castAs<VectorType>();
1830 unsigned numIElts = IVT->getNumElements();
1831
1832 if (IType->isExtVectorType())
1833 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1834 else
1835 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1836 IVT->getVectorKind());
1837 CheckSubElementType(ElementEntity, IList, VecType, Index,
1838 StructuredList, StructuredIndex);
1839 numEltsInit += numIElts;
1840 }
1841 }
1842
1843 // OpenCL and HLSL require all elements to be initialized.
1844 if (numEltsInit != maxElements) {
1845 if (!VerifyOnly)
1846 SemaRef.Diag(IList->getBeginLoc(),
1847 diag::err_vector_incorrect_num_initializers)
1848 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1849 hadError = true;
1850 }
1851}
1852
1853/// Check if the type of a class element has an accessible destructor, and marks
1854/// it referenced. Returns true if we shouldn't form a reference to the
1855/// destructor.
1856///
1857/// Aggregate initialization requires a class element's destructor be
1858/// accessible per 11.6.1 [dcl.init.aggr]:
1859///
1860/// The destructor for each element of class type is potentially invoked
1861/// (15.4 [class.dtor]) from the context where the aggregate initialization
1862/// occurs.
1863static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1864 Sema &SemaRef) {
1865 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1866 if (!CXXRD)
1867 return false;
1868
1869 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1870 SemaRef.CheckDestructorAccess(Loc, Destructor,
1871 SemaRef.PDiag(diag::err_access_dtor_temp)
1872 << ElementType);
1873 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1874 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1875}
1876
1877void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1878 InitListExpr *IList, QualType &DeclType,
1879 llvm::APSInt elementIndex,
1880 bool SubobjectIsDesignatorContext,
1881 unsigned &Index,
1882 InitListExpr *StructuredList,
1883 unsigned &StructuredIndex) {
1884 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1885
1886 if (!VerifyOnly) {
1887 if (checkDestructorReference(arrayType->getElementType(),
1888 IList->getEndLoc(), SemaRef)) {
1889 hadError = true;
1890 return;
1891 }
1892 }
1893
1894 // Check for the special-case of initializing an array with a string.
1895 if (Index < IList->getNumInits()) {
1896 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1897 SIF_None) {
1898 // We place the string literal directly into the resulting
1899 // initializer list. This is the only place where the structure
1900 // of the structured initializer list doesn't match exactly,
1901 // because doing so would involve allocating one character
1902 // constant for each string.
1903 // FIXME: Should we do these checks in verify-only mode too?
1904 if (!VerifyOnly)
1905 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1906 if (StructuredList) {
1907 UpdateStructuredListElement(StructuredList, StructuredIndex,
1908 IList->getInit(Index));
1909 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1910 }
1911 ++Index;
1912 return;
1913 }
1914 }
1915 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1916 // Check for VLAs; in standard C it would be possible to check this
1917 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1918 // them in all sorts of strange places).
1919 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1920 if (!VerifyOnly) {
1921 // C2x 6.7.9p4: An entity of variable length array type shall not be
1922 // initialized except by an empty initializer.
1923 //
1924 // The C extension warnings are issued from ParseBraceInitializer() and
1925 // do not need to be issued here. However, we continue to issue an error
1926 // in the case there are initializers or we are compiling C++. We allow
1927 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1928 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1929 // FIXME: should we allow this construct in C++ when it makes sense to do
1930 // so?
1931 if (HasErr)
1932 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1933 diag::err_variable_object_no_init)
1934 << VAT->getSizeExpr()->getSourceRange();
1935 }
1936 hadError = HasErr;
1937 ++Index;
1938 ++StructuredIndex;
1939 return;
1940 }
1941
1942 // We might know the maximum number of elements in advance.
1943 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1944 elementIndex.isUnsigned());
1945 bool maxElementsKnown = false;
1946 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1947 maxElements = CAT->getSize();
1948 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1949 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1950 maxElementsKnown = true;
1951 }
1952
1953 QualType elementType = arrayType->getElementType();
1954 while (Index < IList->getNumInits()) {
1955 Expr *Init = IList->getInit(Index);
1956 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1957 // If we're not the subobject that matches up with the '{' for
1958 // the designator, we shouldn't be handling the
1959 // designator. Return immediately.
1960 if (!SubobjectIsDesignatorContext)
1961 return;
1962
1963 // Handle this designated initializer. elementIndex will be
1964 // updated to be the next array element we'll initialize.
1965 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1966 DeclType, nullptr, &elementIndex, Index,
1967 StructuredList, StructuredIndex, true,
1968 false)) {
1969 hadError = true;
1970 continue;
1971 }
1972
1973 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1974 maxElements = maxElements.extend(elementIndex.getBitWidth());
1975 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1976 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1977 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1978
1979 // If the array is of incomplete type, keep track of the number of
1980 // elements in the initializer.
1981 if (!maxElementsKnown && elementIndex > maxElements)
1982 maxElements = elementIndex;
1983
1984 continue;
1985 }
1986
1987 // If we know the maximum number of elements, and we've already
1988 // hit it, stop consuming elements in the initializer list.
1989 if (maxElementsKnown && elementIndex == maxElements)
1990 break;
1991
1992 InitializedEntity ElementEntity =
1993 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1994 Entity);
1995 // Check this element.
1996 CheckSubElementType(ElementEntity, IList, elementType, Index,
1997 StructuredList, StructuredIndex);
1998 ++elementIndex;
1999
2000 // If the array is of incomplete type, keep track of the number of
2001 // elements in the initializer.
2002 if (!maxElementsKnown && elementIndex > maxElements)
2003 maxElements = elementIndex;
2004 }
2005 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2006 // If this is an incomplete array type, the actual type needs to
2007 // be calculated here.
2008 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2009 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2010 // Sizing an array implicitly to zero is not allowed by ISO C,
2011 // but is supported by GNU.
2012 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2013 }
2014
2015 DeclType = SemaRef.Context.getConstantArrayType(
2016 elementType, maxElements, nullptr, ArrayType::Normal, 0);
2017 }
2018 if (!hadError) {
2019 // If there are any members of the array that get value-initialized, check
2020 // that is possible. That happens if we know the bound and don't have
2021 // enough elements, or if we're performing an array new with an unknown
2022 // bound.
2023 if ((maxElementsKnown && elementIndex < maxElements) ||
2024 Entity.isVariableLengthArrayNew())
2025 CheckEmptyInitializable(
2026 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
2027 IList->getEndLoc());
2028 }
2029}
2030
2031bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2032 Expr *InitExpr,
2033 FieldDecl *Field,
2034 bool TopLevelObject) {
2035 // Handle GNU flexible array initializers.
2036 unsigned FlexArrayDiag;
2037 if (isa<InitListExpr>(InitExpr) &&
2038 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2039 // Empty flexible array init always allowed as an extension
2040 FlexArrayDiag = diag::ext_flexible_array_init;
2041 } else if (!TopLevelObject) {
2042 // Disallow flexible array init on non-top-level object
2043 FlexArrayDiag = diag::err_flexible_array_init;
2044 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2045 // Disallow flexible array init on anything which is not a variable.
2046 FlexArrayDiag = diag::err_flexible_array_init;
2047 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2048 // Disallow flexible array init on local variables.
2049 FlexArrayDiag = diag::err_flexible_array_init;
2050 } else {
2051 // Allow other cases.
2052 FlexArrayDiag = diag::ext_flexible_array_init;
2053 }
2054
2055 if (!VerifyOnly) {
2056 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2057 << InitExpr->getBeginLoc();
2058 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2059 << Field;
2060 }
2061
2062 return FlexArrayDiag != diag::ext_flexible_array_init;
2063}
2064
2065void InitListChecker::CheckStructUnionTypes(
2066 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2067 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
2068 bool SubobjectIsDesignatorContext, unsigned &Index,
2069 InitListExpr *StructuredList, unsigned &StructuredIndex,
2070 bool TopLevelObject) {
2071 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
2072
2073 // If the record is invalid, some of it's members are invalid. To avoid
2074 // confusion, we forgo checking the initializer for the entire record.
2075 if (structDecl->isInvalidDecl()) {
2076 // Assume it was supposed to consume a single initializer.
2077 ++Index;
2078 hadError = true;
2079 return;
2080 }
2081
2082 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
2083 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2084
2085 if (!VerifyOnly)
2086 for (FieldDecl *FD : RD->fields()) {
2087 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2088 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2089 hadError = true;
2090 return;
2091 }
2092 }
2093
2094 // If there's a default initializer, use it.
2095 if (isa<CXXRecordDecl>(RD) &&
2096 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2097 if (!StructuredList)
2098 return;
2099 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2100 Field != FieldEnd; ++Field) {
2101 if (Field->hasInClassInitializer()) {
2102 StructuredList->setInitializedFieldInUnion(*Field);
2103 // FIXME: Actually build a CXXDefaultInitExpr?
2104 return;
2105 }
2106 }
2107 }
2108
2109 // Value-initialize the first member of the union that isn't an unnamed
2110 // bitfield.
2111 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2112 Field != FieldEnd; ++Field) {
2113 if (!Field->isUnnamedBitfield()) {
2114 CheckEmptyInitializable(
2115 InitializedEntity::InitializeMember(*Field, &Entity),
2116 IList->getEndLoc());
2117 if (StructuredList)
2118 StructuredList->setInitializedFieldInUnion(*Field);
2119 break;
2120 }
2121 }
2122 return;
2123 }
2124
2125 bool InitializedSomething = false;
2126
2127 // If we have any base classes, they are initialized prior to the fields.
2128 for (auto &Base : Bases) {
2129 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2130
2131 // Designated inits always initialize fields, so if we see one, all
2132 // remaining base classes have no explicit initializer.
2133 if (Init && isa<DesignatedInitExpr>(Init))
2134 Init = nullptr;
2135
2136 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2137 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2138 SemaRef.Context, &Base, false, &Entity);
2139 if (Init) {
2140 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2141 StructuredList, StructuredIndex);
2142 InitializedSomething = true;
2143 } else {
2144 CheckEmptyInitializable(BaseEntity, InitLoc);
2145 }
2146
2147 if (!VerifyOnly)
2148 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2149 hadError = true;
2150 return;
2151 }
2152 }
2153
2154 // If structDecl is a forward declaration, this loop won't do
2155 // anything except look at designated initializers; That's okay,
2156 // because an error should get printed out elsewhere. It might be
2157 // worthwhile to skip over the rest of the initializer, though.
2158 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2159 RecordDecl::field_iterator FieldEnd = RD->field_end();
2160 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2161 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2162 });
2163 bool CheckForMissingFields =
2164 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2165 bool HasDesignatedInit = false;
2166
2167 while (Index < IList->getNumInits()) {
2168 Expr *Init = IList->getInit(Index);
2169 SourceLocation InitLoc = Init->getBeginLoc();
2170
2171 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2172 // If we're not the subobject that matches up with the '{' for
2173 // the designator, we shouldn't be handling the
2174 // designator. Return immediately.
2175 if (!SubobjectIsDesignatorContext)
2176 return;
2177
2178 HasDesignatedInit = true;
2179
2180 // Handle this designated initializer. Field will be updated to
2181 // the next field that we'll be initializing.
2182 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2183 DeclType, &Field, nullptr, Index,
2184 StructuredList, StructuredIndex,
2185 true, TopLevelObject))
2186 hadError = true;
2187 else if (!VerifyOnly) {
2188 // Find the field named by the designated initializer.
2189 RecordDecl::field_iterator F = RD->field_begin();
2190 while (std::next(F) != Field)
2191 ++F;
2192 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2193 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2194 hadError = true;
2195 return;
2196 }
2197 }
2198
2199 InitializedSomething = true;
2200
2201 // Disable check for missing fields when designators are used.
2202 // This matches gcc behaviour.
2203 CheckForMissingFields = false;
2204 continue;
2205 }
2206
2207 // Check if this is an initializer of forms:
2208 //
2209 // struct foo f = {};
2210 // struct foo g = {0};
2211 //
2212 // These are okay for randomized structures. [C99 6.7.8p19]
2213 //
2214 // Also, if there is only one element in the structure, we allow something
2215 // like this, because it's really not randomized in the tranditional sense.
2216 //
2217 // struct foo h = {bar};
2218 auto IsZeroInitializer = [&](const Expr *I) {
2219 if (IList->getNumInits() == 1) {
2220 if (NumRecordDecls == 1)
2221 return true;
2222 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2223 return IL->getValue().isZero();
2224 }
2225 return false;
2226 };
2227
2228 // Don't allow non-designated initializers on randomized structures.
2229 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2230 if (!VerifyOnly)
2231 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2232 hadError = true;
2233 break;
2234 }
2235
2236 if (Field == FieldEnd) {
2237 // We've run out of fields. We're done.
2238 break;
2239 }
2240
2241 // We've already initialized a member of a union. We're done.
2242 if (InitializedSomething && DeclType->isUnionType())
2243 break;
2244
2245 // If we've hit the flexible array member at the end, we're done.
2246 if (Field->getType()->isIncompleteArrayType())
2247 break;
2248
2249 if (Field->isUnnamedBitfield()) {
2250 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2251 ++Field;
2252 continue;
2253 }
2254
2255 // Make sure we can use this declaration.
2256 bool InvalidUse;
2257 if (VerifyOnly)
2258 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2259 else
2260 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2261 *Field, IList->getInit(Index)->getBeginLoc());
2262 if (InvalidUse) {
2263 ++Index;
2264 ++Field;
2265 hadError = true;
2266 continue;
2267 }
2268
2269 if (!VerifyOnly) {
2270 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2271 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2272 hadError = true;
2273 return;
2274 }
2275 }
2276
2277 InitializedEntity MemberEntity =
2278 InitializedEntity::InitializeMember(*Field, &Entity);
2279 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2280 StructuredList, StructuredIndex);
2281 InitializedSomething = true;
2282
2283 if (DeclType->isUnionType() && StructuredList) {
2284 // Initialize the first field within the union.
2285 StructuredList->setInitializedFieldInUnion(*Field);
2286 }
2287
2288 ++Field;
2289 }
2290
2291 // Emit warnings for missing struct field initializers.
2292 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2293 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2294 !DeclType->isUnionType()) {
2295 // It is possible we have one or more unnamed bitfields remaining.
2296 // Find first (if any) named field and emit warning.
2297 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2298 it != end; ++it) {
2299 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2300 SemaRef.Diag(IList->getSourceRange().getEnd(),
2301 diag::warn_missing_field_initializers) << *it;
2302 break;
2303 }
2304 }
2305 }
2306
2307 // Check that any remaining fields can be value-initialized if we're not
2308 // building a structured list. (If we are, we'll check this later.)
2309 if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() &&
2310 !Field->getType()->isIncompleteArrayType()) {
2311 for (; Field != FieldEnd && !hadError; ++Field) {
2312 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2313 CheckEmptyInitializable(
2314 InitializedEntity::InitializeMember(*Field, &Entity),
2315 IList->getEndLoc());
2316 }
2317 }
2318
2319 // Check that the types of the remaining fields have accessible destructors.
2320 if (!VerifyOnly) {
2321 // If the initializer expression has a designated initializer, check the
2322 // elements for which a designated initializer is not provided too.
2323 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2324 : Field;
2325 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2326 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2327 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2328 hadError = true;
2329 return;
2330 }
2331 }
2332 }
2333
2334 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2335 Index >= IList->getNumInits())
2336 return;
2337
2338 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2339 TopLevelObject)) {
2340 hadError = true;
2341 ++Index;
2342 return;
2343 }
2344
2345 InitializedEntity MemberEntity =
2346 InitializedEntity::InitializeMember(*Field, &Entity);
2347
2348 if (isa<InitListExpr>(IList->getInit(Index)))
2349 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2350 StructuredList, StructuredIndex);
2351 else
2352 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2353 StructuredList, StructuredIndex);
2354}
2355
2356/// Expand a field designator that refers to a member of an
2357/// anonymous struct or union into a series of field designators that
2358/// refers to the field within the appropriate subobject.
2359///
2360static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2361 DesignatedInitExpr *DIE,
2362 unsigned DesigIdx,
2363 IndirectFieldDecl *IndirectField) {
2364 typedef DesignatedInitExpr::Designator Designator;
2365
2366 // Build the replacement designators.
2367 SmallVector<Designator, 4> Replacements;
2368 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2369 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2370 if (PI + 1 == PE)
2371 Replacements.push_back(Designator::CreateFieldDesignator(
2372 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2373 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2374 else
2375 Replacements.push_back(Designator::CreateFieldDesignator(
2376 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2377 assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(*PI)", "clang/lib/Sema/SemaInit.cpp"
, 2377, __extension__ __PRETTY_FUNCTION__))
;
2378 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2379 }
2380
2381 // Expand the current designator into the set of replacement
2382 // designators, so we have a full subobject path down to where the
2383 // member of the anonymous struct/union is actually stored.
2384 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2385 &Replacements[0] + Replacements.size());
2386}
2387
2388static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2389 DesignatedInitExpr *DIE) {
2390 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2391 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2392 for (unsigned I = 0; I < NumIndexExprs; ++I)
2393 IndexExprs[I] = DIE->getSubExpr(I + 1);
2394 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2395 IndexExprs,
2396 DIE->getEqualOrColonLoc(),
2397 DIE->usesGNUSyntax(), DIE->getInit());
2398}
2399
2400namespace {
2401
2402// Callback to only accept typo corrections that are for field members of
2403// the given struct or union.
2404class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2405 public:
2406 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2407 : Record(RD) {}
2408
2409 bool ValidateCandidate(const TypoCorrection &candidate) override {
2410 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2411 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2412 }
2413
2414 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2415 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2416 }
2417
2418 private:
2419 RecordDecl *Record;
2420};
2421
2422} // end anonymous namespace
2423
2424/// Check the well-formedness of a C99 designated initializer.
2425///
2426/// Determines whether the designated initializer @p DIE, which
2427/// resides at the given @p Index within the initializer list @p
2428/// IList, is well-formed for a current object of type @p DeclType
2429/// (C99 6.7.8). The actual subobject that this designator refers to
2430/// within the current subobject is returned in either
2431/// @p NextField or @p NextElementIndex (whichever is appropriate).
2432///
2433/// @param IList The initializer list in which this designated
2434/// initializer occurs.
2435///
2436/// @param DIE The designated initializer expression.
2437///
2438/// @param DesigIdx The index of the current designator.
2439///
2440/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2441/// into which the designation in @p DIE should refer.
2442///
2443/// @param NextField If non-NULL and the first designator in @p DIE is
2444/// a field, this will be set to the field declaration corresponding
2445/// to the field named by the designator. On input, this is expected to be
2446/// the next field that would be initialized in the absence of designation,
2447/// if the complete object being initialized is a struct.
2448///
2449/// @param NextElementIndex If non-NULL and the first designator in @p
2450/// DIE is an array designator or GNU array-range designator, this
2451/// will be set to the last index initialized by this designator.
2452///
2453/// @param Index Index into @p IList where the designated initializer
2454/// @p DIE occurs.
2455///
2456/// @param StructuredList The initializer list expression that
2457/// describes all of the subobject initializers in the order they'll
2458/// actually be initialized.
2459///
2460/// @returns true if there was an error, false otherwise.
2461bool
2462InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2463 InitListExpr *IList,
2464 DesignatedInitExpr *DIE,
2465 unsigned DesigIdx,
2466 QualType &CurrentObjectType,
2467 RecordDecl::field_iterator *NextField,
2468 llvm::APSInt *NextElementIndex,
2469 unsigned &Index,
2470 InitListExpr *StructuredList,
2471 unsigned &StructuredIndex,
2472 bool FinishSubobjectInit,
2473 bool TopLevelObject) {
2474 if (DesigIdx == DIE->size()) {
2475 // C++20 designated initialization can result in direct-list-initialization
2476 // of the designated subobject. This is the only way that we can end up
2477 // performing direct initialization as part of aggregate initialization, so
2478 // it needs special handling.
2479 if (DIE->isDirectInit()) {
2480 Expr *Init = DIE->getInit();
2481 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"designator result in direct non-list initialization?") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\""
, "clang/lib/Sema/SemaInit.cpp", 2482, __extension__ __PRETTY_FUNCTION__
))
2482 "designator result in direct non-list initialization?")(static_cast <bool> (isa<InitListExpr>(Init) &&
"designator result in direct non-list initialization?") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"designator result in direct non-list initialization?\""
, "clang/lib/Sema/SemaInit.cpp", 2482, __extension__ __PRETTY_FUNCTION__
))
;
2483 InitializationKind Kind = InitializationKind::CreateDirectList(
2484 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2485 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2486 /*TopLevelOfInitList*/ true);
2487 if (StructuredList) {
2488 ExprResult Result = VerifyOnly
2489 ? getDummyInit()
2490 : Seq.Perform(SemaRef, Entity, Kind, Init);
2491 UpdateStructuredListElement(StructuredList, StructuredIndex,
2492 Result.get());
2493 }
2494 ++Index;
2495 return !Seq;
2496 }
2497
2498 // Check the actual initialization for the designated object type.
2499 bool prevHadError = hadError;
2500
2501 // Temporarily remove the designator expression from the
2502 // initializer list that the child calls see, so that we don't try
2503 // to re-process the designator.
2504 unsigned OldIndex = Index;
2505 IList->setInit(OldIndex, DIE->getInit());
2506
2507 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2508 StructuredIndex, /*DirectlyDesignated=*/true);
2509
2510 // Restore the designated initializer expression in the syntactic
2511 // form of the initializer list.
2512 if (IList->getInit(OldIndex) != DIE->getInit())
2513 DIE->setInit(IList->getInit(OldIndex));
2514 IList->setInit(OldIndex, DIE);
2515
2516 return hadError && !prevHadError;
2517 }
2518
2519 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2520 bool IsFirstDesignator = (DesigIdx == 0);
2521 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2522 // Determine the structural initializer list that corresponds to the
2523 // current subobject.
2524 if (IsFirstDesignator)
2525 StructuredList = FullyStructuredList;
2526 else {
2527 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2528 StructuredList->getInit(StructuredIndex) : nullptr;
2529 if (!ExistingInit && StructuredList->hasArrayFiller())
2530 ExistingInit = StructuredList->getArrayFiller();
2531
2532 if (!ExistingInit)
2533 StructuredList = getStructuredSubobjectInit(
2534 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2535 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2536 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2537 StructuredList = Result;
2538 else {
2539 // We are creating an initializer list that initializes the
2540 // subobjects of the current object, but there was already an
2541 // initialization that completely initialized the current
2542 // subobject, e.g., by a compound literal:
2543 //
2544 // struct X { int a, b; };
2545 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2546 //
2547 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2548 // designated initializer re-initializes only its current object
2549 // subobject [0].b.
2550 diagnoseInitOverride(ExistingInit,
2551 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2552 /*UnionOverride=*/false,
2553 /*FullyOverwritten=*/false);
2554
2555 if (!VerifyOnly) {
2556 if (DesignatedInitUpdateExpr *E =
2557 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2558 StructuredList = E->getUpdater();
2559 else {
2560 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2561 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2562 ExistingInit, DIE->getEndLoc());
2563 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2564 StructuredList = DIUE->getUpdater();
2565 }
2566 } else {
2567 // We don't need to track the structured representation of a
2568 // designated init update of an already-fully-initialized object in
2569 // verify-only mode. The only reason we would need the structure is
2570 // to determine where the uninitialized "holes" are, and in this
2571 // case, we know there aren't any and we can't introduce any.
2572 StructuredList = nullptr;
2573 }
2574 }
2575 }
2576 }
2577
2578 if (D->isFieldDesignator()) {
2579 // C99 6.7.8p7:
2580 //
2581 // If a designator has the form
2582 //
2583 // . identifier
2584 //
2585 // then the current object (defined below) shall have
2586 // structure or union type and the identifier shall be the
2587 // name of a member of that type.
2588 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2589 if (!RT) {
2590 SourceLocation Loc = D->getDotLoc();
2591 if (Loc.isInvalid())
2592 Loc = D->getFieldLoc();
2593 if (!VerifyOnly)
2594 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2595 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2596 ++Index;
2597 return true;
2598 }
2599
2600 FieldDecl *KnownField = D->getFieldDecl();
2601 if (!KnownField) {
2602 const IdentifierInfo *FieldName = D->getFieldName();
2603 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2604 for (NamedDecl *ND : Lookup) {
2605 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2606 KnownField = FD;
2607 break;
2608 }
2609 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2610 // In verify mode, don't modify the original.
2611 if (VerifyOnly)
2612 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2613 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2614 D = DIE->getDesignator(DesigIdx);
2615 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2616 break;
2617 }
2618 }
2619 if (!KnownField) {
2620 if (VerifyOnly) {
2621 ++Index;
2622 return true; // No typo correction when just trying this out.
2623 }
2624
2625 // Name lookup found something, but it wasn't a field.
2626 if (!Lookup.empty()) {
2627 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2628 << FieldName;
2629 SemaRef.Diag(Lookup.front()->getLocation(),
2630 diag::note_field_designator_found);
2631 ++Index;
2632 return true;
2633 }
2634
2635 // Name lookup didn't find anything.
2636 // Determine whether this was a typo for another field name.
2637 FieldInitializerValidatorCCC CCC(RT->getDecl());
2638 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2639 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2640 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2641 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2642 SemaRef.diagnoseTypo(
2643 Corrected,
2644 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2645 << FieldName << CurrentObjectType);
2646 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2647 hadError = true;
2648 } else {
2649 // Typo correction didn't find anything.
2650 SourceLocation Loc = D->getFieldLoc();
2651
2652 // The loc can be invalid with a "null" designator (i.e. an anonymous
2653 // union/struct). Do our best to approximate the location.
2654 if (Loc.isInvalid())
2655 Loc = IList->getBeginLoc();
2656
2657 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2658 << FieldName << CurrentObjectType << DIE->getSourceRange();
2659 ++Index;
2660 return true;
2661 }
2662 }
2663 }
2664
2665 unsigned NumBases = 0;
2666 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2667 NumBases = CXXRD->getNumBases();
2668
2669 unsigned FieldIndex = NumBases;
2670
2671 for (auto *FI : RT->getDecl()->fields()) {
2672 if (FI->isUnnamedBitfield())
2673 continue;
2674 if (declaresSameEntity(KnownField, FI)) {
2675 KnownField = FI;
2676 break;
2677 }
2678 ++FieldIndex;
2679 }
2680
2681 RecordDecl::field_iterator Field =
2682 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2683
2684 // All of the fields of a union are located at the same place in
2685 // the initializer list.
2686 if (RT->getDecl()->isUnion()) {
2687 FieldIndex = 0;
2688 if (StructuredList) {
2689 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2690 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2691 assert(StructuredList->getNumInits() == 1(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "clang/lib/Sema/SemaInit.cpp", 2692, __extension__ __PRETTY_FUNCTION__
))
2692 && "A union should never have more than one initializer!")(static_cast <bool> (StructuredList->getNumInits() ==
1 && "A union should never have more than one initializer!"
) ? void (0) : __assert_fail ("StructuredList->getNumInits() == 1 && \"A union should never have more than one initializer!\""
, "clang/lib/Sema/SemaInit.cpp", 2692, __extension__ __PRETTY_FUNCTION__
))
;
2693
2694 Expr *ExistingInit = StructuredList->getInit(0);
2695 if (ExistingInit) {
2696 // We're about to throw away an initializer, emit warning.
2697 diagnoseInitOverride(
2698 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2699 /*UnionOverride=*/true,
2700 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2701 : true);
2702 }
2703
2704 // remove existing initializer
2705 StructuredList->resizeInits(SemaRef.Context, 0);
2706 StructuredList->setInitializedFieldInUnion(nullptr);
2707 }
2708
2709 StructuredList->setInitializedFieldInUnion(*Field);
2710 }
2711 }
2712
2713 // Make sure we can use this declaration.
2714 bool InvalidUse;
2715 if (VerifyOnly)
2716 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2717 else
2718 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2719 if (InvalidUse) {
2720 ++Index;
2721 return true;
2722 }
2723
2724 // C++20 [dcl.init.list]p3:
2725 // The ordered identifiers in the designators of the designated-
2726 // initializer-list shall form a subsequence of the ordered identifiers
2727 // in the direct non-static data members of T.
2728 //
2729 // Note that this is not a condition on forming the aggregate
2730 // initialization, only on actually performing initialization,
2731 // so it is not checked in VerifyOnly mode.
2732 //
2733 // FIXME: This is the only reordering diagnostic we produce, and it only
2734 // catches cases where we have a top-level field designator that jumps
2735 // backwards. This is the only such case that is reachable in an
2736 // otherwise-valid C++20 program, so is the only case that's required for
2737 // conformance, but for consistency, we should diagnose all the other
2738 // cases where a designator takes us backwards too.
2739 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2740 NextField &&
2741 (*NextField == RT->getDecl()->field_end() ||
2742 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2743 // Find the field that we just initialized.
2744 FieldDecl *PrevField = nullptr;
2745 for (auto FI = RT->getDecl()->field_begin();
2746 FI != RT->getDecl()->field_end(); ++FI) {
2747 if (FI->isUnnamedBitfield())
2748 continue;
2749 if (*NextField != RT->getDecl()->field_end() &&
2750 declaresSameEntity(*FI, **NextField))
2751 break;
2752 PrevField = *FI;
2753 }
2754
2755 if (PrevField &&
2756 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2757 SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
2758 << KnownField << PrevField << DIE->getSourceRange();
2759
2760 unsigned OldIndex = NumBases + PrevField->getFieldIndex();
2761 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2762 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2763 SemaRef.Diag(PrevInit->getBeginLoc(),
2764 diag::note_previous_field_init)
2765 << PrevField << PrevInit->getSourceRange();
2766 }
2767 }
2768 }
2769 }
2770
2771
2772 // Update the designator with the field declaration.
2773 if (!VerifyOnly)
2774 D->setFieldDecl(*Field);
2775
2776 // Make sure that our non-designated initializer list has space
2777 // for a subobject corresponding to this field.
2778 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2779 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2780
2781 // This designator names a flexible array member.
2782 if (Field->getType()->isIncompleteArrayType()) {
2783 bool Invalid = false;
2784 if ((DesigIdx + 1) != DIE->size()) {
2785 // We can't designate an object within the flexible array
2786 // member (because GCC doesn't allow it).
2787 if (!VerifyOnly) {
2788 DesignatedInitExpr::Designator *NextD
2789 = DIE->getDesignator(DesigIdx + 1);
2790 SemaRef.Diag(NextD->getBeginLoc(),
2791 diag::err_designator_into_flexible_array_member)
2792 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2793 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2794 << *Field;
2795 }
2796 Invalid = true;
2797 }
2798
2799 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2800 !isa<StringLiteral>(DIE->getInit())) {
2801 // The initializer is not an initializer list.
2802 if (!VerifyOnly) {
2803 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2804 diag::err_flexible_array_init_needs_braces)
2805 << DIE->getInit()->getSourceRange();
2806 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2807 << *Field;
2808 }
2809 Invalid = true;
2810 }
2811
2812 // Check GNU flexible array initializer.
2813 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2814 TopLevelObject))
2815 Invalid = true;
2816
2817 if (Invalid) {
2818 ++Index;
2819 return true;
2820 }
2821
2822 // Initialize the array.
2823 bool prevHadError = hadError;
2824 unsigned newStructuredIndex = FieldIndex;
2825 unsigned OldIndex = Index;
2826 IList->setInit(Index, DIE->getInit());
2827
2828 InitializedEntity MemberEntity =
2829 InitializedEntity::InitializeMember(*Field, &Entity);
2830 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2831 StructuredList, newStructuredIndex);
2832
2833 IList->setInit(OldIndex, DIE);
2834 if (hadError && !prevHadError) {
2835 ++Field;
2836 ++FieldIndex;
2837 if (NextField)
2838 *NextField = Field;
2839 StructuredIndex = FieldIndex;
2840 return true;
2841 }
2842 } else {
2843 // Recurse to check later designated subobjects.
2844 QualType FieldType = Field->getType();
2845 unsigned newStructuredIndex = FieldIndex;
2846
2847 InitializedEntity MemberEntity =
2848 InitializedEntity::InitializeMember(*Field, &Entity);
2849 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2850 FieldType, nullptr, nullptr, Index,
2851 StructuredList, newStructuredIndex,
2852 FinishSubobjectInit, false))
2853 return true;
2854 }
2855
2856 // Find the position of the next field to be initialized in this
2857 // subobject.
2858 ++Field;
2859 ++FieldIndex;
2860
2861 // If this the first designator, our caller will continue checking
2862 // the rest of this struct/class/union subobject.
2863 if (IsFirstDesignator) {
2864 if (NextField)
2865 *NextField = Field;
2866 StructuredIndex = FieldIndex;
2867 return false;
2868 }
2869
2870 if (!FinishSubobjectInit)
2871 return false;
2872
2873 // We've already initialized something in the union; we're done.
2874 if (RT->getDecl()->isUnion())
2875 return hadError;
2876
2877 // Check the remaining fields within this class/struct/union subobject.
2878 bool prevHadError = hadError;
2879
2880 auto NoBases =
2881 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2882 CXXRecordDecl::base_class_iterator());
2883 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2884 false, Index, StructuredList, FieldIndex);
2885 return hadError && !prevHadError;
2886 }
2887
2888 // C99 6.7.8p6:
2889 //
2890 // If a designator has the form
2891 //
2892 // [ constant-expression ]
2893 //
2894 // then the current object (defined below) shall have array
2895 // type and the expression shall be an integer constant
2896 // expression. If the array is of unknown size, any
2897 // nonnegative value is valid.
2898 //
2899 // Additionally, cope with the GNU extension that permits
2900 // designators of the form
2901 //
2902 // [ constant-expression ... constant-expression ]
2903 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2904 if (!AT) {
2905 if (!VerifyOnly)
2906 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2907 << CurrentObjectType;
2908 ++Index;
2909 return true;
2910 }
2911
2912 Expr *IndexExpr = nullptr;
2913 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2914 if (D->isArrayDesignator()) {
2915 IndexExpr = DIE->getArrayIndex(*D);
2916 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2917 DesignatedEndIndex = DesignatedStartIndex;
2918 } else {
2919 assert(D->isArrayRangeDesignator() && "Need array-range designator")(static_cast <bool> (D->isArrayRangeDesignator() &&
"Need array-range designator") ? void (0) : __assert_fail ("D->isArrayRangeDesignator() && \"Need array-range designator\""
, "clang/lib/Sema/SemaInit.cpp", 2919, __extension__ __PRETTY_FUNCTION__
))
;
2920
2921 DesignatedStartIndex =
2922 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2923 DesignatedEndIndex =
2924 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2925 IndexExpr = DIE->getArrayRangeEnd(*D);
2926
2927 // Codegen can't handle evaluating array range designators that have side
2928 // effects, because we replicate the AST value for each initialized element.
2929 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2930 // elements with something that has a side effect, so codegen can emit an
2931 // "error unsupported" error instead of miscompiling the app.
2932 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2933 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2934 FullyStructuredList->sawArrayRangeDesignator();
2935 }
2936
2937 if (isa<ConstantArrayType>(AT)) {
2938 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2939 DesignatedStartIndex
2940 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2941 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2942 DesignatedEndIndex
2943 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2944 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2945 if (DesignatedEndIndex >= MaxElements) {
2946 if (!VerifyOnly)
2947 SemaRef.Diag(IndexExpr->getBeginLoc(),
2948 diag::err_array_designator_too_large)
2949 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
2950 << IndexExpr->getSourceRange();
2951 ++Index;
2952 return true;
2953 }
2954 } else {
2955 unsigned DesignatedIndexBitWidth =
2956 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2957 DesignatedStartIndex =
2958 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2959 DesignatedEndIndex =
2960 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2961 DesignatedStartIndex.setIsUnsigned(true);
2962 DesignatedEndIndex.setIsUnsigned(true);
2963 }
2964
2965 bool IsStringLiteralInitUpdate =
2966 StructuredList && StructuredList->isStringLiteralInit();
2967 if (IsStringLiteralInitUpdate && VerifyOnly) {
2968 // We're just verifying an update to a string literal init. We don't need
2969 // to split the string up into individual characters to do that.
2970 StructuredList = nullptr;
2971 } else if (IsStringLiteralInitUpdate) {
2972 // We're modifying a string literal init; we have to decompose the string
2973 // so we can modify the individual characters.
2974 ASTContext &Context = SemaRef.Context;
2975 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
2976
2977 // Compute the character type
2978 QualType CharTy = AT->getElementType();
2979
2980 // Compute the type of the integer literals.
2981 QualType PromotedCharTy = CharTy;
2982 if (Context.isPromotableIntegerType(CharTy))
2983 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2984 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2985
2986 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2987 // Get the length of the string.
2988 uint64_t StrLen = SL->getLength();
2989 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2990 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2991 StructuredList->resizeInits(Context, StrLen);
2992
2993 // Build a literal for each character in the string, and put them into
2994 // the init list.
2995 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2996 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2997 Expr *Init = new (Context) IntegerLiteral(
2998 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2999 if (CharTy != PromotedCharTy)
3000 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3001 Init, nullptr, VK_PRValue,
3002 FPOptionsOverride());
3003 StructuredList->updateInit(Context, i, Init);
3004 }
3005 } else {
3006 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3007 std::string Str;
3008 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3009
3010 // Get the length of the string.
3011 uint64_t StrLen = Str.size();
3012 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3013 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3014 StructuredList->resizeInits(Context, StrLen);
3015
3016 // Build a literal for each character in the string, and put them into
3017 // the init list.
3018 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3019 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3020 Expr *Init = new (Context) IntegerLiteral(
3021 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3022 if (CharTy != PromotedCharTy)
3023 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3024 Init, nullptr, VK_PRValue,
3025 FPOptionsOverride());
3026 StructuredList->updateInit(Context, i, Init);
3027 }
3028 }
3029 }
3030
3031 // Make sure that our non-designated initializer list has space
3032 // for a subobject corresponding to this array element.
3033 if (StructuredList &&
3034 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3035 StructuredList->resizeInits(SemaRef.Context,
3036 DesignatedEndIndex.getZExtValue() + 1);
3037
3038 // Repeatedly perform subobject initializations in the range
3039 // [DesignatedStartIndex, DesignatedEndIndex].
3040
3041 // Move to the next designator
3042 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3043 unsigned OldIndex = Index;
3044
3045 InitializedEntity ElementEntity =
3046 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3047
3048 while (DesignatedStartIndex <= DesignatedEndIndex) {
3049 // Recurse to check later designated subobjects.
3050 QualType ElementType = AT->getElementType();
3051 Index = OldIndex;
3052
3053 ElementEntity.setElementIndex(ElementIndex);
3054 if (CheckDesignatedInitializer(
3055 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3056 nullptr, Index, StructuredList, ElementIndex,
3057 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3058 false))
3059 return true;
3060
3061 // Move to the next index in the array that we'll be initializing.
3062 ++DesignatedStartIndex;
3063 ElementIndex = DesignatedStartIndex.getZExtValue();
3064 }
3065
3066 // If this the first designator, our caller will continue checking
3067 // the rest of this array subobject.
3068 if (IsFirstDesignator) {
3069 if (NextElementIndex)
3070 *NextElementIndex = DesignatedStartIndex;
3071 StructuredIndex = ElementIndex;
3072 return false;
3073 }
3074
3075 if (!FinishSubobjectInit)
3076 return false;
3077
3078 // Check the remaining elements within this array subobject.
3079 bool prevHadError = hadError;
3080 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3081 /*SubobjectIsDesignatorContext=*/false, Index,
3082 StructuredList, ElementIndex);
3083 return hadError && !prevHadError;
3084}
3085
3086// Get the structured initializer list for a subobject of type
3087// @p CurrentObjectType.
3088InitListExpr *
3089InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3090 QualType CurrentObjectType,
3091 InitListExpr *StructuredList,
3092 unsigned StructuredIndex,
3093 SourceRange InitRange,
3094 bool IsFullyOverwritten) {
3095 if (!StructuredList)
3096 return nullptr;
3097
3098 Expr *ExistingInit = nullptr;
3099 if (StructuredIndex < StructuredList->getNumInits())
3100 ExistingInit = StructuredList->getInit(StructuredIndex);
3101
3102 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3103 // There might have already been initializers for subobjects of the current
3104 // object, but a subsequent initializer list will overwrite the entirety
3105 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3106 //
3107 // struct P { char x[6]; };
3108 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3109 //
3110 // The first designated initializer is ignored, and l.x is just "f".
3111 if (!IsFullyOverwritten)
3112 return Result;
3113
3114 if (ExistingInit) {
3115 // We are creating an initializer list that initializes the
3116 // subobjects of the current object, but there was already an
3117 // initialization that completely initialized the current
3118 // subobject:
3119 //
3120 // struct X { int a, b; };
3121 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3122 //
3123 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3124 // designated initializer overwrites the [0].b initializer
3125 // from the prior initialization.
3126 //
3127 // When the existing initializer is an expression rather than an
3128 // initializer list, we cannot decompose and update it in this way.
3129 // For example:
3130 //
3131 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3132 //
3133 // This case is handled by CheckDesignatedInitializer.
3134 diagnoseInitOverride(ExistingInit, InitRange);
3135 }
3136
3137 unsigned ExpectedNumInits = 0;
3138 if (Index < IList->getNumInits()) {
3139 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3140 ExpectedNumInits = Init->getNumInits();
3141 else
3142 ExpectedNumInits = IList->getNumInits() - Index;
3143 }
3144
3145 InitListExpr *Result =
3146 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3147
3148 // Link this new initializer list into the structured initializer
3149 // lists.
3150 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3151 return Result;
3152}
3153
3154InitListExpr *
3155InitListChecker::createInitListExpr(QualType CurrentObjectType,
3156 SourceRange InitRange,
3157 unsigned ExpectedNumInits) {
3158 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3159 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3160
3161 QualType ResultType = CurrentObjectType;
3162 if (!ResultType->isArrayType())
3163 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3164 Result->setType(ResultType);
3165
3166 // Pre-allocate storage for the structured initializer list.
3167 unsigned NumElements = 0;
3168
3169 if (const ArrayType *AType
3170 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3171 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3172 NumElements = CAType->getSize().getZExtValue();
3173 // Simple heuristic so that we don't allocate a very large
3174 // initializer with many empty entries at the end.
3175 if (NumElements > ExpectedNumInits)
3176 NumElements = 0;
3177 }
3178 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3179 NumElements = VType->getNumElements();
3180 } else if (CurrentObjectType->isRecordType()) {
3181 NumElements = numStructUnionElements(CurrentObjectType);
3182 }
3183
3184 Result->reserveInits(SemaRef.Context, NumElements);
3185
3186 return Result;
3187}
3188
3189/// Update the initializer at index @p StructuredIndex within the
3190/// structured initializer list to the value @p expr.
3191void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3192 unsigned &StructuredIndex,
3193 Expr *expr) {
3194 // No structured initializer list to update
3195 if (!StructuredList)
3196 return;
3197
3198 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3199 StructuredIndex, expr)) {
3200 // This initializer overwrites a previous initializer.
3201 // No need to diagnose when `expr` is nullptr because a more relevant
3202 // diagnostic has already been issued and this diagnostic is potentially
3203 // noise.
3204 if (expr)
3205 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3206 }
3207
3208 ++StructuredIndex;
3209}
3210
3211/// Determine whether we can perform aggregate initialization for the purposes
3212/// of overload resolution.
3213bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3214 const InitializedEntity &Entity, InitListExpr *From) {
3215 QualType Type = Entity.getType();
3216 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3217 /*TreatUnavailableAsInvalid=*/false,
3218 /*InOverloadResolution=*/true);
3219 return !Check.HadError();
3220}
3221
3222/// Check that the given Index expression is a valid array designator
3223/// value. This is essentially just a wrapper around
3224/// VerifyIntegerConstantExpression that also checks for negative values
3225/// and produces a reasonable diagnostic if there is a
3226/// failure. Returns the index expression, possibly with an implicit cast
3227/// added, on success. If everything went okay, Value will receive the
3228/// value of the constant expression.
3229static ExprResult
3230CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3231 SourceLocation Loc = Index->getBeginLoc();
3232
3233 // Make sure this is an integer constant expression.
3234 ExprResult Result =
3235 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3236 if (Result.isInvalid())
3237 return Result;
3238
3239 if (Value.isSigned() && Value.isNegative())
3240 return S.Diag(Loc, diag::err_array_designator_negative)
3241 << toString(Value, 10) << Index->getSourceRange();
3242
3243 Value.setIsUnsigned(true);
3244 return Result;
3245}
3246
3247ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3248 SourceLocation EqualOrColonLoc,
3249 bool GNUSyntax,
3250 ExprResult Init) {
3251 typedef DesignatedInitExpr::Designator ASTDesignator;
3252
3253 bool Invalid = false;
3254 SmallVector<ASTDesignator, 32> Designators;
3255 SmallVector<Expr *, 32> InitExpressions;
3256
3257 // Build designators and check array designator expressions.
3258 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3259 const Designator &D = Desig.getDesignator(Idx);
3260
3261 if (D.isFieldDesignator()) {
3262 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3263 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3264 } else if (D.isArrayDesignator()) {
3265 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3266 llvm::APSInt IndexValue;
3267 if (!Index->isTypeDependent() && !Index->isValueDependent())
3268 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3269 if (!Index)
3270 Invalid = true;
3271 else {
3272 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3273 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3274 InitExpressions.push_back(Index);
3275 }
3276 } else if (D.isArrayRangeDesignator()) {
3277 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3278 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3279 llvm::APSInt StartValue;
3280 llvm::APSInt EndValue;
3281 bool StartDependent = StartIndex->isTypeDependent() ||
3282 StartIndex->isValueDependent();
3283 bool EndDependent = EndIndex->isTypeDependent() ||
3284 EndIndex->isValueDependent();
3285 if (!StartDependent)
3286 StartIndex =
3287 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3288 if (!EndDependent)
3289 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3290
3291 if (!StartIndex || !EndIndex)
3292 Invalid = true;
3293 else {
3294 // Make sure we're comparing values with the same bit width.
3295 if (StartDependent || EndDependent) {
3296 // Nothing to compute.
3297 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3298 EndValue = EndValue.extend(StartValue.getBitWidth());
3299 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3300 StartValue = StartValue.extend(EndValue.getBitWidth());
3301
3302 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3303 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3304 << toString(StartValue, 10) << toString(EndValue, 10)
3305 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3306 Invalid = true;
3307 } else {
3308 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3309 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3310 D.getRBracketLoc()));
3311 InitExpressions.push_back(StartIndex);
3312 InitExpressions.push_back(EndIndex);
3313 }
3314 }
3315 }
3316 }
3317
3318 if (Invalid || Init.isInvalid())
3319 return ExprError();
3320
3321 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3322 EqualOrColonLoc, GNUSyntax,
3323 Init.getAs<Expr>());
3324}
3325
3326//===----------------------------------------------------------------------===//
3327// Initialization entity
3328//===----------------------------------------------------------------------===//
3329
3330InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3331 const InitializedEntity &Parent)
3332 : Parent(&Parent), Index(Index)
3333{
3334 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3335 Kind = EK_ArrayElement;
3336 Type = AT->getElementType();
3337 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3338 Kind = EK_VectorElement;
3339 Type = VT->getElementType();
3340 } else {
3341 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3342 assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ?
void (0) : __assert_fail ("CT && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 3342, __extension__ __PRETTY_FUNCTION__
))
;
3343 Kind = EK_ComplexElement;
3344 Type = CT->getElementType();
3345 }
3346}
3347
3348InitializedEntity
3349InitializedEntity::InitializeBase(ASTContext &Context,
3350 const CXXBaseSpecifier *Base,
3351 bool IsInheritedVirtualBase,
3352 const InitializedEntity *Parent) {
3353 InitializedEntity Result;
3354 Result.Kind = EK_Base;
3355 Result.Parent = Parent;
3356 Result.Base = {Base, IsInheritedVirtualBase};
3357 Result.Type = Base->getType();
3358 return Result;
3359}
3360
3361DeclarationName InitializedEntity::getName() const {
3362 switch (getKind()) {
3363 case EK_Parameter:
3364 case EK_Parameter_CF_Audited: {
3365 ParmVarDecl *D = Parameter.getPointer();
3366 return (D ? D->getDeclName() : DeclarationName());
3367 }
3368
3369 case EK_Variable:
3370 case EK_Member:
3371 case EK_ParenAggInitMember:
3372 case EK_Binding:
3373 case EK_TemplateParameter:
3374 return Variable.VariableOrMember->getDeclName();
3375
3376 case EK_LambdaCapture:
3377 return DeclarationName(Capture.VarID);
3378
3379 case EK_Result:
3380 case EK_StmtExprResult:
3381 case EK_Exception:
3382 case EK_New:
3383 case EK_Temporary:
3384 case EK_Base:
3385 case EK_Delegating:
3386 case EK_ArrayElement:
3387 case EK_VectorElement:
3388 case EK_ComplexElement:
3389 case EK_BlockElement:
3390 case EK_LambdaToBlockConversionBlockElement:
3391 case EK_CompoundLiteralInit:
3392 case EK_RelatedResult:
3393 return DeclarationName();
3394 }
3395
3396 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3396)
;
3397}
3398
3399ValueDecl *InitializedEntity::getDecl() const {
3400 switch (getKind()) {
3401 case EK_Variable:
3402 case EK_Member:
3403 case EK_ParenAggInitMember:
3404 case EK_Binding:
3405 case EK_TemplateParameter:
3406 return Variable.VariableOrMember;
3407
3408 case EK_Parameter:
3409 case EK_Parameter_CF_Audited:
3410 return Parameter.getPointer();
3411
3412 case EK_Result:
3413 case EK_StmtExprResult:
3414 case EK_Exception:
3415 case EK_New:
3416 case EK_Temporary:
3417 case EK_Base:
3418 case EK_Delegating:
3419 case EK_ArrayElement:
3420 case EK_VectorElement:
3421 case EK_ComplexElement:
3422 case EK_BlockElement:
3423 case EK_LambdaToBlockConversionBlockElement:
3424 case EK_LambdaCapture:
3425 case EK_CompoundLiteralInit:
3426 case EK_RelatedResult:
3427 return nullptr;
3428 }
3429
3430 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3430)
;
3431}
3432
3433bool InitializedEntity::allowsNRVO() const {
3434 switch (getKind()) {
3435 case EK_Result:
3436 case EK_Exception:
3437 return LocAndNRVO.NRVO;
3438
3439 case EK_StmtExprResult:
3440 case EK_Variable:
3441 case EK_Parameter:
3442 case EK_Parameter_CF_Audited:
3443 case EK_TemplateParameter:
3444 case EK_Member:
3445 case EK_ParenAggInitMember:
3446 case EK_Binding:
3447 case EK_New:
3448 case EK_Temporary:
3449 case EK_CompoundLiteralInit:
3450 case EK_Base:
3451 case EK_Delegating:
3452 case EK_ArrayElement:
3453 case EK_VectorElement:
3454 case EK_ComplexElement:
3455 case EK_BlockElement:
3456 case EK_LambdaToBlockConversionBlockElement:
3457 case EK_LambdaCapture:
3458 case EK_RelatedResult:
3459 break;
3460 }
3461
3462 return false;
3463}
3464
3465unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3466 assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail
("getParent() != this", "clang/lib/Sema/SemaInit.cpp", 3466,
__extension__ __PRETTY_FUNCTION__))
;
3467 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3468 for (unsigned I = 0; I != Depth; ++I)
3469 OS << "`-";
3470
3471 switch (getKind()) {
3472 case EK_Variable: OS << "Variable"; break;
3473 case EK_Parameter: OS << "Parameter"; break;
3474 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3475 break;
3476 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3477 case EK_Result: OS << "Result"; break;
3478 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3479 case EK_Exception: OS << "Exception"; break;
3480 case EK_Member:
3481 case EK_ParenAggInitMember:
3482 OS << "Member";
3483 break;
3484 case EK_Binding: OS << "Binding"; break;
3485 case EK_New: OS << "New"; break;
3486 case EK_Temporary: OS << "Temporary"; break;
3487 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3488 case EK_RelatedResult: OS << "RelatedResult"; break;
3489 case EK_Base: OS << "Base"; break;
3490 case EK_Delegating: OS << "Delegating"; break;
3491 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3492 case EK_VectorElement: OS << "VectorElement " << Index; break;
3493 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3494 case EK_BlockElement: OS << "Block"; break;
3495 case EK_LambdaToBlockConversionBlockElement:
3496 OS << "Block (lambda)";
3497 break;
3498 case EK_LambdaCapture:
3499 OS << "LambdaCapture ";
3500 OS << DeclarationName(Capture.VarID);
3501 break;
3502 }
3503
3504 if (auto *D = getDecl()) {
3505 OS << " ";
3506 D->printQualifiedName(OS);
3507 }
3508
3509 OS << " '" << getType() << "'\n";
3510
3511 return Depth + 1;
3512}
3513
3514LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const {
3515 dumpImpl(llvm::errs());
3516}
3517
3518//===----------------------------------------------------------------------===//
3519// Initialization sequence
3520//===----------------------------------------------------------------------===//
3521
3522void InitializationSequence::Step::Destroy() {
3523 switch (Kind) {
3524 case SK_ResolveAddressOfOverloadedFunction:
3525 case SK_CastDerivedToBasePRValue:
3526 case SK_CastDerivedToBaseXValue:
3527 case SK_CastDerivedToBaseLValue:
3528 case SK_BindReference:
3529 case SK_BindReferenceToTemporary:
3530 case SK_FinalCopy:
3531 case SK_ExtraneousCopyToTemporary:
3532 case SK_UserConversion:
3533 case SK_QualificationConversionPRValue:
3534 case SK_QualificationConversionXValue:
3535 case SK_QualificationConversionLValue:
3536 case SK_FunctionReferenceConversion:
3537 case SK_AtomicConversion:
3538 case SK_ListInitialization:
3539 case SK_UnwrapInitList:
3540 case SK_RewrapInitList:
3541 case SK_ConstructorInitialization:
3542 case SK_ConstructorInitializationFromList:
3543 case SK_ZeroInitialization:
3544 case SK_CAssignment:
3545 case SK_StringInit:
3546 case SK_ObjCObjectConversion:
3547 case SK_ArrayLoopIndex:
3548 case SK_ArrayLoopInit:
3549 case SK_ArrayInit:
3550 case SK_GNUArrayInit:
3551 case SK_ParenthesizedArrayInit:
3552 case SK_PassByIndirectCopyRestore:
3553 case SK_PassByIndirectRestore:
3554 case SK_ProduceObjCObject:
3555 case SK_StdInitializerList:
3556 case SK_StdInitializerListConstructorCall:
3557 case SK_OCLSamplerInit:
3558 case SK_OCLZeroOpaqueType:
3559 case SK_ParenthesizedListInit:
3560 break;
3561
3562 case SK_ConversionSequence:
3563 case SK_ConversionSequenceNoNarrowing:
3564 delete ICS;
3565 }
3566}
3567
3568bool InitializationSequence::isDirectReferenceBinding() const {
3569 // There can be some lvalue adjustments after the SK_BindReference step.
3570 for (const Step &S : llvm::reverse(Steps)) {
3571 if (S.Kind == SK_BindReference)
3572 return true;
3573 if (S.Kind == SK_BindReferenceToTemporary)
3574 return false;
3575 }
3576 return false;
3577}
3578
3579bool InitializationSequence::isAmbiguous() const {
3580 if (!Failed())
3581 return false;
3582
3583 switch (getFailureKind()) {
3584 case FK_TooManyInitsForReference:
3585 case FK_ParenthesizedListInitForReference:
3586 case FK_ArrayNeedsInitList:
3587 case FK_ArrayNeedsInitListOrStringLiteral:
3588 case FK_ArrayNeedsInitListOrWideStringLiteral:
3589 case FK_NarrowStringIntoWideCharArray:
3590 case FK_WideStringIntoCharArray:
3591 case FK_IncompatWideStringIntoWideChar:
3592 case FK_PlainStringIntoUTF8Char:
3593 case FK_UTF8StringIntoPlainChar:
3594 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3595 case FK_NonConstLValueReferenceBindingToTemporary:
3596 case FK_NonConstLValueReferenceBindingToBitfield:
3597 case FK_NonConstLValueReferenceBindingToVectorElement:
3598 case FK_NonConstLValueReferenceBindingToMatrixElement:
3599 case FK_NonConstLValueReferenceBindingToUnrelated:
3600 case FK_RValueReferenceBindingToLValue:
3601 case FK_ReferenceAddrspaceMismatchTemporary:
3602 case FK_ReferenceInitDropsQualifiers:
3603 case FK_ReferenceInitFailed:
3604 case FK_ConversionFailed:
3605 case FK_ConversionFromPropertyFailed:
3606 case FK_TooManyInitsForScalar:
3607 case FK_ParenthesizedListInitForScalar:
3608 case FK_ReferenceBindingToInitList:
3609 case FK_InitListBadDestinationType:
3610 case FK_DefaultInitOfConst:
3611 case FK_Incomplete:
3612 case FK_ArrayTypeMismatch:
3613 case FK_NonConstantArrayInit:
3614 case FK_ListInitializationFailed:
3615 case FK_VariableLengthArrayHasInitializer:
3616 case FK_PlaceholderType:
3617 case FK_ExplicitConstructor:
3618 case FK_AddressOfUnaddressableFunction:
3619 case FK_ParenthesizedListInitFailed:
3620 case FK_DesignatedInitForNonAggregate:
3621 return false;
3622
3623 case FK_ReferenceInitOverloadFailed:
3624 case FK_UserConversionOverloadFailed:
3625 case FK_ConstructorOverloadFailed:
3626 case FK_ListConstructorOverloadFailed:
3627 return FailedOverloadResult == OR_Ambiguous;
3628 }
3629
3630 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3630)
;
3631}
3632
3633bool InitializationSequence::isConstructorInitialization() const {
3634 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3635}
3636
3637void
3638InitializationSequence
3639::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3640 DeclAccessPair Found,
3641 bool HadMultipleCandidates) {
3642 Step S;
3643 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3644 S.Type = Function->getType();
3645 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3646 S.Function.Function = Function;
3647 S.Function.FoundDecl = Found;
3648 Steps.push_back(S);
3649}
3650
3651void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3652 ExprValueKind VK) {
3653 Step S;
3654 switch (VK) {
3655 case VK_PRValue:
3656 S.Kind = SK_CastDerivedToBasePRValue;
3657 break;
3658 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3659 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3660 }
3661 S.Type = BaseType;
3662 Steps.push_back(S);
3663}
3664
3665void InitializationSequence::AddReferenceBindingStep(QualType T,
3666 bool BindingTemporary) {
3667 Step S;
3668 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3669 S.Type = T;
3670 Steps.push_back(S);
3671}
3672
3673void InitializationSequence::AddFinalCopy(QualType T) {
3674 Step S;
3675 S.Kind = SK_FinalCopy;
3676 S.Type = T;
3677 Steps.push_back(S);
3678}
3679
3680void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3681 Step S;
3682 S.Kind = SK_ExtraneousCopyToTemporary;
3683 S.Type = T;
3684 Steps.push_back(S);
3685}
3686
3687void
3688InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3689 DeclAccessPair FoundDecl,
3690 QualType T,
3691 bool HadMultipleCandidates) {
3692 Step S;
3693 S.Kind = SK_UserConversion;
3694 S.Type = T;
3695 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3696 S.Function.Function = Function;
3697 S.Function.FoundDecl = FoundDecl;
3698 Steps.push_back(S);
3699}
3700
3701void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3702 ExprValueKind VK) {
3703 Step S;
3704 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3705 switch (VK) {
3706 case VK_PRValue:
3707 S.Kind = SK_QualificationConversionPRValue;
3708 break;
3709 case VK_XValue:
3710 S.Kind = SK_QualificationConversionXValue;
3711 break;
3712 case VK_LValue:
3713 S.Kind = SK_QualificationConversionLValue;
3714 break;
3715 }
3716 S.Type = Ty;
3717 Steps.push_back(S);
3718}
3719
3720void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3721 Step S;
3722 S.Kind = SK_FunctionReferenceConversion;
3723 S.Type = Ty;
3724 Steps.push_back(S);
3725}
3726
3727void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3728 Step S;
3729 S.Kind = SK_AtomicConversion;
3730 S.Type = Ty;
3731 Steps.push_back(S);
3732}
3733
3734void InitializationSequence::AddConversionSequenceStep(
3735 const ImplicitConversionSequence &ICS, QualType T,
3736 bool TopLevelOfInitList) {
3737 Step S;
3738 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3739 : SK_ConversionSequence;
3740 S.Type = T;
3741 S.ICS = new ImplicitConversionSequence(ICS);
3742 Steps.push_back(S);
3743}
3744
3745void InitializationSequence::AddListInitializationStep(QualType T) {
3746 Step S;
3747 S.Kind = SK_ListInitialization;
3748 S.Type = T;
3749 Steps.push_back(S);
3750}
3751
3752void InitializationSequence::AddConstructorInitializationStep(
3753 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3754 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3755 Step S;
3756 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3757 : SK_ConstructorInitializationFromList
3758 : SK_ConstructorInitialization;
3759 S.Type = T;
3760 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3761 S.Function.Function = Constructor;
3762 S.Function.FoundDecl = FoundDecl;
3763 Steps.push_back(S);
3764}
3765
3766void InitializationSequence::AddZeroInitializationStep(QualType T) {
3767 Step S;
3768 S.Kind = SK_ZeroInitialization;
3769 S.Type = T;
3770 Steps.push_back(S);
3771}
3772
3773void InitializationSequence::AddCAssignmentStep(QualType T) {
3774 Step S;
3775 S.Kind = SK_CAssignment;
3776 S.Type = T;
3777 Steps.push_back(S);
3778}
3779
3780void InitializationSequence::AddStringInitStep(QualType T) {
3781 Step S;
3782 S.Kind = SK_StringInit;
3783 S.Type = T;
3784 Steps.push_back(S);
3785}
3786
3787void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3788 Step S;
3789 S.Kind = SK_ObjCObjectConversion;
3790 S.Type = T;
3791 Steps.push_back(S);
3792}
3793
3794void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3795 Step S;
3796 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3797 S.Type = T;
3798 Steps.push_back(S);
3799}
3800
3801void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3802 Step S;
3803 S.Kind = SK_ArrayLoopIndex;
3804 S.Type = EltT;
3805 Steps.insert(Steps.begin(), S);
3806
3807 S.Kind = SK_ArrayLoopInit;
3808 S.Type = T;
3809 Steps.push_back(S);
3810}
3811
3812void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3813 Step S;
3814 S.Kind = SK_ParenthesizedArrayInit;
3815 S.Type = T;
3816 Steps.push_back(S);
3817}
3818
3819void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3820 bool shouldCopy) {
3821 Step s;
3822 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3823 : SK_PassByIndirectRestore);
3824 s.Type = type;
3825 Steps.push_back(s);
3826}
3827
3828void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3829 Step S;
3830 S.Kind = SK_ProduceObjCObject;
3831 S.Type = T;
3832 Steps.push_back(S);
3833}
3834
3835void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3836 Step S;
3837 S.Kind = SK_StdInitializerList;
3838 S.Type = T;
3839 Steps.push_back(S);
3840}
3841
3842void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3843 Step S;
3844 S.Kind = SK_OCLSamplerInit;
3845 S.Type = T;
3846 Steps.push_back(S);
3847}
3848
3849void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3850 Step S;
3851 S.Kind = SK_OCLZeroOpaqueType;
3852 S.Type = T;
3853 Steps.push_back(S);
3854}
3855
3856void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
3857 Step S;
3858 S.Kind = SK_ParenthesizedListInit;
3859 S.Type = T;
3860 Steps.push_back(S);
3861}
3862
3863void InitializationSequence::RewrapReferenceInitList(QualType T,
3864 InitListExpr *Syntactic) {
3865 assert(Syntactic->getNumInits() == 1 &&(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "clang/lib/Sema/SemaInit.cpp", 3866, __extension__ __PRETTY_FUNCTION__
))
3866 "Can only rewrap trivial init lists.")(static_cast <bool> (Syntactic->getNumInits() == 1 &&
"Can only rewrap trivial init lists.") ? void (0) : __assert_fail
("Syntactic->getNumInits() == 1 && \"Can only rewrap trivial init lists.\""
, "clang/lib/Sema/SemaInit.cpp", 3866, __extension__ __PRETTY_FUNCTION__
))
;
3867 Step S;
3868 S.Kind = SK_UnwrapInitList;
3869 S.Type = Syntactic->getInit(0)->getType();
3870 Steps.insert(Steps.begin(), S);
3871
3872 S.Kind = SK_RewrapInitList;
3873 S.Type = T;
3874 S.WrappingSyntacticList = Syntactic;
3875 Steps.push_back(S);
3876}
3877
3878void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3879 OverloadingResult Result) {
3880 setSequenceKind(FailedSequence);
3881 this->Failure = Failure;
3882 this->FailedOverloadResult = Result;
3883}
3884
3885//===----------------------------------------------------------------------===//
3886// Attempt initialization
3887//===----------------------------------------------------------------------===//
3888
3889/// Tries to add a zero initializer. Returns true if that worked.
3890static bool
3891maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3892 const InitializedEntity &Entity) {
3893 if (Entity.getKind() != InitializedEntity::EK_Variable)
3894 return false;
3895
3896 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3897 if (VD->getInit() || VD->getEndLoc().isMacroID())
3898 return false;
3899
3900 QualType VariableTy = VD->getType().getCanonicalType();
3901 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3902 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3903 if (!Init.empty()) {
3904 Sequence.AddZeroInitializationStep(Entity.getType());
3905 Sequence.SetZeroInitializationFixit(Init, Loc);
3906 return true;
3907 }
3908 return false;
3909}
3910
3911static void MaybeProduceObjCObject(Sema &S,
3912 InitializationSequence &Sequence,
3913 const InitializedEntity &Entity) {
3914 if (!S.getLangOpts().ObjCAutoRefCount) return;
3915
3916 /// When initializing a parameter, produce the value if it's marked
3917 /// __attribute__((ns_consumed)).
3918 if (Entity.isParameterKind()) {
3919 if (!Entity.isParameterConsumed())
3920 return;
3921
3922 assert(Entity.getType()->isObjCRetainableType() &&(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "clang/lib/Sema/SemaInit.cpp", 3923, __extension__ __PRETTY_FUNCTION__
))
3923 "consuming an object of unretainable type?")(static_cast <bool> (Entity.getType()->isObjCRetainableType
() && "consuming an object of unretainable type?") ? void
(0) : __assert_fail ("Entity.getType()->isObjCRetainableType() && \"consuming an object of unretainable type?\""
, "clang/lib/Sema/SemaInit.cpp", 3923, __extension__ __PRETTY_FUNCTION__
))
;
3924 Sequence.AddProduceObjCObjectStep(Entity.getType());
3925
3926 /// When initializing a return value, if the return type is a
3927 /// retainable type, then returns need to immediately retain the
3928 /// object. If an autorelease is required, it will be done at the
3929 /// last instant.
3930 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3931 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
3932 if (!Entity.getType()->isObjCRetainableType())
3933 return;
3934
3935 Sequence.AddProduceObjCObjectStep(Entity.getType());
3936 }
3937}
3938
3939static void TryListInitialization(Sema &S,
3940 const InitializedEntity &Entity,
3941 const InitializationKind &Kind,
3942 InitListExpr *InitList,
3943 InitializationSequence &Sequence,
3944 bool TreatUnavailableAsInvalid);
3945
3946/// When initializing from init list via constructor, handle
3947/// initialization of an object of type std::initializer_list<T>.
3948///
3949/// \return true if we have handled initialization of an object of type
3950/// std::initializer_list<T>, false otherwise.
3951static bool TryInitializerListConstruction(Sema &S,
3952 InitListExpr *List,
3953 QualType DestType,
3954 InitializationSequence &Sequence,
3955 bool TreatUnavailableAsInvalid) {
3956 QualType E;
3957 if (!S.isStdInitializerList(DestType, &E))
3958 return false;
3959
3960 if (!S.isCompleteType(List->getExprLoc(), E)) {
3961 Sequence.setIncompleteTypeFailure(E);
3962 return true;
3963 }
3964
3965 // Try initializing a temporary array from the init list.
3966 QualType ArrayType = S.Context.getConstantArrayType(
3967 E.withConst(),
3968 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3969 List->getNumInits()),
3970 nullptr, clang::ArrayType::Normal, 0);
3971 InitializedEntity HiddenArray =
3972 InitializedEntity::InitializeTemporary(ArrayType);
3973 InitializationKind Kind = InitializationKind::CreateDirectList(
3974 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3975 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3976 TreatUnavailableAsInvalid);
3977 if (Sequence)
3978 Sequence.AddStdInitializerListConstructionStep(DestType);
3979 return true;
3980}
3981
3982/// Determine if the constructor has the signature of a copy or move
3983/// constructor for the type T of the class in which it was found. That is,
3984/// determine if its first parameter is of type T or reference to (possibly
3985/// cv-qualified) T.
3986static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3987 const ConstructorInfo &Info) {
3988 if (Info.Constructor->getNumParams() == 0)
3989 return false;
3990
3991 QualType ParmT =
3992 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3993 QualType ClassT =
3994 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3995
3996 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3997}
3998
3999static OverloadingResult
4000ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
4001 MultiExprArg Args,
4002 OverloadCandidateSet &CandidateSet,
4003 QualType DestType,
4004 DeclContext::lookup_result Ctors,
4005 OverloadCandidateSet::iterator &Best,
4006 bool CopyInitializing, bool AllowExplicit,
4007 bool OnlyListConstructors, bool IsListInit,
4008 bool SecondStepOfCopyInit = false) {
4009 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
4010 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4011
4012 for (NamedDecl *D : Ctors) {
4013 auto Info = getConstructorInfo(D);
4014 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4015 continue;
4016
4017 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4018 continue;
4019
4020 // C++11 [over.best.ics]p4:
4021 // ... and the constructor or user-defined conversion function is a
4022 // candidate by
4023 // - 13.3.1.3, when the argument is the temporary in the second step
4024 // of a class copy-initialization, or
4025 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4026 // - the second phase of 13.3.1.7 when the initializer list has exactly
4027 // one element that is itself an initializer list, and the target is
4028 // the first parameter of a constructor of class X, and the conversion
4029 // is to X or reference to (possibly cv-qualified X),
4030 // user-defined conversion sequences are not considered.
4031 bool SuppressUserConversions =
4032 SecondStepOfCopyInit ||
4033 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4034 hasCopyOrMoveCtorParam(S.Context, Info));
4035
4036 if (Info.ConstructorTmpl)
4037 S.AddTemplateOverloadCandidate(
4038 Info.ConstructorTmpl, Info.FoundDecl,
4039 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4040 /*PartialOverloading=*/false, AllowExplicit);
4041 else {
4042 // C++ [over.match.copy]p1:
4043 // - When initializing a temporary to be bound to the first parameter
4044 // of a constructor [for type T] that takes a reference to possibly
4045 // cv-qualified T as its first argument, called with a single
4046 // argument in the context of direct-initialization, explicit
4047 // conversion functions are also considered.
4048 // FIXME: What if a constructor template instantiates to such a signature?
4049 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4050 Args.size() == 1 &&
4051 hasCopyOrMoveCtorParam(S.Context, Info);
4052 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4053 CandidateSet, SuppressUserConversions,
4054 /*PartialOverloading=*/false, AllowExplicit,
4055 AllowExplicitConv);
4056 }
4057 }
4058
4059 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4060 //
4061 // When initializing an object of class type T by constructor
4062 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4063 // from a single expression of class type U, conversion functions of
4064 // U that convert to the non-reference type cv T are candidates.
4065 // Explicit conversion functions are only candidates during
4066 // direct-initialization.
4067 //
4068 // Note: SecondStepOfCopyInit is only ever true in this case when
4069 // evaluating whether to produce a C++98 compatibility warning.
4070 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4071 !SecondStepOfCopyInit) {
4072 Expr *Initializer = Args[0];
4073 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4074 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4075 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4076 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4077 NamedDecl *D = *I;
4078 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4079 D = D->getUnderlyingDecl();
4080
4081 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4082 CXXConversionDecl *Conv;
4083 if (ConvTemplate)
4084 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4085 else
4086 Conv = cast<CXXConversionDecl>(D);
4087
4088 if (ConvTemplate)
4089 S.AddTemplateConversionCandidate(
4090 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4091 CandidateSet, AllowExplicit, AllowExplicit,
4092 /*AllowResultConversion*/ false);
4093 else
4094 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4095 DestType, CandidateSet, AllowExplicit,
4096 AllowExplicit,
4097 /*AllowResultConversion*/ false);
4098 }
4099 }
4100 }
4101
4102 // Perform overload resolution and return the result.
4103 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4104}
4105
4106/// Attempt initialization by constructor (C++ [dcl.init]), which
4107/// enumerates the constructors of the initialized entity and performs overload
4108/// resolution to select the best.
4109/// \param DestType The destination class type.
4110/// \param DestArrayType The destination type, which is either DestType or
4111/// a (possibly multidimensional) array of DestType.
4112/// \param IsListInit Is this list-initialization?
4113/// \param IsInitListCopy Is this non-list-initialization resulting from a
4114/// list-initialization from {x} where x is the same
4115/// type as the entity?
4116static void TryConstructorInitialization(Sema &S,
4117 const InitializedEntity &Entity,
4118 const InitializationKind &Kind,
4119 MultiExprArg Args, QualType DestType,
4120 QualType DestArrayType,
4121 InitializationSequence &Sequence,
4122 bool IsListInit = false,
4123 bool IsInitListCopy = false) {
4124 assert(((!IsListInit && !IsInitListCopy) ||(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4127, __extension__ __PRETTY_FUNCTION__
))
4125 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4127, __extension__ __PRETTY_FUNCTION__
))
4126 "IsListInit/IsInitListCopy must come with a single initializer list "(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4127, __extension__ __PRETTY_FUNCTION__
))
4127 "argument.")(static_cast <bool> (((!IsListInit && !IsInitListCopy
) || (Args.size() == 1 && isa<InitListExpr>(Args
[0]))) && "IsListInit/IsInitListCopy must come with a single initializer list "
"argument.") ? void (0) : __assert_fail ("((!IsListInit && !IsInitListCopy) || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && \"IsListInit/IsInitListCopy must come with a single initializer list \" \"argument.\""
, "clang/lib/Sema/SemaInit.cpp", 4127, __extension__ __PRETTY_FUNCTION__
))
;
4128 InitListExpr *ILE =
4129 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4130 MultiExprArg UnwrappedArgs =
4131 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4132
4133 // The type we're constructing needs to be complete.
4134 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4135 Sequence.setIncompleteTypeFailure(DestType);
4136 return;
4137 }
4138
4139 // C++17 [dcl.init]p17:
4140 // - If the initializer expression is a prvalue and the cv-unqualified
4141 // version of the source type is the same class as the class of the
4142 // destination, the initializer expression is used to initialize the
4143 // destination object.
4144 // Per DR (no number yet), this does not apply when initializing a base
4145 // class or delegating to another constructor from a mem-initializer.
4146 // ObjC++: Lambda captured by the block in the lambda to block conversion
4147 // should avoid copy elision.
4148 if (S.getLangOpts().CPlusPlus17 &&
4149 Entity.getKind() != InitializedEntity::EK_Base &&
4150 Entity.getKind() != InitializedEntity::EK_Delegating &&
4151 Entity.getKind() !=
4152 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
4153 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4154 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4155 // Convert qualifications if necessary.
4156 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4157 if (ILE)
4158 Sequence.RewrapReferenceInitList(DestType, ILE);
4159 return;
4160 }
4161
4162 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4163 assert(DestRecordType && "Constructor initialization requires record type")(static_cast <bool> (DestRecordType && "Constructor initialization requires record type"
) ? void (0) : __assert_fail ("DestRecordType && \"Constructor initialization requires record type\""
, "clang/lib/Sema/SemaInit.cpp", 4163, __extension__ __PRETTY_FUNCTION__
))
;
4164 CXXRecordDecl *DestRecordDecl
4165 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4166
4167 // Build the candidate set directly in the initialization sequence
4168 // structure, so that it will persist if we fail.
4169 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4170
4171 // Determine whether we are allowed to call explicit constructors or
4172 // explicit conversion operators.
4173 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4174 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4175
4176 // - Otherwise, if T is a class type, constructors are considered. The
4177 // applicable constructors are enumerated, and the best one is chosen
4178 // through overload resolution.
4179 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4180
4181 OverloadingResult Result = OR_No_Viable_Function;
4182 OverloadCandidateSet::iterator Best;
4183 bool AsInitializerList = false;
4184
4185 // C++11 [over.match.list]p1, per DR1467:
4186 // When objects of non-aggregate type T are list-initialized, such that
4187 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4188 // according to the rules in this section, overload resolution selects
4189 // the constructor in two phases:
4190 //
4191 // - Initially, the candidate functions are the initializer-list
4192 // constructors of the class T and the argument list consists of the
4193 // initializer list as a single argument.
4194 if (IsListInit) {
4195 AsInitializerList = true;
4196
4197 // If the initializer list has no elements and T has a default constructor,
4198 // the first phase is omitted.
4199 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4200 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
4201 CandidateSet, DestType, Ctors, Best,
4202 CopyInitialization, AllowExplicit,
4203 /*OnlyListConstructors=*/true,
4204 IsListInit);
4205 }
4206
4207 // C++11 [over.match.list]p1:
4208 // - If no viable initializer-list constructor is found, overload resolution
4209 // is performed again, where the candidate functions are all the
4210 // constructors of the class T and the argument list consists of the
4211 // elements of the initializer list.
4212 if (Result == OR_No_Viable_Function) {
4213 AsInitializerList = false;
4214 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
4215 CandidateSet, DestType, Ctors, Best,
4216 CopyInitialization, AllowExplicit,
4217 /*OnlyListConstructors=*/false,
4218 IsListInit);
4219 }
4220 if (Result) {
4221 Sequence.SetOverloadFailure(
4222 IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4223 : InitializationSequence::FK_ConstructorOverloadFailed,
4224 Result);
4225
4226 if (Result != OR_Deleted)
4227 return;
4228 }
4229
4230 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4231
4232 // In C++17, ResolveConstructorOverload can select a conversion function
4233 // instead of a constructor.
4234 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4235 // Add the user-defined conversion step that calls the conversion function.
4236 QualType ConvType = CD->getConversionType();
4237 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "clang/lib/Sema/SemaInit.cpp", 4238, __extension__ __PRETTY_FUNCTION__
))
4238 "should not have selected this conversion function")(static_cast <bool> (S.Context.hasSameUnqualifiedType(ConvType
, DestType) && "should not have selected this conversion function"
) ? void (0) : __assert_fail ("S.Context.hasSameUnqualifiedType(ConvType, DestType) && \"should not have selected this conversion function\""
, "clang/lib/Sema/SemaInit.cpp", 4238, __extension__ __PRETTY_FUNCTION__
))
;
4239 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4240 HadMultipleCandidates);
4241 if (!S.Context.hasSameType(ConvType, DestType))
4242 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4243 if (IsListInit)
4244 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4245 return;
4246 }
4247
4248 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4249 if (Result != OR_Deleted) {
4250 // C++11 [dcl.init]p6:
4251 // If a program calls for the default initialization of an object
4252 // of a const-qualified type T, T shall be a class type with a
4253 // user-provided default constructor.
4254 // C++ core issue 253 proposal:
4255 // If the implicit default constructor initializes all subobjects, no
4256 // initializer should be required.
4257 // The 253 proposal is for example needed to process libstdc++ headers
4258 // in 5.x.
4259 if (Kind.getKind() == InitializationKind::IK_Default &&
4260 Entity.getType().isConstQualified()) {
4261 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4262 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4263 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4264 return;
4265 }
4266 }
4267
4268 // C++11 [over.match.list]p1:
4269 // In copy-list-initialization, if an explicit constructor is chosen, the
4270 // initializer is ill-formed.
4271 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4272 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4273 return;
4274 }
4275 }
4276
4277 // [class.copy.elision]p3:
4278 // In some copy-initialization contexts, a two-stage overload resolution
4279 // is performed.
4280 // If the first overload resolution selects a deleted function, we also
4281 // need the initialization sequence to decide whether to perform the second
4282 // overload resolution.
4283 // For deleted functions in other contexts, there is no need to get the
4284 // initialization sequence.
4285 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4286 return;
4287
4288 // Add the constructor initialization step. Any cv-qualification conversion is
4289 // subsumed by the initialization.
4290 Sequence.AddConstructorInitializationStep(
4291 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4292 IsListInit | IsInitListCopy, AsInitializerList);
4293}
4294
4295static bool
4296ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4297 Expr *Initializer,
4298 QualType &SourceType,
4299 QualType &UnqualifiedSourceType,
4300 QualType UnqualifiedTargetType,
4301 InitializationSequence &Sequence) {
4302 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4303 S.Context.OverloadTy) {
4304 DeclAccessPair Found;
4305 bool HadMultipleCandidates = false;
4306 if (FunctionDecl *Fn
4307 = S.ResolveAddressOfOverloadedFunction(Initializer,
4308 UnqualifiedTargetType,
4309 false, Found,
4310 &HadMultipleCandidates)) {
4311 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4312 HadMultipleCandidates);
4313 SourceType = Fn->getType();
4314 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4315 } else if (!UnqualifiedTargetType->isRecordType()) {
4316 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4317 return true;
4318 }
4319 }
4320 return false;
4321}
4322
4323static void TryReferenceInitializationCore(Sema &S,
4324 const InitializedEntity &Entity,
4325 const InitializationKind &Kind,
4326 Expr *Initializer,
4327 QualType cv1T1, QualType T1,
4328 Qualifiers T1Quals,
4329 QualType cv2T2, QualType T2,
4330 Qualifiers T2Quals,
4331 InitializationSequence &Sequence);
4332
4333static void TryValueInitialization(Sema &S,
4334 const InitializedEntity &Entity,
4335 const InitializationKind &Kind,
4336 InitializationSequence &Sequence,
4337 InitListExpr *InitList = nullptr);
4338
4339/// Attempt list initialization of a reference.
4340static void TryReferenceListInitialization(Sema &S,
4341 const InitializedEntity &Entity,
4342 const InitializationKind &Kind,
4343 InitListExpr *InitList,
4344 InitializationSequence &Sequence,
4345 bool TreatUnavailableAsInvalid) {
4346 // First, catch C++03 where this isn't possible.
4347 if (!S.getLangOpts().CPlusPlus11) {
4348 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4349 return;
4350 }
4351 // Can't reference initialize a compound literal.
4352 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4353 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4354 return;
4355 }
4356
4357 QualType DestType = Entity.getType();
4358 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4359 Qualifiers T1Quals;
4360 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4361
4362 // Reference initialization via an initializer list works thus:
4363 // If the initializer list consists of a single element that is
4364 // reference-related to the referenced type, bind directly to that element
4365 // (possibly creating temporaries).
4366 // Otherwise, initialize a temporary with the initializer list and
4367 // bind to that.
4368 if (InitList->getNumInits() == 1) {
4369 Expr *Initializer = InitList->getInit(0);
4370 QualType cv2T2 = S.getCompletedType(Initializer);
4371 Qualifiers T2Quals;
4372 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4373
4374 // If this fails, creating a temporary wouldn't work either.
4375 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4376 T1, Sequence))
4377 return;
4378
4379 SourceLocation DeclLoc = Initializer->getBeginLoc();
4380 Sema::ReferenceCompareResult RefRelationship
4381 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4382 if (RefRelationship >= Sema::Ref_Related) {
4383 // Try to bind the reference here.
4384 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4385 T1Quals, cv2T2, T2, T2Quals, Sequence);
4386 if (Sequence)
4387 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4388 return;
4389 }
4390
4391 // Update the initializer if we've resolved an overloaded function.
4392 if (Sequence.step_begin() != Sequence.step_end())
4393 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4394 }
4395 // Perform address space compatibility check.
4396 QualType cv1T1IgnoreAS = cv1T1;
4397 if (T1Quals.hasAddressSpace()) {
4398 Qualifiers T2Quals;
4399 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4400 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4401 Sequence.SetFailed(
4402 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4403 return;
4404 }
4405 // Ignore address space of reference type at this point and perform address
4406 // space conversion after the reference binding step.
4407 cv1T1IgnoreAS =
4408 S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4409 }
4410 // Not reference-related. Create a temporary and bind to that.
4411 InitializedEntity TempEntity =
4412 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4413
4414 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4415 TreatUnavailableAsInvalid);
4416 if (Sequence) {
4417 if (DestType->isRValueReferenceType() ||
4418 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4419 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4420 /*BindingTemporary=*/true);
4421 if (T1Quals.hasAddressSpace())
4422 Sequence.AddQualificationConversionStep(
4423 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4424 } else
4425 Sequence.SetFailed(
4426 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4427 }
4428}
4429
4430/// Attempt list initialization (C++0x [dcl.init.list])
4431static void TryListInitialization(Sema &S,
4432 const InitializedEntity &Entity,
4433 const InitializationKind &Kind,
4434 InitListExpr *InitList,
4435 InitializationSequence &Sequence,
4436 bool TreatUnavailableAsInvalid) {
4437 QualType DestType = Entity.getType();
4438
4439 // C++ doesn't allow scalar initialization with more than one argument.
4440 // But C99 complex numbers are scalars and it makes sense there.
4441 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4442 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4443 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4444 return;
4445 }
4446 if (DestType->isReferenceType()) {
4447 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4448 TreatUnavailableAsInvalid);
4449 return;
4450 }
4451
4452 if (DestType->isRecordType() &&
4453 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4454 Sequence.setIncompleteTypeFailure(DestType);
4455 return;
4456 }
4457
4458 // C++20 [dcl.init.list]p3:
4459 // - If the braced-init-list contains a designated-initializer-list, T shall
4460 // be an aggregate class. [...] Aggregate initialization is performed.
4461 //
4462 // We allow arrays here too in order to support array designators.
4463 //
4464 // FIXME: This check should precede the handling of reference initialization.
4465 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4466 // as a tentative DR resolution.
4467 bool IsDesignatedInit = InitList->hasDesignatedInit();
4468 if (!DestType->isAggregateType() && IsDesignatedInit) {
4469 Sequence.SetFailed(
4470 InitializationSequence::FK_DesignatedInitForNonAggregate);
4471 return;
4472 }
4473
4474 // C++11 [dcl.init.list]p3, per DR1467:
4475 // - If T is a class type and the initializer list has a single element of
4476 // type cv U, where U is T or a class derived from T, the object is
4477 // initialized from that element (by copy-initialization for
4478 // copy-list-initialization, or by direct-initialization for
4479 // direct-list-initialization).
4480 // - Otherwise, if T is a character array and the initializer list has a
4481 // single element that is an appropriately-typed string literal
4482 // (8.5.2 [dcl.init.string]), initialization is performed as described
4483 // in that section.
4484 // - Otherwise, if T is an aggregate, [...] (continue below).
4485 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4486 !IsDesignatedInit) {
4487 if (DestType->isRecordType()) {
4488 QualType InitType = InitList->getInit(0)->getType();
4489 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4490 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4491 Expr *InitListAsExpr = InitList;
4492 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4493 DestType, Sequence,
4494 /*InitListSyntax*/false,
4495 /*IsInitListCopy*/true);
4496 return;
4497 }
4498 }
4499 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4500 Expr *SubInit[1] = {InitList->getInit(0)};
4501 if (!isa<VariableArrayType>(DestAT) &&
4502 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4503 InitializationKind SubKind =
4504 Kind.getKind() == InitializationKind::IK_DirectList
4505 ? InitializationKind::CreateDirect(Kind.getLocation(),
4506 InitList->getLBraceLoc(),
4507 InitList->getRBraceLoc())
4508 : Kind;
4509 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4510 /*TopLevelOfInitList*/ true,
4511 TreatUnavailableAsInvalid);
4512
4513 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4514 // the element is not an appropriately-typed string literal, in which
4515 // case we should proceed as in C++11 (below).
4516 if (Sequence) {
4517 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4518 return;
4519 }
4520 }
4521 }
4522 }
4523
4524 // C++11 [dcl.init.list]p3:
4525 // - If T is an aggregate, aggregate initialization is performed.
4526 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4527 (S.getLangOpts().CPlusPlus11 &&
4528 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4529 if (S.getLangOpts().CPlusPlus11) {
4530 // - Otherwise, if the initializer list has no elements and T is a
4531 // class type with a default constructor, the object is
4532 // value-initialized.
4533 if (InitList->getNumInits() == 0) {
4534 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4535 if (S.LookupDefaultConstructor(RD)) {
4536 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4537 return;
4538 }
4539 }
4540
4541 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4542 // an initializer_list object constructed [...]
4543 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4544 TreatUnavailableAsInvalid))
4545 return;
4546
4547 // - Otherwise, if T is a class type, constructors are considered.
4548 Expr *InitListAsExpr = InitList;
4549 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4550 DestType, Sequence, /*InitListSyntax*/true);
4551 } else
4552 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4553 return;
4554 }
4555
4556 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4557 InitList->getNumInits() == 1) {
4558 Expr *E = InitList->getInit(0);
4559
4560 // - Otherwise, if T is an enumeration with a fixed underlying type,
4561 // the initializer-list has a single element v, and the initialization
4562 // is direct-list-initialization, the object is initialized with the
4563 // value T(v); if a narrowing conversion is required to convert v to
4564 // the underlying type of T, the program is ill-formed.
4565 auto *ET = DestType->getAs<EnumType>();
4566 if (S.getLangOpts().CPlusPlus17 &&
4567 Kind.getKind() == InitializationKind::IK_DirectList &&
4568 ET && ET->getDecl()->isFixed() &&
4569 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4570 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4571 E->getType()->isFloatingType())) {
4572 // There are two ways that T(v) can work when T is an enumeration type.
4573 // If there is either an implicit conversion sequence from v to T or
4574 // a conversion function that can convert from v to T, then we use that.
4575 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4576 // type, it is converted to the enumeration type via its underlying type.
4577 // There is no overlap possible between these two cases (except when the
4578 // source value is already of the destination type), and the first
4579 // case is handled by the general case for single-element lists below.
4580 ImplicitConversionSequence ICS;
4581 ICS.setStandard();
4582 ICS.Standard.setAsIdentityConversion();
4583 if (!E->isPRValue())
4584 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4585 // If E is of a floating-point type, then the conversion is ill-formed
4586 // due to narrowing, but go through the motions in order to produce the
4587 // right diagnostic.
4588 ICS.Standard.Second = E->getType()->isFloatingType()
4589 ? ICK_Floating_Integral
4590 : ICK_Integral_Conversion;
4591 ICS.Standard.setFromType(E->getType());
4592 ICS.Standard.setToType(0, E->getType());
4593 ICS.Standard.setToType(1, DestType);
4594 ICS.Standard.setToType(2, DestType);
4595 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4596 /*TopLevelOfInitList*/true);
4597 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4598 return;
4599 }
4600
4601 // - Otherwise, if the initializer list has a single element of type E
4602 // [...references are handled above...], the object or reference is
4603 // initialized from that element (by copy-initialization for
4604 // copy-list-initialization, or by direct-initialization for
4605 // direct-list-initialization); if a narrowing conversion is required
4606 // to convert the element to T, the program is ill-formed.
4607 //
4608 // Per core-24034, this is direct-initialization if we were performing
4609 // direct-list-initialization and copy-initialization otherwise.
4610 // We can't use InitListChecker for this, because it always performs
4611 // copy-initialization. This only matters if we might use an 'explicit'
4612 // conversion operator, or for the special case conversion of nullptr_t to
4613 // bool, so we only need to handle those cases.
4614 //
4615 // FIXME: Why not do this in all cases?
4616 Expr *Init = InitList->getInit(0);
4617 if (Init->getType()->isRecordType() ||
4618 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4619 InitializationKind SubKind =
4620 Kind.getKind() == InitializationKind::IK_DirectList
4621 ? InitializationKind::CreateDirect(Kind.getLocation(),
4622 InitList->getLBraceLoc(),
4623 InitList->getRBraceLoc())
4624 : Kind;
4625 Expr *SubInit[1] = { Init };
4626 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4627 /*TopLevelOfInitList*/true,
4628 TreatUnavailableAsInvalid);
4629 if (Sequence)
4630 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4631 return;
4632 }
4633 }
4634
4635 InitListChecker CheckInitList(S, Entity, InitList,
4636 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4637 if (CheckInitList.HadError()) {
4638 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4639 return;
4640 }
4641
4642 // Add the list initialization step with the built init list.
4643 Sequence.AddListInitializationStep(DestType);
4644}
4645
4646/// Try a reference initialization that involves calling a conversion
4647/// function.
4648static OverloadingResult TryRefInitWithConversionFunction(
4649 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4650 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4651 InitializationSequence &Sequence) {
4652 QualType DestType = Entity.getType();
4653 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4654 QualType T1 = cv1T1.getUnqualifiedType();
4655 QualType cv2T2 = Initializer->getType();
4656 QualType T2 = cv2T2.getUnqualifiedType();
4657
4658 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\""
, "clang/lib/Sema/SemaInit.cpp", 4659, __extension__ __PRETTY_FUNCTION__
))
4659 "Must have incompatible references when binding via conversion")(static_cast <bool> (!S.CompareReferenceRelationship(Initializer
->getBeginLoc(), T1, T2) && "Must have incompatible references when binding via conversion"
) ? void (0) : __assert_fail ("!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && \"Must have incompatible references when binding via conversion\""
, "clang/lib/Sema/SemaInit.cpp", 4659, __extension__ __PRETTY_FUNCTION__
))
;
4660
4661 // Build the candidate set directly in the initialization sequence
4662 // structure, so that it will persist if we fail.
4663 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4664 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4665
4666 // Determine whether we are allowed to call explicit conversion operators.
4667 // Note that none of [over.match.copy], [over.match.conv], nor
4668 // [over.match.ref] permit an explicit constructor to be chosen when
4669 // initializing a reference, not even for direct-initialization.
4670 bool AllowExplicitCtors = false;
4671 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4672
4673 const RecordType *T1RecordType = nullptr;
4674 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4675 S.isCompleteType(Kind.getLocation(), T1)) {
4676 // The type we're converting to is a class type. Enumerate its constructors
4677 // to see if there is a suitable conversion.
4678 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4679
4680 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4681 auto Info = getConstructorInfo(D);
4682 if (!Info.Constructor)
4683 continue;
4684
4685 if (!Info.Constructor->isInvalidDecl() &&
4686 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4687 if (Info.ConstructorTmpl)
4688 S.AddTemplateOverloadCandidate(
4689 Info.ConstructorTmpl, Info.FoundDecl,
4690 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4691 /*SuppressUserConversions=*/true,
4692 /*PartialOverloading*/ false, AllowExplicitCtors);
4693 else
4694 S.AddOverloadCandidate(
4695 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4696 /*SuppressUserConversions=*/true,
4697 /*PartialOverloading*/ false, AllowExplicitCtors);
4698 }
4699 }
4700 }
4701 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4702 return OR_No_Viable_Function;
4703
4704 const RecordType *T2RecordType = nullptr;
4705 if ((T2RecordType = T2->getAs<RecordType>()) &&
4706 S.isCompleteType(Kind.getLocation(), T2)) {
4707 // The type we're converting from is a class type, enumerate its conversion
4708 // functions.
4709 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4710
4711 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4712 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4713 NamedDecl *D = *I;
4714 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4715 if (isa<UsingShadowDecl>(D))
4716 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4717
4718 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4719 CXXConversionDecl *Conv;
4720 if (ConvTemplate)
4721 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4722 else
4723 Conv = cast<CXXConversionDecl>(D);
4724
4725 // If the conversion function doesn't return a reference type,
4726 // it can't be considered for this conversion unless we're allowed to
4727 // consider rvalues.
4728 // FIXME: Do we need to make sure that we only consider conversion
4729 // candidates with reference-compatible results? That might be needed to
4730 // break recursion.
4731 if ((AllowRValues ||
4732 Conv->getConversionType()->isLValueReferenceType())) {
4733 if (ConvTemplate)
4734 S.AddTemplateConversionCandidate(
4735 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4736 CandidateSet,
4737 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4738 else
4739 S.AddConversionCandidate(
4740 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4741 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4742 }
4743 }
4744 }
4745 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4746 return OR_No_Viable_Function;
4747
4748 SourceLocation DeclLoc = Initializer->getBeginLoc();
4749
4750 // Perform overload resolution. If it fails, return the failed result.
4751 OverloadCandidateSet::iterator Best;
4752 if (OverloadingResult Result
4753 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4754 return Result;
4755
4756 FunctionDecl *Function = Best->Function;
4757 // This is the overload that will be used for this initialization step if we
4758 // use this initialization. Mark it as referenced.
4759 Function->setReferenced();
4760
4761 // Compute the returned type and value kind of the conversion.
4762 QualType cv3T3;
4763 if (isa<CXXConversionDecl>(Function))
4764 cv3T3 = Function->getReturnType();
4765 else
4766 cv3T3 = T1;
4767
4768 ExprValueKind VK = VK_PRValue;
4769 if (cv3T3->isLValueReferenceType())
4770 VK = VK_LValue;
4771 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4772 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4773 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4774
4775 // Add the user-defined conversion step.
4776 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4777 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4778 HadMultipleCandidates);
4779
4780 // Determine whether we'll need to perform derived-to-base adjustments or
4781 // other conversions.
4782 Sema::ReferenceConversions RefConv;
4783 Sema::ReferenceCompareResult NewRefRelationship =
4784 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4785
4786 // Add the final conversion sequence, if necessary.
4787 if (NewRefRelationship == Sema::Ref_Incompatible) {
4788 assert(!isa<CXXConstructorDecl>(Function) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "clang/lib/Sema/SemaInit.cpp", 4789, __extension__ __PRETTY_FUNCTION__
))
4789 "should not have conversion after constructor")(static_cast <bool> (!isa<CXXConstructorDecl>(Function
) && "should not have conversion after constructor") ?
void (0) : __assert_fail ("!isa<CXXConstructorDecl>(Function) && \"should not have conversion after constructor\""
, "clang/lib/Sema/SemaInit.cpp", 4789, __extension__ __PRETTY_FUNCTION__
))
;
4790
4791 ImplicitConversionSequence ICS;
4792 ICS.setStandard();
4793 ICS.Standard = Best->FinalConversion;
4794 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4795
4796 // Every implicit conversion results in a prvalue, except for a glvalue
4797 // derived-to-base conversion, which we handle below.
4798 cv3T3 = ICS.Standard.getToType(2);
4799 VK = VK_PRValue;
4800 }
4801
4802 // If the converted initializer is a prvalue, its type T4 is adjusted to
4803 // type "cv1 T4" and the temporary materialization conversion is applied.
4804 //
4805 // We adjust the cv-qualifications to match the reference regardless of
4806 // whether we have a prvalue so that the AST records the change. In this
4807 // case, T4 is "cv3 T3".
4808 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4809 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4810 Sequence.AddQualificationConversionStep(cv1T4, VK);
4811 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4812 VK = IsLValueRef ? VK_LValue : VK_XValue;
4813
4814 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4815 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4816 else if (RefConv & Sema::ReferenceConversions::ObjC)
4817 Sequence.AddObjCObjectConversionStep(cv1T1);
4818 else if (RefConv & Sema::ReferenceConversions::Function)
4819 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4820 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4821 if (!S.Context.hasSameType(cv1T4, cv1T1))
4822 Sequence.AddQualificationConversionStep(cv1T1, VK);
4823 }
4824
4825 return OR_Success;
4826}
4827
4828static void CheckCXX98CompatAccessibleCopy(Sema &S,
4829 const InitializedEntity &Entity,
4830 Expr *CurInitExpr);
4831
4832/// Attempt reference initialization (C++0x [dcl.init.ref])
4833static void TryReferenceInitialization(Sema &S,
4834 const InitializedEntity &Entity,
4835 const InitializationKind &Kind,
4836 Expr *Initializer,
4837 InitializationSequence &Sequence) {
4838 QualType DestType = Entity.getType();
4839 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4840 Qualifiers T1Quals;
4841 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4842 QualType cv2T2 = S.getCompletedType(Initializer);
4843 Qualifiers T2Quals;
4844 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4845
4846 // If the initializer is the address of an overloaded function, try
4847 // to resolve the overloaded function. If all goes well, T2 is the
4848 // type of the resulting function.
4849 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4850 T1, Sequence))
4851 return;
4852
4853 // Delegate everything else to a subfunction.
4854 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4855 T1Quals, cv2T2, T2, T2Quals, Sequence);
4856}
4857
4858/// Determine whether an expression is a non-referenceable glvalue (one to
4859/// which a reference can never bind). Attempting to bind a reference to
4860/// such a glvalue will always create a temporary.
4861static bool isNonReferenceableGLValue(Expr *E) {
4862 return E->refersToBitField() || E->refersToVectorElement() ||
4863 E->refersToMatrixElement();
4864}
4865
4866/// Reference initialization without resolving overloaded functions.
4867///
4868/// We also can get here in C if we call a builtin which is declared as
4869/// a function with a parameter of reference type (such as __builtin_va_end()).
4870static void TryReferenceInitializationCore(Sema &S,
4871 const InitializedEntity &Entity,
4872 const InitializationKind &Kind,
4873 Expr *Initializer,
4874 QualType cv1T1, QualType T1,
4875 Qualifiers T1Quals,
4876 QualType cv2T2, QualType T2,
4877 Qualifiers T2Quals,
4878 InitializationSequence &Sequence) {
4879 QualType DestType = Entity.getType();
4880 SourceLocation DeclLoc = Initializer->getBeginLoc();
4881
4882 // Compute some basic properties of the types and the initializer.
4883 bool isLValueRef = DestType->isLValueReferenceType();
4884 bool isRValueRef = !isLValueRef;
4885 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4886
4887 Sema::ReferenceConversions RefConv;
4888 Sema::ReferenceCompareResult RefRelationship =
4889 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4890
4891 // C++0x [dcl.init.ref]p5:
4892 // A reference to type "cv1 T1" is initialized by an expression of type
4893 // "cv2 T2" as follows:
4894 //
4895 // - If the reference is an lvalue reference and the initializer
4896 // expression
4897 // Note the analogous bullet points for rvalue refs to functions. Because
4898 // there are no function rvalues in C++, rvalue refs to functions are treated
4899 // like lvalue refs.
4900 OverloadingResult ConvOvlResult = OR_Success;
4901 bool T1Function = T1->isFunctionType();
4902 if (isLValueRef || T1Function) {
4903 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4904 (RefRelationship == Sema::Ref_Compatible ||
4905 (Kind.isCStyleOrFunctionalCast() &&
4906 RefRelationship == Sema::Ref_Related))) {
4907 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4908 // reference-compatible with "cv2 T2," or
4909 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
4910 Sema::ReferenceConversions::ObjC)) {
4911 // If we're converting the pointee, add any qualifiers first;
4912 // these qualifiers must all be top-level, so just convert to "cv1 T2".
4913 if (RefConv & (Sema::ReferenceConversions::Qualification))
4914 Sequence.AddQualificationConversionStep(
4915 S.Context.getQualifiedType(T2, T1Quals),
4916 Initializer->getValueKind());
4917 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4918 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4919 else
4920 Sequence.AddObjCObjectConversionStep(cv1T1);
4921 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
4922 // Perform a (possibly multi-level) qualification conversion.
4923 Sequence.AddQualificationConversionStep(cv1T1,
4924 Initializer->getValueKind());
4925 } else if (RefConv & Sema::ReferenceConversions::Function) {
4926 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4927 }
4928
4929 // We only create a temporary here when binding a reference to a
4930 // bit-field or vector element. Those cases are't supposed to be
4931 // handled by this bullet, but the outcome is the same either way.
4932 Sequence.AddReferenceBindingStep(cv1T1, false);
4933 return;
4934 }
4935
4936 // - has a class type (i.e., T2 is a class type), where T1 is not
4937 // reference-related to T2, and can be implicitly converted to an
4938 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4939 // with "cv3 T3" (this conversion is selected by enumerating the
4940 // applicable conversion functions (13.3.1.6) and choosing the best
4941 // one through overload resolution (13.3)),
4942 // If we have an rvalue ref to function type here, the rhs must be
4943 // an rvalue. DR1287 removed the "implicitly" here.
4944 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4945 (isLValueRef || InitCategory.isRValue())) {
4946 if (S.getLangOpts().CPlusPlus) {
4947 // Try conversion functions only for C++.
4948 ConvOvlResult = TryRefInitWithConversionFunction(
4949 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4950 /*IsLValueRef*/ isLValueRef, Sequence);
4951 if (ConvOvlResult == OR_Success)
4952 return;
4953 if (ConvOvlResult != OR_No_Viable_Function)
4954 Sequence.SetOverloadFailure(
4955 InitializationSequence::FK_ReferenceInitOverloadFailed,
4956 ConvOvlResult);
4957 } else {
4958 ConvOvlResult = OR_No_Viable_Function;
4959 }
4960 }
4961 }
4962
4963 // - Otherwise, the reference shall be an lvalue reference to a
4964 // non-volatile const type (i.e., cv1 shall be const), or the reference
4965 // shall be an rvalue reference.
4966 // For address spaces, we interpret this to mean that an addr space
4967 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4968 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4969 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
4970 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4971 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4972 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4973 Sequence.SetOverloadFailure(
4974 InitializationSequence::FK_ReferenceInitOverloadFailed,
4975 ConvOvlResult);
4976 else if (!InitCategory.isLValue())
4977 Sequence.SetFailed(
4978 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4979 ? InitializationSequence::
4980 FK_NonConstLValueReferenceBindingToTemporary
4981 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
4982 else {
4983 InitializationSequence::FailureKind FK;
4984 switch (RefRelationship) {
4985 case Sema::Ref_Compatible:
4986 if (Initializer->refersToBitField())
4987 FK = InitializationSequence::
4988 FK_NonConstLValueReferenceBindingToBitfield;
4989 else if (Initializer->refersToVectorElement())
4990 FK = InitializationSequence::
4991 FK_NonConstLValueReferenceBindingToVectorElement;
4992 else if (Initializer->refersToMatrixElement())
4993 FK = InitializationSequence::
4994 FK_NonConstLValueReferenceBindingToMatrixElement;
4995 else
4996 llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer"
, "clang/lib/Sema/SemaInit.cpp", 4996)
;
4997 break;
4998 case Sema::Ref_Related:
4999 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5000 break;
5001 case Sema::Ref_Incompatible:
5002 FK = InitializationSequence::
5003 FK_NonConstLValueReferenceBindingToUnrelated;
5004 break;
5005 }
5006 Sequence.SetFailed(FK);
5007 }
5008 return;
5009 }
5010
5011 // - If the initializer expression
5012 // - is an
5013 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5014 // [1z] rvalue (but not a bit-field) or
5015 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5016 //
5017 // Note: functions are handled above and below rather than here...
5018 if (!T1Function &&
5019 (RefRelationship == Sema::Ref_Compatible ||
5020 (Kind.isCStyleOrFunctionalCast() &&
5021 RefRelationship == Sema::Ref_Related)) &&
5022 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5023 (InitCategory.isPRValue() &&
5024 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5025 T2->isArrayType())))) {
5026 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5027 if (InitCategory.isPRValue() && T2->isRecordType()) {
5028 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5029 // compiler the freedom to perform a copy here or bind to the
5030 // object, while C++0x requires that we bind directly to the
5031 // object. Hence, we always bind to the object without making an
5032 // extra copy. However, in C++03 requires that we check for the
5033 // presence of a suitable copy constructor:
5034 //
5035 // The constructor that would be used to make the copy shall
5036 // be callable whether or not the copy is actually done.
5037 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5038 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5039 else if (S.getLangOpts().CPlusPlus11)
5040 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
5041 }
5042
5043 // C++1z [dcl.init.ref]/5.2.1.2:
5044 // If the converted initializer is a prvalue, its type T4 is adjusted
5045 // to type "cv1 T4" and the temporary materialization conversion is
5046 // applied.
5047 // Postpone address space conversions to after the temporary materialization
5048 // conversion to allow creating temporaries in the alloca address space.
5049 auto T1QualsIgnoreAS = T1Quals;
5050 auto T2QualsIgnoreAS = T2Quals;
5051 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5052 T1QualsIgnoreAS.removeAddressSpace();
5053 T2QualsIgnoreAS.removeAddressSpace();
5054 }
5055 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5056 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5057 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5058 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5059 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5060 // Add addr space conversion if required.
5061 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5062 auto T4Quals = cv1T4.getQualifiers();
5063 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5064 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5065 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5066 cv1T4 = cv1T4WithAS;
5067 }
5068
5069 // In any case, the reference is bound to the resulting glvalue (or to
5070 // an appropriate base class subobject).
5071 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5072 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5073 else if (RefConv & Sema::ReferenceConversions::ObjC)
5074 Sequence.AddObjCObjectConversionStep(cv1T1);
5075 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5076 if (!S.Context.hasSameType(cv1T4, cv1T1))
5077 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5078 }
5079 return;
5080 }
5081
5082 // - has a class type (i.e., T2 is a class type), where T1 is not
5083 // reference-related to T2, and can be implicitly converted to an
5084 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5085 // where "cv1 T1" is reference-compatible with "cv3 T3",
5086 //
5087 // DR1287 removes the "implicitly" here.
5088 if (T2->isRecordType()) {
5089 if (RefRelationship == Sema::Ref_Incompatible) {
5090 ConvOvlResult = TryRefInitWithConversionFunction(
5091 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5092 /*IsLValueRef*/ isLValueRef, Sequence);
5093 if (ConvOvlResult)
5094 Sequence.SetOverloadFailure(
5095 InitializationSequence::FK_ReferenceInitOverloadFailed,
5096 ConvOvlResult);
5097
5098 return;
5099 }
5100
5101 if (RefRelationship == Sema::Ref_Compatible &&
5102 isRValueRef && InitCategory.isLValue()) {
5103 Sequence.SetFailed(
5104 InitializationSequence::FK_RValueReferenceBindingToLValue);
5105 return;
5106 }
5107
5108 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5109 return;
5110 }
5111
5112 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5113 // from the initializer expression using the rules for a non-reference
5114 // copy-initialization (8.5). The reference is then bound to the
5115 // temporary. [...]
5116
5117 // Ignore address space of reference type at this point and perform address
5118 // space conversion after the reference binding step.
5119 QualType cv1T1IgnoreAS =
5120 T1Quals.hasAddressSpace()
5121 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5122 : cv1T1;
5123
5124 InitializedEntity TempEntity =
5125 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5126
5127 // FIXME: Why do we use an implicit conversion here rather than trying
5128 // copy-initialization?
5129 ImplicitConversionSequence ICS
5130 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5131 /*SuppressUserConversions=*/false,
5132 Sema::AllowedExplicit::None,
5133 /*FIXME:InOverloadResolution=*/false,
5134 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5135 /*AllowObjCWritebackConversion=*/false);
5136
5137 if (ICS.isBad()) {
5138 // FIXME: Use the conversion function set stored in ICS to turn
5139 // this into an overloading ambiguity diagnostic. However, we need
5140 // to keep that set as an OverloadCandidateSet rather than as some
5141 // other kind of set.
5142 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5143 Sequence.SetOverloadFailure(
5144 InitializationSequence::FK_ReferenceInitOverloadFailed,
5145 ConvOvlResult);
5146 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5147 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5148 else
5149 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5150 return;
5151 } else {
5152 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
5153 }
5154
5155 // [...] If T1 is reference-related to T2, cv1 must be the
5156 // same cv-qualification as, or greater cv-qualification
5157 // than, cv2; otherwise, the program is ill-formed.
5158 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5159 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5160 if (RefRelationship == Sema::Ref_Related &&
5161 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5162 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5163 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5164 return;
5165 }
5166
5167 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5168 // reference, the initializer expression shall not be an lvalue.
5169 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5170 InitCategory.isLValue()) {
5171 Sequence.SetFailed(
5172 InitializationSequence::FK_RValueReferenceBindingToLValue);
5173 return;
5174 }
5175
5176 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5177
5178 if (T1Quals.hasAddressSpace()) {
5179 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
5180 LangAS::Default)) {
5181 Sequence.SetFailed(
5182 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5183 return;
5184 }
5185 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5186 : VK_XValue);
5187 }
5188}
5189
5190/// Attempt character array initialization from a string literal
5191/// (C++ [dcl.init.string], C99 6.7.8).
5192static void TryStringLiteralInitialization(Sema &S,
5193 const InitializedEntity &Entity,
5194 const InitializationKind &Kind,
5195 Expr *Initializer,
5196 InitializationSequence &Sequence) {
5197 Sequence.AddStringInitStep(Entity.getType());
5198}
5199
5200/// Attempt value initialization (C++ [dcl.init]p7).
5201static void TryValueInitialization(Sema &S,
5202 const InitializedEntity &Entity,
5203 const InitializationKind &Kind,
5204 InitializationSequence &Sequence,
5205 InitListExpr *InitList) {
5206 assert((!InitList || InitList->getNumInits() == 0) &&(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "clang/lib/Sema/SemaInit.cpp", 5207, __extension__ __PRETTY_FUNCTION__
))
5207 "Shouldn't use value-init for non-empty init lists")(static_cast <bool> ((!InitList || InitList->getNumInits
() == 0) && "Shouldn't use value-init for non-empty init lists"
) ? void (0) : __assert_fail ("(!InitList || InitList->getNumInits() == 0) && \"Shouldn't use value-init for non-empty init lists\""
, "clang/lib/Sema/SemaInit.cpp", 5207, __extension__ __PRETTY_FUNCTION__
))
;
5208
5209 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5210 //
5211 // To value-initialize an object of type T means:
5212 QualType T = Entity.getType();
5213
5214 // -- if T is an array type, then each element is value-initialized;
5215 T = S.Context.getBaseElementType(T);
5216
5217 if (const RecordType *RT = T->getAs<RecordType>()) {
5218 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5219 bool NeedZeroInitialization = true;
5220 // C++98:
5221 // -- if T is a class type (clause 9) with a user-declared constructor
5222 // (12.1), then the default constructor for T is called (and the
5223 // initialization is ill-formed if T has no accessible default
5224 // constructor);
5225 // C++11:
5226 // -- if T is a class type (clause 9) with either no default constructor
5227 // (12.1 [class.ctor]) or a default constructor that is user-provided
5228 // or deleted, then the object is default-initialized;
5229 //
5230 // Note that the C++11 rule is the same as the C++98 rule if there are no
5231 // defaulted or deleted constructors, so we just use it unconditionally.
5232 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5233 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5234 NeedZeroInitialization = false;
5235
5236 // -- if T is a (possibly cv-qualified) non-union class type without a
5237 // user-provided or deleted default constructor, then the object is
5238 // zero-initialized and, if T has a non-trivial default constructor,
5239 // default-initialized;
5240 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5241 // constructor' part was removed by DR1507.
5242 if (NeedZeroInitialization)
5243 Sequence.AddZeroInitializationStep(Entity.getType());
5244
5245 // C++03:
5246 // -- if T is a non-union class type without a user-declared constructor,
5247 // then every non-static data member and base class component of T is
5248 // value-initialized;
5249 // [...] A program that calls for [...] value-initialization of an
5250 // entity of reference type is ill-formed.
5251 //
5252 // C++11 doesn't need this handling, because value-initialization does not
5253 // occur recursively there, and the implicit default constructor is
5254 // defined as deleted in the problematic cases.
5255 if (!S.getLangOpts().CPlusPlus11 &&
5256 ClassDecl->hasUninitializedReferenceMember()) {
5257 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5258 return;
5259 }
5260
5261 // If this is list-value-initialization, pass the empty init list on when
5262 // building the constructor call. This affects the semantics of a few
5263 // things (such as whether an explicit default constructor can be called).
5264 Expr *InitListAsExpr = InitList;
5265 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5266 bool InitListSyntax = InitList;
5267
5268 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5269 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5270 return TryConstructorInitialization(
5271 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5272 }
5273 }
5274
5275 Sequence.AddZeroInitializationStep(Entity.getType());
5276}
5277
5278/// Attempt default initialization (C++ [dcl.init]p6).
5279static void TryDefaultInitialization(Sema &S,
5280 const InitializedEntity &Entity,
5281 const InitializationKind &Kind,
5282 InitializationSequence &Sequence) {
5283 assert(Kind.getKind() == InitializationKind::IK_Default)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Default) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Default"
, "clang/lib/Sema/SemaInit.cpp", 5283, __extension__ __PRETTY_FUNCTION__
))
;
5284
5285 // C++ [dcl.init]p6:
5286 // To default-initialize an object of type T means:
5287 // - if T is an array type, each element is default-initialized;
5288 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5289
5290 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5291 // constructor for T is called (and the initialization is ill-formed if
5292 // T has no accessible default constructor);
5293 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5294 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5295 Entity.getType(), Sequence);
5296 return;
5297 }
5298
5299 // - otherwise, no initialization is performed.
5300
5301 // If a program calls for the default initialization of an object of
5302 // a const-qualified type T, T shall be a class type with a user-provided
5303 // default constructor.
5304 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5305 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5306 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5307 return;
5308 }
5309
5310 // If the destination type has a lifetime property, zero-initialize it.
5311 if (DestType.getQualifiers().hasObjCLifetime()) {
5312 Sequence.AddZeroInitializationStep(Entity.getType());
5313 return;
5314 }
5315}
5316
5317static void TryOrBuildParenListInitialization(
5318 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5319 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5320 ExprResult *Result = nullptr) {
5321 unsigned EntityIndexToProcess = 0;
5322 SmallVector<Expr *, 4> InitExprs;
5323 QualType ResultType;
5324 Expr *ArrayFiller = nullptr;
5325 FieldDecl *InitializedFieldInUnion = nullptr;
5326
5327 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5328 const InitializationKind &SubKind,
5329 Expr *Arg, Expr **InitExpr = nullptr) {
5330 InitializationSequence IS = [&]() {
5331 if (Arg)
5332 return InitializationSequence(S, SubEntity, SubKind, Arg);
5333 return InitializationSequence(S, SubEntity, SubKind, std::nullopt);
5334 }();
5335
5336 if (IS.Failed()) {
5337 if (!VerifyOnly) {
5338 if (Arg)
5339 IS.Diagnose(S, SubEntity, SubKind, Arg);
5340 else
5341 IS.Diagnose(S, SubEntity, SubKind, std::nullopt);
5342 } else {
5343 Sequence.SetFailed(
5344 InitializationSequence::FK_ParenthesizedListInitFailed);
5345 }
5346
5347 return false;
5348 }
5349 if (!VerifyOnly) {
5350 ExprResult ER;
5351 if (Arg)
5352 ER = IS.Perform(S, SubEntity, SubKind, Arg);
5353 else
5354 ER = IS.Perform(S, SubEntity, SubKind, std::nullopt);
5355 if (InitExpr)
5356 *InitExpr = ER.get();
5357 else
5358 InitExprs.push_back(ER.get());
5359 }
5360 return true;
5361 };
5362
5363 if (const ArrayType *AT =
5364 S.getASTContext().getAsArrayType(Entity.getType())) {
5365 SmallVector<InitializedEntity, 4> ElementEntities;
5366 uint64_t ArrayLength;
5367 // C++ [dcl.init]p16.5
5368 // if the destination type is an array, the object is initialized as
5369 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5370 // the destination type is an array of unknown bound, it is defined as
5371 // having k elements.
5372 if (const ConstantArrayType *CAT =
5373 S.getASTContext().getAsConstantArrayType(Entity.getType())) {
5374 ArrayLength = CAT->getSize().getZExtValue();
5375 ResultType = Entity.getType();
5376 } else if (const VariableArrayType *VAT =
5377 S.getASTContext().getAsVariableArrayType(Entity.getType())) {
5378 // Braced-initialization of variable array types is not allowed, even if
5379 // the size is greater than or equal to the number of args, so we don't
5380 // allow them to be initialized via parenthesized aggregate initialization
5381 // either.
5382 const Expr *SE = VAT->getSizeExpr();
5383 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5384 << SE->getSourceRange();
5385 return;
5386 } else {
5387 assert(isa<IncompleteArrayType>(Entity.getType()))(static_cast <bool> (isa<IncompleteArrayType>(Entity
.getType())) ? void (0) : __assert_fail ("isa<IncompleteArrayType>(Entity.getType())"
, "clang/lib/Sema/SemaInit.cpp", 5387, __extension__ __PRETTY_FUNCTION__
))
;
5388 ArrayLength = Args.size();
5389 }
5390 EntityIndexToProcess = ArrayLength;
5391
5392 // ...the ith array element is copy-initialized with xi for each
5393 // 1 <= i <= k
5394 for (Expr *E : Args) {
5395 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5396 S.getASTContext(), EntityIndexToProcess, Entity);
5397 InitializationKind SubKind = InitializationKind::CreateForInit(
5398 E->getExprLoc(), /*isDirectInit=*/false, E);
5399 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5400 return;
5401 }
5402 // ...and value-initialized for each k < i <= n;
5403 if (ArrayLength > Args.size()) {
5404 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5405 S.getASTContext(), Args.size(), Entity);
5406 InitializationKind SubKind = InitializationKind::CreateValue(
5407 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5408 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5409 return;
5410 }
5411
5412 if (ResultType.isNull()) {
5413 ResultType = S.Context.getConstantArrayType(
5414 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5415 /*SizeExpr=*/nullptr, ArrayType::Normal, 0);
5416 }
5417 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5418 bool IsUnion = RT->isUnionType();
5419 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5420
5421 if (!IsUnion) {
5422 for (const CXXBaseSpecifier &Base : RD->bases()) {
5423 InitializedEntity SubEntity = InitializedEntity::InitializeBase(
5424 S.getASTContext(), &Base, false, &Entity);
5425 if (EntityIndexToProcess < Args.size()) {
5426 // C++ [dcl.init]p16.6.2.2.
5427 // ...the object is initialized is follows. Let e1, ..., en be the
5428 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5429 // the elements of the expression-list...The element ei is
5430 // copy-initialized with xi for 1 <= i <= k.
5431 Expr *E = Args[EntityIndexToProcess];
5432 InitializationKind SubKind = InitializationKind::CreateForInit(
5433 E->getExprLoc(), /*isDirectInit=*/false, E);
5434 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5435 return;
5436 } else {
5437 // We've processed all of the args, but there are still base classes
5438 // that have to be initialized.
5439 // C++ [dcl.init]p17.6.2.2
5440 // The remaining elements...otherwise are value initialzed
5441 InitializationKind SubKind = InitializationKind::CreateValue(
5442 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5443 /*IsImplicit=*/true);
5444 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5445 return;
5446 }
5447 EntityIndexToProcess++;
5448 }
5449 }
5450
5451 for (FieldDecl *FD : RD->fields()) {
5452 // Unnamed bitfields should not be initialized at all, either with an arg
5453 // or by default.
5454 if (FD->isUnnamedBitfield())
5455 continue;
5456
5457 InitializedEntity SubEntity =
5458 InitializedEntity::InitializeMemberFromParenAggInit(FD);
5459
5460 if (EntityIndexToProcess < Args.size()) {
5461 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5462 Expr *E = Args[EntityIndexToProcess];
5463
5464 // Incomplete array types indicate flexible array members. Do not allow
5465 // paren list initializations of structs with these members, as GCC
5466 // doesn't either.
5467 if (FD->getType()->isIncompleteArrayType()) {
5468 if (!VerifyOnly) {
5469 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5470 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5471 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5472 }
5473 Sequence.SetFailed(
5474 InitializationSequence::FK_ParenthesizedListInitFailed);
5475 return;
5476 }
5477
5478 InitializationKind SubKind = InitializationKind::CreateForInit(
5479 E->getExprLoc(), /*isDirectInit=*/false, E);
5480 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5481 return;
5482
5483 // Unions should have only one initializer expression, so we bail out
5484 // after processing the first field. If there are more initializers then
5485 // it will be caught when we later check whether EntityIndexToProcess is
5486 // less than Args.size();
5487 if (IsUnion) {
5488 InitializedFieldInUnion = FD;
5489 EntityIndexToProcess = 1;
5490 break;
5491 }
5492 } else {
5493 // We've processed all of the args, but there are still members that
5494 // have to be initialized.
5495 if (FD->hasInClassInitializer()) {
5496 if (!VerifyOnly) {
5497 // C++ [dcl.init]p16.6.2.2
5498 // The remaining elements are initialized with their default
5499 // member initializers, if any
5500 ExprResult DIE = S.BuildCXXDefaultInitExpr(FD->getLocation(), FD);
5501 if (DIE.isInvalid())
5502 return;
5503 S.checkInitializerLifetime(SubEntity, DIE.get());
5504 InitExprs.push_back(DIE.get());
5505 }
5506 } else {
5507 // C++ [dcl.init]p17.6.2.2
5508 // The remaining elements...otherwise are value initialzed
5509 if (FD->getType()->isReferenceType()) {
5510 Sequence.SetFailed(
5511 InitializationSequence::FK_ParenthesizedListInitFailed);
5512 if (!VerifyOnly) {
5513 SourceRange SR = Kind.getParenOrBraceRange();
5514 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5515 << FD->getType() << SR;
5516 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5517 }
5518 return;
5519 }
5520 InitializationKind SubKind = InitializationKind::CreateValue(
5521 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5522 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5523 return;
5524 }
5525 }
5526 EntityIndexToProcess++;
5527 }
5528 ResultType = Entity.getType();
5529 }
5530
5531 // Not all of the args have been processed, so there must've been more args
5532 // than were required to initialize the element.
5533 if (EntityIndexToProcess < Args.size()) {
5534 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
5535 if (!VerifyOnly) {
5536 QualType T = Entity.getType();
5537 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5538 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5539 Args.back()->getEndLoc());
5540 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5541 << InitKind << ExcessInitSR;
5542 }
5543 return;
5544 }
5545
5546 if (VerifyOnly) {
5547 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
5548 Sequence.AddParenthesizedListInitStep(Entity.getType());
5549 } else if (Result) {
5550 SourceRange SR = Kind.getParenOrBraceRange();
5551 auto *CPLIE = CXXParenListInitExpr::Create(
5552 S.getASTContext(), InitExprs, ResultType, Args.size(),
5553 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5554 if (ArrayFiller)
5555 CPLIE->setArrayFiller(ArrayFiller);
5556 if (InitializedFieldInUnion)
5557 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5558 *Result = CPLIE;
5559 S.Diag(Kind.getLocation(),
5560 diag::warn_cxx17_compat_aggregate_init_paren_list)
5561 << Kind.getLocation() << SR << ResultType;
5562 }
5563
5564 return;
5565}
5566
5567/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5568/// which enumerates all conversion functions and performs overload resolution
5569/// to select the best.
5570static void TryUserDefinedConversion(Sema &S,
5571 QualType DestType,
5572 const InitializationKind &Kind,
5573 Expr *Initializer,
5574 InitializationSequence &Sequence,
5575 bool TopLevelOfInitList) {
5576 assert(!DestType->isReferenceType() && "References are handled elsewhere")(static_cast <bool> (!DestType->isReferenceType() &&
"References are handled elsewhere") ? void (0) : __assert_fail
("!DestType->isReferenceType() && \"References are handled elsewhere\""
, "clang/lib/Sema/SemaInit.cpp", 5576, __extension__ __PRETTY_FUNCTION__
))
;
5577 QualType SourceType = Initializer->getType();
5578 assert((DestType->isRecordType() || SourceType->isRecordType()) &&(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "clang/lib/Sema/SemaInit.cpp", 5579, __extension__ __PRETTY_FUNCTION__
))
5579 "Must have a class type to perform a user-defined conversion")(static_cast <bool> ((DestType->isRecordType() || SourceType
->isRecordType()) && "Must have a class type to perform a user-defined conversion"
) ? void (0) : __assert_fail ("(DestType->isRecordType() || SourceType->isRecordType()) && \"Must have a class type to perform a user-defined conversion\""
, "clang/lib/Sema/SemaInit.cpp", 5579, __extension__ __PRETTY_FUNCTION__
))
;
5580
5581 // Build the candidate set directly in the initialization sequence
5582 // structure, so that it will persist if we fail.
5583 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5584 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5585 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5586
5587 // Determine whether we are allowed to call explicit constructors or
5588 // explicit conversion operators.
5589 bool AllowExplicit = Kind.AllowExplicit();
5590
5591 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5592 // The type we're converting to is a class type. Enumerate its constructors
5593 // to see if there is a suitable conversion.
5594 CXXRecordDecl *DestRecordDecl
5595 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5596
5597 // Try to complete the type we're converting to.
5598 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5599 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5600 auto Info = getConstructorInfo(D);
5601 if (!Info.Constructor)
5602 continue;
5603
5604 if (!Info.Constructor->isInvalidDecl() &&
5605 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5606 if (Info.ConstructorTmpl)
5607 S.AddTemplateOverloadCandidate(
5608 Info.ConstructorTmpl, Info.FoundDecl,
5609 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5610 /*SuppressUserConversions=*/true,
5611 /*PartialOverloading*/ false, AllowExplicit);
5612 else
5613 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5614 Initializer, CandidateSet,
5615 /*SuppressUserConversions=*/true,
5616 /*PartialOverloading*/ false, AllowExplicit);
5617 }
5618 }
5619 }
5620 }
5621
5622 SourceLocation DeclLoc = Initializer->getBeginLoc();
5623
5624 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5625 // The type we're converting from is a class type, enumerate its conversion
5626 // functions.
5627
5628 // We can only enumerate the conversion functions for a complete type; if
5629 // the type isn't complete, simply skip this step.
5630 if (S.isCompleteType(DeclLoc, SourceType)) {
5631 CXXRecordDecl *SourceRecordDecl
5632 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5633
5634 const auto &Conversions =
5635 SourceRecordDecl->getVisibleConversionFunctions();
5636 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5637 NamedDecl *D = *I;
5638 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5639 if (isa<UsingShadowDecl>(D))
5640 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5641
5642 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5643 CXXConversionDecl *Conv;
5644 if (ConvTemplate)
5645 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5646 else
5647 Conv = cast<CXXConversionDecl>(D);
5648
5649 if (ConvTemplate)
5650 S.AddTemplateConversionCandidate(
5651 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5652 CandidateSet, AllowExplicit, AllowExplicit);
5653 else
5654 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5655 DestType, CandidateSet, AllowExplicit,
5656 AllowExplicit);
5657 }
5658 }
5659 }
5660
5661 // Perform overload resolution. If it fails, return the failed result.
5662 OverloadCandidateSet::iterator Best;
5663 if (OverloadingResult Result
5664 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5665 Sequence.SetOverloadFailure(
5666 InitializationSequence::FK_UserConversionOverloadFailed, Result);
5667
5668 // [class.copy.elision]p3:
5669 // In some copy-initialization contexts, a two-stage overload resolution
5670 // is performed.
5671 // If the first overload resolution selects a deleted function, we also
5672 // need the initialization sequence to decide whether to perform the second
5673 // overload resolution.
5674 if (!(Result == OR_Deleted &&
5675 Kind.getKind() == InitializationKind::IK_Copy))
5676 return;
5677 }
5678
5679 FunctionDecl *Function = Best->Function;
5680 Function->setReferenced();
5681 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5682
5683 if (isa<CXXConstructorDecl>(Function)) {
5684 // Add the user-defined conversion step. Any cv-qualification conversion is
5685 // subsumed by the initialization. Per DR5, the created temporary is of the
5686 // cv-unqualified type of the destination.
5687 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5688 DestType.getUnqualifiedType(),
5689 HadMultipleCandidates);
5690
5691 // C++14 and before:
5692 // - if the function is a constructor, the call initializes a temporary
5693 // of the cv-unqualified version of the destination type. The [...]
5694 // temporary [...] is then used to direct-initialize, according to the
5695 // rules above, the object that is the destination of the
5696 // copy-initialization.
5697 // Note that this just performs a simple object copy from the temporary.
5698 //
5699 // C++17:
5700 // - if the function is a constructor, the call is a prvalue of the
5701 // cv-unqualified version of the destination type whose return object
5702 // is initialized by the constructor. The call is used to
5703 // direct-initialize, according to the rules above, the object that
5704 // is the destination of the copy-initialization.
5705 // Therefore we need to do nothing further.
5706 //
5707 // FIXME: Mark this copy as extraneous.
5708 if (!S.getLangOpts().CPlusPlus17)
5709 Sequence.AddFinalCopy(DestType);
5710 else if (DestType.hasQualifiers())
5711 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5712 return;
5713 }
5714
5715 // Add the user-defined conversion step that calls the conversion function.
5716 QualType ConvType = Function->getCallResultType();
5717 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5718 HadMultipleCandidates);
5719
5720 if (ConvType->getAs<RecordType>()) {
5721 // The call is used to direct-initialize [...] the object that is the
5722 // destination of the copy-initialization.
5723 //
5724 // In C++17, this does not call a constructor if we enter /17.6.1:
5725 // - If the initializer expression is a prvalue and the cv-unqualified
5726 // version of the source type is the same as the class of the
5727 // destination [... do not make an extra copy]
5728 //
5729 // FIXME: Mark this copy as extraneous.
5730 if (!S.getLangOpts().CPlusPlus17 ||
5731 Function->getReturnType()->isReferenceType() ||
5732 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5733 Sequence.AddFinalCopy(DestType);
5734 else if (!S.Context.hasSameType(ConvType, DestType))
5735 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5736 return;
5737 }
5738
5739 // If the conversion following the call to the conversion function
5740 // is interesting, add it as a separate step.
5741 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5742 Best->FinalConversion.Third) {
5743 ImplicitConversionSequence ICS;
5744 ICS.setStandard();
5745 ICS.Standard = Best->FinalConversion;
5746 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5747 }
5748}
5749
5750/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5751/// a function with a pointer return type contains a 'return false;' statement.
5752/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5753/// code using that header.
5754///
5755/// Work around this by treating 'return false;' as zero-initializing the result
5756/// if it's used in a pointer-returning function in a system header.
5757static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5758 const InitializedEntity &Entity,
5759 const Expr *Init) {
5760 return S.getLangOpts().CPlusPlus11 &&
5761 Entity.getKind() == InitializedEntity::EK_Result &&
5762 Entity.getType()->isPointerType() &&
5763 isa<CXXBoolLiteralExpr>(Init) &&
5764 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5765 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5766}
5767
5768/// The non-zero enum values here are indexes into diagnostic alternatives.
5769enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5770
5771/// Determines whether this expression is an acceptable ICR source.
5772static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5773 bool isAddressOf, bool &isWeakAccess) {
5774 // Skip parens.
5775 e = e->IgnoreParens();
5776
5777 // Skip address-of nodes.
5778 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5779 if (op->getOpcode() == UO_AddrOf)
5780 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5781 isWeakAccess);
5782
5783 // Skip certain casts.
5784 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5785 switch (ce->getCastKind()) {
5786 case CK_Dependent:
5787 case CK_BitCast:
5788 case CK_LValueBitCast:
5789 case CK_NoOp:
5790 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5791
5792 case CK_ArrayToPointerDecay:
5793 return IIK_nonscalar;
5794
5795 case CK_NullToPointer:
5796 return IIK_okay;
5797
5798 default:
5799 break;
5800 }
5801
5802 // If we have a declaration reference, it had better be a local variable.
5803 } else if (isa<DeclRefExpr>(e)) {
5804 // set isWeakAccess to true, to mean that there will be an implicit
5805 // load which requires a cleanup.
5806 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5807 isWeakAccess = true;
5808
5809 if (!isAddressOf) return IIK_nonlocal;
5810
5811 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5812 if (!var) return IIK_nonlocal;
5813
5814 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5815
5816 // If we have a conditional operator, check both sides.
5817 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5818 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5819 isWeakAccess))
5820 return iik;
5821
5822 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5823
5824 // These are never scalar.
5825 } else if (isa<ArraySubscriptExpr>(e)) {
5826 return IIK_nonscalar;
5827
5828 // Otherwise, it needs to be a null pointer constant.
5829 } else {
5830 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5831 ? IIK_okay : IIK_nonlocal);
5832 }
5833
5834 return IIK_nonlocal;
5835}
5836
5837/// Check whether the given expression is a valid operand for an
5838/// indirect copy/restore.
5839static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5840 assert(src->isPRValue())(static_cast <bool> (src->isPRValue()) ? void (0) : __assert_fail
("src->isPRValue()", "clang/lib/Sema/SemaInit.cpp", 5840,
__extension__ __PRETTY_FUNCTION__))
;
5841 bool isWeakAccess = false;
5842 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5843 // If isWeakAccess to true, there will be an implicit
5844 // load which requires a cleanup.
5845 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5846 S.Cleanup.setExprNeedsCleanups(true);
5847
5848 if (iik == IIK_okay) return;
5849
5850 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5851 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5852 << src->getSourceRange();
5853}
5854
5855/// Determine whether we have compatible array types for the
5856/// purposes of GNU by-copy array initialization.
5857static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5858 const ArrayType *Source) {
5859 // If the source and destination array types are equivalent, we're
5860 // done.
5861 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5862 return true;
5863
5864 // Make sure that the element types are the same.
5865 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5866 return false;
5867
5868 // The only mismatch we allow is when the destination is an
5869 // incomplete array type and the source is a constant array type.
5870 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5871}
5872
5873static bool tryObjCWritebackConversion(Sema &S,
5874 InitializationSequence &Sequence,
5875 const InitializedEntity &Entity,
5876 Expr *Initializer) {
5877 bool ArrayDecay = false;
5878 QualType ArgType = Initializer->getType();
5879 QualType ArgPointee;
5880 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5881 ArrayDecay = true;
5882 ArgPointee = ArgArrayType->getElementType();
5883 ArgType = S.Context.getPointerType(ArgPointee);
5884 }
5885
5886 // Handle write-back conversion.
5887 QualType ConvertedArgType;
5888 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5889 ConvertedArgType))
5890 return false;
5891
5892 // We should copy unless we're passing to an argument explicitly
5893 // marked 'out'.
5894 bool ShouldCopy = true;
5895 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5896 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5897
5898 // Do we need an lvalue conversion?
5899 if (ArrayDecay || Initializer->isGLValue()) {
5900 ImplicitConversionSequence ICS;
5901 ICS.setStandard();
5902 ICS.Standard.setAsIdentityConversion();
5903
5904 QualType ResultType;
5905 if (ArrayDecay) {
5906 ICS.Standard.First = ICK_Array_To_Pointer;
5907 ResultType = S.Context.getPointerType(ArgPointee);
5908 } else {
5909 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5910 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5911 }
5912
5913 Sequence.AddConversionSequenceStep(ICS, ResultType);
5914 }
5915
5916 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5917 return true;
5918}
5919
5920static bool TryOCLSamplerInitialization(Sema &S,
5921 InitializationSequence &Sequence,
5922 QualType DestType,
5923 Expr *Initializer) {
5924 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5925 (!Initializer->isIntegerConstantExpr(S.Context) &&
5926 !Initializer->getType()->isSamplerT()))
5927 return false;
5928
5929 Sequence.AddOCLSamplerInitStep(DestType);
5930 return true;
5931}
5932
5933static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5934 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5935 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5936}
5937
5938static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5939 InitializationSequence &Sequence,
5940 QualType DestType,
5941 Expr *Initializer) {
5942 if (!S.getLangOpts().OpenCL)
5943 return false;
5944
5945 //
5946 // OpenCL 1.2 spec, s6.12.10
5947 //
5948 // The event argument can also be used to associate the
5949 // async_work_group_copy with a previous async copy allowing
5950 // an event to be shared by multiple async copies; otherwise
5951 // event should be zero.
5952 //
5953 if (DestType->isEventT() || DestType->isQueueT()) {
5954 if (!IsZeroInitializer(Initializer, S))
5955 return false;
5956
5957 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5958 return true;
5959 }
5960
5961 // We should allow zero initialization for all types defined in the
5962 // cl_intel_device_side_avc_motion_estimation extension, except
5963 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5964 if (S.getOpenCLOptions().isAvailableOption(
5965 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
5966 DestType->isOCLIntelSubgroupAVCType()) {
5967 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5968 DestType->isOCLIntelSubgroupAVCMceResultType())
5969 return false;
5970 if (!IsZeroInitializer(Initializer, S))
5971 return false;
5972
5973 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5974 return true;
5975 }