Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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