Bug Summary

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