Bug Summary

File:clang/lib/Sema/SemaInit.cpp
Warning:line 6944, 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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac=. -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 -o /tmp/scan-build-2020-11-24-172238-38865-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/Sema/SemaInit.cpp

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