Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp

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