Bug Summary

File:clang/lib/Sema/SemaInit.cpp
Warning:line 7011, column 16
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaInit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include -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-13/lib/clang/13.0.0/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 -O2 -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema/SemaInit.cpp

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