Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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-17/lib/clang/17 -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 _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -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-17/lib/clang/17/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/= -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-2023-05-10-133810-16478-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/EnterExpressionEvaluationContext.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/PointerIntPair.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// Sema Initialization Checking
37//===----------------------------------------------------------------------===//
38
39/// Check whether T is compatible with a wide character type (wchar_t,
40/// char16_t or char32_t).
41static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
42 if (Context.typesAreCompatible(Context.getWideCharType(), T))
43 return true;
44 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
45 return Context.typesAreCompatible(Context.Char16Ty, T) ||
46 Context.typesAreCompatible(Context.Char32Ty, T);
47 }
48 return false;
49}
50
51enum StringInitFailureKind {
52 SIF_None,
53 SIF_NarrowStringIntoWideChar,
54 SIF_WideStringIntoChar,
55 SIF_IncompatWideStringIntoWideChar,
56 SIF_UTF8StringIntoPlainChar,
57 SIF_PlainStringIntoUTF8Char,
58 SIF_Other
59};
60
61/// Check whether the array of type AT can be initialized by the Init
62/// expression by means of string initialization. Returns SIF_None if so,
63/// otherwise returns a StringInitFailureKind that describes why the
64/// initialization would not work.
65static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
66 ASTContext &Context) {
67 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
68 return SIF_Other;
69
70 // See if this is a string literal or @encode.
71 Init = Init->IgnoreParens();
72
73 // Handle @encode, which is a narrow string.
74 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
75 return SIF_None;
76
77 // Otherwise we can only handle string literals.
78 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
79 if (!SL)
80 return SIF_Other;
81
82 const QualType ElemTy =
83 Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
84
85 auto IsCharOrUnsignedChar = [](const QualType &T) {
86 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
87 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
88 };
89
90 switch (SL->getKind()) {
91 case StringLiteral::UTF8:
92 // char8_t array can be initialized with a UTF-8 string.
93 // - C++20 [dcl.init.string] (DR)
94 // Additionally, an array of char or unsigned char may be initialized
95 // by a UTF-8 string literal.
96 if (ElemTy->isChar8Type() ||
97 (Context.getLangOpts().Char8 &&
98 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
99 return SIF_None;
100 [[fallthrough]];
101 case StringLiteral::Ordinary:
102 // char array can be initialized with a narrow string.
103 // Only allow char x[] = "foo"; not char x[] = L"foo";
104 if (ElemTy->isCharType())
105 return (SL->getKind() == StringLiteral::UTF8 &&
106 Context.getLangOpts().Char8)
107 ? SIF_UTF8StringIntoPlainChar
108 : SIF_None;
109 if (ElemTy->isChar8Type())
110 return SIF_PlainStringIntoUTF8Char;
111 if (IsWideCharCompatible(ElemTy, Context))
112 return SIF_NarrowStringIntoWideChar;
113 return SIF_Other;
114 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
115 // "An array with element type compatible with a qualified or unqualified
116 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
117 // string literal with the corresponding encoding prefix (L, u, or U,
118 // respectively), optionally enclosed in braces.
119 case StringLiteral::UTF16:
120 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
121 return SIF_None;
122 if (ElemTy->isCharType() || ElemTy->isChar8Type())
123 return SIF_WideStringIntoChar;
124 if (IsWideCharCompatible(ElemTy, Context))
125 return SIF_IncompatWideStringIntoWideChar;
126 return SIF_Other;
127 case StringLiteral::UTF32:
128 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
129 return SIF_None;
130 if (ElemTy->isCharType() || ElemTy->isChar8Type())
131 return SIF_WideStringIntoChar;
132 if (IsWideCharCompatible(ElemTy, Context))
133 return SIF_IncompatWideStringIntoWideChar;
134 return SIF_Other;
135 case StringLiteral::Wide:
136 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
137 return SIF_None;
138 if (ElemTy->isCharType() || ElemTy->isChar8Type())
139 return SIF_WideStringIntoChar;
140 if (IsWideCharCompatible(ElemTy, Context))
141 return SIF_IncompatWideStringIntoWideChar;
142 return SIF_Other;
143 }
144
145 llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?"
, "clang/lib/Sema/SemaInit.cpp", 145)
;
146}
147
148static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
149 ASTContext &Context) {
150 const ArrayType *arrayType = Context.getAsArrayType(declType);
151 if (!arrayType)
152 return SIF_Other;
153 return IsStringInit(init, arrayType, Context);
154}
155
156bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
157 return ::IsStringInit(Init, AT, Context) == SIF_None;
158}
159
160/// Update the type of a string literal, including any surrounding parentheses,
161/// to match the type of the object which it is initializing.
162static void updateStringLiteralType(Expr *E, QualType Ty) {
163 while (true) {
164 E->setType(Ty);
165 E->setValueKind(VK_PRValue);
166 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) {
167 break;
168 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
169 E = PE->getSubExpr();
170 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
171 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", 171, __extension__ __PRETTY_FUNCTION__
))
;
172 E = UO->getSubExpr();
173 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
174 E = GSE->getResultExpr();
175 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
176 E = CE->getChosenSubExpr();
177 } else {
178 llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init"
, "clang/lib/Sema/SemaInit.cpp", 178)
;
179 }
180 }
181}
182
183/// Fix a compound literal initializing an array so it's correctly marked
184/// as an rvalue.
185static void updateGNUCompoundLiteralRValue(Expr *E) {
186 while (true) {
187 E->setValueKind(VK_PRValue);
188 if (isa<CompoundLiteralExpr>(E)) {
189 break;
190 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
191 E = PE->getSubExpr();
192 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
193 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", 193, __extension__ __PRETTY_FUNCTION__
))
;
194 E = UO->getSubExpr();
195 } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
196 E = GSE->getResultExpr();
197 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
198 E = CE->getChosenSubExpr();
199 } else {
200 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", 200)
;
201 }
202 }
203}
204
205static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
206 Sema &S) {
207 // Get the length of the string as parsed.
208 auto *ConstantArrayTy =
209 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
210 uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
211
212 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
213 // C99 6.7.8p14. We have an array of character type with unknown size
214 // being initialized to a string literal.
215 llvm::APInt ConstVal(32, StrLength);
216 // Return a new array type (C99 6.7.8p22).
217 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
218 ConstVal, nullptr,
219 ArrayType::Normal, 0);
220 updateStringLiteralType(Str, DeclT);
221 return;
222 }
223
224 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
225
226 // We have an array of character type with known size. However,
227 // the size may be smaller or larger than the string we are initializing.
228 // FIXME: Avoid truncation for 64-bit length strings.
229 if (S.getLangOpts().CPlusPlus) {
230 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
231 // For Pascal strings it's OK to strip off the terminating null character,
232 // so the example below is valid:
233 //
234 // unsigned char a[2] = "\pa";
235 if (SL->isPascal())
236 StrLength--;
237 }
238
239 // [dcl.init.string]p2
240 if (StrLength > CAT->getSize().getZExtValue())
241 S.Diag(Str->getBeginLoc(),
242 diag::err_initializer_string_for_char_array_too_long)
243 << CAT->getSize().getZExtValue() << StrLength
244 << Str->getSourceRange();
245 } else {
246 // C99 6.7.8p14.
247 if (StrLength-1 > CAT->getSize().getZExtValue())
248 S.Diag(Str->getBeginLoc(),
249 diag::ext_initializer_string_for_char_array_too_long)
250 << Str->getSourceRange();
251 }
252
253 // Set the type to the actual size that we are initializing. If we have
254 // something like:
255 // char x[1] = "foo";
256 // then this will set the string literal's type to char[1].
257 updateStringLiteralType(Str, DeclT);
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic checking for initializer lists.
262//===----------------------------------------------------------------------===//
263
264namespace {
265
266/// Semantic checking for initializer lists.
267///
268/// The InitListChecker class contains a set of routines that each
269/// handle the initialization of a certain kind of entity, e.g.,
270/// arrays, vectors, struct/union types, scalars, etc. The
271/// InitListChecker itself performs a recursive walk of the subobject
272/// structure of the type to be initialized, while stepping through
273/// the initializer list one element at a time. The IList and Index
274/// parameters to each of the Check* routines contain the active
275/// (syntactic) initializer list and the index into that initializer
276/// list that represents the current initializer. Each routine is
277/// responsible for moving that Index forward as it consumes elements.
278///
279/// Each Check* routine also has a StructuredList/StructuredIndex
280/// arguments, which contains the current "structured" (semantic)
281/// initializer list and the index into that initializer list where we
282/// are copying initializers as we map them over to the semantic
283/// list. Once we have completed our recursive walk of the subobject
284/// structure, we will have constructed a full semantic initializer
285/// list.
286///
287/// C99 designators cause changes in the initializer list traversal,
288/// because they make the initialization "jump" into a specific
289/// subobject and then continue the initialization from that
290/// point. CheckDesignatedInitializer() recursively steps into the
291/// designated subobject and manages backing out the recursion to
292/// initialize the subobjects after the one designated.
293///
294/// If an initializer list contains any designators, we build a placeholder
295/// structured list even in 'verify only' mode, so that we can track which
296/// elements need 'empty' initializtion.
297class InitListChecker {
298 Sema &SemaRef;
299 bool hadError = false;
300 bool VerifyOnly; // No diagnostics.
301 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
302 bool InOverloadResolution;
303 InitListExpr *FullyStructuredList = nullptr;
304 NoInitExpr *DummyExpr = nullptr;
305
306 NoInitExpr *getDummyInit() {
307 if (!DummyExpr)
308 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
309 return DummyExpr;
310 }
311
312 void CheckImplicitInitList(const InitializedEntity &Entity,
313 InitListExpr *ParentIList, QualType T,
314 unsigned &Index, InitListExpr *StructuredList,
315 unsigned &StructuredIndex);
316 void CheckExplicitInitList(const InitializedEntity &Entity,
317 InitListExpr *IList, QualType &T,
318 InitListExpr *StructuredList,
319 bool TopLevelObject = false);
320 void CheckListElementTypes(const InitializedEntity &Entity,
321 InitListExpr *IList, QualType &DeclType,
322 bool SubobjectIsDesignatorContext,
323 unsigned &Index,
324 InitListExpr *StructuredList,
325 unsigned &StructuredIndex,
326 bool TopLevelObject = false);
327 void CheckSubElementType(const InitializedEntity &Entity,
328 InitListExpr *IList, QualType ElemType,
329 unsigned &Index,
330 InitListExpr *StructuredList,
331 unsigned &StructuredIndex,
332 bool DirectlyDesignated = false);
333 void CheckComplexType(const InitializedEntity &Entity,
334 InitListExpr *IList, QualType DeclType,
335 unsigned &Index,
336 InitListExpr *StructuredList,
337 unsigned &StructuredIndex);
338 void CheckScalarType(const InitializedEntity &Entity,
339 InitListExpr *IList, QualType DeclType,
340 unsigned &Index,
341 InitListExpr *StructuredList,
342 unsigned &StructuredIndex);
343 void CheckReferenceType(const InitializedEntity &Entity,
344 InitListExpr *IList, QualType DeclType,
345 unsigned &Index,
346 InitListExpr *StructuredList,
347 unsigned &StructuredIndex);
348 void CheckVectorType(const InitializedEntity &Entity,
349 InitListExpr *IList, QualType DeclType, unsigned &Index,
350 InitListExpr *StructuredList,
351 unsigned &StructuredIndex);
352 void CheckStructUnionTypes(const InitializedEntity &Entity,
353 InitListExpr *IList, QualType DeclType,
354 CXXRecordDecl::base_class_range Bases,
355 RecordDecl::field_iterator Field,
356 bool SubobjectIsDesignatorContext, unsigned &Index,
357 InitListExpr *StructuredList,
358 unsigned &StructuredIndex,
359 bool TopLevelObject = false);
360 void CheckArrayType(const InitializedEntity &Entity,
361 InitListExpr *IList, QualType &DeclType,
362 llvm::APSInt elementIndex,
363 bool SubobjectIsDesignatorContext, unsigned &Index,
364 InitListExpr *StructuredList,
365 unsigned &StructuredIndex);
366 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
367 InitListExpr *IList, DesignatedInitExpr *DIE,
368 unsigned DesigIdx,
369 QualType &CurrentObjectType,
370 RecordDecl::field_iterator *NextField,
371 llvm::APSInt *NextElementIndex,
372 unsigned &Index,
373 InitListExpr *StructuredList,
374 unsigned &StructuredIndex,
375 bool FinishSubobjectInit,
376 bool TopLevelObject);
377 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
378 QualType CurrentObjectType,
379 InitListExpr *StructuredList,
380 unsigned StructuredIndex,
381 SourceRange InitRange,
382 bool IsFullyOverwritten = false);
383 void UpdateStructuredListElement(InitListExpr *StructuredList,
384 unsigned &StructuredIndex,
385 Expr *expr);
386 InitListExpr *createInitListExpr(QualType CurrentObjectType,
387 SourceRange InitRange,
388 unsigned ExpectedNumInits);
389 int numArrayElements(QualType DeclType);
390 int numStructUnionElements(QualType DeclType);
391
392 ExprResult PerformEmptyInit(SourceLocation Loc,
393 const InitializedEntity &Entity);
394
395 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
396 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
397 bool UnionOverride = false,
398 bool FullyOverwritten = true) {
399 // Overriding an initializer via a designator is valid with C99 designated
400 // initializers, but ill-formed with C++20 designated initializers.
401 unsigned DiagID =
402 SemaRef.getLangOpts().CPlusPlus
403 ? (UnionOverride ? diag::ext_initializer_union_overrides
404 : diag::ext_initializer_overrides)
405 : diag::warn_initializer_overrides;
406
407 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
408 // In overload resolution, we have to strictly enforce the rules, and so
409 // don't allow any overriding of prior initializers. This matters for a
410 // case such as:
411 //
412 // union U { int a, b; };
413 // struct S { int a, b; };
414 // void f(U), f(S);
415 //
416 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
417 // consistency, we disallow all overriding of prior initializers in
418 // overload resolution, not only overriding of union members.
419 hadError = true;
420 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
421 // If we'll be keeping around the old initializer but overwriting part of
422 // the object it initialized, and that object is not trivially
423 // destructible, this can leak. Don't allow that, not even as an
424 // extension.
425 //
426 // FIXME: It might be reasonable to allow this in cases where the part of
427 // the initializer that we're overriding has trivial destruction.
428 DiagID = diag::err_initializer_overrides_destructed;
429 } else if (!OldInit->getSourceRange().isValid()) {
430 // We need to check on source range validity because the previous
431 // initializer does not have to be an explicit initializer. e.g.,
432 //
433 // struct P { int a, b; };
434 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
435 //
436 // There is an overwrite taking place because the first braced initializer
437 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
438 //
439 // Such overwrites are harmless, so we don't diagnose them. (Note that in
440 // C++, this cannot be reached unless we've already seen and diagnosed a
441 // different conformance issue, such as a mixture of designated and
442 // non-designated initializers or a multi-level designator.)
443 return;
444 }
445
446 if (!VerifyOnly) {
447 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
448 << NewInitRange << FullyOverwritten << OldInit->getType();
449 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
450 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
451 << OldInit->getSourceRange();
452 }
453 }
454
455 // Explanation on the "FillWithNoInit" mode:
456 //
457 // Assume we have the following definitions (Case#1):
458 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
459 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
460 //
461 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
462 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
463 //
464 // But if we have (Case#2):
465 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
466 //
467 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
468 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
469 //
470 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
471 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
472 // initializers but with special "NoInitExpr" place holders, which tells the
473 // CodeGen not to generate any initializers for these parts.
474 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
475 const InitializedEntity &ParentEntity,
476 InitListExpr *ILE, bool &RequiresSecondPass,
477 bool FillWithNoInit);
478 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
479 const InitializedEntity &ParentEntity,
480 InitListExpr *ILE, bool &RequiresSecondPass,
481 bool FillWithNoInit = false);
482 void FillInEmptyInitializations(const InitializedEntity &Entity,
483 InitListExpr *ILE, bool &RequiresSecondPass,
484 InitListExpr *OuterILE, unsigned OuterIndex,
485 bool FillWithNoInit = false);
486 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
487 Expr *InitExpr, FieldDecl *Field,
488 bool TopLevelObject);
489 void CheckEmptyInitializable(const InitializedEntity &Entity,
490 SourceLocation Loc);
491
492public:
493 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
494 QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
495 bool InOverloadResolution = false);
496 bool HadError() { return hadError; }
497
498 // Retrieves the fully-structured initializer list used for
499 // semantic analysis and code generation.
500 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
501};
502
503} // end anonymous namespace
504
505ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
506 const InitializedEntity &Entity) {
507 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
508 true);
509 MultiExprArg SubInit;
510 Expr *InitExpr;
511 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
512
513 // C++ [dcl.init.aggr]p7:
514 // If there are fewer initializer-clauses in the list than there are
515 // members in the aggregate, then each member not explicitly initialized
516 // ...
517 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
518 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
519 if (EmptyInitList) {
520 // C++1y / DR1070:
521 // shall be initialized [...] from an empty initializer list.
522 //
523 // We apply the resolution of this DR to C++11 but not C++98, since C++98
524 // does not have useful semantics for initialization from an init list.
525 // We treat this as copy-initialization, because aggregate initialization
526 // always performs copy-initialization on its elements.
527 //
528 // Only do this if we're initializing a class type, to avoid filling in
529 // the initializer list where possible.
530 InitExpr = VerifyOnly
531 ? &DummyInitList
532 : new (SemaRef.Context)
533 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
534 InitExpr->setType(SemaRef.Context.VoidTy);
535 SubInit = InitExpr;
536 Kind = InitializationKind::CreateCopy(Loc, Loc);
537 } else {
538 // C++03:
539 // shall be value-initialized.
540 }
541
542 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
543 // libstdc++4.6 marks the vector default constructor as explicit in
544 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
545 // stlport does so too. Look for std::__debug for libstdc++, and for
546 // std:: for stlport. This is effectively a compiler-side implementation of
547 // LWG2193.
548 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
549 InitializationSequence::FK_ExplicitConstructor) {
550 OverloadCandidateSet::iterator Best;
551 OverloadingResult O =
552 InitSeq.getFailedCandidateSet()
553 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
554 (void)O;
555 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", 555, __extension__ __PRETTY_FUNCTION__
))
;
556 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
557 CXXRecordDecl *R = CtorDecl->getParent();
558
559 if (CtorDecl->getMinRequiredArguments() == 0 &&
560 CtorDecl->isExplicit() && R->getDeclName() &&
561 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
562 bool IsInStd = false;
563 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
564 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
565 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
566 IsInStd = true;
567 }
568
569 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
570 .Cases("basic_string", "deque", "forward_list", true)
571 .Cases("list", "map", "multimap", "multiset", true)
572 .Cases("priority_queue", "queue", "set", "stack", true)
573 .Cases("unordered_map", "unordered_set", "vector", true)
574 .Default(false)) {
575 InitSeq.InitializeFrom(
576 SemaRef, Entity,
577 InitializationKind::CreateValue(Loc, Loc, Loc, true),
578 MultiExprArg(), /*TopLevelOfInitList=*/false,
579 TreatUnavailableAsInvalid);
580 // Emit a warning for this. System header warnings aren't shown
581 // by default, but people working on system headers should see it.
582 if (!VerifyOnly) {
583 SemaRef.Diag(CtorDecl->getLocation(),
584 diag::warn_invalid_initializer_from_system_header);
585 if (Entity.getKind() == InitializedEntity::EK_Member)
586 SemaRef.Diag(Entity.getDecl()->getLocation(),
587 diag::note_used_in_initialization_here);
588 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
589 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
590 }
591 }
592 }
593 }
594 if (!InitSeq) {
595 if (!VerifyOnly) {
596 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
597 if (Entity.getKind() == InitializedEntity::EK_Member)
598 SemaRef.Diag(Entity.getDecl()->getLocation(),
599 diag::note_in_omitted_aggregate_initializer)
600 << /*field*/1 << Entity.getDecl();
601 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
602 bool IsTrailingArrayNewMember =
603 Entity.getParent() &&
604 Entity.getParent()->isVariableLengthArrayNew();
605 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
606 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
607 << Entity.getElementIndex();
608 }
609 }
610 hadError = true;
611 return ExprError();
612 }
613
614 return VerifyOnly ? ExprResult()
615 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
616}
617
618void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
619 SourceLocation Loc) {
620 // If we're building a fully-structured list, we'll check this at the end
621 // once we know which elements are actually initialized. Otherwise, we know
622 // that there are no designators so we can just check now.
623 if (FullyStructuredList)
624 return;
625 PerformEmptyInit(Loc, Entity);
626}
627
628void InitListChecker::FillInEmptyInitForBase(
629 unsigned Init, const CXXBaseSpecifier &Base,
630 const InitializedEntity &ParentEntity, InitListExpr *ILE,
631 bool &RequiresSecondPass, bool FillWithNoInit) {
632 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
633 SemaRef.Context, &Base, false, &ParentEntity);
634
635 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
636 ExprResult BaseInit = FillWithNoInit
637 ? new (SemaRef.Context) NoInitExpr(Base.getType())
638 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
639 if (BaseInit.isInvalid()) {
640 hadError = true;
641 return;
642 }
643
644 if (!VerifyOnly) {
645 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", 645, __extension__ __PRETTY_FUNCTION__
))
;
646 ILE->setInit(Init, BaseInit.getAs<Expr>());
647 }
648 } else if (InitListExpr *InnerILE =
649 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
650 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
651 ILE, Init, FillWithNoInit);
652 } else if (DesignatedInitUpdateExpr *InnerDIUE =
653 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
654 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
655 RequiresSecondPass, ILE, Init,
656 /*FillWithNoInit =*/true);
657 }
658}
659
660void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
661 const InitializedEntity &ParentEntity,
662 InitListExpr *ILE,
663 bool &RequiresSecondPass,
664 bool FillWithNoInit) {
665 SourceLocation Loc = ILE->getEndLoc();
666 unsigned NumInits = ILE->getNumInits();
667 InitializedEntity MemberEntity
668 = InitializedEntity::InitializeMember(Field, &ParentEntity);
669
670 if (Init >= NumInits || !ILE->getInit(Init)) {
671 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
672 if (!RType->getDecl()->isUnion())
673 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", 674, __extension__ __PRETTY_FUNCTION__
))
674 "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", 674, __extension__ __PRETTY_FUNCTION__
))
;
675
676 if (FillWithNoInit) {
677 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", 677, __extension__ __PRETTY_FUNCTION__
))
;
678 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
679 if (Init < NumInits)
680 ILE->setInit(Init, Filler);
681 else
682 ILE->updateInit(SemaRef.Context, Init, Filler);
683 return;
684 }
685 // C++1y [dcl.init.aggr]p7:
686 // If there are fewer initializer-clauses in the list than there are
687 // members in the aggregate, then each member not explicitly initialized
688 // shall be initialized from its brace-or-equal-initializer [...]
689 if (Field->hasInClassInitializer()) {
690 if (VerifyOnly)
691 return;
692
693 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
694 if (DIE.isInvalid()) {
695 hadError = true;
696 return;
697 }
698 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
699 if (Init < NumInits)
700 ILE->setInit(Init, DIE.get());
701 else {
702 ILE->updateInit(SemaRef.Context, Init, DIE.get());
703 RequiresSecondPass = true;
704 }
705 return;
706 }
707
708 if (Field->getType()->isReferenceType()) {
709 if (!VerifyOnly) {
710 // C++ [dcl.init.aggr]p9:
711 // If an incomplete or empty initializer-list leaves a
712 // member of reference type uninitialized, the program is
713 // ill-formed.
714 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
715 << Field->getType()
716 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
717 ->getSourceRange();
718 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
719 }
720 hadError = true;
721 return;
722 }
723
724 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
725 if (MemberInit.isInvalid()) {
726 hadError = true;
727 return;
728 }
729
730 if (hadError || VerifyOnly) {
731 // Do nothing
732 } else if (Init < NumInits) {
733 ILE->setInit(Init, MemberInit.getAs<Expr>());
734 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
735 // Empty initialization requires a constructor call, so
736 // extend the initializer list to include the constructor
737 // call and make a note that we'll need to take another pass
738 // through the initializer list.
739 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
740 RequiresSecondPass = true;
741 }
742 } else if (InitListExpr *InnerILE
743 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
744 FillInEmptyInitializations(MemberEntity, InnerILE,
745 RequiresSecondPass, ILE, Init, FillWithNoInit);
746 } else if (DesignatedInitUpdateExpr *InnerDIUE =
747 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
748 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
749 RequiresSecondPass, ILE, Init,
750 /*FillWithNoInit =*/true);
751 }
752}
753
754/// Recursively replaces NULL values within the given initializer list
755/// with expressions that perform value-initialization of the
756/// appropriate type, and finish off the InitListExpr formation.
757void
758InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
759 InitListExpr *ILE,
760 bool &RequiresSecondPass,
761 InitListExpr *OuterILE,
762 unsigned OuterIndex,
763 bool FillWithNoInit) {
764 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", 765, __extension__ __PRETTY_FUNCTION__
))
765 "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", 765, __extension__ __PRETTY_FUNCTION__
))
;
766
767 // We don't need to do any checks when just filling NoInitExprs; that can't
768 // fail.
769 if (FillWithNoInit && VerifyOnly)
770 return;
771
772 // If this is a nested initializer list, we might have changed its contents
773 // (and therefore some of its properties, such as instantiation-dependence)
774 // while filling it in. Inform the outer initializer list so that its state
775 // can be updated to match.
776 // FIXME: We should fully build the inner initializers before constructing
777 // the outer InitListExpr instead of mutating AST nodes after they have
778 // been used as subexpressions of other nodes.
779 struct UpdateOuterILEWithUpdatedInit {
780 InitListExpr *Outer;
781 unsigned OuterIndex;
782 ~UpdateOuterILEWithUpdatedInit() {
783 if (Outer)
784 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
785 }
786 } UpdateOuterRAII = {OuterILE, OuterIndex};
787
788 // A transparent ILE is not performing aggregate initialization and should
789 // not be filled in.
790 if (ILE->isTransparent())
791 return;
792
793 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
794 const RecordDecl *RDecl = RType->getDecl();
795 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
796 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
797 Entity, ILE, RequiresSecondPass, FillWithNoInit);
798 else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
799 cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
800 for (auto *Field : RDecl->fields()) {
801 if (Field->hasInClassInitializer()) {
802 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
803 FillWithNoInit);
804 break;
805 }
806 }
807 } else {
808 // The fields beyond ILE->getNumInits() are default initialized, so in
809 // order to leave them uninitialized, the ILE is expanded and the extra
810 // fields are then filled with NoInitExpr.
811 unsigned NumElems = numStructUnionElements(ILE->getType());
812 if (RDecl->hasFlexibleArrayMember())
813 ++NumElems;
814 if (!VerifyOnly && ILE->getNumInits() < NumElems)
815 ILE->resizeInits(SemaRef.Context, NumElems);
816
817 unsigned Init = 0;
818
819 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
820 for (auto &Base : CXXRD->bases()) {
821 if (hadError)
822 return;
823
824 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
825 FillWithNoInit);
826 ++Init;
827 }
828 }
829
830 for (auto *Field : RDecl->fields()) {
831 if (Field->isUnnamedBitfield())
832 continue;
833
834 if (hadError)
835 return;
836
837 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
838 FillWithNoInit);
839 if (hadError)
840 return;
841
842 ++Init;
843
844 // Only look at the first initialization of a union.
845 if (RDecl->isUnion())
846 break;
847 }
848 }
849
850 return;
851 }
852
853 QualType ElementType;
854
855 InitializedEntity ElementEntity = Entity;
856 unsigned NumInits = ILE->getNumInits();
857 unsigned NumElements = NumInits;
858 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
859 ElementType = AType->getElementType();
860 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
861 NumElements = CAType->getSize().getZExtValue();
862 // For an array new with an unknown bound, ask for one additional element
863 // in order to populate the array filler.
864 if (Entity.isVariableLengthArrayNew())
865 ++NumElements;
866 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
867 0, Entity);
868 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
869 ElementType = VType->getElementType();
870 NumElements = VType->getNumElements();
871 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
872 0, Entity);
873 } else
874 ElementType = ILE->getType();
875
876 bool SkipEmptyInitChecks = false;
877 for (unsigned Init = 0; Init != NumElements; ++Init) {
878 if (hadError)
879 return;
880
881 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
882 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
883 ElementEntity.setElementIndex(Init);
884
885 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
886 return;
887
888 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
889 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
890 ILE->setInit(Init, ILE->getArrayFiller());
891 else if (!InitExpr && !ILE->hasArrayFiller()) {
892 // In VerifyOnly mode, there's no point performing empty initialization
893 // more than once.
894 if (SkipEmptyInitChecks)
895 continue;
896
897 Expr *Filler = nullptr;
898
899 if (FillWithNoInit)
900 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
901 else {
902 ExprResult ElementInit =
903 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
904 if (ElementInit.isInvalid()) {
905 hadError = true;
906 return;
907 }
908
909 Filler = ElementInit.getAs<Expr>();
910 }
911
912 if (hadError) {
913 // Do nothing
914 } else if (VerifyOnly) {
915 SkipEmptyInitChecks = true;
916 } else if (Init < NumInits) {
917 // For arrays, just set the expression used for value-initialization
918 // of the "holes" in the array.
919 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
920 ILE->setArrayFiller(Filler);
921 else
922 ILE->setInit(Init, Filler);
923 } else {
924 // For arrays, just set the expression used for value-initialization
925 // of the rest of elements and exit.
926 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
927 ILE->setArrayFiller(Filler);
928 return;
929 }
930
931 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
932 // Empty initialization requires a constructor call, so
933 // extend the initializer list to include the constructor
934 // call and make a note that we'll need to take another pass
935 // through the initializer list.
936 ILE->updateInit(SemaRef.Context, Init, Filler);
937 RequiresSecondPass = true;
938 }
939 }
940 } else if (InitListExpr *InnerILE
941 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
942 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
943 ILE, Init, FillWithNoInit);
944 } else if (DesignatedInitUpdateExpr *InnerDIUE =
945 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
946 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
947 RequiresSecondPass, ILE, Init,
948 /*FillWithNoInit =*/true);
949 }
950 }
951}
952
953static bool hasAnyDesignatedInits(const InitListExpr *IL) {
954 for (const Stmt *Init : *IL)
955 if (Init && isa<DesignatedInitExpr>(Init))
956 return true;
957 return false;
958}
959
960InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
961 InitListExpr *IL, QualType &T, bool VerifyOnly,
962 bool TreatUnavailableAsInvalid,
963 bool InOverloadResolution)
964 : SemaRef(S), VerifyOnly(VerifyOnly),
965 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
966 InOverloadResolution(InOverloadResolution) {
967 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
968 FullyStructuredList =
969 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
970
971 // FIXME: Check that IL isn't already the semantic form of some other
972 // InitListExpr. If it is, we'd create a broken AST.
973 if (!VerifyOnly)
974 FullyStructuredList->setSyntacticForm(IL);
975 }
976
977 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
978 /*TopLevelObject=*/true);
979
980 if (!hadError && FullyStructuredList) {
981 bool RequiresSecondPass = false;
982 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
983 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
984 if (RequiresSecondPass && !hadError)
985 FillInEmptyInitializations(Entity, FullyStructuredList,
986 RequiresSecondPass, nullptr, 0);
987 }
988 if (hadError && FullyStructuredList)
989 FullyStructuredList->markError();
990}
991
992int InitListChecker::numArrayElements(QualType DeclType) {
993 // FIXME: use a proper constant
994 int maxElements = 0x7FFFFFFF;
995 if (const ConstantArrayType *CAT =
996 SemaRef.Context.getAsConstantArrayType(DeclType)) {
997 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
998 }
999 return maxElements;
1000}
1001
1002int InitListChecker::numStructUnionElements(QualType DeclType) {
1003 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1004 int InitializableMembers = 0;
1005 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1006 InitializableMembers += CXXRD->getNumBases();
1007 for (const auto *Field : structDecl->fields())
1008 if (!Field->isUnnamedBitfield())
1009 ++InitializableMembers;
1010
1011 if (structDecl->isUnion())
1012 return std::min(InitializableMembers, 1);
1013 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1014}
1015
1016/// Determine whether Entity is an entity for which it is idiomatic to elide
1017/// the braces in aggregate initialization.
1018static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1019 // Recursive initialization of the one and only field within an aggregate
1020 // class is considered idiomatic. This case arises in particular for
1021 // initialization of std::array, where the C++ standard suggests the idiom of
1022 //
1023 // std::array<T, N> arr = {1, 2, 3};
1024 //
1025 // (where std::array is an aggregate struct containing a single array field.
1026
1027 if (!Entity.getParent())
1028 return false;
1029
1030 // Allows elide brace initialization for aggregates with empty base.
1031 if (Entity.getKind() == InitializedEntity::EK_Base) {
1032 auto *ParentRD =
1033 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1034 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1035 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1036 }
1037
1038 // Allow brace elision if the only subobject is a field.
1039 if (Entity.getKind() == InitializedEntity::EK_Member) {
1040 auto *ParentRD =
1041 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1042 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1043 if (CXXRD->getNumBases()) {
1044 return false;
1045 }
1046 }
1047 auto FieldIt = ParentRD->field_begin();
1048 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", 1049, __extension__ __PRETTY_FUNCTION__
))
1049 "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", 1049, __extension__ __PRETTY_FUNCTION__
))
;
1050 return ++FieldIt == ParentRD->field_end();
1051 }
1052
1053 return false;
1054}
1055
1056/// Check whether the range of the initializer \p ParentIList from element
1057/// \p Index onwards can be used to initialize an object of type \p T. Update
1058/// \p Index to indicate how many elements of the list were consumed.
1059///
1060/// This also fills in \p StructuredList, from element \p StructuredIndex
1061/// onwards, with the fully-braced, desugared form of the initialization.
1062void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1063 InitListExpr *ParentIList,
1064 QualType T, unsigned &Index,
1065 InitListExpr *StructuredList,
1066 unsigned &StructuredIndex) {
1067 int maxElements = 0;
1068
1069 if (T->isArrayType())
1070 maxElements = numArrayElements(T);
1071 else if (T->isRecordType())
1072 maxElements = numStructUnionElements(T);
1073 else if (T->isVectorType())
1074 maxElements = T->castAs<VectorType>()->getNumElements();
1075 else
1076 llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type"
, "clang/lib/Sema/SemaInit.cpp", 1076)
;
1077
1078 if (maxElements == 0) {
1079 if (!VerifyOnly)
1080 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1081 diag::err_implicit_empty_initializer);
1082 ++Index;
1083 hadError = true;
1084 return;
1085 }
1086
1087 // Build a structured initializer list corresponding to this subobject.
1088 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1089 ParentIList, Index, T, StructuredList, StructuredIndex,
1090 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1091 ParentIList->getSourceRange().getEnd()));
1092 unsigned StructuredSubobjectInitIndex = 0;
1093
1094 // Check the element types and build the structural subobject.
1095 unsigned StartIndex = Index;
1096 CheckListElementTypes(Entity, ParentIList, T,
1097 /*SubobjectIsDesignatorContext=*/false, Index,
1098 StructuredSubobjectInitList,
1099 StructuredSubobjectInitIndex);
1100
1101 if (StructuredSubobjectInitList) {
1102 StructuredSubobjectInitList->setType(T);
1103
1104 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1105 // Update the structured sub-object initializer so that it's ending
1106 // range corresponds with the end of the last initializer it used.
1107 if (EndIndex < ParentIList->getNumInits() &&
1108 ParentIList->getInit(EndIndex)) {
1109 SourceLocation EndLoc
1110 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1111 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1112 }
1113
1114 // Complain about missing braces.
1115 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1116 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1117 !isIdiomaticBraceElisionEntity(Entity)) {
1118 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1119 diag::warn_missing_braces)
1120 << StructuredSubobjectInitList->getSourceRange()
1121 << FixItHint::CreateInsertion(
1122 StructuredSubobjectInitList->getBeginLoc(), "{")
1123 << FixItHint::CreateInsertion(
1124 SemaRef.getLocForEndOfToken(
1125 StructuredSubobjectInitList->getEndLoc()),
1126 "}");
1127 }
1128
1129 // Warn if this type won't be an aggregate in future versions of C++.
1130 auto *CXXRD = T->getAsCXXRecordDecl();
1131 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1132 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1133 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1134 << StructuredSubobjectInitList->getSourceRange() << T;
1135 }
1136 }
1137}
1138
1139/// Warn that \p Entity was of scalar type and was initialized by a
1140/// single-element braced initializer list.
1141static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1142 SourceRange Braces) {
1143 // Don't warn during template instantiation. If the initialization was
1144 // non-dependent, we warned during the initial parse; otherwise, the
1145 // type might not be scalar in some uses of the template.
1146 if (S.inTemplateInstantiation())
1147 return;
1148
1149 unsigned DiagID = 0;
1150
1151 switch (Entity.getKind()) {
1152 case InitializedEntity::EK_VectorElement:
1153 case InitializedEntity::EK_ComplexElement:
1154 case InitializedEntity::EK_ArrayElement:
1155 case InitializedEntity::EK_Parameter:
1156 case InitializedEntity::EK_Parameter_CF_Audited:
1157 case InitializedEntity::EK_TemplateParameter:
1158 case InitializedEntity::EK_Result:
1159 // Extra braces here are suspicious.
1160 DiagID = diag::warn_braces_around_init;
1161 break;
1162
1163 case InitializedEntity::EK_Member:
1164 // Warn on aggregate initialization but not on ctor init list or
1165 // default member initializer.
1166 if (Entity.getParent())
1167 DiagID = diag::warn_braces_around_init;
1168 break;
1169
1170 case InitializedEntity::EK_Variable:
1171 case InitializedEntity::EK_LambdaCapture:
1172 // No warning, might be direct-list-initialization.
1173 // FIXME: Should we warn for copy-list-initialization in these cases?
1174 break;
1175
1176 case InitializedEntity::EK_New:
1177 case InitializedEntity::EK_Temporary:
1178 case InitializedEntity::EK_CompoundLiteralInit:
1179 // No warning, braces are part of the syntax of the underlying construct.
1180 break;
1181
1182 case InitializedEntity::EK_RelatedResult:
1183 // No warning, we already warned when initializing the result.
1184 break;
1185
1186 case InitializedEntity::EK_Exception:
1187 case InitializedEntity::EK_Base:
1188 case InitializedEntity::EK_Delegating:
1189 case InitializedEntity::EK_BlockElement:
1190 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1191 case InitializedEntity::EK_Binding:
1192 case InitializedEntity::EK_StmtExprResult:
1193 case InitializedEntity::EK_ParenAggInitMember:
1194 llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init"
, "clang/lib/Sema/SemaInit.cpp", 1194)
;
1195 }
1196
1197 if (DiagID) {
1198 S.Diag(Braces.getBegin(), DiagID)
1199 << Entity.getType()->isSizelessBuiltinType() << Braces
1200 << FixItHint::CreateRemoval(Braces.getBegin())
1201 << FixItHint::CreateRemoval(Braces.getEnd());
1202 }
1203}
1204
1205/// Check whether the initializer \p IList (that was written with explicit
1206/// braces) can be used to initialize an object of type \p T.
1207///
1208/// This also fills in \p StructuredList with the fully-braced, desugared
1209/// form of the initialization.
1210void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1211 InitListExpr *IList, QualType &T,
1212 InitListExpr *StructuredList,
1213 bool TopLevelObject) {
1214 unsigned Index = 0, StructuredIndex = 0;
1215 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1216 Index, StructuredList, StructuredIndex, TopLevelObject);
1217 if (StructuredList) {
1218 QualType ExprTy = T;
1219 if (!ExprTy->isArrayType())
1220 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1221 if (!VerifyOnly)
1222 IList->setType(ExprTy);
1223 StructuredList->setType(ExprTy);
1224 }
1225 if (hadError)
1226 return;
1227
1228 // Don't complain for incomplete types, since we'll get an error elsewhere.
1229 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1230 // We have leftover initializers
1231 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1232 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1233 hadError = ExtraInitsIsError;
1234 if (VerifyOnly) {
1235 return;
1236 } else if (StructuredIndex == 1 &&
1237 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1238 SIF_None) {
1239 unsigned DK =
1240 ExtraInitsIsError
1241 ? diag::err_excess_initializers_in_char_array_initializer
1242 : diag::ext_excess_initializers_in_char_array_initializer;
1243 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1244 << IList->getInit(Index)->getSourceRange();
1245 } else if (T->isSizelessBuiltinType()) {
1246 unsigned DK = ExtraInitsIsError
1247 ? diag::err_excess_initializers_for_sizeless_type
1248 : diag::ext_excess_initializers_for_sizeless_type;
1249 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1250 << T << IList->getInit(Index)->getSourceRange();
1251 } else {
1252 int initKind = T->isArrayType() ? 0 :
1253 T->isVectorType() ? 1 :
1254 T->isScalarType() ? 2 :
1255 T->isUnionType() ? 3 :
1256 4;
1257
1258 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1259 : diag::ext_excess_initializers;
1260 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1261 << initKind << IList->getInit(Index)->getSourceRange();
1262 }
1263 }
1264
1265 if (!VerifyOnly) {
1266 if (T->isScalarType() && IList->getNumInits() == 1 &&
1267 !isa<InitListExpr>(IList->getInit(0)))
1268 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1269
1270 // Warn if this is a class type that won't be an aggregate in future
1271 // versions of C++.
1272 auto *CXXRD = T->getAsCXXRecordDecl();
1273 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1274 // Don't warn if there's an equivalent default constructor that would be
1275 // used instead.
1276 bool HasEquivCtor = false;
1277 if (IList->getNumInits() == 0) {
1278 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1279 HasEquivCtor = CD && !CD->isDeleted();
1280 }
1281
1282 if (!HasEquivCtor) {
1283 SemaRef.Diag(IList->getBeginLoc(),
1284 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1285 << IList->getSourceRange() << T;
1286 }
1287 }
1288 }
1289}
1290
1291void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1292 InitListExpr *IList,
1293 QualType &DeclType,
1294 bool SubobjectIsDesignatorContext,
1295 unsigned &Index,
1296 InitListExpr *StructuredList,
1297 unsigned &StructuredIndex,
1298 bool TopLevelObject) {
1299 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1300 // Explicitly braced initializer for complex type can be real+imaginary
1301 // parts.
1302 CheckComplexType(Entity, IList, DeclType, Index,
1303 StructuredList, StructuredIndex);
1304 } else if (DeclType->isScalarType()) {
1305 CheckScalarType(Entity, IList, DeclType, Index,
1306 StructuredList, StructuredIndex);
1307 } else if (DeclType->isVectorType()) {
1308 CheckVectorType(Entity, IList, DeclType, Index,
1309 StructuredList, StructuredIndex);
1310 } else if (DeclType->isRecordType()) {
1311 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", 1312, __extension__ __PRETTY_FUNCTION__
))
1312 "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", 1312, __extension__ __PRETTY_FUNCTION__
))
;
1313 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
1314 auto Bases =
1315 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1316 CXXRecordDecl::base_class_iterator());
1317 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1318 Bases = CXXRD->bases();
1319 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1320 SubobjectIsDesignatorContext, Index, StructuredList,
1321 StructuredIndex, TopLevelObject);
1322 } else if (DeclType->isArrayType()) {
1323 llvm::APSInt Zero(
1324 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1325 false);
1326 CheckArrayType(Entity, IList, DeclType, Zero,
1327 SubobjectIsDesignatorContext, Index,
1328 StructuredList, StructuredIndex);
1329 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1330 // This type is invalid, issue a diagnostic.
1331 ++Index;
1332 if (!VerifyOnly)
1333 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1334 << DeclType;
1335 hadError = true;
1336 } else if (DeclType->isReferenceType()) {
1337 CheckReferenceType(Entity, IList, DeclType, Index,
1338 StructuredList, StructuredIndex);
1339 } else if (DeclType->isObjCObjectType()) {
1340 if (!VerifyOnly)
1341 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1342 hadError = true;
1343 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1344 DeclType->isSizelessBuiltinType()) {
1345 // Checks for scalar type are sufficient for these types too.
1346 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1347 StructuredIndex);
1348 } else {
1349 if (!VerifyOnly)
1350 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1351 << DeclType;
1352 hadError = true;
1353 }
1354}
1355
1356void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1357 InitListExpr *IList,
1358 QualType ElemType,
1359 unsigned &Index,
1360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex,
1362 bool DirectlyDesignated) {
1363 Expr *expr = IList->getInit(Index);
1364
1365 if (ElemType->isReferenceType())
1366 return CheckReferenceType(Entity, IList, ElemType, Index,
1367 StructuredList, StructuredIndex);
1368
1369 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1370 if (SubInitList->getNumInits() == 1 &&
1371 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1372 SIF_None) {
1373 // FIXME: It would be more faithful and no less correct to include an
1374 // InitListExpr in the semantic form of the initializer list in this case.
1375 expr = SubInitList->getInit(0);
1376 }
1377 // Nested aggregate initialization and C++ initialization are handled later.
1378 } else if (isa<ImplicitValueInitExpr>(expr)) {
1379 // This happens during template instantiation when we see an InitListExpr
1380 // that we've already checked once.
1381 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", 1382, __extension__ __PRETTY_FUNCTION__
))
1382 "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", 1382, __extension__ __PRETTY_FUNCTION__
))
;
1383 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1384 ++Index;
1385 return;
1386 }
1387
1388 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1389 // C++ [dcl.init.aggr]p2:
1390 // Each member is copy-initialized from the corresponding
1391 // initializer-clause.
1392
1393 // FIXME: Better EqualLoc?
1394 InitializationKind Kind =
1395 InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1396
1397 // Vector elements can be initialized from other vectors in which case
1398 // we need initialization entity with a type of a vector (and not a vector
1399 // element!) initializing multiple vector elements.
1400 auto TmpEntity =
1401 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1402 ? InitializedEntity::InitializeTemporary(ElemType)
1403 : Entity;
1404
1405 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1406 /*TopLevelOfInitList*/ true);
1407
1408 // C++14 [dcl.init.aggr]p13:
1409 // If the assignment-expression can initialize a member, the member is
1410 // initialized. Otherwise [...] brace elision is assumed
1411 //
1412 // Brace elision is never performed if the element is not an
1413 // assignment-expression.
1414 if (Seq || isa<InitListExpr>(expr)) {
1415 if (!VerifyOnly) {
1416 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1417 if (Result.isInvalid())
1418 hadError = true;
1419
1420 UpdateStructuredListElement(StructuredList, StructuredIndex,
1421 Result.getAs<Expr>());
1422 } else if (!Seq) {
1423 hadError = true;
1424 } else if (StructuredList) {
1425 UpdateStructuredListElement(StructuredList, StructuredIndex,
1426 getDummyInit());
1427 }
1428 ++Index;
1429 return;
1430 }
1431
1432 // Fall through for subaggregate initialization
1433 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1434 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1435 return CheckScalarType(Entity, IList, ElemType, Index,
1436 StructuredList, StructuredIndex);
1437 } else if (const ArrayType *arrayType =
1438 SemaRef.Context.getAsArrayType(ElemType)) {
1439 // arrayType can be incomplete if we're initializing a flexible
1440 // array member. There's nothing we can do with the completed
1441 // type here, though.
1442
1443 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1444 // FIXME: Should we do this checking in verify-only mode?
1445 if (!VerifyOnly)
1446 CheckStringInit(expr, ElemType, arrayType, SemaRef);
1447 if (StructuredList)
1448 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1449 ++Index;
1450 return;
1451 }
1452
1453 // Fall through for subaggregate initialization.
1454
1455 } else {
1456 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", 1457, __extension__ __PRETTY_FUNCTION__
))
1457 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", 1457, __extension__ __PRETTY_FUNCTION__
))
;
1458
1459 // C99 6.7.8p13:
1460 //
1461 // The initializer for a structure or union object that has
1462 // automatic storage duration shall be either an initializer
1463 // list as described below, or a single expression that has
1464 // compatible structure or union type. In the latter case, the
1465 // initial value of the object, including unnamed members, is
1466 // that of the expression.
1467 ExprResult ExprRes = expr;
1468 if (SemaRef.CheckSingleAssignmentConstraints(
1469 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1470 if (ExprRes.isInvalid())
1471 hadError = true;
1472 else {
1473 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1474 if (ExprRes.isInvalid())
1475 hadError = true;
1476 }
1477 UpdateStructuredListElement(StructuredList, StructuredIndex,
1478 ExprRes.getAs<Expr>());
1479 ++Index;
1480 return;
1481 }
1482 ExprRes.get();
1483 // Fall through for subaggregate initialization
1484 }
1485
1486 // C++ [dcl.init.aggr]p12:
1487 //
1488 // [...] Otherwise, if the member is itself a non-empty
1489 // subaggregate, brace elision is assumed and the initializer is
1490 // considered for the initialization of the first member of
1491 // the subaggregate.
1492 // OpenCL vector initializer is handled elsewhere.
1493 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1494 ElemType->isAggregateType()) {
1495 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1496 StructuredIndex);
1497 ++StructuredIndex;
1498
1499 // In C++20, brace elision is not permitted for a designated initializer.
1500 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1501 if (InOverloadResolution)
1502 hadError = true;
1503 if (!VerifyOnly) {
1504 SemaRef.Diag(expr->getBeginLoc(),
1505 diag::ext_designated_init_brace_elision)
1506 << expr->getSourceRange()
1507 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1508 << FixItHint::CreateInsertion(
1509 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1510 }
1511 }
1512 } else {
1513 if (!VerifyOnly) {
1514 // We cannot initialize this element, so let PerformCopyInitialization
1515 // produce the appropriate diagnostic. We already checked that this
1516 // initialization will fail.
1517 ExprResult Copy =
1518 SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1519 /*TopLevelOfInitList=*/true);
1520 (void)Copy;
1521 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", 1522, __extension__ __PRETTY_FUNCTION__
))
1522 "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", 1522, __extension__ __PRETTY_FUNCTION__
))
;
1523 }
1524 hadError = true;
1525 ++Index;
1526 ++StructuredIndex;
1527 }
1528}
1529
1530void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1531 InitListExpr *IList, QualType DeclType,
1532 unsigned &Index,
1533 InitListExpr *StructuredList,
1534 unsigned &StructuredIndex) {
1535 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", 1535, __extension__ __PRETTY_FUNCTION__
))
;
1536
1537 // As an extension, clang supports complex initializers, which initialize
1538 // a complex number component-wise. When an explicit initializer list for
1539 // a complex number contains two initializers, this extension kicks in:
1540 // it expects the initializer list to contain two elements convertible to
1541 // the element type of the complex type. The first element initializes
1542 // the real part, and the second element intitializes the imaginary part.
1543
1544 if (IList->getNumInits() < 2)
1545 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1546 StructuredIndex);
1547
1548 // This is an extension in C. (The builtin _Complex type does not exist
1549 // in the C++ standard.)
1550 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1551 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1552 << IList->getSourceRange();
1553
1554 // Initialize the complex number.
1555 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1556 InitializedEntity ElementEntity =
1557 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1558
1559 for (unsigned i = 0; i < 2; ++i) {
1560 ElementEntity.setElementIndex(Index);
1561 CheckSubElementType(ElementEntity, IList, elementType, Index,
1562 StructuredList, StructuredIndex);
1563 }
1564}
1565
1566void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1567 InitListExpr *IList, QualType DeclType,
1568 unsigned &Index,
1569 InitListExpr *StructuredList,
1570 unsigned &StructuredIndex) {
1571 if (Index >= IList->getNumInits()) {
1572 if (!VerifyOnly) {
1573 if (SemaRef.getLangOpts().CPlusPlus) {
1574 if (DeclType->isSizelessBuiltinType())
1575 SemaRef.Diag(IList->getBeginLoc(),
1576 SemaRef.getLangOpts().CPlusPlus11
1577 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1578 : diag::err_empty_sizeless_initializer)
1579 << DeclType << IList->getSourceRange();
1580 else
1581 SemaRef.Diag(IList->getBeginLoc(),
1582 SemaRef.getLangOpts().CPlusPlus11
1583 ? diag::warn_cxx98_compat_empty_scalar_initializer
1584 : diag::err_empty_scalar_initializer)
1585 << IList->getSourceRange();
1586 }
1587 }
1588 hadError =
1589 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1590 ++Index;
1591 ++StructuredIndex;
1592 return;
1593 }
1594
1595 Expr *expr = IList->getInit(Index);
1596 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1597 // FIXME: This is invalid, and accepting it causes overload resolution
1598 // to pick the wrong overload in some corner cases.
1599 if (!VerifyOnly)
1600 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1601 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1602
1603 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1604 StructuredIndex);
1605 return;
1606 } else if (isa<DesignatedInitExpr>(expr)) {
1607 if (!VerifyOnly)
1608 SemaRef.Diag(expr->getBeginLoc(),
1609 diag::err_designator_for_scalar_or_sizeless_init)
1610 << DeclType->isSizelessBuiltinType() << DeclType
1611 << expr->getSourceRange();
1612 hadError = true;
1613 ++Index;
1614 ++StructuredIndex;
1615 return;
1616 }
1617
1618 ExprResult Result;
1619 if (VerifyOnly) {
1620 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1621 Result = getDummyInit();
1622 else
1623 Result = ExprError();
1624 } else {
1625 Result =
1626 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1627 /*TopLevelOfInitList=*/true);
1628 }
1629
1630 Expr *ResultExpr = nullptr;
1631
1632 if (Result.isInvalid())
1633 hadError = true; // types weren't compatible.
1634 else {
1635 ResultExpr = Result.getAs<Expr>();
1636
1637 if (ResultExpr != expr && !VerifyOnly) {
1638 // The type was promoted, update initializer list.
1639 // FIXME: Why are we updating the syntactic init list?
1640 IList->setInit(Index, ResultExpr);
1641 }
1642 }
1643 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1644 ++Index;
1645}
1646
1647void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1648 InitListExpr *IList, QualType DeclType,
1649 unsigned &Index,
1650 InitListExpr *StructuredList,
1651 unsigned &StructuredIndex) {
1652 if (Index >= IList->getNumInits()) {
1653 // FIXME: It would be wonderful if we could point at the actual member. In
1654 // general, it would be useful to pass location information down the stack,
1655 // so that we know the location (or decl) of the "current object" being
1656 // initialized.
1657 if (!VerifyOnly)
1658 SemaRef.Diag(IList->getBeginLoc(),
1659 diag::err_init_reference_member_uninitialized)
1660 << DeclType << IList->getSourceRange();
1661 hadError = true;
1662 ++Index;
1663 ++StructuredIndex;
1664 return;
1665 }
1666
1667 Expr *expr = IList->getInit(Index);
1668 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1669 if (!VerifyOnly)
1670 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1671 << DeclType << IList->getSourceRange();
1672 hadError = true;
1673 ++Index;
1674 ++StructuredIndex;
1675 return;
1676 }
1677
1678 ExprResult Result;
1679 if (VerifyOnly) {
1680 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1681 Result = getDummyInit();
1682 else
1683 Result = ExprError();
1684 } else {
1685 Result =
1686 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1687 /*TopLevelOfInitList=*/true);
1688 }
1689
1690 if (Result.isInvalid())
1691 hadError = true;
1692
1693 expr = Result.getAs<Expr>();
1694 // FIXME: Why are we updating the syntactic init list?
1695 if (!VerifyOnly && expr)
1696 IList->setInit(Index, expr);
1697
1698 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1699 ++Index;
1700}
1701
1702void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1703 InitListExpr *IList, QualType DeclType,
1704 unsigned &Index,
1705 InitListExpr *StructuredList,
1706 unsigned &StructuredIndex) {
1707 const VectorType *VT = DeclType->castAs<VectorType>();
1708 unsigned maxElements = VT->getNumElements();
1709 unsigned numEltsInit = 0;
1710 QualType elementType = VT->getElementType();
1711
1712 if (Index >= IList->getNumInits()) {
1713 // Make sure the element type can be value-initialized.
1714 CheckEmptyInitializable(
1715 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1716 IList->getEndLoc());
1717 return;
1718 }
1719
1720 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1721 // If the initializing element is a vector, try to copy-initialize
1722 // instead of breaking it apart (which is doomed to failure anyway).
1723 Expr *Init = IList->getInit(Index);
1724 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1725 ExprResult Result;
1726 if (VerifyOnly) {
1727 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1728 Result = getDummyInit();
1729 else
1730 Result = ExprError();
1731 } else {
1732 Result =
1733 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1734 /*TopLevelOfInitList=*/true);
1735 }
1736
1737 Expr *ResultExpr = nullptr;
1738 if (Result.isInvalid())
1739 hadError = true; // types weren't compatible.
1740 else {
1741 ResultExpr = Result.getAs<Expr>();
1742
1743 if (ResultExpr != Init && !VerifyOnly) {
1744 // The type was promoted, update initializer list.
1745 // FIXME: Why are we updating the syntactic init list?
1746 IList->setInit(Index, ResultExpr);
1747 }
1748 }
1749 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1750 ++Index;
1751 return;
1752 }
1753
1754 InitializedEntity ElementEntity =
1755 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1756
1757 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1758 // Don't attempt to go past the end of the init list
1759 if (Index >= IList->getNumInits()) {
1760 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1761 break;
1762 }
1763
1764 ElementEntity.setElementIndex(Index);
1765 CheckSubElementType(ElementEntity, IList, elementType, Index,
1766 StructuredList, StructuredIndex);
1767 }
1768
1769 if (VerifyOnly)
1770 return;
1771
1772 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1773 const VectorType *T = Entity.getType()->castAs<VectorType>();
1774 if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector ||
1775 T->getVectorKind() == VectorType::NeonPolyVector)) {
1776 // The ability to use vector initializer lists is a GNU vector extension
1777 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1778 // endian machines it works fine, however on big endian machines it
1779 // exhibits surprising behaviour:
1780 //
1781 // uint32x2_t x = {42, 64};
1782 // return vget_lane_u32(x, 0); // Will return 64.
1783 //
1784 // Because of this, explicitly call out that it is non-portable.
1785 //
1786 SemaRef.Diag(IList->getBeginLoc(),
1787 diag::warn_neon_vector_initializer_non_portable);
1788
1789 const char *typeCode;
1790 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1791
1792 if (elementType->isFloatingType())
1793 typeCode = "f";
1794 else if (elementType->isSignedIntegerType())
1795 typeCode = "s";
1796 else if (elementType->isUnsignedIntegerType())
1797 typeCode = "u";
1798 else
1799 llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "clang/lib/Sema/SemaInit.cpp"
, 1799)
;
1800
1801 SemaRef.Diag(IList->getBeginLoc(),
1802 SemaRef.Context.getTypeSize(VT) > 64
1803 ? diag::note_neon_vector_initializer_non_portable_q
1804 : diag::note_neon_vector_initializer_non_portable)
1805 << typeCode << typeSize;
1806 }
1807
1808 return;
1809 }
1810
1811 InitializedEntity ElementEntity =
1812 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1813
1814 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1815 for (unsigned i = 0; i < maxElements; ++i) {
1816 // Don't attempt to go past the end of the init list
1817 if (Index >= IList->getNumInits())
1818 break;
1819
1820 ElementEntity.setElementIndex(Index);
1821
1822 QualType IType = IList->getInit(Index)->getType();
1823 if (!IType->isVectorType()) {
1824 CheckSubElementType(ElementEntity, IList, elementType, Index,
1825 StructuredList, StructuredIndex);
1826 ++numEltsInit;
1827 } else {
1828 QualType VecType;
1829 const VectorType *IVT = IType->castAs<VectorType>();
1830 unsigned numIElts = IVT->getNumElements();
1831
1832 if (IType->isExtVectorType())
1833 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1834 else
1835 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1836 IVT->getVectorKind());
1837 CheckSubElementType(ElementEntity, IList, VecType, Index,
1838 StructuredList, StructuredIndex);
1839 numEltsInit += numIElts;
1840 }
1841 }
1842
1843 // OpenCL and HLSL require all elements to be initialized.
1844 if (numEltsInit != maxElements) {
1845 if (!VerifyOnly)
1846 SemaRef.Diag(IList->getBeginLoc(),
1847 diag::err_vector_incorrect_num_initializers)
1848 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1849 hadError = true;
1850 }
1851}
1852
1853/// Check if the type of a class element has an accessible destructor, and marks
1854/// it referenced. Returns true if we shouldn't form a reference to the
1855/// destructor.
1856///
1857/// Aggregate initialization requires a class element's destructor be
1858/// accessible per 11.6.1 [dcl.init.aggr]:
1859///
1860/// The destructor for each element of class type is potentially invoked
1861/// (15.4 [class.dtor]) from the context where the aggregate initialization
1862/// occurs.
1863static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1864 Sema &SemaRef) {
1865 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1866 if (!CXXRD)
1867 return false;
1868
1869 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1870 SemaRef.CheckDestructorAccess(Loc, Destructor,
1871 SemaRef.PDiag(diag::err_access_dtor_temp)
1872 << ElementType);
1873 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1874 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1875}
1876
1877void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1878 InitListExpr *IList, QualType &DeclType,
1879 llvm::APSInt elementIndex,
1880 bool SubobjectIsDesignatorContext,
1881 unsigned &Index,
1882 InitListExpr *StructuredList,
1883 unsigned &StructuredIndex) {
1884 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1885
1886 if (!VerifyOnly) {
1887 if (checkDestructorReference(arrayType->getElementType(),
1888 IList->getEndLoc(), SemaRef)) {
1889 hadError = true;
1890 return;
1891 }
1892 }
1893
1894 // Check for the special-case of initializing an array with a string.
1895 if (Index < IList->getNumInits()) {
1896 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1897 SIF_None) {
1898 // We place the string literal directly into the resulting
1899 // initializer list. This is the only place where the structure
1900 // of the structured initializer list doesn't match exactly,
1901 // because doing so would involve allocating one character
1902 // constant for each string.
1903 // FIXME: Should we do these checks in verify-only mode too?
1904 if (!VerifyOnly)
1905 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1906 if (StructuredList) {
1907 UpdateStructuredListElement(StructuredList, StructuredIndex,
1908 IList->getInit(Index));
1909 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1910 }
1911 ++Index;
1912 return;
1913 }
1914 }
1915 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1916 // Check for VLAs; in standard C it would be possible to check this
1917 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1918 // them in all sorts of strange places).
1919 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1920 if (!VerifyOnly) {
1921 // C2x 6.7.9p4: An entity of variable length array type shall not be
1922 // initialized except by an empty initializer.
1923 //
1924 // The C extension warnings are issued from ParseBraceInitializer() and
1925 // do not need to be issued here. However, we continue to issue an error
1926 // in the case there are initializers or we are compiling C++. We allow
1927 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1928 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1929 // FIXME: should we allow this construct in C++ when it makes sense to do
1930 // so?
1931 if (HasErr)
1932 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1933 diag::err_variable_object_no_init)
1934 << VAT->getSizeExpr()->getSourceRange();
1935 }
1936 hadError = HasErr;
1937 ++Index;
1938 ++StructuredIndex;
1939 return;
1940 }
1941
1942 // We might know the maximum number of elements in advance.
1943 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1944 elementIndex.isUnsigned());
1945 bool maxElementsKnown = false;
1946 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1947 maxElements = CAT->getSize();
1948 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1949 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1950 maxElementsKnown = true;
1951 }
1952
1953 QualType elementType = arrayType->getElementType();
1954 while (Index < IList->getNumInits()) {
1955 Expr *Init = IList->getInit(Index);
1956 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1957 // If we're not the subobject that matches up with the '{' for
1958 // the designator, we shouldn't be handling the
1959 // designator. Return immediately.
1960 if (!SubobjectIsDesignatorContext)
1961 return;
1962
1963 // Handle this designated initializer. elementIndex will be
1964 // updated to be the next array element we'll initialize.
1965 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1966 DeclType, nullptr, &elementIndex, Index,
1967 StructuredList, StructuredIndex, true,
1968 false)) {
1969 hadError = true;
1970 continue;
1971 }
1972
1973 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1974 maxElements = maxElements.extend(elementIndex.getBitWidth());
1975 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1976 elementIndex = elementIndex.extend(maxElements.getBitWidth());
1977 elementIndex.setIsUnsigned(maxElements.isUnsigned());
1978
1979 // If the array is of incomplete type, keep track of the number of
1980 // elements in the initializer.
1981 if (!maxElementsKnown && elementIndex > maxElements)
1982 maxElements = elementIndex;
1983
1984 continue;
1985 }
1986
1987 // If we know the maximum number of elements, and we've already
1988 // hit it, stop consuming elements in the initializer list.
1989 if (maxElementsKnown && elementIndex == maxElements)
1990 break;
1991
1992 InitializedEntity ElementEntity =
1993 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1994 Entity);
1995 // Check this element.
1996 CheckSubElementType(ElementEntity, IList, elementType, Index,
1997 StructuredList, StructuredIndex);
1998 ++elementIndex;
1999
2000 // If the array is of incomplete type, keep track of the number of
2001 // elements in the initializer.
2002 if (!maxElementsKnown && elementIndex > maxElements)
2003 maxElements = elementIndex;
2004 }
2005 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2006 // If this is an incomplete array type, the actual type needs to
2007 // be calculated here.
2008 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2009 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2010 // Sizing an array implicitly to zero is not allowed by ISO C,
2011 // but is supported by GNU.
2012 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2013 }
2014
2015 DeclType = SemaRef.Context.getConstantArrayType(
2016 elementType, maxElements, nullptr, ArrayType::Normal, 0);
2017 }
2018 if (!hadError) {
2019 // If there are any members of the array that get value-initialized, check
2020 // that is possible. That happens if we know the bound and don't have
2021 // enough elements, or if we're performing an array new with an unknown
2022 // bound.
2023 if ((maxElementsKnown && elementIndex < maxElements) ||
2024 Entity.isVariableLengthArrayNew())
2025 CheckEmptyInitializable(
2026 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
2027 IList->getEndLoc());
2028 }
2029}
2030
2031bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2032 Expr *InitExpr,
2033 FieldDecl *Field,
2034 bool TopLevelObject) {
2035 // Handle GNU flexible array initializers.
2036 unsigned FlexArrayDiag;
2037 if (isa<InitListExpr>(InitExpr) &&
2038 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2039 // Empty flexible array init always allowed as an extension
2040 FlexArrayDiag = diag::ext_flexible_array_init;
2041 } else if (!TopLevelObject) {
2042 // Disallow flexible array init on non-top-level object
2043 FlexArrayDiag = diag::err_flexible_array_init;
2044 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2045 // Disallow flexible array init on anything which is not a variable.
2046 FlexArrayDiag = diag::err_flexible_array_init;
2047 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2048 // Disallow flexible array init on local variables.
2049 FlexArrayDiag = diag::err_flexible_array_init;
2050 } else {
2051 // Allow other cases.
2052 FlexArrayDiag = diag::ext_flexible_array_init;
2053 }
2054
2055 if (!VerifyOnly) {
2056 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2057 << InitExpr->getBeginLoc();
2058 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2059 << Field;
2060 }
2061
2062 return FlexArrayDiag != diag::ext_flexible_array_init;
2063}
2064
2065void InitListChecker::CheckStructUnionTypes(
2066 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2067 CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
2068 bool SubobjectIsDesignatorContext, unsigned &Index,
2069 InitListExpr *StructuredList, unsigned &StructuredIndex,
2070 bool TopLevelObject) {
2071 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
2072
2073 // If the record is invalid, some of it's members are invalid. To avoid
2074 // confusion, we forgo checking the initializer for the entire record.
2075 if (structDecl->isInvalidDecl()) {
2076 // Assume it was supposed to consume a single initializer.
2077 ++Index;
2078 hadError = true;
2079 return;
2080 }
2081
2082 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
2083 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2084
2085 if (!VerifyOnly)
2086 for (FieldDecl *FD : RD->fields()) {
2087 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2088 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2089 hadError = true;
2090 return;
2091 }
2092 }
2093
2094 // If there's a default initializer, use it.
2095 if (isa<CXXRecordDecl>(RD) &&
2096 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2097 if (!StructuredList)
2098 return;
2099 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2100 Field != FieldEnd; ++Field) {
2101 if (Field->hasInClassInitializer()) {
2102 StructuredList->setInitializedFieldInUnion(*Field);
2103 // FIXME: Actually build a CXXDefaultInitExpr?
2104 return;
2105 }
2106 }
2107 }
2108
2109 // Value-initialize the first member of the union that isn't an unnamed
2110 // bitfield.
2111 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2112 Field != FieldEnd; ++Field) {
2113 if (!Field->isUnnamedBitfield()) {
2114 CheckEmptyInitializable(
2115 InitializedEntity::InitializeMember(*Field, &Entity),
2116 IList->getEndLoc());
2117 if (StructuredList)
2118 StructuredList->setInitializedFieldInUnion(*Field);
2119 break;
2120 }
2121 }
2122 return;
2123 }
2124
2125 bool InitializedSomething = false;
2126
2127 // If we have any base classes, they are initialized prior to the fields.
2128 for (auto &Base : Bases) {
2129 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2130
2131 // Designated inits always initialize fields, so if we see one, all
2132 // remaining base classes have no explicit initializer.
2133 if (Init && isa<DesignatedInitExpr>(Init))
2134 Init = nullptr;
2135
2136 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2137 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2138 SemaRef.Context, &Base, false, &Entity);
2139 if (Init) {
2140 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2141 StructuredList, StructuredIndex);
2142 InitializedSomething = true;
2143 } else {
2144 CheckEmptyInitializable(BaseEntity, InitLoc);
2145 }
2146
2147 if (!VerifyOnly)
2148 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2149 hadError = true;
2150 return;
2151 }
2152 }
2153
2154 // If structDecl is a forward declaration, this loop won't do
2155 // anything except look at designated initializers; That's okay,
2156 // because an error should get printed out elsewhere. It might be
2157 // worthwhile to skip over the rest of the initializer, though.
2158 RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2159 RecordDecl::field_iterator FieldEnd = RD->field_end();
2160 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2161 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2162 });
2163 bool CheckForMissingFields =
2164 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2165 bool HasDesignatedInit = false;
2166
2167 while (Index < IList->getNumInits()) {
2168 Expr *Init = IList->getInit(Index);
2169 SourceLocation InitLoc = Init->getBeginLoc();
2170
2171 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2172 // If we're not the subobject that matches up with the '{' for
2173 // the designator, we shouldn't be handling the
2174 // designator. Return immediately.
2175 if (!SubobjectIsDesignatorContext)
2176 return;
2177
2178 HasDesignatedInit = true;
2179
2180 // Handle this designated initializer. Field will be updated to
2181 // the next field that we'll be initializing.
2182 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2183 DeclType, &Field, nullptr, Index,
2184 StructuredList, StructuredIndex,
2185 true, TopLevelObject))
2186 hadError = true;
2187 else if (!VerifyOnly) {
2188 // Find the field named by the designated initializer.
2189 RecordDecl::field_iterator F = RD->field_begin();
2190 while (std::next(F) != Field)
2191 ++F;
2192 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2193 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2194 hadError = true;
2195 return;
2196 }
2197 }
2198
2199 InitializedSomething = true;
2200
2201 // Disable check for missing fields when designators are used.
2202 // This matches gcc behaviour.
2203 CheckForMissingFields = false;
2204 continue;
2205 }
2206
2207 // Check if this is an initializer of forms:
2208 //
2209 // struct foo f = {};
2210 // struct foo g = {0};
2211 //
2212 // These are okay for randomized structures. [C99 6.7.8p19]
2213 //
2214 // Also, if there is only one element in the structure, we allow something
2215 // like this, because it's really not randomized in the tranditional sense.
2216 //
2217 // struct foo h = {bar};
2218 auto IsZeroInitializer = [&](const Expr *I) {
2219 if (IList->getNumInits() == 1) {
2220 if (NumRecordDecls == 1)
2221 return true;
2222 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2223 return IL->getValue().isZero();
2224 }
2225 return false;
2226 };
2227
2228 // Don't allow non-designated initializers on randomized structures.
2229 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2230 if (!VerifyOnly)
2231 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2232 hadError = true;
2233 break;
2234 }
2235
2236 if (Field == FieldEnd) {
2237 // We've run out of fields. We're done.
2238 break;
2239 }
2240
2241 // We've already initialized a member of a union. We're done.
2242 if (InitializedSomething && DeclType->isUnionType())
2243 break;
2244
2245 // If we've hit the flexible array member at the end, we're done.
2246 if (Field->getType()->isIncompleteArrayType())
2247 break;
2248
2249 if (Field->isUnnamedBitfield()) {
2250 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2251 ++Field;
2252 continue;
2253 }
2254
2255 // Make sure we can use this declaration.
2256 bool InvalidUse;
2257 if (VerifyOnly)
2258 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2259 else
2260 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2261 *Field, IList->getInit(Index)->getBeginLoc());
2262 if (InvalidUse) {
2263 ++Index;
2264 ++Field;
2265 hadError = true;
2266 continue;
2267 }
2268
2269 if (!VerifyOnly) {
2270 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2271 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2272 hadError = true;
2273 return;
2274 }
2275 }
2276
2277 InitializedEntity MemberEntity =
2278 InitializedEntity::InitializeMember(*Field, &Entity);
2279 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2280 StructuredList, StructuredIndex);
2281 InitializedSomething = true;
2282
2283 if (DeclType->isUnionType() && StructuredList) {
2284 // Initialize the first field within the union.
2285 StructuredList->setInitializedFieldInUnion(*Field);
2286 }
2287
2288 ++Field;
2289 }
2290
2291 // Emit warnings for missing struct field initializers.
2292 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2293 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
2294 !DeclType->isUnionType()) {
2295 // It is possible we have one or more unnamed bitfields remaining.
2296 // Find first (if any) named field and emit warning.
2297 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2298 it != end; ++it) {
2299 if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
2300 SemaRef.Diag(IList->getSourceRange().getEnd(),
2301 diag::warn_missing_field_initializers) << *it;
2302 break;
2303 }
2304 }
2305 }
2306
2307 // Check that any remaining fields can be value-initialized if we're not
2308 // building a structured list. (If we are, we'll check this later.)
2309 if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() &&
2310 !Field->getType()->isIncompleteArrayType()) {
2311 for (; Field != FieldEnd && !hadError; ++Field) {
2312 if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2313 CheckEmptyInitializable(
2314 InitializedEntity::InitializeMember(*Field, &Entity),
2315 IList->getEndLoc());
2316 }
2317 }
2318
2319 // Check that the types of the remaining fields have accessible destructors.
2320 if (!VerifyOnly) {
2321 // If the initializer expression has a designated initializer, check the
2322 // elements for which a designated initializer is not provided too.
2323 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2324 : Field;
2325 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2326 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2327 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2328 hadError = true;
2329 return;
2330 }
2331 }
2332 }
2333
2334 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2335 Index >= IList->getNumInits())
2336 return;
2337
2338 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2339 TopLevelObject)) {
2340 hadError = true;
2341 ++Index;
2342 return;
2343 }
2344
2345 InitializedEntity MemberEntity =
2346 InitializedEntity::InitializeMember(*Field, &Entity);
2347
2348 if (isa<InitListExpr>(IList->getInit(Index)))
2349 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2350 StructuredList, StructuredIndex);
2351 else
2352 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2353 StructuredList, StructuredIndex);
2354}
2355
2356/// Expand a field designator that refers to a member of an
2357/// anonymous struct or union into a series of field designators that
2358/// refers to the field within the appropriate subobject.
2359///
2360static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2361 DesignatedInitExpr *DIE,
2362 unsigned DesigIdx,
2363 IndirectFieldDecl *IndirectField) {
2364 typedef DesignatedInitExpr::Designator Designator;
2365
2366 // Build the replacement designators.
2367 SmallVector<Designator, 4> Replacements;
2368 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2369 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2370 if (PI + 1 == PE)
2371 Replacements.push_back(Designator::CreateFieldDesignator(
2372 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2373 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2374 else
2375 Replacements.push_back(Designator::CreateFieldDesignator(
2376 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2377 assert(isa<FieldDecl>(*PI))(static_cast <bool> (isa<FieldDecl>(*PI)) ? void (
0) : __assert_fail ("isa<FieldDecl>(*PI)", "clang/lib/Sema/SemaInit.cpp"
, 2377, __extension__ __PRETTY_FUNCTION__))
;
2378 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2379 }
2380
2381 // Expand the current designator into the set of replacement
2382 // designators, so we have a full subobject path down to where the
2383 // member of the anonymous struct/union is actually stored.
2384 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2385 &Replacements[0] + Replacements.size());
2386}
2387
2388static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2389 DesignatedInitExpr *DIE) {
2390 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2391 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2392 for (unsigned I = 0; I < NumIndexExprs; ++I)
2393 IndexExprs[I] = DIE->getSubExpr(I + 1);
2394 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2395 IndexExprs,
2396 DIE->getEqualOrColonLoc(),
2397 DIE->usesGNUSyntax(), DIE->getInit());
2398}
2399
2400namespace {
2401
2402// Callback to only accept typo corrections that are for field members of
2403// the given struct or union.
2404class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2405 public:
2406 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2407 : Record(RD) {}
2408
2409 bool ValidateCandidate(const TypoCorrection &candidate) override {
2410 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2411 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2412 }
2413
2414 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2415 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2416 }
2417
2418 private:
2419 RecordDecl *Record;
2420};
2421
2422} // end anonymous namespace
2423
2424/// Check the well-formedness of a C99 designated initializer.
2425///
2426/// Determines whether the designated initializer @p DIE, which
2427/// resides at the given @p Index within the initializer list @p
2428/// IList, is well-formed for a current object of type @p DeclType
2429/// (C99 6.7.8). The actual subobject that this designator refers to
2430/// within the current subobject is returned in either
2431/// @p NextField or @p NextElementIndex (whichever is appropriate).
2432///
2433/// @param IList The initializer list in which this designated
2434/// initializer occurs.
2435///
2436/// @param DIE The designated initializer expression.
2437///
2438/// @param DesigIdx The index of the current designator.
2439///
2440/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2441/// into which the designation in @p DIE should refer.
2442///
2443/// @param NextField If non-NULL and the first designator in @p DIE is
2444/// a field, this will be set to the field declaration corresponding
2445/// to the field named by the designator. On input, this is expected to be
2446/// the next field that would be initialized in the absence of designation,
2447/// if the complete object being initialized is a struct.
2448///
2449/// @param NextElementIndex If non-NULL and the first designator in @p
2450/// DIE is an array designator or GNU array-range designator, this
2451/// will be set to the last index initialized by this designator.
2452///
2453/// @param Index Index into @p IList where the designated initializer
2454/// @p DIE occurs.
2455///
2456/// @param StructuredList The initializer list expression that
2457/// describes all of the subobject initializers in the order they'll
2458/// actually be initialized.
2459///
2460/// @returns true if there was an error, false otherwise.
2461bool
2462InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2463 InitListExpr *IList,
2464 DesignatedInitExpr *DIE,
2465 unsigned DesigIdx,
2466 QualType &CurrentObjectType,
2467 RecordDecl::field_iterator *NextField,
2468 llvm::APSInt *NextElementIndex,
2469 unsigned &Index,
2470 InitListExpr *StructuredList,
2471 unsigned &StructuredIndex,
2472 bool FinishSubobjectInit,
2473 bool TopLevelObject) {
2474 if (DesigIdx == DIE->size()) {
2475 // C++20 designated initialization can result in direct-list-initialization
2476 // of the designated subobject. This is the only way that we can end up
2477 // performing direct initialization as part of aggregate initialization, so
2478 // it needs special handling.
2479 if (DIE->isDirectInit()) {
2480 Expr *Init = DIE->getInit();
2481 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", 2482, __extension__ __PRETTY_FUNCTION__
))
2482 "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", 2482, __extension__ __PRETTY_FUNCTION__
))
;
2483 InitializationKind Kind = InitializationKind::CreateDirectList(
2484 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2485 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2486 /*TopLevelOfInitList*/ true);
2487 if (StructuredList) {
2488 ExprResult Result = VerifyOnly
2489 ? getDummyInit()
2490 : Seq.Perform(SemaRef, Entity, Kind, Init);
2491 UpdateStructuredListElement(StructuredList, StructuredIndex,
2492 Result.get());
2493 }
2494 ++Index;
2495 return !Seq;
2496 }
2497
2498 // Check the actual initialization for the designated object type.
2499 bool prevHadError = hadError;
2500
2501 // Temporarily remove the designator expression from the
2502 // initializer list that the child calls see, so that we don't try
2503 // to re-process the designator.
2504 unsigned OldIndex = Index;
2505 IList->setInit(OldIndex, DIE->getInit());
2506
2507 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2508 StructuredIndex, /*DirectlyDesignated=*/true);
2509
2510 // Restore the designated initializer expression in the syntactic
2511 // form of the initializer list.
2512 if (IList->getInit(OldIndex) != DIE->getInit())
2513 DIE->setInit(IList->getInit(OldIndex));
2514 IList->setInit(OldIndex, DIE);
2515
2516 return hadError && !prevHadError;
2517 }
2518
2519 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2520 bool IsFirstDesignator = (DesigIdx == 0);
2521 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2522 // Determine the structural initializer list that corresponds to the
2523 // current subobject.
2524 if (IsFirstDesignator)
2525 StructuredList = FullyStructuredList;
2526 else {
2527 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2528 StructuredList->getInit(StructuredIndex) : nullptr;
2529 if (!ExistingInit && StructuredList->hasArrayFiller())
2530 ExistingInit = StructuredList->getArrayFiller();
2531
2532 if (!ExistingInit)
2533 StructuredList = getStructuredSubobjectInit(
2534 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2535 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2536 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2537 StructuredList = Result;
2538 else {
2539 // We are creating an initializer list that initializes the
2540 // subobjects of the current object, but there was already an
2541 // initialization that completely initialized the current
2542 // subobject, e.g., by a compound literal:
2543 //
2544 // struct X { int a, b; };
2545 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2546 //
2547 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2548 // designated initializer re-initializes only its current object
2549 // subobject [0].b.
2550 diagnoseInitOverride(ExistingInit,
2551 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2552 /*UnionOverride=*/false,
2553 /*FullyOverwritten=*/false);
2554
2555 if (!VerifyOnly) {
2556 if (DesignatedInitUpdateExpr *E =
2557 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2558 StructuredList = E->getUpdater();
2559 else {
2560 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2561 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2562 ExistingInit, DIE->getEndLoc());
2563 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2564 StructuredList = DIUE->getUpdater();
2565 }
2566 } else {
2567 // We don't need to track the structured representation of a
2568 // designated init update of an already-fully-initialized object in
2569 // verify-only mode. The only reason we would need the structure is
2570 // to determine where the uninitialized "holes" are, and in this
2571 // case, we know there aren't any and we can't introduce any.
2572 StructuredList = nullptr;
2573 }
2574 }
2575 }
2576 }
2577
2578 if (D->isFieldDesignator()) {
2579 // C99 6.7.8p7:
2580 //
2581 // If a designator has the form
2582 //
2583 // . identifier
2584 //
2585 // then the current object (defined below) shall have
2586 // structure or union type and the identifier shall be the
2587 // name of a member of that type.
2588 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2589 if (!RT) {
2590 SourceLocation Loc = D->getDotLoc();
2591 if (Loc.isInvalid())
2592 Loc = D->getFieldLoc();
2593 if (!VerifyOnly)
2594 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2595 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2596 ++Index;
2597 return true;
2598 }
2599
2600 FieldDecl *KnownField = D->getFieldDecl();
2601 if (!KnownField) {
2602 const IdentifierInfo *FieldName = D->getFieldName();
2603 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2604 for (NamedDecl *ND : Lookup) {
2605 if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2606 KnownField = FD;
2607 break;
2608 }
2609 if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2610 // In verify mode, don't modify the original.
2611 if (VerifyOnly)
2612 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2613 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2614 D = DIE->getDesignator(DesigIdx);
2615 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2616 break;
2617 }
2618 }
2619 if (!KnownField) {
2620 if (VerifyOnly) {
2621 ++Index;
2622 return true; // No typo correction when just trying this out.
2623 }
2624
2625 // Name lookup found something, but it wasn't a field.
2626 if (!Lookup.empty()) {
2627 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2628 << FieldName;
2629 SemaRef.Diag(Lookup.front()->getLocation(),
2630 diag::note_field_designator_found);
2631 ++Index;
2632 return true;
2633 }
2634
2635 // Name lookup didn't find anything.
2636 // Determine whether this was a typo for another field name.
2637 FieldInitializerValidatorCCC CCC(RT->getDecl());
2638 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2639 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2640 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2641 Sema::CTK_ErrorRecovery, RT->getDecl())) {
2642 SemaRef.diagnoseTypo(
2643 Corrected,
2644 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2645 << FieldName << CurrentObjectType);
2646 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2647 hadError = true;
2648 } else {
2649 // Typo correction didn't find anything.
2650 SourceLocation Loc = D->getFieldLoc();
2651
2652 // The loc can be invalid with a "null" designator (i.e. an anonymous
2653 // union/struct). Do our best to approximate the location.
2654 if (Loc.isInvalid())
2655 Loc = IList->getBeginLoc();
2656
2657 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2658 << FieldName << CurrentObjectType << DIE->getSourceRange();
2659 ++Index;
2660 return true;
2661 }
2662 }
2663 }
2664
2665 unsigned NumBases = 0;
2666 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2667 NumBases = CXXRD->getNumBases();
2668
2669 unsigned FieldIndex = NumBases;
2670
2671 for (auto *FI : RT->getDecl()->fields()) {
2672 if (FI->isUnnamedBitfield())
2673 continue;
2674 if (declaresSameEntity(KnownField, FI)) {
2675 KnownField = FI;
2676 break;
2677 }
2678 ++FieldIndex;
2679 }
2680
2681 RecordDecl::field_iterator Field =
2682 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2683
2684 // All of the fields of a union are located at the same place in
2685 // the initializer list.
2686 if (RT->getDecl()->isUnion()) {
2687 FieldIndex = 0;
2688 if (StructuredList) {
2689 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2690 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2691 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", 2692, __extension__ __PRETTY_FUNCTION__
))
2692 && "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", 2692, __extension__ __PRETTY_FUNCTION__
))
;
2693
2694 Expr *ExistingInit = StructuredList->getInit(0);
2695 if (ExistingInit) {
2696 // We're about to throw away an initializer, emit warning.
2697 diagnoseInitOverride(
2698 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2699 /*UnionOverride=*/true,
2700 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2701 : true);
2702 }
2703
2704 // remove existing initializer
2705 StructuredList->resizeInits(SemaRef.Context, 0);
2706 StructuredList->setInitializedFieldInUnion(nullptr);
2707 }
2708
2709 StructuredList->setInitializedFieldInUnion(*Field);
2710 }
2711 }
2712
2713 // Make sure we can use this declaration.
2714 bool InvalidUse;
2715 if (VerifyOnly)
2716 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2717 else
2718 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2719 if (InvalidUse) {
2720 ++Index;
2721 return true;
2722 }
2723
2724 // C++20 [dcl.init.list]p3:
2725 // The ordered identifiers in the designators of the designated-
2726 // initializer-list shall form a subsequence of the ordered identifiers
2727 // in the direct non-static data members of T.
2728 //
2729 // Note that this is not a condition on forming the aggregate
2730 // initialization, only on actually performing initialization,
2731 // so it is not checked in VerifyOnly mode.
2732 //
2733 // FIXME: This is the only reordering diagnostic we produce, and it only
2734 // catches cases where we have a top-level field designator that jumps
2735 // backwards. This is the only such case that is reachable in an
2736 // otherwise-valid C++20 program, so is the only case that's required for
2737 // conformance, but for consistency, we should diagnose all the other
2738 // cases where a designator takes us backwards too.
2739 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2740 NextField &&
2741 (*NextField == RT->getDecl()->field_end() ||
2742 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2743 // Find the field that we just initialized.
2744 FieldDecl *PrevField = nullptr;
2745 for (auto FI = RT->getDecl()->field_begin();
2746 FI != RT->getDecl()->field_end(); ++FI) {
2747 if (FI->isUnnamedBitfield())
2748 continue;
2749 if (*NextField != RT->getDecl()->field_end() &&
2750 declaresSameEntity(*FI, **NextField))
2751 break;
2752 PrevField = *FI;
2753 }
2754
2755 if (PrevField &&
2756 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2757 SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
2758 << KnownField << PrevField << DIE->getSourceRange();
2759
2760 unsigned OldIndex = NumBases + PrevField->getFieldIndex();
2761 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2762 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2763 SemaRef.Diag(PrevInit->getBeginLoc(),
2764 diag::note_previous_field_init)
2765 << PrevField << PrevInit->getSourceRange();
2766 }
2767 }
2768 }
2769 }
2770
2771
2772 // Update the designator with the field declaration.
2773 if (!VerifyOnly)
2774 D->setFieldDecl(*Field);
2775
2776 // Make sure that our non-designated initializer list has space
2777 // for a subobject corresponding to this field.
2778 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2779 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2780
2781 // This designator names a flexible array member.
2782 if (Field->getType()->isIncompleteArrayType()) {
2783 bool Invalid = false;
2784 if ((DesigIdx + 1) != DIE->size()) {
2785 // We can't designate an object within the flexible array
2786 // member (because GCC doesn't allow it).
2787 if (!VerifyOnly) {
2788 DesignatedInitExpr::Designator *NextD
2789 = DIE->getDesignator(DesigIdx + 1);
2790 SemaRef.Diag(NextD->getBeginLoc(),
2791 diag::err_designator_into_flexible_array_member)
2792 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2793 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2794 << *Field;
2795 }
2796 Invalid = true;
2797 }
2798
2799 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2800 !isa<StringLiteral>(DIE->getInit())) {
2801 // The initializer is not an initializer list.
2802 if (!VerifyOnly) {
2803 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2804 diag::err_flexible_array_init_needs_braces)
2805 << DIE->getInit()->getSourceRange();
2806 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2807 << *Field;
2808 }
2809 Invalid = true;
2810 }
2811
2812 // Check GNU flexible array initializer.
2813 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2814 TopLevelObject))
2815 Invalid = true;
2816
2817 if (Invalid) {
2818 ++Index;
2819 return true;
2820 }
2821
2822 // Initialize the array.
2823 bool prevHadError = hadError;
2824 unsigned newStructuredIndex = FieldIndex;
2825 unsigned OldIndex = Index;
2826 IList->setInit(Index, DIE->getInit());
2827
2828 InitializedEntity MemberEntity =
2829 InitializedEntity::InitializeMember(*Field, &Entity);
2830 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2831 StructuredList, newStructuredIndex);
2832
2833 IList->setInit(OldIndex, DIE);
2834 if (hadError && !prevHadError) {
2835 ++Field;
2836 ++FieldIndex;
2837 if (NextField)
2838 *NextField = Field;
2839 StructuredIndex = FieldIndex;
2840 return true;
2841 }
2842 } else {
2843 // Recurse to check later designated subobjects.
2844 QualType FieldType = Field->getType();
2845 unsigned newStructuredIndex = FieldIndex;
2846
2847 InitializedEntity MemberEntity =
2848 InitializedEntity::InitializeMember(*Field, &Entity);
2849 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2850 FieldType, nullptr, nullptr, Index,
2851 StructuredList, newStructuredIndex,
2852 FinishSubobjectInit, false))
2853 return true;
2854 }
2855
2856 // Find the position of the next field to be initialized in this
2857 // subobject.
2858 ++Field;
2859 ++FieldIndex;
2860
2861 // If this the first designator, our caller will continue checking
2862 // the rest of this struct/class/union subobject.
2863 if (IsFirstDesignator) {
2864 if (NextField)
2865 *NextField = Field;
2866 StructuredIndex = FieldIndex;
2867 return false;
2868 }
2869
2870 if (!FinishSubobjectInit)
2871 return false;
2872
2873 // We've already initialized something in the union; we're done.
2874 if (RT->getDecl()->isUnion())
2875 return hadError;
2876
2877 // Check the remaining fields within this class/struct/union subobject.
2878 bool prevHadError = hadError;
2879
2880 auto NoBases =
2881 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2882 CXXRecordDecl::base_class_iterator());
2883 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2884 false, Index, StructuredList, FieldIndex);
2885 return hadError && !prevHadError;
2886 }
2887
2888 // C99 6.7.8p6:
2889 //
2890 // If a designator has the form
2891 //
2892 // [ constant-expression ]
2893 //
2894 // then the current object (defined below) shall have array
2895 // type and the expression shall be an integer constant
2896 // expression. If the array is of unknown size, any
2897 // nonnegative value is valid.
2898 //
2899 // Additionally, cope with the GNU extension that permits
2900 // designators of the form
2901 //
2902 // [ constant-expression ... constant-expression ]
2903 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2904 if (!AT) {
2905 if (!VerifyOnly)
2906 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2907 << CurrentObjectType;
2908 ++Index;
2909 return true;
2910 }
2911
2912 Expr *IndexExpr = nullptr;
2913 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2914 if (D->isArrayDesignator()) {
2915 IndexExpr = DIE->getArrayIndex(*D);
2916 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2917 DesignatedEndIndex = DesignatedStartIndex;
2918 } else {
2919 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", 2919, __extension__ __PRETTY_FUNCTION__
))
;
2920
2921 DesignatedStartIndex =
2922 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2923 DesignatedEndIndex =
2924 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2925 IndexExpr = DIE->getArrayRangeEnd(*D);
2926
2927 // Codegen can't handle evaluating array range designators that have side
2928 // effects, because we replicate the AST value for each initialized element.
2929 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2930 // elements with something that has a side effect, so codegen can emit an
2931 // "error unsupported" error instead of miscompiling the app.
2932 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2933 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2934 FullyStructuredList->sawArrayRangeDesignator();
2935 }
2936
2937 if (isa<ConstantArrayType>(AT)) {
2938 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2939 DesignatedStartIndex
2940 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2941 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2942 DesignatedEndIndex
2943 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2944 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2945 if (DesignatedEndIndex >= MaxElements) {
2946 if (!VerifyOnly)
2947 SemaRef.Diag(IndexExpr->getBeginLoc(),
2948 diag::err_array_designator_too_large)
2949 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
2950 << IndexExpr->getSourceRange();
2951 ++Index;
2952 return true;
2953 }
2954 } else {
2955 unsigned DesignatedIndexBitWidth =
2956 ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2957 DesignatedStartIndex =
2958 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2959 DesignatedEndIndex =
2960 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2961 DesignatedStartIndex.setIsUnsigned(true);
2962 DesignatedEndIndex.setIsUnsigned(true);
2963 }
2964
2965 bool IsStringLiteralInitUpdate =
2966 StructuredList && StructuredList->isStringLiteralInit();
2967 if (IsStringLiteralInitUpdate && VerifyOnly) {
2968 // We're just verifying an update to a string literal init. We don't need
2969 // to split the string up into individual characters to do that.
2970 StructuredList = nullptr;
2971 } else if (IsStringLiteralInitUpdate) {
2972 // We're modifying a string literal init; we have to decompose the string
2973 // so we can modify the individual characters.
2974 ASTContext &Context = SemaRef.Context;
2975 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
2976
2977 // Compute the character type
2978 QualType CharTy = AT->getElementType();
2979
2980 // Compute the type of the integer literals.
2981 QualType PromotedCharTy = CharTy;
2982 if (Context.isPromotableIntegerType(CharTy))
2983 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2984 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2985
2986 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2987 // Get the length of the string.
2988 uint64_t StrLen = SL->getLength();
2989 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2990 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2991 StructuredList->resizeInits(Context, StrLen);
2992
2993 // Build a literal for each character in the string, and put them into
2994 // the init list.
2995 for (unsigned i = 0, e = StrLen; i != e; ++i) {
2996 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2997 Expr *Init = new (Context) IntegerLiteral(
2998 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2999 if (CharTy != PromotedCharTy)
3000 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3001 Init, nullptr, VK_PRValue,
3002 FPOptionsOverride());
3003 StructuredList->updateInit(Context, i, Init);
3004 }
3005 } else {
3006 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3007 std::string Str;
3008 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3009
3010 // Get the length of the string.
3011 uint64_t StrLen = Str.size();
3012 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3013 StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3014 StructuredList->resizeInits(Context, StrLen);
3015
3016 // Build a literal for each character in the string, and put them into
3017 // the init list.
3018 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3019 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3020 Expr *Init = new (Context) IntegerLiteral(
3021 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3022 if (CharTy != PromotedCharTy)
3023 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3024 Init, nullptr, VK_PRValue,
3025 FPOptionsOverride());
3026 StructuredList->updateInit(Context, i, Init);
3027 }
3028 }
3029 }
3030
3031 // Make sure that our non-designated initializer list has space
3032 // for a subobject corresponding to this array element.
3033 if (StructuredList &&
3034 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3035 StructuredList->resizeInits(SemaRef.Context,
3036 DesignatedEndIndex.getZExtValue() + 1);
3037
3038 // Repeatedly perform subobject initializations in the range
3039 // [DesignatedStartIndex, DesignatedEndIndex].
3040
3041 // Move to the next designator
3042 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3043 unsigned OldIndex = Index;
3044
3045 InitializedEntity ElementEntity =
3046 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3047
3048 while (DesignatedStartIndex <= DesignatedEndIndex) {
3049 // Recurse to check later designated subobjects.
3050 QualType ElementType = AT->getElementType();
3051 Index = OldIndex;
3052
3053 ElementEntity.setElementIndex(ElementIndex);
3054 if (CheckDesignatedInitializer(
3055 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3056 nullptr, Index, StructuredList, ElementIndex,
3057 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3058 false))
3059 return true;
3060
3061 // Move to the next index in the array that we'll be initializing.
3062 ++DesignatedStartIndex;
3063 ElementIndex = DesignatedStartIndex.getZExtValue();
3064 }
3065
3066 // If this the first designator, our caller will continue checking
3067 // the rest of this array subobject.
3068 if (IsFirstDesignator) {
3069 if (NextElementIndex)
3070 *NextElementIndex = DesignatedStartIndex;
3071 StructuredIndex = ElementIndex;
3072 return false;
3073 }
3074
3075 if (!FinishSubobjectInit)
3076 return false;
3077
3078 // Check the remaining elements within this array subobject.
3079 bool prevHadError = hadError;
3080 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3081 /*SubobjectIsDesignatorContext=*/false, Index,
3082 StructuredList, ElementIndex);
3083 return hadError && !prevHadError;
3084}
3085
3086// Get the structured initializer list for a subobject of type
3087// @p CurrentObjectType.
3088InitListExpr *
3089InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3090 QualType CurrentObjectType,
3091 InitListExpr *StructuredList,
3092 unsigned StructuredIndex,
3093 SourceRange InitRange,
3094 bool IsFullyOverwritten) {
3095 if (!StructuredList)
3096 return nullptr;
3097
3098 Expr *ExistingInit = nullptr;
3099 if (StructuredIndex < StructuredList->getNumInits())
3100 ExistingInit = StructuredList->getInit(StructuredIndex);
3101
3102 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3103 // There might have already been initializers for subobjects of the current
3104 // object, but a subsequent initializer list will overwrite the entirety
3105 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3106 //
3107 // struct P { char x[6]; };
3108 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3109 //
3110 // The first designated initializer is ignored, and l.x is just "f".
3111 if (!IsFullyOverwritten)
3112 return Result;
3113
3114 if (ExistingInit) {
3115 // We are creating an initializer list that initializes the
3116 // subobjects of the current object, but there was already an
3117 // initialization that completely initialized the current
3118 // subobject:
3119 //
3120 // struct X { int a, b; };
3121 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3122 //
3123 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3124 // designated initializer overwrites the [0].b initializer
3125 // from the prior initialization.
3126 //
3127 // When the existing initializer is an expression rather than an
3128 // initializer list, we cannot decompose and update it in this way.
3129 // For example:
3130 //
3131 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3132 //
3133 // This case is handled by CheckDesignatedInitializer.
3134 diagnoseInitOverride(ExistingInit, InitRange);
3135 }
3136
3137 unsigned ExpectedNumInits = 0;
3138 if (Index < IList->getNumInits()) {
3139 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3140 ExpectedNumInits = Init->getNumInits();
3141 else
3142 ExpectedNumInits = IList->getNumInits() - Index;
3143 }
3144
3145 InitListExpr *Result =
3146 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3147
3148 // Link this new initializer list into the structured initializer
3149 // lists.
3150 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3151 return Result;
3152}
3153
3154InitListExpr *
3155InitListChecker::createInitListExpr(QualType CurrentObjectType,
3156 SourceRange InitRange,
3157 unsigned ExpectedNumInits) {
3158 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3159 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3160
3161 QualType ResultType = CurrentObjectType;
3162 if (!ResultType->isArrayType())
3163 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3164 Result->setType(ResultType);
3165
3166 // Pre-allocate storage for the structured initializer list.
3167 unsigned NumElements = 0;
3168
3169 if (const ArrayType *AType
3170 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3171 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3172 NumElements = CAType->getSize().getZExtValue();
3173 // Simple heuristic so that we don't allocate a very large
3174 // initializer with many empty entries at the end.
3175 if (NumElements > ExpectedNumInits)
3176 NumElements = 0;
3177 }
3178 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3179 NumElements = VType->getNumElements();
3180 } else if (CurrentObjectType->isRecordType()) {
3181 NumElements = numStructUnionElements(CurrentObjectType);
3182 }
3183
3184 Result->reserveInits(SemaRef.Context, NumElements);
3185
3186 return Result;
3187}
3188
3189/// Update the initializer at index @p StructuredIndex within the
3190/// structured initializer list to the value @p expr.
3191void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3192 unsigned &StructuredIndex,
3193 Expr *expr) {
3194 // No structured initializer list to update
3195 if (!StructuredList)
3196 return;
3197
3198 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3199 StructuredIndex, expr)) {
3200 // This initializer overwrites a previous initializer.
3201 // No need to diagnose when `expr` is nullptr because a more relevant
3202 // diagnostic has already been issued and this diagnostic is potentially
3203 // noise.
3204 if (expr)
3205 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3206 }
3207
3208 ++StructuredIndex;
3209}
3210
3211/// Determine whether we can perform aggregate initialization for the purposes
3212/// of overload resolution.
3213bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3214 const InitializedEntity &Entity, InitListExpr *From) {
3215 QualType Type = Entity.getType();
3216 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3217 /*TreatUnavailableAsInvalid=*/false,
3218 /*InOverloadResolution=*/true);
3219 return !Check.HadError();
3220}
3221
3222/// Check that the given Index expression is a valid array designator
3223/// value. This is essentially just a wrapper around
3224/// VerifyIntegerConstantExpression that also checks for negative values
3225/// and produces a reasonable diagnostic if there is a
3226/// failure. Returns the index expression, possibly with an implicit cast
3227/// added, on success. If everything went okay, Value will receive the
3228/// value of the constant expression.
3229static ExprResult
3230CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3231 SourceLocation Loc = Index->getBeginLoc();
3232
3233 // Make sure this is an integer constant expression.
3234 ExprResult Result =
3235 S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3236 if (Result.isInvalid())
3237 return Result;
3238
3239 if (Value.isSigned() && Value.isNegative())
3240 return S.Diag(Loc, diag::err_array_designator_negative)
3241 << toString(Value, 10) << Index->getSourceRange();
3242
3243 Value.setIsUnsigned(true);
3244 return Result;
3245}
3246
3247ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3248 SourceLocation EqualOrColonLoc,
3249 bool GNUSyntax,
3250 ExprResult Init) {
3251 typedef DesignatedInitExpr::Designator ASTDesignator;
3252
3253 bool Invalid = false;
3254 SmallVector<ASTDesignator, 32> Designators;
3255 SmallVector<Expr *, 32> InitExpressions;
3256
3257 // Build designators and check array designator expressions.
3258 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3259 const Designator &D = Desig.getDesignator(Idx);
3260
3261 if (D.isFieldDesignator()) {
3262 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3263 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3264 } else if (D.isArrayDesignator()) {
3265 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3266 llvm::APSInt IndexValue;
3267 if (!Index->isTypeDependent() && !Index->isValueDependent())
3268 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3269 if (!Index)
3270 Invalid = true;
3271 else {
3272 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3273 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3274 InitExpressions.push_back(Index);
3275 }
3276 } else if (D.isArrayRangeDesignator()) {
3277 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3278 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3279 llvm::APSInt StartValue;
3280 llvm::APSInt EndValue;
3281 bool StartDependent = StartIndex->isTypeDependent() ||
3282 StartIndex->isValueDependent();
3283 bool EndDependent = EndIndex->isTypeDependent() ||
3284 EndIndex->isValueDependent();
3285 if (!StartDependent)
3286 StartIndex =
3287 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3288 if (!EndDependent)
3289 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3290
3291 if (!StartIndex || !EndIndex)
3292 Invalid = true;
3293 else {
3294 // Make sure we're comparing values with the same bit width.
3295 if (StartDependent || EndDependent) {
3296 // Nothing to compute.
3297 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3298 EndValue = EndValue.extend(StartValue.getBitWidth());
3299 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3300 StartValue = StartValue.extend(EndValue.getBitWidth());
3301
3302 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3303 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3304 << toString(StartValue, 10) << toString(EndValue, 10)
3305 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3306 Invalid = true;
3307 } else {
3308 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3309 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3310 D.getRBracketLoc()));
3311 InitExpressions.push_back(StartIndex);
3312 InitExpressions.push_back(EndIndex);
3313 }
3314 }
3315 }
3316 }
3317
3318 if (Invalid || Init.isInvalid())
3319 return ExprError();
3320
3321 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3322 EqualOrColonLoc, GNUSyntax,
3323 Init.getAs<Expr>());
3324}
3325
3326//===----------------------------------------------------------------------===//
3327// Initialization entity
3328//===----------------------------------------------------------------------===//
3329
3330InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3331 const InitializedEntity &Parent)
3332 : Parent(&Parent), Index(Index)
3333{
3334 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3335 Kind = EK_ArrayElement;
3336 Type = AT->getElementType();
3337 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3338 Kind = EK_VectorElement;
3339 Type = VT->getElementType();
3340 } else {
3341 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3342 assert(CT && "Unexpected type")(static_cast <bool> (CT && "Unexpected type") ?
void (0) : __assert_fail ("CT && \"Unexpected type\""
, "clang/lib/Sema/SemaInit.cpp", 3342, __extension__ __PRETTY_FUNCTION__
))
;
3343 Kind = EK_ComplexElement;
3344 Type = CT->getElementType();
3345 }
3346}
3347
3348InitializedEntity
3349InitializedEntity::InitializeBase(ASTContext &Context,
3350 const CXXBaseSpecifier *Base,
3351 bool IsInheritedVirtualBase,
3352 const InitializedEntity *Parent) {
3353 InitializedEntity Result;
3354 Result.Kind = EK_Base;
3355 Result.Parent = Parent;
3356 Result.Base = {Base, IsInheritedVirtualBase};
3357 Result.Type = Base->getType();
3358 return Result;
3359}
3360
3361DeclarationName InitializedEntity::getName() const {
3362 switch (getKind()) {
3363 case EK_Parameter:
3364 case EK_Parameter_CF_Audited: {
3365 ParmVarDecl *D = Parameter.getPointer();
3366 return (D ? D->getDeclName() : DeclarationName());
3367 }
3368
3369 case EK_Variable:
3370 case EK_Member:
3371 case EK_ParenAggInitMember:
3372 case EK_Binding:
3373 case EK_TemplateParameter:
3374 return Variable.VariableOrMember->getDeclName();
3375
3376 case EK_LambdaCapture:
3377 return DeclarationName(Capture.VarID);
3378
3379 case EK_Result:
3380 case EK_StmtExprResult:
3381 case EK_Exception:
3382 case EK_New:
3383 case EK_Temporary:
3384 case EK_Base:
3385 case EK_Delegating:
3386 case EK_ArrayElement:
3387 case EK_VectorElement:
3388 case EK_ComplexElement:
3389 case EK_BlockElement:
3390 case EK_LambdaToBlockConversionBlockElement:
3391 case EK_CompoundLiteralInit:
3392 case EK_RelatedResult:
3393 return DeclarationName();
3394 }
3395
3396 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3396)
;
3397}
3398
3399ValueDecl *InitializedEntity::getDecl() const {
3400 switch (getKind()) {
3401 case EK_Variable:
3402 case EK_Member:
3403 case EK_ParenAggInitMember:
3404 case EK_Binding:
3405 case EK_TemplateParameter:
3406 return Variable.VariableOrMember;
3407
3408 case EK_Parameter:
3409 case EK_Parameter_CF_Audited:
3410 return Parameter.getPointer();
3411
3412 case EK_Result:
3413 case EK_StmtExprResult:
3414 case EK_Exception:
3415 case EK_New:
3416 case EK_Temporary:
3417 case EK_Base:
3418 case EK_Delegating:
3419 case EK_ArrayElement:
3420 case EK_VectorElement:
3421 case EK_ComplexElement:
3422 case EK_BlockElement:
3423 case EK_LambdaToBlockConversionBlockElement:
3424 case EK_LambdaCapture:
3425 case EK_CompoundLiteralInit:
3426 case EK_RelatedResult:
3427 return nullptr;
3428 }
3429
3430 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3430)
;
3431}
3432
3433bool InitializedEntity::allowsNRVO() const {
3434 switch (getKind()) {
3435 case EK_Result:
3436 case EK_Exception:
3437 return LocAndNRVO.NRVO;
3438
3439 case EK_StmtExprResult:
3440 case EK_Variable:
3441 case EK_Parameter:
3442 case EK_Parameter_CF_Audited:
3443 case EK_TemplateParameter:
3444 case EK_Member:
3445 case EK_ParenAggInitMember:
3446 case EK_Binding:
3447 case EK_New:
3448 case EK_Temporary:
3449 case EK_CompoundLiteralInit:
3450 case EK_Base:
3451 case EK_Delegating:
3452 case EK_ArrayElement:
3453 case EK_VectorElement:
3454 case EK_ComplexElement:
3455 case EK_BlockElement:
3456 case EK_LambdaToBlockConversionBlockElement:
3457 case EK_LambdaCapture:
3458 case EK_RelatedResult:
3459 break;
3460 }
3461
3462 return false;
3463}
3464
3465unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3466 assert(getParent() != this)(static_cast <bool> (getParent() != this) ? void (0) : __assert_fail
("getParent() != this", "clang/lib/Sema/SemaInit.cpp", 3466,
__extension__ __PRETTY_FUNCTION__))
;
3467 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3468 for (unsigned I = 0; I != Depth; ++I)
3469 OS << "`-";
3470
3471 switch (getKind()) {
3472 case EK_Variable: OS << "Variable"; break;
3473 case EK_Parameter: OS << "Parameter"; break;
3474 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3475 break;
3476 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3477 case EK_Result: OS << "Result"; break;
3478 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3479 case EK_Exception: OS << "Exception"; break;
3480 case EK_Member:
3481 case EK_ParenAggInitMember:
3482 OS << "Member";
3483 break;
3484 case EK_Binding: OS << "Binding"; break;
3485 case EK_New: OS << "New"; break;
3486 case EK_Temporary: OS << "Temporary"; break;
3487 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3488 case EK_RelatedResult: OS << "RelatedResult"; break;
3489 case EK_Base: OS << "Base"; break;
3490 case EK_Delegating: OS << "Delegating"; break;
3491 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3492 case EK_VectorElement: OS << "VectorElement " << Index; break;
3493 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3494 case EK_BlockElement: OS << "Block"; break;
3495 case EK_LambdaToBlockConversionBlockElement:
3496 OS << "Block (lambda)";
3497 break;
3498 case EK_LambdaCapture:
3499 OS << "LambdaCapture ";
3500 OS << DeclarationName(Capture.VarID);
3501 break;
3502 }
3503
3504 if (auto *D = getDecl()) {
3505 OS << " ";
3506 D->printQualifiedName(OS);
3507 }
3508
3509 OS << " '" << getType() << "'\n";
3510
3511 return Depth + 1;
3512}
3513
3514LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const {
3515 dumpImpl(llvm::errs());
3516}
3517
3518//===----------------------------------------------------------------------===//
3519// Initialization sequence
3520//===----------------------------------------------------------------------===//
3521
3522void InitializationSequence::Step::Destroy() {
3523 switch (Kind) {
3524 case SK_ResolveAddressOfOverloadedFunction:
3525 case SK_CastDerivedToBasePRValue:
3526 case SK_CastDerivedToBaseXValue:
3527 case SK_CastDerivedToBaseLValue:
3528 case SK_BindReference:
3529 case SK_BindReferenceToTemporary:
3530 case SK_FinalCopy:
3531 case SK_ExtraneousCopyToTemporary:
3532 case SK_UserConversion:
3533 case SK_QualificationConversionPRValue:
3534 case SK_QualificationConversionXValue:
3535 case SK_QualificationConversionLValue:
3536 case SK_FunctionReferenceConversion:
3537 case SK_AtomicConversion:
3538 case SK_ListInitialization:
3539 case SK_UnwrapInitList:
3540 case SK_RewrapInitList:
3541 case SK_ConstructorInitialization:
3542 case SK_ConstructorInitializationFromList:
3543 case SK_ZeroInitialization:
3544 case SK_CAssignment:
3545 case SK_StringInit:
3546 case SK_ObjCObjectConversion:
3547 case SK_ArrayLoopIndex:
3548 case SK_ArrayLoopInit:
3549 case SK_ArrayInit:
3550 case SK_GNUArrayInit:
3551 case SK_ParenthesizedArrayInit:
3552 case SK_PassByIndirectCopyRestore:
3553 case SK_PassByIndirectRestore:
3554 case SK_ProduceObjCObject:
3555 case SK_StdInitializerList:
3556 case SK_StdInitializerListConstructorCall:
3557 case SK_OCLSamplerInit:
3558 case SK_OCLZeroOpaqueType:
3559 case SK_ParenthesizedListInit:
3560 break;
3561
3562 case SK_ConversionSequence:
3563 case SK_ConversionSequenceNoNarrowing:
3564 delete ICS;
3565 }
3566}
3567
3568bool InitializationSequence::isDirectReferenceBinding() const {
3569 // There can be some lvalue adjustments after the SK_BindReference step.
3570 for (const Step &S : llvm::reverse(Steps)) {
3571 if (S.Kind == SK_BindReference)
3572 return true;
3573 if (S.Kind == SK_BindReferenceToTemporary)
3574 return false;
3575 }
3576 return false;
3577}
3578
3579bool InitializationSequence::isAmbiguous() const {
3580 if (!Failed())
3581 return false;
3582
3583 switch (getFailureKind()) {
3584 case FK_TooManyInitsForReference:
3585 case FK_ParenthesizedListInitForReference:
3586 case FK_ArrayNeedsInitList:
3587 case FK_ArrayNeedsInitListOrStringLiteral:
3588 case FK_ArrayNeedsInitListOrWideStringLiteral:
3589 case FK_NarrowStringIntoWideCharArray:
3590 case FK_WideStringIntoCharArray:
3591 case FK_IncompatWideStringIntoWideChar:
3592 case FK_PlainStringIntoUTF8Char:
3593 case FK_UTF8StringIntoPlainChar:
3594 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3595 case FK_NonConstLValueReferenceBindingToTemporary:
3596 case FK_NonConstLValueReferenceBindingToBitfield:
3597 case FK_NonConstLValueReferenceBindingToVectorElement:
3598 case FK_NonConstLValueReferenceBindingToMatrixElement:
3599 case FK_NonConstLValueReferenceBindingToUnrelated:
3600 case FK_RValueReferenceBindingToLValue:
3601 case FK_ReferenceAddrspaceMismatchTemporary:
3602 case FK_ReferenceInitDropsQualifiers:
3603 case FK_ReferenceInitFailed:
3604 case FK_ConversionFailed:
3605 case FK_ConversionFromPropertyFailed:
3606 case FK_TooManyInitsForScalar:
3607 case FK_ParenthesizedListInitForScalar:
3608 case FK_ReferenceBindingToInitList:
3609 case FK_InitListBadDestinationType:
3610 case FK_DefaultInitOfConst:
3611 case FK_Incomplete:
3612 case FK_ArrayTypeMismatch:
3613 case FK_NonConstantArrayInit:
3614 case FK_ListInitializationFailed:
3615 case FK_VariableLengthArrayHasInitializer:
3616 case FK_PlaceholderType:
3617 case FK_ExplicitConstructor:
3618 case FK_AddressOfUnaddressableFunction:
3619 case FK_ParenthesizedListInitFailed:
3620 case FK_DesignatedInitForNonAggregate:
3621 return false;
3622
3623 case FK_ReferenceInitOverloadFailed:
3624 case FK_UserConversionOverloadFailed:
3625 case FK_ConstructorOverloadFailed:
3626 case FK_ListConstructorOverloadFailed:
3627 return FailedOverloadResult == OR_Ambiguous;
3628 }
3629
3630 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 3630)
;
3631}
3632
3633bool InitializationSequence::isConstructorInitialization() const {
3634 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3635}
3636
3637void
3638InitializationSequence
3639::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3640 DeclAccessPair Found,
3641 bool HadMultipleCandidates) {
3642 Step S;
3643 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3644 S.Type = Function->getType();
3645 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3646 S.Function.Function = Function;
3647 S.Function.FoundDecl = Found;
3648 Steps.push_back(S);
3649}
3650
3651void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3652 ExprValueKind VK) {
3653 Step S;
3654 switch (VK) {
3655 case VK_PRValue:
3656 S.Kind = SK_CastDerivedToBasePRValue;
3657 break;
3658 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3659 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3660 }
3661 S.Type = BaseType;
3662 Steps.push_back(S);
3663}
3664
3665void InitializationSequence::AddReferenceBindingStep(QualType T,
3666 bool BindingTemporary) {
3667 Step S;
3668 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3669 S.Type = T;
3670 Steps.push_back(S);
3671}
3672
3673void InitializationSequence::AddFinalCopy(QualType T) {
3674 Step S;
3675 S.Kind = SK_FinalCopy;
3676 S.Type = T;
3677 Steps.push_back(S);
3678}
3679
3680void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3681 Step S;
3682 S.Kind = SK_ExtraneousCopyToTemporary;
3683 S.Type = T;
3684 Steps.push_back(S);
3685}
3686
3687void
3688InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3689 DeclAccessPair FoundDecl,
3690 QualType T,
3691 bool HadMultipleCandidates) {
3692 Step S;
3693 S.Kind = SK_UserConversion;
3694 S.Type = T;
3695 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3696 S.Function.Function = Function;
3697 S.Function.FoundDecl = FoundDecl;
3698 Steps.push_back(S);
3699}
3700
3701void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3702 ExprValueKind VK) {
3703 Step S;
3704 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3705 switch (VK) {
3706 case VK_PRValue:
3707 S.Kind = SK_QualificationConversionPRValue;
3708 break;
3709 case VK_XValue:
3710 S.Kind = SK_QualificationConversionXValue;
3711 break;
3712 case VK_LValue:
3713 S.Kind = SK_QualificationConversionLValue;
3714 break;
3715 }
3716 S.Type = Ty;
3717 Steps.push_back(S);
3718}
3719
3720void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3721 Step S;
3722 S.Kind = SK_FunctionReferenceConversion;
3723 S.Type = Ty;
3724 Steps.push_back(S);
3725}
3726
3727void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3728 Step S;
3729 S.Kind = SK_AtomicConversion;
3730 S.Type = Ty;
3731 Steps.push_back(S);
3732}
3733
3734void InitializationSequence::AddConversionSequenceStep(
3735 const ImplicitConversionSequence &ICS, QualType T,
3736 bool TopLevelOfInitList) {
3737 Step S;
3738 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3739 : SK_ConversionSequence;
3740 S.Type = T;
3741 S.ICS = new ImplicitConversionSequence(ICS);
3742 Steps.push_back(S);
3743}
3744
3745void InitializationSequence::AddListInitializationStep(QualType T) {
3746 Step S;
3747 S.Kind = SK_ListInitialization;
3748 S.Type = T;
3749 Steps.push_back(S);
3750}
3751
3752void InitializationSequence::AddConstructorInitializationStep(
3753 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3754 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3755 Step S;
3756 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3757 : SK_ConstructorInitializationFromList
3758 : SK_ConstructorInitialization;
3759 S.Type = T;
3760 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3761 S.Function.Function = Constructor;
3762 S.Function.FoundDecl = FoundDecl;
3763 Steps.push_back(S);
3764}
3765
3766void InitializationSequence::AddZeroInitializationStep(QualType T) {
3767 Step S;
3768 S.Kind = SK_ZeroInitialization;
3769 S.Type = T;
3770 Steps.push_back(S);
3771}
3772
3773void InitializationSequence::AddCAssignmentStep(QualType T) {
3774 Step S;
3775 S.Kind = SK_CAssignment;
3776 S.Type = T;
3777 Steps.push_back(S);
3778}
3779
3780void InitializationSequence::AddStringInitStep(QualType T) {
3781 Step S;
3782 S.Kind = SK_StringInit;
3783 S.Type = T;
3784 Steps.push_back(S);
3785}
3786
3787void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3788 Step S;
3789 S.Kind = SK_ObjCObjectConversion;
3790 S.Type = T;
3791 Steps.push_back(S);
3792}
3793
3794void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3795 Step S;
3796 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3797 S.Type = T;
3798 Steps.push_back(S);
3799}
3800
3801void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3802 Step S;
3803 S.Kind = SK_ArrayLoopIndex;
3804 S.Type = EltT;
3805 Steps.insert(Steps.begin(), S);
3806
3807 S.Kind = SK_ArrayLoopInit;
3808 S.Type = T;
3809 Steps.push_back(S);
3810}
3811
3812void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3813 Step S;
3814 S.Kind = SK_ParenthesizedArrayInit;
3815 S.Type = T;
3816 Steps.push_back(S);
3817}
3818
3819void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3820 bool shouldCopy) {
3821 Step s;
3822 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3823 : SK_PassByIndirectRestore);
3824 s.Type = type;
3825 Steps.push_back(s);
3826}
3827
3828void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3829 Step S;
3830 S.Kind = SK_ProduceObjCObject;
3831 S.Type = T;
3832 Steps.push_back(S);
3833}
3834
3835void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3836 Step S;
3837 S.Kind = SK_StdInitializerList;
3838 S.Type = T;
3839 Steps.push_back(S);
3840}
3841
3842void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3843 Step S;
3844 S.Kind = SK_OCLSamplerInit;
3845 S.Type = T;
3846 Steps.push_back(S);
3847}
3848
3849void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3850 Step S;
3851 S.Kind = SK_OCLZeroOpaqueType;
3852 S.Type = T;
3853 Steps.push_back(S);
3854}
3855
3856void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
3857 Step S;
3858 S.Kind = SK_ParenthesizedListInit;
3859 S.Type = T;
3860 Steps.push_back(S);
3861}
3862
3863void InitializationSequence::RewrapReferenceInitList(QualType T,
3864 InitListExpr *Syntactic) {
3865 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", 3866, __extension__ __PRETTY_FUNCTION__
))
3866 "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", 3866, __extension__ __PRETTY_FUNCTION__
))
;
3867 Step S;
3868 S.Kind = SK_UnwrapInitList;
3869 S.Type = Syntactic->getInit(0)->getType();
3870 Steps.insert(Steps.begin(), S);
3871
3872 S.Kind = SK_RewrapInitList;
3873 S.Type = T;
3874 S.WrappingSyntacticList = Syntactic;
3875 Steps.push_back(S);
3876}
3877
3878void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3879 OverloadingResult Result) {
3880 setSequenceKind(FailedSequence);
3881 this->Failure = Failure;
3882 this->FailedOverloadResult = Result;
3883}
3884
3885//===----------------------------------------------------------------------===//
3886// Attempt initialization
3887//===----------------------------------------------------------------------===//
3888
3889/// Tries to add a zero initializer. Returns true if that worked.
3890static bool
3891maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3892 const InitializedEntity &Entity) {
3893 if (Entity.getKind() != InitializedEntity::EK_Variable)
3894 return false;
3895
3896 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3897 if (VD->getInit() || VD->getEndLoc().isMacroID())
3898 return false;
3899
3900 QualType VariableTy = VD->getType().getCanonicalType();
3901 SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3902 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3903 if (!Init.empty()) {
3904 Sequence.AddZeroInitializationStep(Entity.getType());
3905 Sequence.SetZeroInitializationFixit(Init, Loc);
3906 return true;
3907 }
3908 return false;
3909}
3910
3911static void MaybeProduceObjCObject(Sema &S,
3912 InitializationSequence &Sequence,
3913 const InitializedEntity &Entity) {
3914 if (!S.getLangOpts().ObjCAutoRefCount) return;
3915
3916 /// When initializing a parameter, produce the value if it's marked
3917 /// __attribute__((ns_consumed)).
3918 if (Entity.isParameterKind()) {
3919 if (!Entity.isParameterConsumed())
3920 return;
3921
3922 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", 3923, __extension__ __PRETTY_FUNCTION__
))
3923 "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", 3923, __extension__ __PRETTY_FUNCTION__
))
;
3924 Sequence.AddProduceObjCObjectStep(Entity.getType());
3925
3926 /// When initializing a return value, if the return type is a
3927 /// retainable type, then returns need to immediately retain the
3928 /// object. If an autorelease is required, it will be done at the
3929 /// last instant.
3930 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3931 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
3932 if (!Entity.getType()->isObjCRetainableType())
3933 return;
3934
3935 Sequence.AddProduceObjCObjectStep(Entity.getType());
3936 }
3937}
3938
3939static void TryListInitialization(Sema &S,
3940 const InitializedEntity &Entity,
3941 const InitializationKind &Kind,
3942 InitListExpr *InitList,
3943 InitializationSequence &Sequence,
3944 bool TreatUnavailableAsInvalid);
3945
3946/// When initializing from init list via constructor, handle
3947/// initialization of an object of type std::initializer_list<T>.
3948///
3949/// \return true if we have handled initialization of an object of type
3950/// std::initializer_list<T>, false otherwise.
3951static bool TryInitializerListConstruction(Sema &S,
3952 InitListExpr *List,
3953 QualType DestType,
3954 InitializationSequence &Sequence,
3955 bool TreatUnavailableAsInvalid) {
3956 QualType E;
3957 if (!S.isStdInitializerList(DestType, &E))
3958 return false;
3959
3960 if (!S.isCompleteType(List->getExprLoc(), E)) {
3961 Sequence.setIncompleteTypeFailure(E);
3962 return true;
3963 }
3964
3965 // Try initializing a temporary array from the init list.
3966 QualType ArrayType = S.Context.getConstantArrayType(
3967 E.withConst(),
3968 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3969 List->getNumInits()),
3970 nullptr, clang::ArrayType::Normal, 0);
3971 InitializedEntity HiddenArray =
3972 InitializedEntity::InitializeTemporary(ArrayType);
3973 InitializationKind Kind = InitializationKind::CreateDirectList(
3974 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3975 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3976 TreatUnavailableAsInvalid);
3977 if (Sequence)
3978 Sequence.AddStdInitializerListConstructionStep(DestType);
3979 return true;
3980}
3981
3982/// Determine if the constructor has the signature of a copy or move
3983/// constructor for the type T of the class in which it was found. That is,
3984/// determine if its first parameter is of type T or reference to (possibly
3985/// cv-qualified) T.
3986static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3987 const ConstructorInfo &Info) {
3988 if (Info.Constructor->getNumParams() == 0)
3989 return false;
3990
3991 QualType ParmT =
3992 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3993 QualType ClassT =
3994 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3995
3996 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3997}
3998
3999static OverloadingResult
4000ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
4001 MultiExprArg Args,
4002 OverloadCandidateSet &CandidateSet,
4003 QualType DestType,
4004 DeclContext::lookup_result Ctors,
4005 OverloadCandidateSet::iterator &Best,
4006 bool CopyInitializing, bool AllowExplicit,
4007 bool OnlyListConstructors, bool IsListInit,
4008 bool SecondStepOfCopyInit = false) {
4009 CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
4010 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4011
4012 for (NamedDecl *D : Ctors) {
4013 auto Info = getConstructorInfo(D);
4014 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4015 continue;
4016
4017 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4018 continue;
4019
4020 // C++11 [over.best.ics]p4:
4021 // ... and the constructor or user-defined conversion function is a
4022 // candidate by
4023 // - 13.3.1.3, when the argument is the temporary in the second step
4024 // of a class copy-initialization, or
4025 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4026 // - the second phase of 13.3.1.7 when the initializer list has exactly
4027 // one element that is itself an initializer list, and the target is
4028 // the first parameter of a constructor of class X, and the conversion
4029 // is to X or reference to (possibly cv-qualified X),
4030 // user-defined conversion sequences are not considered.
4031 bool SuppressUserConversions =
4032 SecondStepOfCopyInit ||
4033 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4034 hasCopyOrMoveCtorParam(S.Context, Info));
4035
4036 if (Info.ConstructorTmpl)
4037 S.AddTemplateOverloadCandidate(
4038 Info.ConstructorTmpl, Info.FoundDecl,
4039 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4040 /*PartialOverloading=*/false, AllowExplicit);
4041 else {
4042 // C++ [over.match.copy]p1:
4043 // - When initializing a temporary to be bound to the first parameter
4044 // of a constructor [for type T] that takes a reference to possibly
4045 // cv-qualified T as its first argument, called with a single
4046 // argument in the context of direct-initialization, explicit
4047 // conversion functions are also considered.
4048 // FIXME: What if a constructor template instantiates to such a signature?
4049 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4050 Args.size() == 1 &&
4051 hasCopyOrMoveCtorParam(S.Context, Info);
4052 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4053 CandidateSet, SuppressUserConversions,
4054 /*PartialOverloading=*/false, AllowExplicit,
4055 AllowExplicitConv);
4056 }
4057 }
4058
4059 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4060 //
4061 // When initializing an object of class type T by constructor
4062 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4063 // from a single expression of class type U, conversion functions of
4064 // U that convert to the non-reference type cv T are candidates.
4065 // Explicit conversion functions are only candidates during
4066 // direct-initialization.
4067 //
4068 // Note: SecondStepOfCopyInit is only ever true in this case when
4069 // evaluating whether to produce a C++98 compatibility warning.
4070 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4071 !SecondStepOfCopyInit) {
4072 Expr *Initializer = Args[0];
4073 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4074 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4075 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4076 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4077 NamedDecl *D = *I;
4078 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4079 D = D->getUnderlyingDecl();
4080
4081 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4082 CXXConversionDecl *Conv;
4083 if (ConvTemplate)
4084 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4085 else
4086 Conv = cast<CXXConversionDecl>(D);
4087
4088 if (ConvTemplate)
4089 S.AddTemplateConversionCandidate(
4090 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4091 CandidateSet, AllowExplicit, AllowExplicit,
4092 /*AllowResultConversion*/ false);
4093 else
4094 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4095 DestType, CandidateSet, AllowExplicit,
4096 AllowExplicit,
4097 /*AllowResultConversion*/ false);
4098 }
4099 }
4100 }
4101
4102 // Perform overload resolution and return the result.
4103 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4104}
4105
4106/// Attempt initialization by constructor (C++ [dcl.init]), which
4107/// enumerates the constructors of the initialized entity and performs overload
4108/// resolution to select the best.
4109/// \param DestType The destination class type.
4110/// \param DestArrayType The destination type, which is either DestType or
4111/// a (possibly multidimensional) array of DestType.
4112/// \param IsListInit Is this list-initialization?
4113/// \param IsInitListCopy Is this non-list-initialization resulting from a
4114/// list-initialization from {x} where x is the same
4115/// type as the entity?
4116static void TryConstructorInitialization(Sema &S,
4117 const InitializedEntity &Entity,
4118 const InitializationKind &Kind,
4119 MultiExprArg Args, QualType DestType,
4120 QualType DestArrayType,
4121 InitializationSequence &Sequence,
4122 bool IsListInit = false,
4123 bool IsInitListCopy = false) {
4124 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", 4127, __extension__ __PRETTY_FUNCTION__
))
4125 (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", 4127, __extension__ __PRETTY_FUNCTION__
))
4126 "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", 4127, __extension__ __PRETTY_FUNCTION__
))
4127 "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", 4127, __extension__ __PRETTY_FUNCTION__
))
;
4128 InitListExpr *ILE =
4129 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4130 MultiExprArg UnwrappedArgs =
4131 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4132
4133 // The type we're constructing needs to be complete.
4134 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4135 Sequence.setIncompleteTypeFailure(DestType);
4136 return;
4137 }
4138
4139 // C++17 [dcl.init]p17:
4140 // - If the initializer expression is a prvalue and the cv-unqualified
4141 // version of the source type is the same class as the class of the
4142 // destination, the initializer expression is used to initialize the
4143 // destination object.
4144 // Per DR (no number yet), this does not apply when initializing a base
4145 // class or delegating to another constructor from a mem-initializer.
4146 // ObjC++: Lambda captured by the block in the lambda to block conversion
4147 // should avoid copy elision.
4148 if (S.getLangOpts().CPlusPlus17 &&
4149 Entity.getKind() != InitializedEntity::EK_Base &&
4150 Entity.getKind() != InitializedEntity::EK_Delegating &&
4151 Entity.getKind() !=
4152 InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
4153 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4154 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4155 // Convert qualifications if necessary.
4156 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4157 if (ILE)
4158 Sequence.RewrapReferenceInitList(DestType, ILE);
4159 return;
4160 }
4161
4162 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4163 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", 4163, __extension__ __PRETTY_FUNCTION__
))
;
4164 CXXRecordDecl *DestRecordDecl
4165 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4166
4167 // Build the candidate set directly in the initialization sequence
4168 // structure, so that it will persist if we fail.
4169 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4170
4171 // Determine whether we are allowed to call explicit constructors or
4172 // explicit conversion operators.
4173 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4174 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4175
4176 // - Otherwise, if T is a class type, constructors are considered. The
4177 // applicable constructors are enumerated, and the best one is chosen
4178 // through overload resolution.
4179 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4180
4181 OverloadingResult Result = OR_No_Viable_Function;
4182 OverloadCandidateSet::iterator Best;
4183 bool AsInitializerList = false;
4184
4185 // C++11 [over.match.list]p1, per DR1467:
4186 // When objects of non-aggregate type T are list-initialized, such that
4187 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4188 // according to the rules in this section, overload resolution selects
4189 // the constructor in two phases:
4190 //
4191 // - Initially, the candidate functions are the initializer-list
4192 // constructors of the class T and the argument list consists of the
4193 // initializer list as a single argument.
4194 if (IsListInit) {
4195 AsInitializerList = true;
4196
4197 // If the initializer list has no elements and T has a default constructor,
4198 // the first phase is omitted.
4199 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4200 Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
4201 CandidateSet, DestType, Ctors, Best,
4202 CopyInitialization, AllowExplicit,
4203 /*OnlyListConstructors=*/true,
4204 IsListInit);
4205 }
4206
4207 // C++11 [over.match.list]p1:
4208 // - If no viable initializer-list constructor is found, overload resolution
4209 // is performed again, where the candidate functions are all the
4210 // constructors of the class T and the argument list consists of the
4211 // elements of the initializer list.
4212 if (Result == OR_No_Viable_Function) {
4213 AsInitializerList = false;
4214 Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
4215 CandidateSet, DestType, Ctors, Best,
4216 CopyInitialization, AllowExplicit,
4217 /*OnlyListConstructors=*/false,
4218 IsListInit);
4219 }
4220 if (Result) {
4221 Sequence.SetOverloadFailure(
4222 IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4223 : InitializationSequence::FK_ConstructorOverloadFailed,
4224 Result);
4225
4226 if (Result != OR_Deleted)
4227 return;
4228 }
4229
4230 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4231
4232 // In C++17, ResolveConstructorOverload can select a conversion function
4233 // instead of a constructor.
4234 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4235 // Add the user-defined conversion step that calls the conversion function.
4236 QualType ConvType = CD->getConversionType();
4237 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", 4238, __extension__ __PRETTY_FUNCTION__
))
4238 "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", 4238, __extension__ __PRETTY_FUNCTION__
))
;
4239 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4240 HadMultipleCandidates);
4241 if (!S.Context.hasSameType(ConvType, DestType))
4242 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4243 if (IsListInit)
4244 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4245 return;
4246 }
4247
4248 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4249 if (Result != OR_Deleted) {
4250 // C++11 [dcl.init]p6:
4251 // If a program calls for the default initialization of an object
4252 // of a const-qualified type T, T shall be a class type with a
4253 // user-provided default constructor.
4254 // C++ core issue 253 proposal:
4255 // If the implicit default constructor initializes all subobjects, no
4256 // initializer should be required.
4257 // The 253 proposal is for example needed to process libstdc++ headers
4258 // in 5.x.
4259 if (Kind.getKind() == InitializationKind::IK_Default &&
4260 Entity.getType().isConstQualified()) {
4261 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4262 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4263 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4264 return;
4265 }
4266 }
4267
4268 // C++11 [over.match.list]p1:
4269 // In copy-list-initialization, if an explicit constructor is chosen, the
4270 // initializer is ill-formed.
4271 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4272 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4273 return;
4274 }
4275 }
4276
4277 // [class.copy.elision]p3:
4278 // In some copy-initialization contexts, a two-stage overload resolution
4279 // is performed.
4280 // If the first overload resolution selects a deleted function, we also
4281 // need the initialization sequence to decide whether to perform the second
4282 // overload resolution.
4283 // For deleted functions in other contexts, there is no need to get the
4284 // initialization sequence.
4285 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4286 return;
4287
4288 // Add the constructor initialization step. Any cv-qualification conversion is
4289 // subsumed by the initialization.
4290 Sequence.AddConstructorInitializationStep(
4291 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4292 IsListInit | IsInitListCopy, AsInitializerList);
4293}
4294
4295static bool
4296ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4297 Expr *Initializer,
4298 QualType &SourceType,
4299 QualType &UnqualifiedSourceType,
4300 QualType UnqualifiedTargetType,
4301 InitializationSequence &Sequence) {
4302 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4303 S.Context.OverloadTy) {
4304 DeclAccessPair Found;
4305 bool HadMultipleCandidates = false;
4306 if (FunctionDecl *Fn
4307 = S.ResolveAddressOfOverloadedFunction(Initializer,
4308 UnqualifiedTargetType,
4309 false, Found,
4310 &HadMultipleCandidates)) {
4311 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4312 HadMultipleCandidates);
4313 SourceType = Fn->getType();
4314 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4315 } else if (!UnqualifiedTargetType->isRecordType()) {
4316 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4317 return true;
4318 }
4319 }
4320 return false;
4321}
4322
4323static void TryReferenceInitializationCore(Sema &S,
4324 const InitializedEntity &Entity,
4325 const InitializationKind &Kind,
4326 Expr *Initializer,
4327 QualType cv1T1, QualType T1,
4328 Qualifiers T1Quals,
4329 QualType cv2T2, QualType T2,
4330 Qualifiers T2Quals,
4331 InitializationSequence &Sequence);
4332
4333static void TryValueInitialization(Sema &S,
4334 const InitializedEntity &Entity,
4335 const InitializationKind &Kind,
4336 InitializationSequence &Sequence,
4337 InitListExpr *InitList = nullptr);
4338
4339/// Attempt list initialization of a reference.
4340static void TryReferenceListInitialization(Sema &S,
4341 const InitializedEntity &Entity,
4342 const InitializationKind &Kind,
4343 InitListExpr *InitList,
4344 InitializationSequence &Sequence,
4345 bool TreatUnavailableAsInvalid) {
4346 // First, catch C++03 where this isn't possible.
4347 if (!S.getLangOpts().CPlusPlus11) {
4348 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4349 return;
4350 }
4351 // Can't reference initialize a compound literal.
4352 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4353 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4354 return;
4355 }
4356
4357 QualType DestType = Entity.getType();
4358 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4359 Qualifiers T1Quals;
4360 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4361
4362 // Reference initialization via an initializer list works thus:
4363 // If the initializer list consists of a single element that is
4364 // reference-related to the referenced type, bind directly to that element
4365 // (possibly creating temporaries).
4366 // Otherwise, initialize a temporary with the initializer list and
4367 // bind to that.
4368 if (InitList->getNumInits() == 1) {
4369 Expr *Initializer = InitList->getInit(0);
4370 QualType cv2T2 = S.getCompletedType(Initializer);
4371 Qualifiers T2Quals;
4372 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4373
4374 // If this fails, creating a temporary wouldn't work either.
4375 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4376 T1, Sequence))
4377 return;
4378
4379 SourceLocation DeclLoc = Initializer->getBeginLoc();
4380 Sema::ReferenceCompareResult RefRelationship
4381 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4382 if (RefRelationship >= Sema::Ref_Related) {
4383 // Try to bind the reference here.
4384 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4385 T1Quals, cv2T2, T2, T2Quals, Sequence);
4386 if (Sequence)
4387 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4388 return;
4389 }
4390
4391 // Update the initializer if we've resolved an overloaded function.
4392 if (Sequence.step_begin() != Sequence.step_end())
4393 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4394 }
4395 // Perform address space compatibility check.
4396 QualType cv1T1IgnoreAS = cv1T1;
4397 if (T1Quals.hasAddressSpace()) {
4398 Qualifiers T2Quals;
4399 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4400 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4401 Sequence.SetFailed(
4402 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4403 return;
4404 }
4405 // Ignore address space of reference type at this point and perform address
4406 // space conversion after the reference binding step.
4407 cv1T1IgnoreAS =
4408 S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4409 }
4410 // Not reference-related. Create a temporary and bind to that.
4411 InitializedEntity TempEntity =
4412 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4413
4414 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4415 TreatUnavailableAsInvalid);
4416 if (Sequence) {
4417 if (DestType->isRValueReferenceType() ||
4418 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4419 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4420 /*BindingTemporary=*/true);
4421 if (T1Quals.hasAddressSpace())
4422 Sequence.AddQualificationConversionStep(
4423 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4424 } else
4425 Sequence.SetFailed(
4426 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4427 }
4428}
4429
4430/// Attempt list initialization (C++0x [dcl.init.list])
4431static void TryListInitialization(Sema &S,
4432 const InitializedEntity &Entity,
4433 const InitializationKind &Kind,
4434 InitListExpr *InitList,
4435 InitializationSequence &Sequence,
4436 bool TreatUnavailableAsInvalid) {
4437 QualType DestType = Entity.getType();
4438
4439 // C++ doesn't allow scalar initialization with more than one argument.
4440 // But C99 complex numbers are scalars and it makes sense there.
4441 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4442 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4443 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4444 return;
4445 }
4446 if (DestType->isReferenceType()) {
4447 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4448 TreatUnavailableAsInvalid);
4449 return;
4450 }
4451
4452 if (DestType->isRecordType() &&
4453 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4454 Sequence.setIncompleteTypeFailure(DestType);
4455 return;
4456 }
4457
4458 // C++20 [dcl.init.list]p3:
4459 // - If the braced-init-list contains a designated-initializer-list, T shall
4460 // be an aggregate class. [...] Aggregate initialization is performed.
4461 //
4462 // We allow arrays here too in order to support array designators.
4463 //
4464 // FIXME: This check should precede the handling of reference initialization.
4465 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4466 // as a tentative DR resolution.
4467 bool IsDesignatedInit = InitList->hasDesignatedInit();
4468 if (!DestType->isAggregateType() && IsDesignatedInit) {
4469 Sequence.SetFailed(
4470 InitializationSequence::FK_DesignatedInitForNonAggregate);
4471 return;
4472 }
4473
4474 // C++11 [dcl.init.list]p3, per DR1467:
4475 // - If T is a class type and the initializer list has a single element of
4476 // type cv U, where U is T or a class derived from T, the object is
4477 // initialized from that element (by copy-initialization for
4478 // copy-list-initialization, or by direct-initialization for
4479 // direct-list-initialization).
4480 // - Otherwise, if T is a character array and the initializer list has a
4481 // single element that is an appropriately-typed string literal
4482 // (8.5.2 [dcl.init.string]), initialization is performed as described
4483 // in that section.
4484 // - Otherwise, if T is an aggregate, [...] (continue below).
4485 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4486 !IsDesignatedInit) {
4487 if (DestType->isRecordType()) {
4488 QualType InitType = InitList->getInit(0)->getType();
4489 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4490 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4491 Expr *InitListAsExpr = InitList;
4492 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4493 DestType, Sequence,
4494 /*InitListSyntax*/false,
4495 /*IsInitListCopy*/true);
4496 return;
4497 }
4498 }
4499 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4500 Expr *SubInit[1] = {InitList->getInit(0)};
4501 if (!isa<VariableArrayType>(DestAT) &&
4502 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4503 InitializationKind SubKind =
4504 Kind.getKind() == InitializationKind::IK_DirectList
4505 ? InitializationKind::CreateDirect(Kind.getLocation(),
4506 InitList->getLBraceLoc(),
4507 InitList->getRBraceLoc())
4508 : Kind;
4509 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4510 /*TopLevelOfInitList*/ true,
4511 TreatUnavailableAsInvalid);
4512
4513 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4514 // the element is not an appropriately-typed string literal, in which
4515 // case we should proceed as in C++11 (below).
4516 if (Sequence) {
4517 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4518 return;
4519 }
4520 }
4521 }
4522 }
4523
4524 // C++11 [dcl.init.list]p3:
4525 // - If T is an aggregate, aggregate initialization is performed.
4526 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4527 (S.getLangOpts().CPlusPlus11 &&
4528 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4529 if (S.getLangOpts().CPlusPlus11) {
4530 // - Otherwise, if the initializer list has no elements and T is a
4531 // class type with a default constructor, the object is
4532 // value-initialized.
4533 if (InitList->getNumInits() == 0) {
4534 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4535 if (S.LookupDefaultConstructor(RD)) {
4536 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4537 return;
4538 }
4539 }
4540
4541 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4542 // an initializer_list object constructed [...]
4543 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4544 TreatUnavailableAsInvalid))
4545 return;
4546
4547 // - Otherwise, if T is a class type, constructors are considered.
4548 Expr *InitListAsExpr = InitList;
4549 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4550 DestType, Sequence, /*InitListSyntax*/true);
4551 } else
4552 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4553 return;
4554 }
4555
4556 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4557 InitList->getNumInits() == 1) {
4558 Expr *E = InitList->getInit(0);
4559
4560 // - Otherwise, if T is an enumeration with a fixed underlying type,
4561 // the initializer-list has a single element v, and the initialization
4562 // is direct-list-initialization, the object is initialized with the
4563 // value T(v); if a narrowing conversion is required to convert v to
4564 // the underlying type of T, the program is ill-formed.
4565 auto *ET = DestType->getAs<EnumType>();
4566 if (S.getLangOpts().CPlusPlus17 &&
4567 Kind.getKind() == InitializationKind::IK_DirectList &&
4568 ET && ET->getDecl()->isFixed() &&
4569 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4570 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4571 E->getType()->isFloatingType())) {
4572 // There are two ways that T(v) can work when T is an enumeration type.
4573 // If there is either an implicit conversion sequence from v to T or
4574 // a conversion function that can convert from v to T, then we use that.
4575 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4576 // type, it is converted to the enumeration type via its underlying type.
4577 // There is no overlap possible between these two cases (except when the
4578 // source value is already of the destination type), and the first
4579 // case is handled by the general case for single-element lists below.
4580 ImplicitConversionSequence ICS;
4581 ICS.setStandard();
4582 ICS.Standard.setAsIdentityConversion();
4583 if (!E->isPRValue())
4584 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4585 // If E is of a floating-point type, then the conversion is ill-formed
4586 // due to narrowing, but go through the motions in order to produce the
4587 // right diagnostic.
4588 ICS.Standard.Second = E->getType()->isFloatingType()
4589 ? ICK_Floating_Integral
4590 : ICK_Integral_Conversion;
4591 ICS.Standard.setFromType(E->getType());
4592 ICS.Standard.setToType(0, E->getType());
4593 ICS.Standard.setToType(1, DestType);
4594 ICS.Standard.setToType(2, DestType);
4595 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4596 /*TopLevelOfInitList*/true);
4597 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4598 return;
4599 }
4600
4601 // - Otherwise, if the initializer list has a single element of type E
4602 // [...references are handled above...], the object or reference is
4603 // initialized from that element (by copy-initialization for
4604 // copy-list-initialization, or by direct-initialization for
4605 // direct-list-initialization); if a narrowing conversion is required
4606 // to convert the element to T, the program is ill-formed.
4607 //
4608 // Per core-24034, this is direct-initialization if we were performing
4609 // direct-list-initialization and copy-initialization otherwise.
4610 // We can't use InitListChecker for this, because it always performs
4611 // copy-initialization. This only matters if we might use an 'explicit'
4612 // conversion operator, or for the special case conversion of nullptr_t to
4613 // bool, so we only need to handle those cases.
4614 //
4615 // FIXME: Why not do this in all cases?
4616 Expr *Init = InitList->getInit(0);
4617 if (Init->getType()->isRecordType() ||
4618 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4619 InitializationKind SubKind =
4620 Kind.getKind() == InitializationKind::IK_DirectList
4621 ? InitializationKind::CreateDirect(Kind.getLocation(),
4622 InitList->getLBraceLoc(),
4623 InitList->getRBraceLoc())
4624 : Kind;
4625 Expr *SubInit[1] = { Init };
4626 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4627 /*TopLevelOfInitList*/true,
4628 TreatUnavailableAsInvalid);
4629 if (Sequence)
4630 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4631 return;
4632 }
4633 }
4634
4635 InitListChecker CheckInitList(S, Entity, InitList,
4636 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4637 if (CheckInitList.HadError()) {
4638 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4639 return;
4640 }
4641
4642 // Add the list initialization step with the built init list.
4643 Sequence.AddListInitializationStep(DestType);
4644}
4645
4646/// Try a reference initialization that involves calling a conversion
4647/// function.
4648static OverloadingResult TryRefInitWithConversionFunction(
4649 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4650 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4651 InitializationSequence &Sequence) {
4652 QualType DestType = Entity.getType();
4653 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4654 QualType T1 = cv1T1.getUnqualifiedType();
4655 QualType cv2T2 = Initializer->getType();
4656 QualType T2 = cv2T2.getUnqualifiedType();
4657
4658 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", 4659, __extension__ __PRETTY_FUNCTION__
))
4659 "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", 4659, __extension__ __PRETTY_FUNCTION__
))
;
4660
4661 // Build the candidate set directly in the initialization sequence
4662 // structure, so that it will persist if we fail.
4663 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4664 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4665
4666 // Determine whether we are allowed to call explicit conversion operators.
4667 // Note that none of [over.match.copy], [over.match.conv], nor
4668 // [over.match.ref] permit an explicit constructor to be chosen when
4669 // initializing a reference, not even for direct-initialization.
4670 bool AllowExplicitCtors = false;
4671 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4672
4673 const RecordType *T1RecordType = nullptr;
4674 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4675 S.isCompleteType(Kind.getLocation(), T1)) {
4676 // The type we're converting to is a class type. Enumerate its constructors
4677 // to see if there is a suitable conversion.
4678 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4679
4680 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4681 auto Info = getConstructorInfo(D);
4682 if (!Info.Constructor)
4683 continue;
4684
4685 if (!Info.Constructor->isInvalidDecl() &&
4686 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4687 if (Info.ConstructorTmpl)
4688 S.AddTemplateOverloadCandidate(
4689 Info.ConstructorTmpl, Info.FoundDecl,
4690 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4691 /*SuppressUserConversions=*/true,
4692 /*PartialOverloading*/ false, AllowExplicitCtors);
4693 else
4694 S.AddOverloadCandidate(
4695 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4696 /*SuppressUserConversions=*/true,
4697 /*PartialOverloading*/ false, AllowExplicitCtors);
4698 }
4699 }
4700 }
4701 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4702 return OR_No_Viable_Function;
4703
4704 const RecordType *T2RecordType = nullptr;
4705 if ((T2RecordType = T2->getAs<RecordType>()) &&
4706 S.isCompleteType(Kind.getLocation(), T2)) {
4707 // The type we're converting from is a class type, enumerate its conversion
4708 // functions.
4709 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4710
4711 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4712 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4713 NamedDecl *D = *I;
4714 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4715 if (isa<UsingShadowDecl>(D))
4716 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4717
4718 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4719 CXXConversionDecl *Conv;
4720 if (ConvTemplate)
4721 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4722 else
4723 Conv = cast<CXXConversionDecl>(D);
4724
4725 // If the conversion function doesn't return a reference type,
4726 // it can't be considered for this conversion unless we're allowed to
4727 // consider rvalues.
4728 // FIXME: Do we need to make sure that we only consider conversion
4729 // candidates with reference-compatible results? That might be needed to
4730 // break recursion.
4731 if ((AllowRValues ||
4732 Conv->getConversionType()->isLValueReferenceType())) {
4733 if (ConvTemplate)
4734 S.AddTemplateConversionCandidate(
4735 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4736 CandidateSet,
4737 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4738 else
4739 S.AddConversionCandidate(
4740 Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4741 /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4742 }
4743 }
4744 }
4745 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4746 return OR_No_Viable_Function;
4747
4748 SourceLocation DeclLoc = Initializer->getBeginLoc();
4749
4750 // Perform overload resolution. If it fails, return the failed result.
4751 OverloadCandidateSet::iterator Best;
4752 if (OverloadingResult Result
4753 = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4754 return Result;
4755
4756 FunctionDecl *Function = Best->Function;
4757 // This is the overload that will be used for this initialization step if we
4758 // use this initialization. Mark it as referenced.
4759 Function->setReferenced();
4760
4761 // Compute the returned type and value kind of the conversion.
4762 QualType cv3T3;
4763 if (isa<CXXConversionDecl>(Function))
4764 cv3T3 = Function->getReturnType();
4765 else
4766 cv3T3 = T1;
4767
4768 ExprValueKind VK = VK_PRValue;
4769 if (cv3T3->isLValueReferenceType())
4770 VK = VK_LValue;
4771 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4772 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4773 cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4774
4775 // Add the user-defined conversion step.
4776 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4777 Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4778 HadMultipleCandidates);
4779
4780 // Determine whether we'll need to perform derived-to-base adjustments or
4781 // other conversions.
4782 Sema::ReferenceConversions RefConv;
4783 Sema::ReferenceCompareResult NewRefRelationship =
4784 S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4785
4786 // Add the final conversion sequence, if necessary.
4787 if (NewRefRelationship == Sema::Ref_Incompatible) {
4788 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", 4789, __extension__ __PRETTY_FUNCTION__
))
4789 "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", 4789, __extension__ __PRETTY_FUNCTION__
))
;
4790
4791 ImplicitConversionSequence ICS;
4792 ICS.setStandard();
4793 ICS.Standard = Best->FinalConversion;
4794 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4795
4796 // Every implicit conversion results in a prvalue, except for a glvalue
4797 // derived-to-base conversion, which we handle below.
4798 cv3T3 = ICS.Standard.getToType(2);
4799 VK = VK_PRValue;
4800 }
4801
4802 // If the converted initializer is a prvalue, its type T4 is adjusted to
4803 // type "cv1 T4" and the temporary materialization conversion is applied.
4804 //
4805 // We adjust the cv-qualifications to match the reference regardless of
4806 // whether we have a prvalue so that the AST records the change. In this
4807 // case, T4 is "cv3 T3".
4808 QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4809 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4810 Sequence.AddQualificationConversionStep(cv1T4, VK);
4811 Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4812 VK = IsLValueRef ? VK_LValue : VK_XValue;
4813
4814 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4815 Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4816 else if (RefConv & Sema::ReferenceConversions::ObjC)
4817 Sequence.AddObjCObjectConversionStep(cv1T1);
4818 else if (RefConv & Sema::ReferenceConversions::Function)
4819 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4820 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4821 if (!S.Context.hasSameType(cv1T4, cv1T1))
4822 Sequence.AddQualificationConversionStep(cv1T1, VK);
4823 }
4824
4825 return OR_Success;
4826}
4827
4828static void CheckCXX98CompatAccessibleCopy(Sema &S,
4829 const InitializedEntity &Entity,
4830 Expr *CurInitExpr);
4831
4832/// Attempt reference initialization (C++0x [dcl.init.ref])
4833static void TryReferenceInitialization(Sema &S,
4834 const InitializedEntity &Entity,
4835 const InitializationKind &Kind,
4836 Expr *Initializer,
4837 InitializationSequence &Sequence) {
4838 QualType DestType = Entity.getType();
4839 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4840 Qualifiers T1Quals;
4841 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4842 QualType cv2T2 = S.getCompletedType(Initializer);
4843 Qualifiers T2Quals;
4844 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4845
4846 // If the initializer is the address of an overloaded function, try
4847 // to resolve the overloaded function. If all goes well, T2 is the
4848 // type of the resulting function.
4849 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4850 T1, Sequence))
4851 return;
4852
4853 // Delegate everything else to a subfunction.
4854 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4855 T1Quals, cv2T2, T2, T2Quals, Sequence);
4856}
4857
4858/// Determine whether an expression is a non-referenceable glvalue (one to
4859/// which a reference can never bind). Attempting to bind a reference to
4860/// such a glvalue will always create a temporary.
4861static bool isNonReferenceableGLValue(Expr *E) {
4862 return E->refersToBitField() || E->refersToVectorElement() ||
4863 E->refersToMatrixElement();
4864}
4865
4866/// Reference initialization without resolving overloaded functions.
4867///
4868/// We also can get here in C if we call a builtin which is declared as
4869/// a function with a parameter of reference type (such as __builtin_va_end()).
4870static void TryReferenceInitializationCore(Sema &S,
4871 const InitializedEntity &Entity,
4872 const InitializationKind &Kind,
4873 Expr *Initializer,
4874 QualType cv1T1, QualType T1,
4875 Qualifiers T1Quals,
4876 QualType cv2T2, QualType T2,
4877 Qualifiers T2Quals,
4878 InitializationSequence &Sequence) {
4879 QualType DestType = Entity.getType();
4880 SourceLocation DeclLoc = Initializer->getBeginLoc();
4881
4882 // Compute some basic properties of the types and the initializer.
4883 bool isLValueRef = DestType->isLValueReferenceType();
4884 bool isRValueRef = !isLValueRef;
4885 Expr::Classification InitCategory = Initializer->Classify(S.Context);
4886
4887 Sema::ReferenceConversions RefConv;
4888 Sema::ReferenceCompareResult RefRelationship =
4889 S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4890
4891 // C++0x [dcl.init.ref]p5:
4892 // A reference to type "cv1 T1" is initialized by an expression of type
4893 // "cv2 T2" as follows:
4894 //
4895 // - If the reference is an lvalue reference and the initializer
4896 // expression
4897 // Note the analogous bullet points for rvalue refs to functions. Because
4898 // there are no function rvalues in C++, rvalue refs to functions are treated
4899 // like lvalue refs.
4900 OverloadingResult ConvOvlResult = OR_Success;
4901 bool T1Function = T1->isFunctionType();
4902 if (isLValueRef || T1Function) {
4903 if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
4904 (RefRelationship == Sema::Ref_Compatible ||
4905 (Kind.isCStyleOrFunctionalCast() &&
4906 RefRelationship == Sema::Ref_Related))) {
4907 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
4908 // reference-compatible with "cv2 T2," or
4909 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
4910 Sema::ReferenceConversions::ObjC)) {
4911 // If we're converting the pointee, add any qualifiers first;
4912 // these qualifiers must all be top-level, so just convert to "cv1 T2".
4913 if (RefConv & (Sema::ReferenceConversions::Qualification))
4914 Sequence.AddQualificationConversionStep(
4915 S.Context.getQualifiedType(T2, T1Quals),
4916 Initializer->getValueKind());
4917 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4918 Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4919 else
4920 Sequence.AddObjCObjectConversionStep(cv1T1);
4921 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
4922 // Perform a (possibly multi-level) qualification conversion.
4923 Sequence.AddQualificationConversionStep(cv1T1,
4924 Initializer->getValueKind());
4925 } else if (RefConv & Sema::ReferenceConversions::Function) {
4926 Sequence.AddFunctionReferenceConversionStep(cv1T1);
4927 }
4928
4929 // We only create a temporary here when binding a reference to a
4930 // bit-field or vector element. Those cases are't supposed to be
4931 // handled by this bullet, but the outcome is the same either way.
4932 Sequence.AddReferenceBindingStep(cv1T1, false);
4933 return;
4934 }
4935
4936 // - has a class type (i.e., T2 is a class type), where T1 is not
4937 // reference-related to T2, and can be implicitly converted to an
4938 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4939 // with "cv3 T3" (this conversion is selected by enumerating the
4940 // applicable conversion functions (13.3.1.6) and choosing the best
4941 // one through overload resolution (13.3)),
4942 // If we have an rvalue ref to function type here, the rhs must be
4943 // an rvalue. DR1287 removed the "implicitly" here.
4944 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
4945 (isLValueRef || InitCategory.isRValue())) {
4946 if (S.getLangOpts().CPlusPlus) {
4947 // Try conversion functions only for C++.
4948 ConvOvlResult = TryRefInitWithConversionFunction(
4949 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4950 /*IsLValueRef*/ isLValueRef, Sequence);
4951 if (ConvOvlResult == OR_Success)
4952 return;
4953 if (ConvOvlResult != OR_No_Viable_Function)
4954 Sequence.SetOverloadFailure(
4955 InitializationSequence::FK_ReferenceInitOverloadFailed,
4956 ConvOvlResult);
4957 } else {
4958 ConvOvlResult = OR_No_Viable_Function;
4959 }
4960 }
4961 }
4962
4963 // - Otherwise, the reference shall be an lvalue reference to a
4964 // non-volatile const type (i.e., cv1 shall be const), or the reference
4965 // shall be an rvalue reference.
4966 // For address spaces, we interpret this to mean that an addr space
4967 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4968 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
4969 T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
4970 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4971 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4972 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
4973 Sequence.SetOverloadFailure(
4974 InitializationSequence::FK_ReferenceInitOverloadFailed,
4975 ConvOvlResult);
4976 else if (!InitCategory.isLValue())
4977 Sequence.SetFailed(
4978 T1Quals.isAddressSpaceSupersetOf(T2Quals)
4979 ? InitializationSequence::
4980 FK_NonConstLValueReferenceBindingToTemporary
4981 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
4982 else {
4983 InitializationSequence::FailureKind FK;
4984 switch (RefRelationship) {
4985 case Sema::Ref_Compatible:
4986 if (Initializer->refersToBitField())
4987 FK = InitializationSequence::
4988 FK_NonConstLValueReferenceBindingToBitfield;
4989 else if (Initializer->refersToVectorElement())
4990 FK = InitializationSequence::
4991 FK_NonConstLValueReferenceBindingToVectorElement;
4992 else if (Initializer->refersToMatrixElement())
4993 FK = InitializationSequence::
4994 FK_NonConstLValueReferenceBindingToMatrixElement;
4995 else
4996 llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer"
, "clang/lib/Sema/SemaInit.cpp", 4996)
;
4997 break;
4998 case Sema::Ref_Related:
4999 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5000 break;
5001 case Sema::Ref_Incompatible:
5002 FK = InitializationSequence::
5003 FK_NonConstLValueReferenceBindingToUnrelated;
5004 break;
5005 }
5006 Sequence.SetFailed(FK);
5007 }
5008 return;
5009 }
5010
5011 // - If the initializer expression
5012 // - is an
5013 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5014 // [1z] rvalue (but not a bit-field) or
5015 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5016 //
5017 // Note: functions are handled above and below rather than here...
5018 if (!T1Function &&
5019 (RefRelationship == Sema::Ref_Compatible ||
5020 (Kind.isCStyleOrFunctionalCast() &&
5021 RefRelationship == Sema::Ref_Related)) &&
5022 ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5023 (InitCategory.isPRValue() &&
5024 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5025 T2->isArrayType())))) {
5026 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5027 if (InitCategory.isPRValue() && T2->isRecordType()) {
5028 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5029 // compiler the freedom to perform a copy here or bind to the
5030 // object, while C++0x requires that we bind directly to the
5031 // object. Hence, we always bind to the object without making an
5032 // extra copy. However, in C++03 requires that we check for the
5033 // presence of a suitable copy constructor:
5034 //
5035 // The constructor that would be used to make the copy shall
5036 // be callable whether or not the copy is actually done.
5037 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5038 Sequence.AddExtraneousCopyToTemporary(cv2T2);
5039 else if (S.getLangOpts().CPlusPlus11)
5040 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
5041 }
5042
5043 // C++1z [dcl.init.ref]/5.2.1.2:
5044 // If the converted initializer is a prvalue, its type T4 is adjusted
5045 // to type "cv1 T4" and the temporary materialization conversion is
5046 // applied.
5047 // Postpone address space conversions to after the temporary materialization
5048 // conversion to allow creating temporaries in the alloca address space.
5049 auto T1QualsIgnoreAS = T1Quals;
5050 auto T2QualsIgnoreAS = T2Quals;
5051 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5052 T1QualsIgnoreAS.removeAddressSpace();
5053 T2QualsIgnoreAS.removeAddressSpace();
5054 }
5055 QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5056 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5057 Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5058 Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5059 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5060 // Add addr space conversion if required.
5061 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5062 auto T4Quals = cv1T4.getQualifiers();
5063 T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5064 QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5065 Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5066 cv1T4 = cv1T4WithAS;
5067 }
5068
5069 // In any case, the reference is bound to the resulting glvalue (or to
5070 // an appropriate base class subobject).
5071 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5072 Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5073 else if (RefConv & Sema::ReferenceConversions::ObjC)
5074 Sequence.AddObjCObjectConversionStep(cv1T1);
5075 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5076 if (!S.Context.hasSameType(cv1T4, cv1T1))
5077 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5078 }
5079 return;
5080 }
5081
5082 // - has a class type (i.e., T2 is a class type), where T1 is not
5083 // reference-related to T2, and can be implicitly converted to an
5084 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5085 // where "cv1 T1" is reference-compatible with "cv3 T3",
5086 //
5087 // DR1287 removes the "implicitly" here.
5088 if (T2->isRecordType()) {
5089 if (RefRelationship == Sema::Ref_Incompatible) {
5090 ConvOvlResult = TryRefInitWithConversionFunction(
5091 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5092 /*IsLValueRef*/ isLValueRef, Sequence);
5093 if (ConvOvlResult)
5094 Sequence.SetOverloadFailure(
5095 InitializationSequence::FK_ReferenceInitOverloadFailed,
5096 ConvOvlResult);
5097
5098 return;
5099 }
5100
5101 if (RefRelationship == Sema::Ref_Compatible &&
5102 isRValueRef && InitCategory.isLValue()) {
5103 Sequence.SetFailed(
5104 InitializationSequence::FK_RValueReferenceBindingToLValue);
5105 return;
5106 }
5107
5108 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5109 return;
5110 }
5111
5112 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5113 // from the initializer expression using the rules for a non-reference
5114 // copy-initialization (8.5). The reference is then bound to the
5115 // temporary. [...]
5116
5117 // Ignore address space of reference type at this point and perform address
5118 // space conversion after the reference binding step.
5119 QualType cv1T1IgnoreAS =
5120 T1Quals.hasAddressSpace()
5121 ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5122 : cv1T1;
5123
5124 InitializedEntity TempEntity =
5125 InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5126
5127 // FIXME: Why do we use an implicit conversion here rather than trying
5128 // copy-initialization?
5129 ImplicitConversionSequence ICS
5130 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5131 /*SuppressUserConversions=*/false,
5132 Sema::AllowedExplicit::None,
5133 /*FIXME:InOverloadResolution=*/false,
5134 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5135 /*AllowObjCWritebackConversion=*/false);
5136
5137 if (ICS.isBad()) {
5138 // FIXME: Use the conversion function set stored in ICS to turn
5139 // this into an overloading ambiguity diagnostic. However, we need
5140 // to keep that set as an OverloadCandidateSet rather than as some
5141 // other kind of set.
5142 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5143 Sequence.SetOverloadFailure(
5144 InitializationSequence::FK_ReferenceInitOverloadFailed,
5145 ConvOvlResult);
5146 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5147 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5148 else
5149 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5150 return;
5151 } else {
5152 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
5153 }
5154
5155 // [...] If T1 is reference-related to T2, cv1 must be the
5156 // same cv-qualification as, or greater cv-qualification
5157 // than, cv2; otherwise, the program is ill-formed.
5158 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5159 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5160 if (RefRelationship == Sema::Ref_Related &&
5161 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5162 !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5163 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5164 return;
5165 }
5166
5167 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5168 // reference, the initializer expression shall not be an lvalue.
5169 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5170 InitCategory.isLValue()) {
5171 Sequence.SetFailed(
5172 InitializationSequence::FK_RValueReferenceBindingToLValue);
5173 return;
5174 }
5175
5176 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5177
5178 if (T1Quals.hasAddressSpace()) {
5179 if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
5180 LangAS::Default)) {
5181 Sequence.SetFailed(
5182 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5183 return;
5184 }
5185 Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5186 : VK_XValue);
5187 }
5188}
5189
5190/// Attempt character array initialization from a string literal
5191/// (C++ [dcl.init.string], C99 6.7.8).
5192static void TryStringLiteralInitialization(Sema &S,
5193 const InitializedEntity &Entity,
5194 const InitializationKind &Kind,
5195 Expr *Initializer,
5196 InitializationSequence &Sequence) {
5197 Sequence.AddStringInitStep(Entity.getType());
5198}
5199
5200/// Attempt value initialization (C++ [dcl.init]p7).
5201static void TryValueInitialization(Sema &S,
5202 const InitializedEntity &Entity,
5203 const InitializationKind &Kind,
5204 InitializationSequence &Sequence,
5205 InitListExpr *InitList) {
5206 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", 5207, __extension__ __PRETTY_FUNCTION__
))
5207 "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", 5207, __extension__ __PRETTY_FUNCTION__
))
;
5208
5209 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5210 //
5211 // To value-initialize an object of type T means:
5212 QualType T = Entity.getType();
5213
5214 // -- if T is an array type, then each element is value-initialized;
5215 T = S.Context.getBaseElementType(T);
5216
5217 if (const RecordType *RT = T->getAs<RecordType>()) {
5218 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5219 bool NeedZeroInitialization = true;
5220 // C++98:
5221 // -- if T is a class type (clause 9) with a user-declared constructor
5222 // (12.1), then the default constructor for T is called (and the
5223 // initialization is ill-formed if T has no accessible default
5224 // constructor);
5225 // C++11:
5226 // -- if T is a class type (clause 9) with either no default constructor
5227 // (12.1 [class.ctor]) or a default constructor that is user-provided
5228 // or deleted, then the object is default-initialized;
5229 //
5230 // Note that the C++11 rule is the same as the C++98 rule if there are no
5231 // defaulted or deleted constructors, so we just use it unconditionally.
5232 CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5233 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5234 NeedZeroInitialization = false;
5235
5236 // -- if T is a (possibly cv-qualified) non-union class type without a
5237 // user-provided or deleted default constructor, then the object is
5238 // zero-initialized and, if T has a non-trivial default constructor,
5239 // default-initialized;
5240 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5241 // constructor' part was removed by DR1507.
5242 if (NeedZeroInitialization)
5243 Sequence.AddZeroInitializationStep(Entity.getType());
5244
5245 // C++03:
5246 // -- if T is a non-union class type without a user-declared constructor,
5247 // then every non-static data member and base class component of T is
5248 // value-initialized;
5249 // [...] A program that calls for [...] value-initialization of an
5250 // entity of reference type is ill-formed.
5251 //
5252 // C++11 doesn't need this handling, because value-initialization does not
5253 // occur recursively there, and the implicit default constructor is
5254 // defined as deleted in the problematic cases.
5255 if (!S.getLangOpts().CPlusPlus11 &&
5256 ClassDecl->hasUninitializedReferenceMember()) {
5257 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5258 return;
5259 }
5260
5261 // If this is list-value-initialization, pass the empty init list on when
5262 // building the constructor call. This affects the semantics of a few
5263 // things (such as whether an explicit default constructor can be called).
5264 Expr *InitListAsExpr = InitList;
5265 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5266 bool InitListSyntax = InitList;
5267
5268 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5269 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5270 return TryConstructorInitialization(
5271 S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5272 }
5273 }
5274
5275 Sequence.AddZeroInitializationStep(Entity.getType());
5276}
5277
5278/// Attempt default initialization (C++ [dcl.init]p6).
5279static void TryDefaultInitialization(Sema &S,
5280 const InitializedEntity &Entity,
5281 const InitializationKind &Kind,
5282 InitializationSequence &Sequence) {
5283 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", 5283, __extension__ __PRETTY_FUNCTION__
))
;
5284
5285 // C++ [dcl.init]p6:
5286 // To default-initialize an object of type T means:
5287 // - if T is an array type, each element is default-initialized;
5288 QualType DestType = S.Context.getBaseElementType(Entity.getType());
5289
5290 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5291 // constructor for T is called (and the initialization is ill-formed if
5292 // T has no accessible default constructor);
5293 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5294 TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5295 Entity.getType(), Sequence);
5296 return;
5297 }
5298
5299 // - otherwise, no initialization is performed.
5300
5301 // If a program calls for the default initialization of an object of
5302 // a const-qualified type T, T shall be a class type with a user-provided
5303 // default constructor.
5304 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5305 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5306 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5307 return;
5308 }
5309
5310 // If the destination type has a lifetime property, zero-initialize it.
5311 if (DestType.getQualifiers().hasObjCLifetime()) {
5312 Sequence.AddZeroInitializationStep(Entity.getType());
5313 return;
5314 }
5315}
5316
5317static void TryOrBuildParenListInitialization(
5318 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5319 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5320 ExprResult *Result = nullptr) {
5321 unsigned EntityIndexToProcess = 0;
5322 SmallVector<Expr *, 4> InitExprs;
5323 QualType ResultType;
5324 Expr *ArrayFiller = nullptr;
5325 FieldDecl *InitializedFieldInUnion = nullptr;
5326
5327 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5328 const InitializationKind &SubKind,
5329 Expr *Arg, Expr **InitExpr = nullptr) {
5330 InitializationSequence IS = [&]() {
5331 if (Arg)
5332 return InitializationSequence(S, SubEntity, SubKind, Arg);
5333 return InitializationSequence(S, SubEntity, SubKind, std::nullopt);
5334 }();
5335
5336 if (IS.Failed()) {
5337 if (!VerifyOnly) {
5338 if (Arg)
5339 IS.Diagnose(S, SubEntity, SubKind, Arg);
5340 else
5341 IS.Diagnose(S, SubEntity, SubKind, std::nullopt);
5342 } else {
5343 Sequence.SetFailed(
5344 InitializationSequence::FK_ParenthesizedListInitFailed);
5345 }
5346
5347 return false;
5348 }
5349 if (!VerifyOnly) {
5350 ExprResult ER;
5351 if (Arg)
5352 ER = IS.Perform(S, SubEntity, SubKind, Arg);
5353 else
5354 ER = IS.Perform(S, SubEntity, SubKind, std::nullopt);
5355 if (InitExpr)
5356 *InitExpr = ER.get();
5357 else
5358 InitExprs.push_back(ER.get());
5359 }
5360 return true;
5361 };
5362
5363 if (const ArrayType *AT =
5364 S.getASTContext().getAsArrayType(Entity.getType())) {
5365 SmallVector<InitializedEntity, 4> ElementEntities;
5366 uint64_t ArrayLength;
5367 // C++ [dcl.init]p16.5
5368 // if the destination type is an array, the object is initialized as
5369 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5370 // the destination type is an array of unknown bound, it is defined as
5371 // having k elements.
5372 if (const ConstantArrayType *CAT =
5373 S.getASTContext().getAsConstantArrayType(Entity.getType())) {
5374 ArrayLength = CAT->getSize().getZExtValue();
5375 ResultType = Entity.getType();
5376 } else if (const VariableArrayType *VAT =
5377 S.getASTContext().getAsVariableArrayType(Entity.getType())) {
5378 // Braced-initialization of variable array types is not allowed, even if
5379 // the size is greater than or equal to the number of args, so we don't
5380 // allow them to be initialized via parenthesized aggregate initialization
5381 // either.
5382 const Expr *SE = VAT->getSizeExpr();
5383 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5384 << SE->getSourceRange();
5385 return;
5386 } else {
5387 assert(isa<IncompleteArrayType>(Entity.getType()))(static_cast <bool> (isa<IncompleteArrayType>(Entity
.getType())) ? void (0) : __assert_fail ("isa<IncompleteArrayType>(Entity.getType())"
, "clang/lib/Sema/SemaInit.cpp", 5387, __extension__ __PRETTY_FUNCTION__
))
;
5388 ArrayLength = Args.size();
5389 }
5390 EntityIndexToProcess = ArrayLength;
5391
5392 // ...the ith array element is copy-initialized with xi for each
5393 // 1 <= i <= k
5394 for (Expr *E : Args) {
5395 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5396 S.getASTContext(), EntityIndexToProcess, Entity);
5397 InitializationKind SubKind = InitializationKind::CreateForInit(
5398 E->getExprLoc(), /*isDirectInit=*/false, E);
5399 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5400 return;
5401 }
5402 // ...and value-initialized for each k < i <= n;
5403 if (ArrayLength > Args.size()) {
5404 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5405 S.getASTContext(), Args.size(), Entity);
5406 InitializationKind SubKind = InitializationKind::CreateValue(
5407 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5408 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5409 return;
5410 }
5411
5412 if (ResultType.isNull()) {
5413 ResultType = S.Context.getConstantArrayType(
5414 AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5415 /*SizeExpr=*/nullptr, ArrayType::Normal, 0);
5416 }
5417 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5418 bool IsUnion = RT->isUnionType();
5419 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5420
5421 if (!IsUnion) {
5422 for (const CXXBaseSpecifier &Base : RD->bases()) {
5423 InitializedEntity SubEntity = InitializedEntity::InitializeBase(
5424 S.getASTContext(), &Base, false, &Entity);
5425 if (EntityIndexToProcess < Args.size()) {
5426 // C++ [dcl.init]p16.6.2.2.
5427 // ...the object is initialized is follows. Let e1, ..., en be the
5428 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5429 // the elements of the expression-list...The element ei is
5430 // copy-initialized with xi for 1 <= i <= k.
5431 Expr *E = Args[EntityIndexToProcess];
5432 InitializationKind SubKind = InitializationKind::CreateForInit(
5433 E->getExprLoc(), /*isDirectInit=*/false, E);
5434 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5435 return;
5436 } else {
5437 // We've processed all of the args, but there are still base classes
5438 // that have to be initialized.
5439 // C++ [dcl.init]p17.6.2.2
5440 // The remaining elements...otherwise are value initialzed
5441 InitializationKind SubKind = InitializationKind::CreateValue(
5442 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5443 /*IsImplicit=*/true);
5444 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5445 return;
5446 }
5447 EntityIndexToProcess++;
5448 }
5449 }
5450
5451 for (FieldDecl *FD : RD->fields()) {
5452 // Unnamed bitfields should not be initialized at all, either with an arg
5453 // or by default.
5454 if (FD->isUnnamedBitfield())
5455 continue;
5456
5457 InitializedEntity SubEntity =
5458 InitializedEntity::InitializeMemberFromParenAggInit(FD);
5459
5460 if (EntityIndexToProcess < Args.size()) {
5461 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5462 Expr *E = Args[EntityIndexToProcess];
5463
5464 // Incomplete array types indicate flexible array members. Do not allow
5465 // paren list initializations of structs with these members, as GCC
5466 // doesn't either.
5467 if (FD->getType()->isIncompleteArrayType()) {
5468 if (!VerifyOnly) {
5469 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5470 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5471 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5472 }
5473 Sequence.SetFailed(
5474 InitializationSequence::FK_ParenthesizedListInitFailed);
5475 return;
5476 }
5477
5478 InitializationKind SubKind = InitializationKind::CreateForInit(
5479 E->getExprLoc(), /*isDirectInit=*/false, E);
5480 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5481 return;
5482
5483 // Unions should have only one initializer expression, so we bail out
5484 // after processing the first field. If there are more initializers then
5485 // it will be caught when we later check whether EntityIndexToProcess is
5486 // less than Args.size();
5487 if (IsUnion) {
5488 InitializedFieldInUnion = FD;
5489 EntityIndexToProcess = 1;
5490 break;
5491 }
5492 } else {
5493 // We've processed all of the args, but there are still members that
5494 // have to be initialized.
5495 if (FD->hasInClassInitializer()) {
5496 if (!VerifyOnly) {
5497 // C++ [dcl.init]p16.6.2.2
5498 // The remaining elements are initialized with their default
5499 // member initializers, if any
5500 ExprResult DIE = S.BuildCXXDefaultInitExpr(FD->getLocation(), FD);
5501 if (DIE.isInvalid())
5502 return;
5503 S.checkInitializerLifetime(SubEntity, DIE.get());
5504 InitExprs.push_back(DIE.get());
5505 }
5506 } else {
5507 // C++ [dcl.init]p17.6.2.2
5508 // The remaining elements...otherwise are value initialzed
5509 if (FD->getType()->isReferenceType()) {
5510 Sequence.SetFailed(
5511 InitializationSequence::FK_ParenthesizedListInitFailed);
5512 if (!VerifyOnly) {
5513 SourceRange SR = Kind.getParenOrBraceRange();
5514 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5515 << FD->getType() << SR;
5516 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5517 }
5518 return;
5519 }
5520 InitializationKind SubKind = InitializationKind::CreateValue(
5521 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5522 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5523 return;
5524 }
5525 }
5526 EntityIndexToProcess++;
5527 }
5528 ResultType = Entity.getType();
5529 }
5530
5531 // Not all of the args have been processed, so there must've been more args
5532 // than were required to initialize the element.
5533 if (EntityIndexToProcess < Args.size()) {
5534 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
5535 if (!VerifyOnly) {
5536 QualType T = Entity.getType();
5537 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5538 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5539 Args.back()->getEndLoc());
5540 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5541 << InitKind << ExcessInitSR;
5542 }
5543 return;
5544 }
5545
5546 if (VerifyOnly) {
5547 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
5548 Sequence.AddParenthesizedListInitStep(Entity.getType());
5549 } else if (Result) {
5550 SourceRange SR = Kind.getParenOrBraceRange();
5551 auto *CPLIE = CXXParenListInitExpr::Create(
5552 S.getASTContext(), InitExprs, ResultType, Args.size(),
5553 Kind.getLocation(), SR.getBegin(), SR.getEnd());
5554 if (ArrayFiller)
5555 CPLIE->setArrayFiller(ArrayFiller);
5556 if (InitializedFieldInUnion)
5557 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5558 *Result = CPLIE;
5559 S.Diag(Kind.getLocation(),
5560 diag::warn_cxx17_compat_aggregate_init_paren_list)
5561 << Kind.getLocation() << SR << ResultType;
5562 }
5563
5564 return;
5565}
5566
5567/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5568/// which enumerates all conversion functions and performs overload resolution
5569/// to select the best.
5570static void TryUserDefinedConversion(Sema &S,
5571 QualType DestType,
5572 const InitializationKind &Kind,
5573 Expr *Initializer,
5574 InitializationSequence &Sequence,
5575 bool TopLevelOfInitList) {
5576 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", 5576, __extension__ __PRETTY_FUNCTION__
))
;
5577 QualType SourceType = Initializer->getType();
5578 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", 5579, __extension__ __PRETTY_FUNCTION__
))
5579 "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", 5579, __extension__ __PRETTY_FUNCTION__
))
;
5580
5581 // Build the candidate set directly in the initialization sequence
5582 // structure, so that it will persist if we fail.
5583 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5584 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5585 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5586
5587 // Determine whether we are allowed to call explicit constructors or
5588 // explicit conversion operators.
5589 bool AllowExplicit = Kind.AllowExplicit();
5590
5591 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5592 // The type we're converting to is a class type. Enumerate its constructors
5593 // to see if there is a suitable conversion.
5594 CXXRecordDecl *DestRecordDecl
5595 = cast<CXXRecordDecl>(DestRecordType->getDecl());
5596
5597 // Try to complete the type we're converting to.
5598 if (S.isCompleteType(Kind.getLocation(), DestType)) {
5599 for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5600 auto Info = getConstructorInfo(D);
5601 if (!Info.Constructor)
5602 continue;
5603
5604 if (!Info.Constructor->isInvalidDecl() &&
5605 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5606 if (Info.ConstructorTmpl)
5607 S.AddTemplateOverloadCandidate(
5608 Info.ConstructorTmpl, Info.FoundDecl,
5609 /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5610 /*SuppressUserConversions=*/true,
5611 /*PartialOverloading*/ false, AllowExplicit);
5612 else
5613 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5614 Initializer, CandidateSet,
5615 /*SuppressUserConversions=*/true,
5616 /*PartialOverloading*/ false, AllowExplicit);
5617 }
5618 }
5619 }
5620 }
5621
5622 SourceLocation DeclLoc = Initializer->getBeginLoc();
5623
5624 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5625 // The type we're converting from is a class type, enumerate its conversion
5626 // functions.
5627
5628 // We can only enumerate the conversion functions for a complete type; if
5629 // the type isn't complete, simply skip this step.
5630 if (S.isCompleteType(DeclLoc, SourceType)) {
5631 CXXRecordDecl *SourceRecordDecl
5632 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5633
5634 const auto &Conversions =
5635 SourceRecordDecl->getVisibleConversionFunctions();
5636 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5637 NamedDecl *D = *I;
5638 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5639 if (isa<UsingShadowDecl>(D))
5640 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5641
5642 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5643 CXXConversionDecl *Conv;
5644 if (ConvTemplate)
5645 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5646 else
5647 Conv = cast<CXXConversionDecl>(D);
5648
5649 if (ConvTemplate)
5650 S.AddTemplateConversionCandidate(
5651 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5652 CandidateSet, AllowExplicit, AllowExplicit);
5653 else
5654 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5655 DestType, CandidateSet, AllowExplicit,
5656 AllowExplicit);
5657 }
5658 }
5659 }
5660
5661 // Perform overload resolution. If it fails, return the failed result.
5662 OverloadCandidateSet::iterator Best;
5663 if (OverloadingResult Result
5664 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5665 Sequence.SetOverloadFailure(
5666 InitializationSequence::FK_UserConversionOverloadFailed, Result);
5667
5668 // [class.copy.elision]p3:
5669 // In some copy-initialization contexts, a two-stage overload resolution
5670 // is performed.
5671 // If the first overload resolution selects a deleted function, we also
5672 // need the initialization sequence to decide whether to perform the second
5673 // overload resolution.
5674 if (!(Result == OR_Deleted &&
5675 Kind.getKind() == InitializationKind::IK_Copy))
5676 return;
5677 }
5678
5679 FunctionDecl *Function = Best->Function;
5680 Function->setReferenced();
5681 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5682
5683 if (isa<CXXConstructorDecl>(Function)) {
5684 // Add the user-defined conversion step. Any cv-qualification conversion is
5685 // subsumed by the initialization. Per DR5, the created temporary is of the
5686 // cv-unqualified type of the destination.
5687 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5688 DestType.getUnqualifiedType(),
5689 HadMultipleCandidates);
5690
5691 // C++14 and before:
5692 // - if the function is a constructor, the call initializes a temporary
5693 // of the cv-unqualified version of the destination type. The [...]
5694 // temporary [...] is then used to direct-initialize, according to the
5695 // rules above, the object that is the destination of the
5696 // copy-initialization.
5697 // Note that this just performs a simple object copy from the temporary.
5698 //
5699 // C++17:
5700 // - if the function is a constructor, the call is a prvalue of the
5701 // cv-unqualified version of the destination type whose return object
5702 // is initialized by the constructor. The call is used to
5703 // direct-initialize, according to the rules above, the object that
5704 // is the destination of the copy-initialization.
5705 // Therefore we need to do nothing further.
5706 //
5707 // FIXME: Mark this copy as extraneous.
5708 if (!S.getLangOpts().CPlusPlus17)
5709 Sequence.AddFinalCopy(DestType);
5710 else if (DestType.hasQualifiers())
5711 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5712 return;
5713 }
5714
5715 // Add the user-defined conversion step that calls the conversion function.
5716 QualType ConvType = Function->getCallResultType();
5717 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5718 HadMultipleCandidates);
5719
5720 if (ConvType->getAs<RecordType>()) {
5721 // The call is used to direct-initialize [...] the object that is the
5722 // destination of the copy-initialization.
5723 //
5724 // In C++17, this does not call a constructor if we enter /17.6.1:
5725 // - If the initializer expression is a prvalue and the cv-unqualified
5726 // version of the source type is the same as the class of the
5727 // destination [... do not make an extra copy]
5728 //
5729 // FIXME: Mark this copy as extraneous.
5730 if (!S.getLangOpts().CPlusPlus17 ||
5731 Function->getReturnType()->isReferenceType() ||
5732 !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5733 Sequence.AddFinalCopy(DestType);
5734 else if (!S.Context.hasSameType(ConvType, DestType))
5735 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5736 return;
5737 }
5738
5739 // If the conversion following the call to the conversion function
5740 // is interesting, add it as a separate step.
5741 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5742 Best->FinalConversion.Third) {
5743 ImplicitConversionSequence ICS;
5744 ICS.setStandard();
5745 ICS.Standard = Best->FinalConversion;
5746 Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5747 }
5748}
5749
5750/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5751/// a function with a pointer return type contains a 'return false;' statement.
5752/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5753/// code using that header.
5754///
5755/// Work around this by treating 'return false;' as zero-initializing the result
5756/// if it's used in a pointer-returning function in a system header.
5757static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5758 const InitializedEntity &Entity,
5759 const Expr *Init) {
5760 return S.getLangOpts().CPlusPlus11 &&
5761 Entity.getKind() == InitializedEntity::EK_Result &&
5762 Entity.getType()->isPointerType() &&
5763 isa<CXXBoolLiteralExpr>(Init) &&
5764 !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5765 S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5766}
5767
5768/// The non-zero enum values here are indexes into diagnostic alternatives.
5769enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5770
5771/// Determines whether this expression is an acceptable ICR source.
5772static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5773 bool isAddressOf, bool &isWeakAccess) {
5774 // Skip parens.
5775 e = e->IgnoreParens();
5776
5777 // Skip address-of nodes.
5778 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5779 if (op->getOpcode() == UO_AddrOf)
5780 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5781 isWeakAccess);
5782
5783 // Skip certain casts.
5784 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5785 switch (ce->getCastKind()) {
5786 case CK_Dependent:
5787 case CK_BitCast:
5788 case CK_LValueBitCast:
5789 case CK_NoOp:
5790 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5791
5792 case CK_ArrayToPointerDecay:
5793 return IIK_nonscalar;
5794
5795 case CK_NullToPointer:
5796 return IIK_okay;
5797
5798 default:
5799 break;
5800 }
5801
5802 // If we have a declaration reference, it had better be a local variable.
5803 } else if (isa<DeclRefExpr>(e)) {
5804 // set isWeakAccess to true, to mean that there will be an implicit
5805 // load which requires a cleanup.
5806 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5807 isWeakAccess = true;
5808
5809 if (!isAddressOf) return IIK_nonlocal;
5810
5811 VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5812 if (!var) return IIK_nonlocal;
5813
5814 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5815
5816 // If we have a conditional operator, check both sides.
5817 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5818 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5819 isWeakAccess))
5820 return iik;
5821
5822 return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5823
5824 // These are never scalar.
5825 } else if (isa<ArraySubscriptExpr>(e)) {
5826 return IIK_nonscalar;
5827
5828 // Otherwise, it needs to be a null pointer constant.
5829 } else {
5830 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5831 ? IIK_okay : IIK_nonlocal);
5832 }
5833
5834 return IIK_nonlocal;
5835}
5836
5837/// Check whether the given expression is a valid operand for an
5838/// indirect copy/restore.
5839static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5840 assert(src->isPRValue())(static_cast <bool> (src->isPRValue()) ? void (0) : __assert_fail
("src->isPRValue()", "clang/lib/Sema/SemaInit.cpp", 5840,
__extension__ __PRETTY_FUNCTION__))
;
5841 bool isWeakAccess = false;
5842 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5843 // If isWeakAccess to true, there will be an implicit
5844 // load which requires a cleanup.
5845 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5846 S.Cleanup.setExprNeedsCleanups(true);
5847
5848 if (iik == IIK_okay) return;
5849
5850 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5851 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5852 << src->getSourceRange();
5853}
5854
5855/// Determine whether we have compatible array types for the
5856/// purposes of GNU by-copy array initialization.
5857static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5858 const ArrayType *Source) {
5859 // If the source and destination array types are equivalent, we're
5860 // done.
5861 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5862 return true;
5863
5864 // Make sure that the element types are the same.
5865 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5866 return false;
5867
5868 // The only mismatch we allow is when the destination is an
5869 // incomplete array type and the source is a constant array type.
5870 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5871}
5872
5873static bool tryObjCWritebackConversion(Sema &S,
5874 InitializationSequence &Sequence,
5875 const InitializedEntity &Entity,
5876 Expr *Initializer) {
5877 bool ArrayDecay = false;
5878 QualType ArgType = Initializer->getType();
5879 QualType ArgPointee;
5880 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5881 ArrayDecay = true;
5882 ArgPointee = ArgArrayType->getElementType();
5883 ArgType = S.Context.getPointerType(ArgPointee);
5884 }
5885
5886 // Handle write-back conversion.
5887 QualType ConvertedArgType;
5888 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5889 ConvertedArgType))
5890 return false;
5891
5892 // We should copy unless we're passing to an argument explicitly
5893 // marked 'out'.
5894 bool ShouldCopy = true;
5895 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5896 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5897
5898 // Do we need an lvalue conversion?
5899 if (ArrayDecay || Initializer->isGLValue()) {
5900 ImplicitConversionSequence ICS;
5901 ICS.setStandard();
5902 ICS.Standard.setAsIdentityConversion();
5903
5904 QualType ResultType;
5905 if (ArrayDecay) {
5906 ICS.Standard.First = ICK_Array_To_Pointer;
5907 ResultType = S.Context.getPointerType(ArgPointee);
5908 } else {
5909 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5910 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
5911 }
5912
5913 Sequence.AddConversionSequenceStep(ICS, ResultType);
5914 }
5915
5916 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
5917 return true;
5918}
5919
5920static bool TryOCLSamplerInitialization(Sema &S,
5921 InitializationSequence &Sequence,
5922 QualType DestType,
5923 Expr *Initializer) {
5924 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
5925 (!Initializer->isIntegerConstantExpr(S.Context) &&
5926 !Initializer->getType()->isSamplerT()))
5927 return false;
5928
5929 Sequence.AddOCLSamplerInitStep(DestType);
5930 return true;
5931}
5932
5933static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
5934 return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
5935 (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
5936}
5937
5938static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
5939 InitializationSequence &Sequence,
5940 QualType DestType,
5941 Expr *Initializer) {
5942 if (!S.getLangOpts().OpenCL)
5943 return false;
5944
5945 //
5946 // OpenCL 1.2 spec, s6.12.10
5947 //
5948 // The event argument can also be used to associate the
5949 // async_work_group_copy with a previous async copy allowing
5950 // an event to be shared by multiple async copies; otherwise
5951 // event should be zero.
5952 //
5953 if (DestType->isEventT() || DestType->isQueueT()) {
5954 if (!IsZeroInitializer(Initializer, S))
5955 return false;
5956
5957 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5958 return true;
5959 }
5960
5961 // We should allow zero initialization for all types defined in the
5962 // cl_intel_device_side_avc_motion_estimation extension, except
5963 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
5964 if (S.getOpenCLOptions().isAvailableOption(
5965 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
5966 DestType->isOCLIntelSubgroupAVCType()) {
5967 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
5968 DestType->isOCLIntelSubgroupAVCMceResultType())
5969 return false;
5970 if (!IsZeroInitializer(Initializer, S))
5971 return false;
5972
5973 Sequence.AddOCLZeroOpaqueTypeStep(DestType);
5974 return true;
5975 }
5976
5977 return false;
5978}
5979
5980InitializationSequence::InitializationSequence(
5981 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5982 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
5983 : FailedOverloadResult(OR_Success),
5984 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
5985 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
5986 TreatUnavailableAsInvalid);
5987}
5988
5989/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
5990/// address of that function, this returns true. Otherwise, it returns false.
5991static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
5992 auto *DRE = dyn_cast<DeclRefExpr>(E);
5993 if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
5994 return false;
5995
5996 return !S.checkAddressOfFunctionIsAvailable(
5997 cast<FunctionDecl>(DRE->getDecl()));
5998}
5999
6000/// Determine whether we can perform an elementwise array copy for this kind
6001/// of entity.
6002static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6003 switch (Entity.getKind()) {
6004 case InitializedEntity::EK_LambdaCapture:
6005 // C++ [expr.prim.lambda]p24:
6006 // For array members, the array elements are direct-initialized in
6007 // increasing subscript order.
6008 return true;
6009
6010 case InitializedEntity::EK_Variable:
6011 // C++ [dcl.decomp]p1:
6012 // [...] each element is copy-initialized or direct-initialized from the
6013 // corresponding element of the assignment-expression [...]
6014 return isa<DecompositionDecl>(Entity.getDecl());
6015
6016 case InitializedEntity::EK_Member:
6017 // C++ [class.copy.ctor]p14:
6018 // - if the member is an array, each element is direct-initialized with
6019 // the corresponding subobject of x
6020 return Entity.isImplicitMemberInitializer();
6021
6022 case InitializedEntity::EK_ArrayElement:
6023 // All the above cases are intended to apply recursively, even though none
6024 // of them actually say that.
6025 if (auto *E = Entity.getParent())
6026 return canPerformArrayCopy(*E);
6027 break;
6028
6029 default:
6030 break;
6031 }
6032
6033 return false;
6034}
6035
6036void InitializationSequence::InitializeFrom(Sema &S,
6037 const InitializedEntity &Entity,
6038 const InitializationKind &Kind,
6039 MultiExprArg Args,
6040 bool TopLevelOfInitList,
6041 bool TreatUnavailableAsInvalid) {
6042 ASTContext &Context = S.Context;
6043
6044 // Eliminate non-overload placeholder types in the arguments. We
6045 // need to do this before checking whether types are dependent
6046 // because lowering a pseudo-object expression might well give us
6047 // something of dependent type.
6048 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1
Assuming 'I' is equal to 'E'
2
Loop condition is false. Execution continues on line 6065
6049 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6050 // FIXME: should we be doing this here?
6051 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6052 if (result.isInvalid()) {
6053 SetFailed(FK_PlaceholderType);
6054 return;
6055 }
6056 Args[I] = result.get();
6057 }
6058
6059 // C++0x [dcl.init]p16:
6060 // The semantics of initializers are as follows. The destination type is
6061 // the type of the object or reference being initialized and the source
6062 // type is the type of the initializer expression. The source type is not
6063 // defined when the initializer is a braced-init-list or when it is a
6064 // parenthesized list of expressions.
6065 QualType DestType = Entity.getType();
6066
6067 if (DestType->isDependentType() ||
3
Assuming the condition is false
5
Taking false branch
6068 Expr::hasAnyTypeDependentArguments(Args)) {
4
Assuming the condition is false
6069 SequenceKind = DependentSequence;
6070 return;
6071 }
6072
6073 // Almost everything is a normal sequence.
6074 setSequenceKind(NormalSequence);
6075
6076 QualType SourceType;
6077 Expr *Initializer = nullptr;
6
'Initializer' initialized to a null pointer value
6078 if (Args.size() == 1) {
7
Assuming the condition is false
8
Taking false branch
6079 Initializer = Args[0];
6080 if (S.getLangOpts().ObjC) {
6081 if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
6082 DestType, Initializer->getType(),
6083 Initializer) ||
6084 S.CheckConversionToObjCLiteral(DestType, Initializer))
6085 Args[0] = Initializer;
6086 }
6087 if (!isa<InitListExpr>(Initializer))
6088 SourceType = Initializer->getType();
6089 }
6090
6091 // - If the initializer is a (non-parenthesized) braced-init-list, the
6092 // object is list-initialized (8.5.4).
6093 if (Kind.getKind() != InitializationKind::IK_Direct) {
9
Assuming the condition is false
10
Taking false branch
6094 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6095 TryListInitialization(S, Entity, Kind, InitList, *this,
6096 TreatUnavailableAsInvalid);
6097 return;
6098 }
6099 }
6100
6101 // - If the destination type is a reference type, see 8.5.3.
6102 if (DestType->isReferenceType()) {
6103 // C++0x [dcl.init.ref]p1:
6104 // A variable declared to be a T& or T&&, that is, "reference to type T"
6105 // (8.3.2), shall be initialized by an object, or function, of type T or
6106 // by an object that can be converted into a T.
6107 // (Therefore, multiple arguments are not permitted.)
6108 if (Args.size() != 1)
6109 SetFailed(FK_TooManyInitsForReference);
6110 // C++17 [dcl.init.ref]p5:
6111 // A reference [...] is initialized by an expression [...] as follows:
6112 // If the initializer is not an expression, presumably we should reject,
6113 // but the standard fails to actually say so.
6114 else if (isa<InitListExpr>(Args[0]))
6115 SetFailed(FK_ParenthesizedListInitForReference);
6116 else
6117 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
6118 return;
6119 }
6120
6121 // - If the initializer is (), the object is value-initialized.
6122 if (Kind.getKind() == InitializationKind::IK_Value ||
12
Taking false branch
6123 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
11
Assuming the condition is false
6124 TryValueInitialization(S, Entity, Kind, *this);
6125 return;
6126 }
6127
6128 // Handle default initialization.
6129 if (Kind.getKind() == InitializationKind::IK_Default) {
13
Taking false branch
6130 TryDefaultInitialization(S, Entity, Kind, *this);
6131 return;
6132 }
6133
6134 // - If the destination type is an array of characters, an array of
6135 // char16_t, an array of char32_t, or an array of wchar_t, and the
6136 // initializer is a string literal, see 8.5.2.
6137 // - Otherwise, if the destination type is an array, the program is
6138 // ill-formed.
6139 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
14
Assuming 'DestAT' is null
6140 if (Initializer && isa<VariableArrayType>(DestAT)) {
6141 SetFailed(FK_VariableLengthArrayHasInitializer);
6142 return;
6143 }
6144
6145 if (Initializer) {
6146 switch (IsStringInit(Initializer, DestAT, Context)) {
6147 case SIF_None:
6148 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6149 return;
6150 case SIF_NarrowStringIntoWideChar:
6151 SetFailed(FK_NarrowStringIntoWideCharArray);
6152 return;
6153 case SIF_WideStringIntoChar:
6154 SetFailed(FK_WideStringIntoCharArray);
6155 return;
6156 case SIF_IncompatWideStringIntoWideChar:
6157 SetFailed(FK_IncompatWideStringIntoWideChar);
6158 return;
6159 case SIF_PlainStringIntoUTF8Char:
6160 SetFailed(FK_PlainStringIntoUTF8Char);
6161 return;
6162 case SIF_UTF8StringIntoPlainChar:
6163 SetFailed(FK_UTF8StringIntoPlainChar);
6164 return;
6165 case SIF_Other:
6166 break;
6167 }
6168 }
6169
6170 // Some kinds of initialization permit an array to be initialized from
6171 // another array of the same type, and perform elementwise initialization.
6172 if (Initializer && isa<ConstantArrayType>(DestAT) &&
6173 S.Context.hasSameUnqualifiedType(Initializer->getType(),
6174 Entity.getType()) &&
6175 canPerformArrayCopy(Entity)) {
6176 // If source is a prvalue, use it directly.
6177 if (Initializer->isPRValue()) {
6178 AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6179 return;
6180 }
6181
6182 // Emit element-at-a-time copy loop.
6183 InitializedEntity Element =
6184 InitializedEntity::InitializeElement(S.Context, 0, Entity);
6185 QualType InitEltT =
6186 Context.getAsArrayType(Initializer->getType())->getElementType();
6187 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6188 Initializer->getValueKind(),
6189 Initializer->getObjectKind());
6190 Expr *OVEAsExpr = &OVE;
6191 InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6192 TreatUnavailableAsInvalid);
6193 if (!Failed())
6194 AddArrayInitLoopStep(Entity.getType(), InitEltT);
6195 return;
6196 }
6197
6198 // Note: as an GNU C extension, we allow initialization of an
6199 // array from a compound literal that creates an array of the same
6200 // type, so long as the initializer has no side effects.
6201 if (!S.getLangOpts().CPlusPlus && Initializer &&
6202 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6203 Initializer->getType()->isArrayType()) {
6204 const ArrayType *SourceAT
6205 = Context.getAsArrayType(Initializer->getType());
6206 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6207 SetFailed(FK_ArrayTypeMismatch);
6208 else if (Initializer->HasSideEffects(S.Context))
6209 SetFailed(FK_NonConstantArrayInit);
6210 else {
6211 AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6212 }
6213 }
6214 // Note: as a GNU C++ extension, we allow list-initialization of a
6215 // class member of array type from a parenthesized initializer list.
6216 else if (S.getLangOpts().CPlusPlus &&
6217 Entity.getKind() == InitializedEntity::EK_Member &&
6218 Initializer && isa<InitListExpr>(Initializer)) {
6219 TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6220 *this, TreatUnavailableAsInvalid);
6221 AddParenthesizedArrayInitStep(DestType);
6222 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6223 Kind.getKind() == InitializationKind::IK_Direct)
6224 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6225 /*VerifyOnly=*/true);
6226 else if (DestAT->getElementType()->isCharType())
6227 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6228 else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6229 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6230 else
6231 SetFailed(FK_ArrayNeedsInitList);
6232
6233 return;
6234 }
6235
6236 // Determine whether we should consider writeback conversions for
6237 // Objective-C ARC.
6238 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
15
Assuming field 'ObjCAutoRefCount' is 0
6239 Entity.isParameterKind();
6240
6241 if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
16
Taking false branch
6242 return;
6243
6244 // We're at the end of the line for C: it's either a write-back conversion
6245 // or it's a C assignment. There's no need to check anything else.
6246 if (!S.getLangOpts().CPlusPlus) {
17
Assuming field 'CPlusPlus' is not equal to 0
18
Taking false branch
6247 // If allowed, check whether this is an Objective-C writeback conversion.
6248 if (allowObjCWritebackConversion &&
6249 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6250 return;
6251 }
6252
6253 if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6254 return;
6255
6256 // Handle initialization in C
6257 AddCAssignmentStep(DestType);
6258 MaybeProduceObjCObject(S, *this, Entity);
6259 return;
6260 }
6261
6262 assert(S.getLangOpts().CPlusPlus)(static_cast <bool> (S.getLangOpts().CPlusPlus) ? void (
0) : __assert_fail ("S.getLangOpts().CPlusPlus", "clang/lib/Sema/SemaInit.cpp"
, 6262, __extension__ __PRETTY_FUNCTION__))
;
19
'?' condition is true
6263
6264 // - If the destination type is a (possibly cv-qualified) class type:
6265 if (DestType->isRecordType()) {
6266 // - If the initialization is direct-initialization, or if it is
6267 // copy-initialization where the cv-unqualified version of the
6268 // source type is the same class as, or a derived class of, the
6269 // class of the destination, constructors are considered. [...]
6270 if (Kind.getKind() == InitializationKind::IK_Direct ||
6271 (Kind.getKind() == InitializationKind::IK_Copy &&
6272 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6273 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) {
6274 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6275 *this);
6276
6277 // We fall back to the "no matching constructor" path if the
6278 // failed candidate set has functions other than the three default
6279 // constructors. For example, conversion function.
6280 if (const auto *RD =
6281 dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6282 // In general, we should call isCompleteType for RD to check its
6283 // completeness, we don't call it here as it was already called in the
6284 // above TryConstructorInitialization.
6285 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6286 RD->isAggregate() && Failed() &&
6287 getFailureKind() == FK_ConstructorOverloadFailed) {
6288 // Do not attempt paren list initialization if overload resolution
6289 // resolves to a deleted function .
6290 //
6291 // We may reach this condition if we have a union wrapping a class with
6292 // a non-trivial copy or move constructor and we call one of those two
6293 // constructors. The union is an aggregate, but the matched constructor
6294 // is implicitly deleted, so we need to prevent aggregate initialization
6295 // (otherwise, it'll attempt aggregate initialization by initializing
6296 // the first element with a reference to the union).
6297 OverloadCandidateSet::iterator Best;
6298 OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
6299 S, Kind.getLocation(), Best);
6300 if (OR != OverloadingResult::OR_Deleted) {
6301 // C++20 [dcl.init] 17.6.2.2:
6302 // - Otherwise, if no constructor is viable, the destination type is
6303 // an
6304 // aggregate class, and the initializer is a parenthesized
6305 // expression-list.
6306 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6307 /*VerifyOnly=*/true);
6308 }
6309 }
6310 } else {
6311 // - Otherwise (i.e., for the remaining copy-initialization cases),
6312 // user-defined conversion sequences that can convert from the
6313 // source type to the destination type or (when a conversion
6314 // function is used) to a derived class thereof are enumerated as
6315 // described in 13.3.1.4, and the best one is chosen through
6316 // overload resolution (13.3).
6317 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6318 TopLevelOfInitList);
6319 }
6320 return;
6321 }
6322
6323 assert(Args.size() >= 1 && "Zero-argument case handled above")(static_cast <bool> (Args.size() >= 1 && "Zero-argument case handled above"
) ? void (0) : __assert_fail ("Args.size() >= 1 && \"Zero-argument case handled above\""
, "clang/lib/Sema/SemaInit.cpp", 6323, __extension__ __PRETTY_FUNCTION__
))
;
20
Taking false branch
21
Assuming the condition is true
22
'?' condition is true
6324
6325 // For HLSL ext vector types we allow list initialization behavior for C++
6326 // constructor syntax. This is accomplished by converting initialization
6327 // arguments an InitListExpr late.
6328 if (S.getLangOpts().HLSL && DestType->isExtVectorType() &&
23
Assuming field 'HLSL' is 0
6329 (SourceType.isNull() ||
6330 !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6331
6332 llvm::SmallVector<Expr *> InitArgs;
6333 for (auto *Arg : Args) {
6334 if (Arg->getType()->isExtVectorType()) {
6335 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6336 unsigned Elm = VTy->getNumElements();
6337 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6338 InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6339 Arg,
6340 IntegerLiteral::Create(
6341 Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6342 Context.IntTy, SourceLocation()),
6343 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6344 SourceLocation()));
6345 }
6346 } else
6347 InitArgs.emplace_back(Arg);
6348 }
6349 InitListExpr *ILE = new (Context) InitListExpr(
6350 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6351 Args[0] = ILE;
6352 AddListInitializationStep(DestType);
6353 return;
6354 }
6355
6356 // The remaining cases all need a source type.
6357 if (Args.size() > 1) {
24
Assuming the condition is false
25
Taking false branch
6358 SetFailed(FK_TooManyInitsForScalar);
6359 return;
6360 } else if (isa<InitListExpr>(Args[0])) {
26
Assuming the object is not a 'InitListExpr'
6361 SetFailed(FK_ParenthesizedListInitForScalar);
6362 return;
6363 }
6364
6365 // - Otherwise, if the source type is a (possibly cv-qualified) class
6366 // type, conversion functions are considered.
6367 if (!SourceType.isNull() && SourceType->isRecordType()) {
6368 // For a conversion to _Atomic(T) from either T or a class type derived
6369 // from T, initialize the T object then convert to _Atomic type.
6370 bool NeedAtomicConversion = false;
6371 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6372 if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6373 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6374 Atomic->getValueType())) {
6375 DestType = Atomic->getValueType();
6376 NeedAtomicConversion = true;
6377 }
6378 }
6379
6380 TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6381 TopLevelOfInitList);
6382 MaybeProduceObjCObject(S, *this, Entity);
6383 if (!Failed() && NeedAtomicConversion)
6384 AddAtomicConversionStep(Entity.getType());
6385 return;
6386 }
6387
6388 // - Otherwise, if the initialization is direct-initialization, the source
6389 // type is std::nullptr_t, and the destination type is bool, the initial
6390 // value of the object being initialized is false.
6391 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6392 DestType->isBooleanType() &&
6393 Kind.getKind() == InitializationKind::IK_Direct) {
6394 AddConversionSequenceStep(
6395 ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
6396 Initializer->isGLValue()),
6397 DestType);
6398 return;
6399 }
6400
6401 // - Otherwise, the initial value of the object being initialized is the
6402 // (possibly converted) value of the initializer expression. Standard
6403 // conversions (Clause 4) will be used, if necessary, to convert the
6404 // initializer expression to the cv-unqualified version of the
6405 // destination type; no user-defined conversions are considered.
6406
6407 ImplicitConversionSequence ICS
6408 = S.TryImplicitConversion(Initializer, DestType,
6409 /*SuppressUserConversions*/true,
6410 Sema::AllowedExplicit::None,
6411 /*InOverloadResolution*/ false,
6412 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6413 allowObjCWritebackConversion);
6414
6415 if (ICS.isStandard() &&
6416 ICS.Standard.Second == ICK_Writeback_Conversion) {
6417 // Objective-C ARC writeback conversion.
6418
6419 // We should copy unless we're passing to an argument explicitly
6420 // marked 'out'.
6421 bool ShouldCopy = true;
6422 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6423 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6424
6425 // If there was an lvalue adjustment, add it as a separate conversion.
6426 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6427 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6428 ImplicitConversionSequence LvalueICS;
6429 LvalueICS.setStandard();
6430 LvalueICS.Standard.setAsIdentityConversion();
6431 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6432 LvalueICS.Standard.First = ICS.Standard.First;
6433 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6434 }
6435
6436 AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6437 } else if (ICS.isBad()) {
27
Taking true branch
6438 DeclAccessPair dap;
6439 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
6440 AddZeroInitializationStep(Entity.getType());
6441 } else if (Initializer->getType() == Context.OverloadTy &&
28
Called C++ object pointer is null
6442 !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
6443 false, dap))
6444 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
6445 else if (Initializer->getType()->isFunctionType() &&
6446 isExprAnUnaddressableFunction(S, Initializer))
6447 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
6448 else
6449 SetFailed(InitializationSequence::FK_ConversionFailed);
6450 } else {
6451 AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6452
6453 MaybeProduceObjCObject(S, *this, Entity);
6454 }
6455}
6456
6457InitializationSequence::~InitializationSequence() {
6458 for (auto &S : Steps)
6459 S.Destroy();
6460}
6461
6462//===----------------------------------------------------------------------===//
6463// Perform initialization
6464//===----------------------------------------------------------------------===//
6465static Sema::AssignmentAction
6466getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6467 switch(Entity.getKind()) {
6468 case InitializedEntity::EK_Variable:
6469 case InitializedEntity::EK_New:
6470 case InitializedEntity::EK_Exception:
6471 case InitializedEntity::EK_Base:
6472 case InitializedEntity::EK_Delegating:
6473 return Sema::AA_Initializing;
6474
6475 case InitializedEntity::EK_Parameter:
6476 if (Entity.getDecl() &&
6477 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6478 return Sema::AA_Sending;
6479
6480 return Sema::AA_Passing;
6481
6482 case InitializedEntity::EK_Parameter_CF_Audited:
6483 if (Entity.getDecl() &&
6484 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6485 return Sema::AA_Sending;
6486
6487 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6488
6489 case InitializedEntity::EK_Result:
6490 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6491 return Sema::AA_Returning;
6492
6493 case InitializedEntity::EK_Temporary:
6494 case InitializedEntity::EK_RelatedResult:
6495 // FIXME: Can we tell apart casting vs. converting?
6496 return Sema::AA_Casting;
6497
6498 case InitializedEntity::EK_TemplateParameter:
6499 // This is really initialization, but refer to it as conversion for
6500 // consistency with CheckConvertedConstantExpression.
6501 return Sema::AA_Converting;
6502
6503 case InitializedEntity::EK_Member:
6504 case InitializedEntity::EK_ParenAggInitMember:
6505 case InitializedEntity::EK_Binding:
6506 case InitializedEntity::EK_ArrayElement:
6507 case InitializedEntity::EK_VectorElement:
6508 case InitializedEntity::EK_ComplexElement:
6509 case InitializedEntity::EK_BlockElement:
6510 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6511 case InitializedEntity::EK_LambdaCapture:
6512 case InitializedEntity::EK_CompoundLiteralInit:
6513 return Sema::AA_Initializing;
6514 }
6515
6516 llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "clang/lib/Sema/SemaInit.cpp"
, 6516)
;
6517}
6518
6519/// Whether we should bind a created object as a temporary when
6520/// initializing the given entity.
6521static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6522 switch (Entity.getKind()) {
6523 case InitializedEntity::EK_ArrayElement:
6524 case InitializedEntity::EK_Member:
6525 case InitializedEntity::EK_ParenAggInitMember:
6526 case InitializedEntity::EK_Result:
6527 case InitializedEntity::EK_StmtExprResult:
6528 case InitializedEntity::EK_New:
6529 case InitializedEntity::EK_Variable:
6530 case InitializedEntity::EK_Base:
6531 case InitializedEntity::EK_Delegating:
6532 case InitializedEntity::EK_VectorElement:
6533 case InitializedEntity::EK_ComplexElement:
6534 case InitializedEntity::EK_Exception:
6535 case InitializedEntity::EK_BlockElement:
6536 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6537 case InitializedEntity::EK_LambdaCapture:
6538 case InitializedEntity::EK_CompoundLiteralInit:
6539 case InitializedEntity::EK_TemplateParameter:
6540 return false;
6541
6542 case InitializedEntity::EK_Parameter:
6543 case InitializedEntity::EK_Parameter_CF_Audited:
6544 case InitializedEntity::EK_Temporary:
6545 case InitializedEntity::EK_RelatedResult:
6546 case InitializedEntity::EK_Binding:
6547 return true;
6548 }
6549
6550 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "clang/lib/Sema/SemaInit.cpp", 6550)
;
6551}
6552
6553/// Whether the given entity, when initialized with an object
6554/// created for that initialization, requires destruction.
6555static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6556 switch (Entity.getKind()) {
6557 case InitializedEntity::EK_Result:
6558 case InitializedEntity::EK_StmtExprResult:
6559 case InitializedEntity::EK_New:
6560 case InitializedEntity::EK_Base:
6561 case InitializedEntity::EK_Delegating:
6562 case InitializedEntity::EK_VectorElement:
6563 case InitializedEntity::EK_ComplexElement:
6564 case InitializedEntity::EK_BlockElement:
6565 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6566 case InitializedEntity::EK_LambdaCapture:
6567 return false;
6568
6569 case InitializedEntity::EK_Member:
6570 case InitializedEntity::EK_ParenAggInitMember:
6571 case InitializedEntity::EK_Binding:
6572 case InitializedEntity::EK_Variable:
6573 case InitializedEntity::EK_Parameter:
6574 case InitializedEntity::EK_Parameter_CF_Audited:
6575 case InitializedEntity::EK_TemplateParameter:
6576 case InitializedEntity::EK_Temporary:
6577 case InitializedEntity::EK_ArrayElement:
6578 case InitializedEntity::EK_Exception:
6579 case InitializedEntity::EK_CompoundLiteralInit:
6580 case InitializedEntity::EK_RelatedResult:
6581 return true;
6582 }
6583
6584 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "clang/lib/Sema/SemaInit.cpp", 6584)
;
6585}
6586
6587/// Get the location at which initialization diagnostics should appear.
6588static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
6589 Expr *Initializer) {
6590 switch (Entity.getKind()) {
6591 case InitializedEntity::EK_Result:
6592 case InitializedEntity::EK_StmtExprResult:
6593 return Entity.getReturnLoc();
6594
6595 case InitializedEntity::EK_Exception:
6596 return Entity.getThrowLoc();
6597
6598 case InitializedEntity::EK_Variable:
6599 case InitializedEntity::EK_Binding:
6600 return Entity.getDecl()->getLocation();
6601
6602 case InitializedEntity::EK_LambdaCapture:
6603 return Entity.getCaptureLoc();
6604
6605 case InitializedEntity::EK_ArrayElement:
6606 case InitializedEntity::EK_Member:
6607 case InitializedEntity::EK_ParenAggInitMember:
6608 case InitializedEntity::EK_Parameter:
6609 case InitializedEntity::EK_Parameter_CF_Audited:
6610 case InitializedEntity::EK_TemplateParameter:
6611 case InitializedEntity::EK_Temporary:
6612 case InitializedEntity::EK_New:
6613 case InitializedEntity::EK_Base:
6614 case InitializedEntity::EK_Delegating:
6615 case InitializedEntity::EK_VectorElement:
6616 case InitializedEntity::EK_ComplexElement:
6617 case InitializedEntity::EK_BlockElement:
6618 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6619 case InitializedEntity::EK_CompoundLiteralInit:
6620 case InitializedEntity::EK_RelatedResult:
6621 return Initializer->getBeginLoc();
6622 }
6623 llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?"
, "clang/lib/Sema/SemaInit.cpp", 6623)
;
6624}
6625
6626/// Make a (potentially elidable) temporary copy of the object
6627/// provided by the given initializer by calling the appropriate copy
6628/// constructor.
6629///
6630/// \param S The Sema object used for type-checking.
6631///
6632/// \param T The type of the temporary object, which must either be
6633/// the type of the initializer expression or a superclass thereof.
6634///
6635/// \param Entity The entity being initialized.
6636///
6637/// \param CurInit The initializer expression.
6638///
6639/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6640/// is permitted in C++03 (but not C++0x) when binding a reference to
6641/// an rvalue.
6642///
6643/// \returns An expression that copies the initializer expression into
6644/// a temporary object, or an error expression if a copy could not be
6645/// created.
6646static ExprResult CopyObject(Sema &S,
6647 QualType T,
6648 const InitializedEntity &Entity,
6649 ExprResult CurInit,
6650 bool IsExtraneousCopy) {
6651 if (CurInit.isInvalid())
6652 return CurInit;
6653 // Determine which class type we're copying to.
6654 Expr *CurInitExpr = (Expr *)CurInit.get();
6655 CXXRecordDecl *Class = nullptr;
6656 if (const RecordType *Record = T->getAs<RecordType>())
6657 Class = cast<CXXRecordDecl>(Record->getDecl());
6658 if (!Class)
6659 return CurInit;
6660
6661 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6662
6663 // Make sure that the type we are copying is complete.
6664 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6665 return CurInit;
6666
6667 // Perform overload resolution using the class's constructors. Per
6668 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6669 // is direct-initialization.
6670 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6671 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
6672
6673 OverloadCandidateSet::iterator Best;
6674 switch (ResolveConstructorOverload(
6675 S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6676 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6677 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6678 /*SecondStepOfCopyInit=*/true)) {
6679 case OR_Success:
6680 break;
6681
6682 case OR_No_Viable_Function:
6683 CandidateSet.NoteCandidates(
6684 PartialDiagnosticAt(
6685 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6686 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6687 : diag::err_temp_copy_no_viable)
6688 << (int)Entity.getKind() << CurInitExpr->getType()
6689 << CurInitExpr->getSourceRange()),
6690 S, OCD_AllCandidates, CurInitExpr);
6691 if (!IsExtraneousCopy || S.isSFINAEContext())
6692 return ExprError();
6693 return CurInit;
6694
6695 case OR_Ambiguous:
6696 CandidateSet.NoteCandidates(
6697 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6698 << (int)Entity.getKind()
6699 << CurInitExpr->getType()
6700 << CurInitExpr->getSourceRange()),
6701 S, OCD_AmbiguousCandidates, CurInitExpr);
6702 return ExprError();
6703
6704 case OR_Deleted:
6705 S.Diag(Loc, diag::err_temp_copy_deleted)
6706 << (int)Entity.getKind() << CurInitExpr->getType()
6707 << CurInitExpr->getSourceRange();
6708 S.NoteDeletedFunction(Best->Function);
6709 return ExprError();
6710 }
6711
6712 bool HadMultipleCandidates = CandidateSet.size() > 1;
6713
6714 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6715 SmallVector<Expr*, 8> ConstructorArgs;
6716 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6717
6718 S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6719 IsExtraneousCopy);
6720
6721 if (IsExtraneousCopy) {
6722 // If this is a totally extraneous copy for C++03 reference
6723 // binding purposes, just return the original initialization
6724 // expression. We don't generate an (elided) copy operation here
6725 // because doing so would require us to pass down a flag to avoid
6726 // infinite recursion, where each step adds another extraneous,
6727 // elidable copy.
6728
6729 // Instantiate the default arguments of any extra parameters in
6730 // the selected copy constructor, as if we were going to create a
6731 // proper call to the copy constructor.
6732 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6733 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6734 if (S.RequireCompleteType(Loc, Parm->getType(),
6735 diag::err_call_incomplete_argument))
6736 break;
6737
6738 // Build the default argument expression; we don't actually care
6739 // if this succeeds or not, because this routine will complain
6740 // if there was a problem.
6741 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6742 }
6743
6744 return CurInitExpr;
6745 }
6746
6747 // Determine the arguments required to actually perform the
6748 // constructor call (we might have derived-to-base conversions, or
6749 // the copy constructor may have default arguments).
6750 if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6751 ConstructorArgs))
6752 return ExprError();
6753
6754 // C++0x [class.copy]p32:
6755 // When certain criteria are met, an implementation is allowed to
6756 // omit the copy/move construction of a class object, even if the
6757 // copy/move constructor and/or destructor for the object have
6758 // side effects. [...]
6759 // - when a temporary class object that has not been bound to a
6760 // reference (12.2) would be copied/moved to a class object
6761 // with the same cv-unqualified type, the copy/move operation
6762 // can be omitted by constructing the temporary object
6763 // directly into the target of the omitted copy/move
6764 //
6765 // Note that the other three bullets are handled elsewhere. Copy
6766 // elision for return statements and throw expressions are handled as part
6767 // of constructor initialization, while copy elision for exception handlers
6768 // is handled by the run-time.
6769 //
6770 // FIXME: If the function parameter is not the same type as the temporary, we
6771 // should still be able to elide the copy, but we don't have a way to
6772 // represent in the AST how much should be elided in this case.
6773 bool Elidable =
6774 CurInitExpr->isTemporaryObject(S.Context, Class) &&
6775 S.Context.hasSameUnqualifiedType(
6776 Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6777 CurInitExpr->getType());
6778
6779 // Actually perform the constructor call.
6780 CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor,
6781 Elidable,
6782 ConstructorArgs,
6783 HadMultipleCandidates,
6784 /*ListInit*/ false,
6785 /*StdInitListInit*/ false,
6786 /*ZeroInit*/ false,
6787 CXXConstructExpr::CK_Complete,
6788 SourceRange());
6789
6790 // If we're supposed to bind temporaries, do so.
6791 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6792 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6793 return CurInit;
6794}
6795
6796/// Check whether elidable copy construction for binding a reference to
6797/// a temporary would have succeeded if we were building in C++98 mode, for
6798/// -Wc++98-compat.
6799static void CheckCXX98CompatAccessibleCopy(Sema &S,
6800 const InitializedEntity &Entity,
6801 Expr *CurInitExpr) {
6802 assert(S.getLangOpts().CPlusPlus11)(static_cast <bool> (S.getLangOpts().CPlusPlus11) ? void
(0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "clang/lib/Sema/SemaInit.cpp"
, 6802, __extension__ __PRETTY_FUNCTION__))
;
6803
6804 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6805 if (!Record)
6806 return;
6807
6808 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6809 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6810 return;
6811
6812 // Find constructors which would have been considered.
6813 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6814 DeclContext::lookup_result Ctors =
6815 S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6816
6817 // Perform overload resolution.
6818 OverloadCandidateSet::iterator Best;
6819 OverloadingResult OR = ResolveConstructorOverload(
6820 S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6821 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6822 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6823 /*SecondStepOfCopyInit=*/true);
6824
6825 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6826 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6827 << CurInitExpr->getSourceRange();
6828
6829 switch (OR) {
6830 case OR_Success:
6831 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6832 Best->FoundDecl, Entity, Diag);
6833 // FIXME: Check default arguments as far as that's possible.
6834 break;
6835
6836 case OR_No_Viable_Function:
6837 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6838 OCD_AllCandidates, CurInitExpr);
6839 break;
6840
6841 case OR_Ambiguous:
6842 CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6843 OCD_AmbiguousCandidates, CurInitExpr);
6844 break;
6845
6846 case OR_Deleted:
6847 S.Diag(Loc, Diag);
6848 S.NoteDeletedFunction(Best->Function);
6849 break;
6850 }
6851}
6852
6853void InitializationSequence::PrintInitLocationNote(Sema &S,
6854 const InitializedEntity &Entity) {
6855 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6856 if (Entity.getDecl()->getLocation().isInvalid())
6857 return;
6858
6859 if (Entity.getDecl()->getDeclName())
6860 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6861 << Entity.getDecl()->getDeclName();
6862 else
6863 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6864 }
6865 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6866 Entity.getMethodDecl())
6867 S.Diag(Entity.getMethodDecl()->getLocation(),
6868 diag::note_method_return_type_change)
6869 << Entity.getMethodDecl()->getDeclName();
6870}
6871
6872/// Returns true if the parameters describe a constructor initialization of
6873/// an explicit temporary object, e.g. "Point(x, y)".
6874static bool isExplicitTemporary(const InitializedEntity &Entity,
6875 const InitializationKind &Kind,
6876 unsigned NumArgs) {
6877 switch (Entity.getKind()) {
6878 case InitializedEntity::EK_Temporary:
6879 case InitializedEntity::EK_CompoundLiteralInit:
6880 case InitializedEntity::EK_RelatedResult:
6881 break;
6882 default:
6883 return false;
6884 }
6885
6886 switch (Kind.getKind()) {
6887 case InitializationKind::IK_DirectList:
6888 return true;
6889 // FIXME: Hack to work around cast weirdness.
6890 case InitializationKind::IK_Direct:
6891 case InitializationKind::IK_Value:
6892 return NumArgs != 1;
6893 default:
6894 return false;
6895 }
6896}
6897
6898static ExprResult
6899PerformConstructorInitialization(Sema &S,
6900 const InitializedEntity &Entity,
6901 const InitializationKind &Kind,
6902 MultiExprArg Args,
6903 const InitializationSequence::Step& Step,
6904 bool &ConstructorInitRequiresZeroInit,
6905 bool IsListInitialization,
6906 bool IsStdInitListInitialization,
6907 SourceLocation LBraceLoc,
6908 SourceLocation RBraceLoc) {
6909 unsigned NumArgs = Args.size();
6910 CXXConstructorDecl *Constructor
6911 = cast<CXXConstructorDecl>(Step.Function.Function);
6912 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
6913
6914 // Build a call to the selected constructor.
6915 SmallVector<Expr*, 8> ConstructorArgs;
6916 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
6917 ? Kind.getEqualLoc()
6918 : Kind.getLocation();
6919
6920 if (Kind.getKind() == InitializationKind::IK_Default) {
6921 // Force even a trivial, implicit default constructor to be
6922 // semantically checked. We do this explicitly because we don't build
6923 // the definition for completely trivial constructors.
6924 assert(Constructor->getParent() && "No parent class for constructor.")(static_cast <bool> (Constructor->getParent() &&
"No parent class for constructor.") ? void (0) : __assert_fail
("Constructor->getParent() && \"No parent class for constructor.\""
, "clang/lib/Sema/SemaInit.cpp", 6924, __extension__ __PRETTY_FUNCTION__
))
;
6925 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6926 Constructor->isTrivial() && !Constructor->isUsed(false)) {
6927 S.runWithSufficientStackSpace(Loc, [&] {
6928 S.DefineImplicitDefaultConstructor(Loc, Constructor);
6929 });
6930 }
6931 }
6932
6933 ExprResult CurInit((Expr *)nullptr);
6934
6935 // C++ [over.match.copy]p1:
6936 // - When initializing a temporary to be bound to the first parameter
6937 // of a constructor that takes a reference to possibly cv-qualified
6938 // T as its first argument, called with a single argument in the
6939 // context of direct-initialization, explicit conversion functions
6940 // are also considered.
6941 bool AllowExplicitConv =
6942 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
6943 hasCopyOrMoveCtorParam(S.Context,
6944 getConstructorInfo(Step.Function.FoundDecl));
6945
6946 // Determine the arguments required to actually perform the constructor
6947 // call.
6948 if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
6949 ConstructorArgs, AllowExplicitConv,
6950 IsListInitialization))
6951 return ExprError();
6952
6953 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
6954 // An explicitly-constructed temporary, e.g., X(1, 2).
6955 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
6956 return ExprError();
6957
6958 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6959 if (!TSInfo)
6960 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
6961 SourceRange ParenOrBraceRange =
6962 (Kind.getKind() == InitializationKind::IK_DirectList)
6963 ? SourceRange(LBraceLoc, RBraceLoc)
6964 : Kind.getParenOrBraceRange();
6965
6966 CXXConstructorDecl *CalleeDecl = Constructor;
6967 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
6968 Step.Function.FoundDecl.getDecl())) {
6969 CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
6970 }
6971 S.MarkFunctionReferenced(Loc, CalleeDecl);
6972
6973 CurInit = S.CheckForImmediateInvocation(
6974 CXXTemporaryObjectExpr::Create(
6975 S.Context, CalleeDecl,
6976 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
6977 ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
6978 IsListInitialization, IsStdInitListInitialization,
6979 ConstructorInitRequiresZeroInit),
6980 CalleeDecl);
6981 } else {
6982 CXXConstructExpr::ConstructionKind ConstructKind =
6983 CXXConstructExpr::CK_Complete;
6984
6985 if (Entity.getKind() == InitializedEntity::EK_Base) {
6986 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
6987 CXXConstructExpr::CK_VirtualBase :
6988 CXXConstructExpr::CK_NonVirtualBase;
6989 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
6990 ConstructKind = CXXConstructExpr::CK_Delegating;
6991 }
6992
6993 // Only get the parenthesis or brace range if it is a list initialization or
6994 // direct construction.
6995 SourceRange ParenOrBraceRange;
6996 if (IsListInitialization)
6997 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
6998 else if (Kind.getKind() == InitializationKind::IK_Direct)
6999 ParenOrBraceRange = Kind.getParenOrBraceRange();
7000
7001 // If the entity allows NRVO, mark the construction as elidable
7002 // unconditionally.
7003 if (Entity.allowsNRVO())
7004 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7005 Step.Function.FoundDecl,
7006 Constructor, /*Elidable=*/true,
7007 ConstructorArgs,
7008 HadMultipleCandidates,
7009 IsListInitialization,
7010 IsStdInitListInitialization,
7011 ConstructorInitRequiresZeroInit,
7012 ConstructKind,
7013 ParenOrBraceRange);
7014 else
7015 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7016 Step.Function.FoundDecl,
7017 Constructor,
7018 ConstructorArgs,
7019 HadMultipleCandidates,
7020 IsListInitialization,
7021 IsStdInitListInitialization,
7022 ConstructorInitRequiresZeroInit,
7023 ConstructKind,
7024 ParenOrBraceRange);
7025 }
7026 if (CurInit.isInvalid())
7027 return ExprError();
7028
7029 // Only check access if all of that succeeded.
7030 S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7031 if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7032 return ExprError();
7033
7034 if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7035 if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
7036 return ExprError();
7037
7038 if (shouldBindAsTemporary(Entity))
7039 CurInit = S.MaybeBindToTemporary(CurInit.get());
7040
7041 return CurInit;
7042}
7043
7044namespace {
7045enum LifetimeKind {
7046 /// The lifetime of a temporary bound to this entity ends at the end of the
7047 /// full-expression, and that's (probably) fine.
7048 LK_FullExpression,
7049
7050 /// The lifetime of a temporary bound to this entity is extended to the
7051 /// lifeitme of the entity itself.
7052 LK_Extended,
7053
7054 /// The lifetime of a temporary bound to this entity probably ends too soon,
7055 /// because the entity is allocated in a new-expression.
7056 LK_New,
7057
7058 /// The lifetime of a temporary bound to this entity ends too soon, because
7059 /// the entity is a return object.
7060 LK_Return,
7061
7062 /// The lifetime of a temporary bound to this entity ends too soon, because
7063 /// the entity is the result of a statement expression.
7064 LK_StmtExprResult,
7065
7066 /// This is a mem-initializer: if it would extend a temporary (other than via
7067 /// a default member initializer), the program is ill-formed.
7068 LK_MemInitializer,
7069};
7070using LifetimeResult =
7071 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7072}
7073
7074/// Determine the declaration which an initialized entity ultimately refers to,
7075/// for the purpose of lifetime-extending a temporary bound to a reference in
7076/// the initialization of \p Entity.
7077static LifetimeResult getEntityLifetime(
7078 const InitializedEntity *Entity,
7079 const InitializedEntity *InitField = nullptr) {
7080 // C++11 [class.temporary]p5:
7081 switch (Entity->getKind()) {
7082 case InitializedEntity::EK_Variable:
7083 // The temporary [...] persists for the lifetime of the reference
7084 return {Entity, LK_Extended};
7085
7086 case InitializedEntity::EK_Member:
7087 // For subobjects, we look at the complete object.
7088 if (Entity->getParent())
7089 return getEntityLifetime(Entity->getParent(), Entity);
7090
7091 // except:
7092 // C++17 [class.base.init]p8:
7093 // A temporary expression bound to a reference member in a
7094 // mem-initializer is ill-formed.
7095 // C++17 [class.base.init]p11:
7096 // A temporary expression bound to a reference member from a
7097 // default member initializer is ill-formed.
7098 //
7099 // The context of p11 and its example suggest that it's only the use of a
7100 // default member initializer from a constructor that makes the program
7101 // ill-formed, not its mere existence, and that it can even be used by
7102 // aggregate initialization.
7103 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7104 : LK_MemInitializer};
7105
7106 case InitializedEntity::EK_Binding:
7107 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7108 // type.
7109 return {Entity, LK_Extended};
7110
7111 case InitializedEntity::EK_Parameter:
7112 case InitializedEntity::EK_Parameter_CF_Audited:
7113 // -- A temporary bound to a reference parameter in a function call
7114 // persists until the completion of the full-expression containing
7115 // the call.
7116 return {nullptr, LK_FullExpression};
7117
7118 case InitializedEntity::EK_TemplateParameter:
7119 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7120 return {nullptr, LK_FullExpression};
7121
7122 case InitializedEntity::EK_Result:
7123 // -- The lifetime of a temporary bound to the returned value in a
7124 // function return statement is not extended; the temporary is
7125 // destroyed at the end of the full-expression in the return statement.
7126 return {nullptr, LK_Return};
7127
7128 case InitializedEntity::EK_StmtExprResult:
7129 // FIXME: Should we lifetime-extend through the result of a statement
7130 // expression?
7131 return {nullptr, LK_StmtExprResult};
7132
7133 case InitializedEntity::EK_New:
7134 // -- A temporary bound to a reference in a new-initializer persists
7135 // until the completion of the full-expression containing the
7136 // new-initializer.
7137 return {nullptr, LK_New};
7138
7139 case InitializedEntity::EK_Temporary:
7140 case InitializedEntity::EK_CompoundLiteralInit:
7141 case InitializedEntity::EK_RelatedResult:
7142 // We don't yet know the storage duration of the surrounding temporary.
7143 // Assume it's got full-expression duration for now, it will patch up our
7144 // storage duration if that's not correct.
7145 return {nullptr, LK_FullExpression};
7146
7147 case InitializedEntity::EK_ArrayElement:
7148 // For subobjects, we look at the complete object.
7149 return getEntityLifetime(Entity->getParent(), InitField);
7150
7151 case InitializedEntity::EK_Base:
7152 // For subobjects, we look at the complete object.
7153 if (Entity->getParent())
7154 return getEntityLifetime(Entity->getParent(), InitField);
7155 return {InitField, LK_MemInitializer};
7156
7157 case InitializedEntity::EK_Delegating:
7158 // We can reach this case for aggregate initialization in a constructor:
7159 // struct A { int &&r; };
7160 // struct B : A { B() : A{0} {} };
7161 // In this case, use the outermost field decl as the context.
7162 return {InitField, LK_MemInitializer};
7163
7164 case InitializedEntity::EK_BlockElement:
7165 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7166 case InitializedEntity::EK_LambdaCapture:
7167 case InitializedEntity::EK_VectorElement:
7168 case InitializedEntity::EK_ComplexElement:
7169 return {nullptr, LK_FullExpression};
7170
7171 case InitializedEntity::EK_Exception:
7172 // FIXME: Can we diagnose lifetime problems with exceptions?
7173 return {nullptr, LK_FullExpression};
7174
7175 case InitializedEntity::EK_ParenAggInitMember:
7176 // -- A temporary object bound to a reference element of an aggregate of
7177 // class type initialized from a parenthesized expression-list
7178 // [dcl.init, 9.3] persists until the completion of the full-expression
7179 // containing the expression-list.
7180 return {nullptr, LK_FullExpression};
7181 }
7182
7183 llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "clang/lib/Sema/SemaInit.cpp"
, 7183)
;
7184}
7185
7186namespace {
7187enum ReferenceKind {
7188 /// Lifetime would be extended by a reference binding to a temporary.
7189 RK_ReferenceBinding,
7190 /// Lifetime would be extended by a std::initializer_list object binding to
7191 /// its backing array.
7192 RK_StdInitializerList,
7193};
7194
7195/// A temporary or local variable. This will be one of:
7196/// * A MaterializeTemporaryExpr.
7197/// * A DeclRefExpr whose declaration is a local.
7198/// * An AddrLabelExpr.
7199/// * A BlockExpr for a block with captures.
7200using Local = Expr*;
7201
7202/// Expressions we stepped over when looking for the local state. Any steps
7203/// that would inhibit lifetime extension or take us out of subexpressions of
7204/// the initializer are included.
7205struct IndirectLocalPathEntry {
7206 enum EntryKind {
7207 DefaultInit,
7208 AddressOf,
7209 VarInit,
7210 LValToRVal,
7211 LifetimeBoundCall,
7212 TemporaryCopy,
7213 LambdaCaptureInit,
7214 GslReferenceInit,
7215 GslPointerInit
7216 } Kind;
7217 Expr *E;
7218 union {
7219 const Decl *D = nullptr;
7220 const LambdaCapture *Capture;
7221 };
7222 IndirectLocalPathEntry() {}
7223 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7224 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7225 : Kind(K), E(E), D(D) {}
7226 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7227 : Kind(K), E(E), Capture(Capture) {}
7228};
7229
7230using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7231
7232struct RevertToOldSizeRAII {
7233 IndirectLocalPath &Path;
7234 unsigned OldSize = Path.size();
7235 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7236 ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7237};
7238
7239using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7240 ReferenceKind RK)>;
7241}
7242
7243static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7244 for (auto E : Path)
7245 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7246 return true;
7247 return false;
7248}
7249
7250static bool pathContainsInit(IndirectLocalPath &Path) {
7251 return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7252 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7253 E.Kind == IndirectLocalPathEntry::VarInit;
7254 });
7255}
7256
7257static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7258 Expr *Init, LocalVisitor Visit,
7259 bool RevisitSubinits,
7260 bool EnableLifetimeWarnings);
7261
7262static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7263 Expr *Init, ReferenceKind RK,
7264 LocalVisitor Visit,
7265 bool EnableLifetimeWarnings);
7266
7267template <typename T> static bool isRecordWithAttr(QualType Type) {
7268 if (auto *RD = Type->getAsCXXRecordDecl())
7269 return RD->hasAttr<T>();
7270 return false;
7271}
7272
7273// Decl::isInStdNamespace will return false for iterators in some STL
7274// implementations due to them being defined in a namespace outside of the std
7275// namespace.
7276static bool isInStlNamespace(const Decl *D) {
7277 const DeclContext *DC = D->getDeclContext();
7278 if (!DC)
7279 return false;
7280 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7281 if (const IdentifierInfo *II = ND->getIdentifier()) {
7282 StringRef Name = II->getName();
7283 if (Name.size() >= 2 && Name.front() == '_' &&
7284 (Name[1] == '_' || isUppercase(Name[1])))
7285 return true;
7286 }
7287
7288 return DC->isStdNamespace();
7289}
7290
7291static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
7292 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7293 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7294 return true;
7295 if (!isInStlNamespace(Callee->getParent()))
7296 return false;
7297 if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) &&
7298 !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType()))
7299 return false;
7300 if (Callee->getReturnType()->isPointerType() ||
7301 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7302 if (!Callee->getIdentifier())
7303 return false;
7304 return llvm::StringSwitch<bool>(Callee->getName())
7305 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7306 .Cases("end", "rend", "cend", "crend", true)
7307 .Cases("c_str", "data", "get", true)
7308 // Map and set types.
7309 .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7310 .Default(false);
7311 } else if (Callee->getReturnType()->isReferenceType()) {
7312 if (!Callee->getIdentifier()) {
7313 auto OO = Callee->getOverloadedOperator();
7314 return OO == OverloadedOperatorKind::OO_Subscript ||
7315 OO == OverloadedOperatorKind::OO_Star;
7316 }
7317 return llvm::StringSwitch<bool>(Callee->getName())
7318 .Cases("front", "back", "at", "top", "value", true)
7319 .Default(false);
7320 }
7321 return false;
7322}
7323
7324static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
7325 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7326 return false;
7327 const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7328 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7329 return false;
7330 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7331 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7332 return false;
7333 if (FD->getReturnType()->isPointerType() ||
7334 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7335 return llvm::StringSwitch<bool>(FD->getName())
7336 .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7337 .Cases("end", "rend", "cend", "crend", true)
7338 .Case("data", true)
7339 .Default(false);
7340 } else if (FD->getReturnType()->isReferenceType()) {
7341 return llvm::StringSwitch<bool>(FD->getName())
7342 .Cases("get", "any_cast", true)
7343 .Default(false);
7344 }
7345 return false;
7346}
7347
7348static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7349 LocalVisitor Visit) {
7350 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7351 // We are not interested in the temporary base objects of gsl Pointers:
7352 // Temp().ptr; // Here ptr might not dangle.
7353 if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7354 return;
7355 // Once we initialized a value with a reference, it can no longer dangle.
7356 if (!Value) {
7357 for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7358 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7359 continue;
7360 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7361 return;
7362 break;
7363 }
7364 }
7365 Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7366 : IndirectLocalPathEntry::GslReferenceInit,
7367 Arg, D});
7368 if (Arg->isGLValue())
7369 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7370 Visit,
7371 /*EnableLifetimeWarnings=*/true);
7372 else
7373 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7374 /*EnableLifetimeWarnings=*/true);
7375 Path.pop_back();
7376 };
7377
7378 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7379 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7380 if (MD && shouldTrackImplicitObjectArg(MD))
7381 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7382 !MD->getReturnType()->isReferenceType());
7383 return;
7384 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7385 FunctionDecl *Callee = OCE->getDirectCallee();
7386 if (Callee && Callee->isCXXInstanceMember() &&
7387 shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7388 VisitPointerArg(Callee, OCE->getArg(0),
7389 !Callee->getReturnType()->isReferenceType());
7390 return;
7391 } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7392 FunctionDecl *Callee = CE->getDirectCallee();
7393 if (Callee && shouldTrackFirstArgument(Callee))
7394 VisitPointerArg(Callee, CE->getArg(0),
7395 !Callee->getReturnType()->isReferenceType());
7396 return;
7397 }
7398
7399 if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7400 const auto *Ctor = CCE->getConstructor();
7401 const CXXRecordDecl *RD = Ctor->getParent();
7402 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7403 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7404 }
7405}
7406
7407static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
7408 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7409 if (!TSI)
7410 return false;
7411 // Don't declare this variable in the second operand of the for-statement;
7412 // GCC miscompiles that by ending its lifetime before evaluating the
7413 // third operand. See gcc.gnu.org/PR86769.
7414 AttributedTypeLoc ATL;
7415 for (TypeLoc TL = TSI->getTypeLoc();
7416 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7417 TL = ATL.getModifiedLoc()) {
7418 if (ATL.getAttrAs<LifetimeBoundAttr>())
7419 return true;
7420 }
7421
7422 // Assume that all assignment operators with a "normal" return type return
7423 // *this, that is, an lvalue reference that is the same type as the implicit
7424 // object parameter (or the LHS for a non-member operator$=).
7425 OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
7426 if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7427 QualType RetT = FD->getReturnType();
7428 if (RetT->isLValueReferenceType()) {
7429 ASTContext &Ctx = FD->getASTContext();
7430 QualType LHST;
7431 auto *MD = dyn_cast<CXXMethodDecl>(FD);
7432 if (MD && MD->isCXXInstanceMember())
7433 LHST = Ctx.getLValueReferenceType(MD->getThisObjectType());
7434 else
7435 LHST = MD->getParamDecl(0)->getType();
7436 if (Ctx.hasSameType(RetT, LHST))
7437 return true;
7438 }
7439 }
7440
7441 return false;
7442}
7443
7444static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7445 LocalVisitor Visit) {
7446 const FunctionDecl *Callee;
7447 ArrayRef<Expr*> Args;
7448
7449 if (auto *CE = dyn_cast<CallExpr>(Call)) {
7450 Callee = CE->getDirectCallee();
7451 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7452 } else {
7453 auto *CCE = cast<CXXConstructExpr>(Call);
7454 Callee = CCE->getConstructor();
7455 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7456 }
7457 if (!Callee)
7458 return;
7459
7460 Expr *ObjectArg = nullptr;
7461 if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7462 ObjectArg = Args[0];
7463 Args = Args.slice(1);
7464 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7465 ObjectArg = MCE->getImplicitObjectArgument();
7466 }
7467
7468 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7469 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7470 if (Arg->isGLValue())
7471 visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7472 Visit,
7473 /*EnableLifetimeWarnings=*/false);
7474 else
7475 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7476 /*EnableLifetimeWarnings=*/false);
7477 Path.pop_back();
7478 };
7479
7480 if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
7481 VisitLifetimeBoundArg(Callee, ObjectArg);
7482
7483 for (unsigned I = 0,
7484 N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7485 I != N; ++I) {
7486 if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7487 VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7488 }
7489}
7490
7491/// Visit the locals that would be reachable through a reference bound to the
7492/// glvalue expression \c Init.
7493static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7494 Expr *Init, ReferenceKind RK,
7495 LocalVisitor Visit,
7496 bool EnableLifetimeWarnings) {
7497 RevertToOldSizeRAII RAII(Path);
7498
7499 // Walk past any constructs which we can lifetime-extend across.
7500 Expr *Old;
7501 do {
7502 Old = Init;
7503
7504 if (auto *FE = dyn_cast<FullExpr>(Init))
7505 Init = FE->getSubExpr();
7506
7507 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7508 // If this is just redundant braces around an initializer, step over it.
7509 if (ILE->isTransparent())
7510 Init = ILE->getInit(0);
7511 }
7512
7513 // Step over any subobject adjustments; we may have a materialized
7514 // temporary inside them.
7515 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7516
7517 // Per current approach for DR1376, look through casts to reference type
7518 // when performing lifetime extension.
7519 if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7520 if (CE->getSubExpr()->isGLValue())
7521 Init = CE->getSubExpr();
7522
7523 // Per the current approach for DR1299, look through array element access
7524 // on array glvalues when performing lifetime extension.
7525 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7526 Init = ASE->getBase();
7527 auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7528 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7529 Init = ICE->getSubExpr();
7530 else
7531 // We can't lifetime extend through this but we might still find some
7532 // retained temporaries.
7533 return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7534 EnableLifetimeWarnings);
7535 }
7536
7537 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7538 // constructor inherits one as an implicit mem-initializer.
7539 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7540 Path.push_back(
7541 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7542 Init = DIE->getExpr();
7543 }
7544 } while (Init != Old);
7545
7546 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7547 if (Visit(Path, Local(MTE), RK))
7548 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7549 EnableLifetimeWarnings);
7550 }
7551
7552 if (isa<CallExpr>(Init)) {
7553 if (EnableLifetimeWarnings)
7554 handleGslAnnotatedTypes(Path, Init, Visit);
7555 return visitLifetimeBoundArguments(Path, Init, Visit);
7556 }
7557
7558 switch (Init->getStmtClass()) {
7559 case Stmt::DeclRefExprClass: {
7560 // If we find the name of a local non-reference parameter, we could have a
7561 // lifetime problem.
7562 auto *DRE = cast<DeclRefExpr>(Init);
7563 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7564 if (VD && VD->hasLocalStorage() &&
7565 !DRE->refersToEnclosingVariableOrCapture()) {
7566 if (!VD->getType()->isReferenceType()) {
7567 Visit(Path, Local(DRE), RK);
7568 } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7569 // The lifetime of a reference parameter is unknown; assume it's OK
7570 // for now.
7571 break;
7572 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7573 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7574 visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7575 RK_ReferenceBinding, Visit,
7576 EnableLifetimeWarnings);
7577 }
7578 }
7579 break;
7580 }
7581
7582 case Stmt::UnaryOperatorClass: {
7583 // The only unary operator that make sense to handle here
7584 // is Deref. All others don't resolve to a "name." This includes
7585 // handling all sorts of rvalues passed to a unary operator.
7586 const UnaryOperator *U = cast<UnaryOperator>(Init);
7587 if (U->getOpcode() == UO_Deref)
7588 visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7589 EnableLifetimeWarnings);
7590 break;
7591 }
7592
7593 case Stmt::OMPArraySectionExprClass: {
7594 visitLocalsRetainedByInitializer(Path,
7595 cast<OMPArraySectionExpr>(Init)->getBase(),
7596 Visit, true, EnableLifetimeWarnings);
7597 break;
7598 }
7599
7600 case Stmt::ConditionalOperatorClass:
7601 case Stmt::BinaryConditionalOperatorClass: {
7602 auto *C = cast<AbstractConditionalOperator>(Init);
7603 if (!C->getTrueExpr()->getType()->isVoidType())
7604 visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7605 EnableLifetimeWarnings);
7606 if (!C->getFalseExpr()->getType()->isVoidType())
7607 visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7608 EnableLifetimeWarnings);
7609 break;
7610 }
7611
7612 // FIXME: Visit the left-hand side of an -> or ->*.
7613
7614 default:
7615 break;
7616 }
7617}
7618
7619/// Visit the locals that would be reachable through an object initialized by
7620/// the prvalue expression \c Init.
7621static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7622 Expr *Init, LocalVisitor Visit,
7623 bool RevisitSubinits,
7624 bool EnableLifetimeWarnings) {
7625 RevertToOldSizeRAII RAII(Path);
7626
7627 Expr *Old;
7628 do {
7629 Old = Init;
7630
7631 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7632 // constructor inherits one as an implicit mem-initializer.
7633 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7634 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7635 Init = DIE->getExpr();
7636 }
7637
7638 if (auto *FE = dyn_cast<FullExpr>(Init))
7639 Init = FE->getSubExpr();
7640
7641 // Dig out the expression which constructs the extended temporary.
7642 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7643
7644 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7645 Init = BTE->getSubExpr();
7646
7647 Init = Init->IgnoreParens();
7648
7649 // Step over value-preserving rvalue casts.
7650 if (auto *CE = dyn_cast<CastExpr>(Init)) {
7651 switch (CE->getCastKind()) {
7652 case CK_LValueToRValue:
7653 // If we can match the lvalue to a const object, we can look at its
7654 // initializer.
7655 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7656 return visitLocalsRetainedByReferenceBinding(
7657 Path, Init, RK_ReferenceBinding,
7658 [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7659 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7660 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7661 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7662 !isVarOnPath(Path, VD)) {
7663 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7664 visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7665 EnableLifetimeWarnings);
7666 }
7667 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7668 if (MTE->getType().isConstQualified())
7669 visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7670 true, EnableLifetimeWarnings);
7671 }
7672 return false;
7673 }, EnableLifetimeWarnings);
7674
7675 // We assume that objects can be retained by pointers cast to integers,
7676 // but not if the integer is cast to floating-point type or to _Complex.
7677 // We assume that casts to 'bool' do not preserve enough information to
7678 // retain a local object.
7679 case CK_NoOp:
7680 case CK_BitCast:
7681 case CK_BaseToDerived:
7682 case CK_DerivedToBase:
7683 case CK_UncheckedDerivedToBase:
7684 case CK_Dynamic:
7685 case CK_ToUnion:
7686 case CK_UserDefinedConversion:
7687 case CK_ConstructorConversion:
7688 case CK_IntegralToPointer:
7689 case CK_PointerToIntegral:
7690 case CK_VectorSplat:
7691 case CK_IntegralCast:
7692 case CK_CPointerToObjCPointerCast:
7693 case CK_BlockPointerToObjCPointerCast:
7694 case CK_AnyPointerToBlockPointerCast:
7695 case CK_AddressSpaceConversion:
7696 break;
7697
7698 case CK_ArrayToPointerDecay:
7699 // Model array-to-pointer decay as taking the address of the array
7700 // lvalue.
7701 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7702 return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7703 RK_ReferenceBinding, Visit,
7704 EnableLifetimeWarnings);
7705
7706 default:
7707 return;
7708 }
7709
7710 Init = CE->getSubExpr();
7711 }
7712 } while (Old != Init);
7713
7714 // C++17 [dcl.init.list]p6:
7715 // initializing an initializer_list object from the array extends the
7716 // lifetime of the array exactly like binding a reference to a temporary.
7717 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7718 return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7719 RK_StdInitializerList, Visit,
7720 EnableLifetimeWarnings);
7721
7722 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7723 // We already visited the elements of this initializer list while
7724 // performing the initialization. Don't visit them again unless we've
7725 // changed the lifetime of the initialized entity.
7726 if (!RevisitSubinits)
7727 return;
7728
7729 if (ILE->isTransparent())
7730 return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7731 RevisitSubinits,
7732 EnableLifetimeWarnings);
7733
7734 if (ILE->getType()->isArrayType()) {
7735 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7736 visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7737 RevisitSubinits,
7738 EnableLifetimeWarnings);
7739 return;
7740 }
7741
7742 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7743 assert(RD->isAggregate() && "aggregate init on non-aggregate")(static_cast <bool> (RD->isAggregate() && "aggregate init on non-aggregate"
) ? void (0) : __assert_fail ("RD->isAggregate() && \"aggregate init on non-aggregate\""
, "clang/lib/Sema/SemaInit.cpp", 7743, __extension__ __PRETTY_FUNCTION__
))
;
7744
7745 // If we lifetime-extend a braced initializer which is initializing an
7746 // aggregate, and that aggregate contains reference members which are
7747 // bound to temporaries, those temporaries are also lifetime-extended.
7748 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7749 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
7750 visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
7751 RK_ReferenceBinding, Visit,
7752 EnableLifetimeWarnings);
7753 else {
7754 unsigned Index = 0;
7755 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7756 visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7757 RevisitSubinits,
7758 EnableLifetimeWarnings);
7759 for (const auto *I : RD->fields()) {
7760 if (Index >= ILE->getNumInits())
7761 break;
7762 if (I->isUnnamedBitfield())
7763 continue;
7764 Expr *SubInit = ILE->getInit(Index);
7765 if (I->getType()->isReferenceType())
7766 visitLocalsRetainedByReferenceBinding(Path, SubInit,
7767 RK_ReferenceBinding, Visit,
7768 EnableLifetimeWarnings);
7769 else
7770 // This might be either aggregate-initialization of a member or
7771 // initialization of a std::initializer_list object. Regardless,
7772 // we should recursively lifetime-extend that initializer.
7773 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7774 RevisitSubinits,
7775 EnableLifetimeWarnings);
7776 ++Index;
7777 }
7778 }
7779 }
7780 return;
7781 }
7782
7783 // The lifetime of an init-capture is that of the closure object constructed
7784 // by a lambda-expression.
7785 if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7786 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7787 for (Expr *E : LE->capture_inits()) {
7788 assert(CapI != LE->capture_end())(static_cast <bool> (CapI != LE->capture_end()) ? void
(0) : __assert_fail ("CapI != LE->capture_end()", "clang/lib/Sema/SemaInit.cpp"
, 7788, __extension__ __PRETTY_FUNCTION__))
;
7789 const LambdaCapture &Cap = *CapI++;
7790 if (!E)
7791 continue;
7792 if (Cap.capturesVariable())
7793 Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7794 if (E->isGLValue())
7795 visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7796 Visit, EnableLifetimeWarnings);
7797 else
7798 visitLocalsRetainedByInitializer(Path, E, Visit, true,
7799 EnableLifetimeWarnings);
7800 if (Cap.capturesVariable())
7801 Path.pop_back();
7802 }
7803 }
7804
7805 // Assume that a copy or move from a temporary references the same objects
7806 // that the temporary does.
7807 if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7808 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7809 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7810 Expr *Arg = MTE->getSubExpr();
7811 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7812 CCE->getConstructor()});
7813 visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7814 /*EnableLifetimeWarnings*/false);
7815 Path.pop_back();
7816 }
7817 }
7818 }
7819
7820 if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7821 if (EnableLifetimeWarnings)
7822 handleGslAnnotatedTypes(Path, Init, Visit);
7823 return visitLifetimeBoundArguments(Path, Init, Visit);
7824 }
7825
7826 switch (Init->getStmtClass()) {
7827 case Stmt::UnaryOperatorClass: {
7828 auto *UO = cast<UnaryOperator>(Init);
7829 // If the initializer is the address of a local, we could have a lifetime
7830 // problem.
7831 if (UO->getOpcode() == UO_AddrOf) {
7832 // If this is &rvalue, then it's ill-formed and we have already diagnosed
7833 // it. Don't produce a redundant warning about the lifetime of the
7834 // temporary.
7835 if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7836 return;
7837
7838 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7839 visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7840 RK_ReferenceBinding, Visit,
7841 EnableLifetimeWarnings);
7842 }
7843 break;
7844 }
7845
7846 case Stmt::BinaryOperatorClass: {
7847 // Handle pointer arithmetic.
7848 auto *BO = cast<BinaryOperator>(Init);
7849 BinaryOperatorKind BOK = BO->getOpcode();
7850 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7851 break;
7852
7853 if (BO->getLHS()->getType()->isPointerType())
7854 visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
7855 EnableLifetimeWarnings);
7856 else if (BO->getRHS()->getType()->isPointerType())
7857 visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
7858 EnableLifetimeWarnings);
7859 break;
7860 }
7861
7862 case Stmt::ConditionalOperatorClass:
7863 case Stmt::BinaryConditionalOperatorClass: {
7864 auto *C = cast<AbstractConditionalOperator>(Init);
7865 // In C++, we can have a throw-expression operand, which has 'void' type
7866 // and isn't interesting from a lifetime perspective.
7867 if (!C->getTrueExpr()->getType()->isVoidType())
7868 visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
7869 EnableLifetimeWarnings);
7870 if (!C->getFalseExpr()->getType()->isVoidType())
7871 visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
7872 EnableLifetimeWarnings);
7873 break;
7874 }
7875
7876 case Stmt::BlockExprClass:
7877 if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7878 // This is a local block, whose lifetime is that of the function.
7879 Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7880 }
7881 break;
7882
7883 case Stmt::AddrLabelExprClass:
7884 // We want to warn if the address of a label would escape the function.
7885 Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7886 break;
7887
7888 default:
7889 break;
7890 }
7891}
7892
7893/// Whether a path to an object supports lifetime extension.
7894enum PathLifetimeKind {
7895 /// Lifetime-extend along this path.
7896 Extend,
7897 /// We should lifetime-extend, but we don't because (due to technical
7898 /// limitations) we can't. This happens for default member initializers,
7899 /// which we don't clone for every use, so we don't have a unique
7900 /// MaterializeTemporaryExpr to update.
7901 ShouldExtend,
7902 /// Do not lifetime extend along this path.
7903 NoExtend
7904};
7905
7906/// Determine whether this is an indirect path to a temporary that we are
7907/// supposed to lifetime-extend along.
7908static PathLifetimeKind
7909shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
7910 PathLifetimeKind Kind = PathLifetimeKind::Extend;
7911 for (auto Elem : Path) {
7912 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
7913 Kind = PathLifetimeKind::ShouldExtend;
7914 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
7915 return PathLifetimeKind::NoExtend;
7916 }
7917 return Kind;
7918}
7919
7920/// Find the range for the first interesting entry in the path at or after I.
7921static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
7922 Expr *E) {
7923 for (unsigned N = Path.size(); I != N; ++I) {
7924 switch (Path[I].Kind) {
7925 case IndirectLocalPathEntry::AddressOf:
7926 case IndirectLocalPathEntry::LValToRVal:
7927 case IndirectLocalPathEntry::LifetimeBoundCall:
7928 case IndirectLocalPathEntry::TemporaryCopy:
7929 case IndirectLocalPathEntry::GslReferenceInit:
7930 case IndirectLocalPathEntry::GslPointerInit:
7931 // These exist primarily to mark the path as not permitting or
7932 // supporting lifetime extension.
7933 break;
7934
7935 case IndirectLocalPathEntry::VarInit:
7936 if (cast<VarDecl>(Path[I].D)->isImplicit())
7937 return SourceRange();
7938 [[fallthrough]];
7939 case IndirectLocalPathEntry::DefaultInit:
7940 return Path[I].E->getSourceRange();
7941
7942 case IndirectLocalPathEntry::LambdaCaptureInit:
7943 if (!Path[I].Capture->capturesVariable())
7944 continue;
7945 return Path[I].E->getSourceRange();
7946 }
7947 }
7948 return E->getSourceRange();
7949}
7950
7951static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
7952 for (const auto &It : llvm::reverse(Path)) {
7953 if (It.Kind == IndirectLocalPathEntry::VarInit)
7954 continue;
7955 if (It.Kind == IndirectLocalPathEntry::AddressOf)
7956 continue;
7957 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
7958 continue;
7959 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
7960 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
7961 }
7962 return false;
7963}
7964
7965void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7966 Expr *Init) {
7967 LifetimeResult LR = getEntityLifetime(&Entity);
7968 LifetimeKind LK = LR.getInt();
7969 const InitializedEntity *ExtendingEntity = LR.getPointer();
7970
7971 // If this entity doesn't have an interesting lifetime, don't bother looking
7972 // for temporaries within its initializer.
7973 if (LK == LK_FullExpression)
7974 return;
7975
7976 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
7977 ReferenceKind RK) -> bool {
7978 SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
7979 SourceLocation DiagLoc = DiagRange.getBegin();
7980
7981 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
7982
7983 bool IsGslPtrInitWithGslTempOwner = false;
7984 bool IsLocalGslOwner = false;
7985 if (pathOnlyInitializesGslPointer(Path)) {
7986 if (isa<DeclRefExpr>(L)) {
7987 // We do not want to follow the references when returning a pointer originating
7988 // from a local owner to avoid the following false positive:
7989 // int &p = *localUniquePtr;
7990 // someContainer.add(std::move(localUniquePtr));
7991 // return p;
7992 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
7993 if (pathContainsInit(Path) || !IsLocalGslOwner)
7994 return false;
7995 } else {
7996 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
7997 isRecordWithAttr<OwnerAttr>(MTE->getType());
7998 // Skipping a chain of initializing gsl::Pointer annotated objects.
7999 // We are looking only for the final source to find out if it was
8000 // a local or temporary owner or the address of a local variable/param.
8001 if (!IsGslPtrInitWithGslTempOwner)
8002 return true;
8003 }
8004 }
8005
8006 switch (LK) {
8007 case LK_FullExpression:
8008 llvm_unreachable("already handled this")::llvm::llvm_unreachable_internal("already handled this", "clang/lib/Sema/SemaInit.cpp"
, 8008)
;
8009
8010 case LK_Extended: {
8011 if (!MTE) {
8012 // The initialized entity has lifetime beyond the full-expression,
8013 // and the local entity does too, so don't warn.
8014 //
8015 // FIXME: We should consider warning if a static / thread storage
8016 // duration variable retains an automatic storage duration local.
8017 return false;
8018 }
8019
8020 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8021 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8022 return false;
8023 }
8024
8025 switch (shouldLifetimeExtendThroughPath(Path)) {
8026 case PathLifetimeKind::Extend:
8027 // Update the storage duration of the materialized temporary.
8028 // FIXME: Rebuild the expression instead of mutating it.
8029 MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8030 ExtendingEntity->allocateManglingNumber());
8031 // Also visit the temporaries lifetime-extended by this initializer.
8032 return true;
8033
8034 case PathLifetimeKind::ShouldExtend:
8035 // We're supposed to lifetime-extend the temporary along this path (per
8036 // the resolution of DR1815), but we don't support that yet.
8037 //
8038 // FIXME: Properly handle this situation. Perhaps the easiest approach
8039 // would be to clone the initializer expression on each use that would
8040 // lifetime extend its temporaries.
8041 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8042 << RK << DiagRange;
8043 break;
8044
8045 case PathLifetimeKind::NoExtend:
8046 // If the path goes through the initialization of a variable or field,
8047 // it can't possibly reach a temporary created in this full-expression.
8048 // We will have already diagnosed any problems with the initializer.
8049 if (pathContainsInit(Path))
8050 return false;
8051
8052 Diag(DiagLoc, diag::warn_dangling_variable)
8053 << RK << !Entity.getParent()
8054 << ExtendingEntity->getDecl()->isImplicit()
8055 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8056 break;
8057 }
8058 break;
8059 }
8060
8061 case LK_MemInitializer: {
8062 if (isa<MaterializeTemporaryExpr>(L)) {
8063 // Under C++ DR1696, if a mem-initializer (or a default member
8064 // initializer used by the absence of one) would lifetime-extend a
8065 // temporary, the program is ill-formed.
8066 if (auto *ExtendingDecl =
8067 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8068 if (IsGslPtrInitWithGslTempOwner) {
8069 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8070 << ExtendingDecl << DiagRange;
8071 Diag(ExtendingDecl->getLocation(),
8072 diag::note_ref_or_ptr_member_declared_here)
8073 << true;
8074 return false;
8075 }
8076 bool IsSubobjectMember = ExtendingEntity != &Entity;
8077 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8078 PathLifetimeKind::NoExtend
8079 ? diag::err_dangling_member
8080 : diag::warn_dangling_member)
8081 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8082 // Don't bother adding a note pointing to the field if we're inside
8083 // its default member initializer; our primary diagnostic points to
8084 // the same place in that case.
8085 if (Path.empty() ||
8086 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8087 Diag(ExtendingDecl->getLocation(),
8088 diag::note_lifetime_extending_member_declared_here)
8089 << RK << IsSubobjectMember;
8090 }
8091 } else {
8092 // We have a mem-initializer but no particular field within it; this
8093 // is either a base class or a delegating initializer directly
8094 // initializing the base-class from something that doesn't live long
8095 // enough.
8096 //
8097 // FIXME: Warn on this.
8098 return false;
8099 }
8100 } else {
8101 // Paths via a default initializer can only occur during error recovery
8102 // (there's no other way that a default initializer can refer to a
8103 // local). Don't produce a bogus warning on those cases.
8104 if (pathContainsInit(Path))
8105 return false;
8106
8107 // Suppress false positives for code like the one below:
8108 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8109 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8110 return false;
8111
8112 auto *DRE = dyn_cast<DeclRefExpr>(L);
8113 auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8114 if (!VD) {
8115 // A member was initialized to a local block.
8116 // FIXME: Warn on this.
8117 return false;
8118 }
8119
8120 if (auto *Member =
8121 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8122 bool IsPointer = !Member->getType()->isReferenceType();
8123 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8124 : diag::warn_bind_ref_member_to_parameter)
8125 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8126 Diag(Member->getLocation(),
8127 diag::note_ref_or_ptr_member_declared_here)
8128 << (unsigned)IsPointer;
8129 }
8130 }
8131 break;
8132 }
8133
8134 case LK_New:
8135 if (isa<MaterializeTemporaryExpr>(L)) {
8136 if (IsGslPtrInitWithGslTempOwner)
8137 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8138 else
8139 Diag(DiagLoc, RK == RK_ReferenceBinding
8140 ? diag::warn_new_dangling_reference
8141 : diag::warn_new_dangling_initializer_list)
8142 << !Entity.getParent() << DiagRange;
8143 } else {
8144 // We can't determine if the allocation outlives the local declaration.
8145 return false;
8146 }
8147 break;
8148
8149 case LK_Return:
8150 case LK_StmtExprResult:
8151 if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8152 // We can't determine if the local variable outlives the statement
8153 // expression.
8154 if (LK == LK_StmtExprResult)
8155 return false;
8156 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8157 << Entity.getType()->isReferenceType() << DRE->getDecl()
8158 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8159 } else if (isa<BlockExpr>(L)) {
8160 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8161 } else if (isa<AddrLabelExpr>(L)) {
8162 // Don't warn when returning a label from a statement expression.
8163 // Leaving the scope doesn't end its lifetime.
8164 if (LK == LK_StmtExprResult)
8165 return false;
8166 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8167 } else {
8168 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8169 << Entity.getType()->isReferenceType() << DiagRange;
8170 }
8171 break;
8172 }
8173
8174 for (unsigned I = 0; I != Path.size(); ++I) {
8175 auto Elem = Path[I];
8176
8177 switch (Elem.Kind) {
8178 case IndirectLocalPathEntry::AddressOf:
8179 case IndirectLocalPathEntry::LValToRVal:
8180 // These exist primarily to mark the path as not permitting or
8181 // supporting lifetime extension.
8182 break;
8183
8184 case IndirectLocalPathEntry::LifetimeBoundCall:
8185 case IndirectLocalPathEntry::TemporaryCopy:
8186 case IndirectLocalPathEntry::GslPointerInit:
8187 case IndirectLocalPathEntry::GslReferenceInit:
8188 // FIXME: Consider adding a note for these.
8189 break;
8190
8191 case IndirectLocalPathEntry::DefaultInit: {
8192 auto *FD = cast<FieldDecl>(Elem.D);
8193 Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer)
8194 << FD << nextPathEntryRange(Path, I + 1, L);
8195 break;
8196 }
8197
8198 case IndirectLocalPathEntry::VarInit: {
8199 const VarDecl *VD = cast<VarDecl>(Elem.D);
8200 Diag(VD->getLocation(), diag::note_local_var_initializer)
8201 << VD->getType()->isReferenceType()
8202 << VD->isImplicit() << VD->getDeclName()
8203 << nextPathEntryRange(Path, I + 1, L);
8204 break;
8205 }
8206
8207 case IndirectLocalPathEntry::LambdaCaptureInit:
8208 if (!Elem.Capture->capturesVariable())
8209 break;
8210 // FIXME: We can't easily tell apart an init-capture from a nested
8211 // capture of an init-capture.
8212 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8213 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8214 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8215 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8216 << nextPathEntryRange(Path, I + 1, L);
8217 break;
8218 }
8219 }
8220
8221 // We didn't lifetime-extend, so don't go any further; we don't need more
8222 // warnings or errors on inner temporaries within this one's initializer.
8223 return false;
8224 };
8225
8226 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8227 diag::warn_dangling_lifetime_pointer, SourceLocation());
8228 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
8229 if (Init->isGLValue())
8230 visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8231 TemporaryVisitor,
8232 EnableLifetimeWarnings);
8233 else
8234 visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8235 EnableLifetimeWarnings);
8236}
8237
8238static void DiagnoseNarrowingInInitList(Sema &S,
8239 const ImplicitConversionSequence &ICS,
8240 QualType PreNarrowingType,
8241 QualType EntityType,
8242 const Expr *PostInit);
8243
8244/// Provide warnings when std::move is used on construction.
8245static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8246 bool IsReturnStmt) {
8247 if (!InitExpr)
8248 return;
8249
8250 if (S.inTemplateInstantiation())
8251 return;
8252
8253 QualType DestType = InitExpr->getType();
8254 if (!DestType->isRecordType())
8255 return;
8256
8257 unsigned DiagID = 0;
8258 if (IsReturnStmt) {
8259 const CXXConstructExpr *CCE =
8260 dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8261 if (!CCE || CCE->getNumArgs() != 1)
8262 return;
8263
8264 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
8265 return;
8266
8267 InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8268 }
8269
8270 // Find the std::move call and get the argument.
8271 const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8272 if (!CE || !CE->isCallToStdMove())
8273 return;
8274
8275 const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8276
8277 if (IsReturnStmt) {
8278 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8279 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8280 return;
8281
8282 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8283 if (!VD || !VD->hasLocalStorage())
8284 return;
8285
8286 // __block variables are not moved implicitly.
8287 if (VD->hasAttr<BlocksAttr>())
8288 return;
8289
8290 QualType SourceType = VD->getType();
8291 if (!SourceType->isRecordType())
8292 return;
8293
8294 if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8295 return;
8296 }
8297
8298 // If we're returning a function parameter, copy elision
8299 // is not possible.
8300 if (isa<ParmVarDecl>(VD))
8301 DiagID = diag::warn_redundant_move_on_return;
8302 else
8303 DiagID = diag::warn_pessimizing_move_on_return;
8304 } else {
8305 DiagID = diag::warn_pessimizing_move_on_initialization;
8306 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8307 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8308 return;
8309 }
8310
8311 S.Diag(CE->getBeginLoc(), DiagID);
8312
8313 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8314 // is within a macro.
8315 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8316 if (CallBegin.isMacroID())
8317 return;
8318 SourceLocation RParen = CE->getRParenLoc();
8319 if (RParen.isMacroID())
8320 return;
8321 SourceLocation LParen;
8322 SourceLocation ArgLoc = Arg->getBeginLoc();
8323
8324 // Special testing for the argument location. Since the fix-it needs the
8325 // location right before the argument, the argument location can be in a
8326 // macro only if it is at the beginning of the macro.
8327 while (ArgLoc.isMacroID() &&
8328 S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
8329 ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
8330 }
8331
8332 if (LParen.isMacroID())
8333 return;
8334
8335 LParen = ArgLoc.getLocWithOffset(-1);
8336
8337 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8338 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8339 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8340}
8341
8342static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8343 // Check to see if we are dereferencing a null pointer. If so, this is
8344 // undefined behavior, so warn about it. This only handles the pattern
8345 // "*null", which is a very syntactic check.
8346 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8347 if (UO->getOpcode() == UO_Deref &&
8348 UO->getSubExpr()->IgnoreParenCasts()->
8349 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8350 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8351 S.PDiag(diag::warn_binding_null_to_reference)
8352 << UO->getSubExpr()->getSourceRange());
8353 }
8354}
8355
8356MaterializeTemporaryExpr *
8357Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
8358 bool BoundToLvalueReference) {
8359 auto MTE = new (Context)
8360 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8361
8362 // Order an ExprWithCleanups for lifetime marks.
8363 //
8364 // TODO: It'll be good to have a single place to check the access of the
8365 // destructor and generate ExprWithCleanups for various uses. Currently these
8366 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8367 // but there may be a chance to merge them.
8368 Cleanup.setExprNeedsCleanups(false);
8369 return MTE;
8370}
8371
8372ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
8373 // In C++98, we don't want to implicitly create an xvalue.
8374 // FIXME: This means that AST consumers need to deal with "prvalues" that
8375 // denote materialized temporaries. Maybe we should add another ValueKind
8376 // for "xvalue pretending to be a prvalue" for C++98 support.
8377 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8378 return E;
8379
8380 // C++1z [conv.rval]/1: T shall be a complete type.
8381 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8382 // If so, we should check for a non-abstract class type here too.
8383 QualType T = E->getType();
8384 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8385 return ExprError();
8386
8387 return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8388}
8389
8390ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
8391 ExprValueKind VK,
8392 CheckedConversionKind CCK) {
8393
8394 CastKind CK = CK_NoOp;
8395
8396 if (VK == VK_PRValue) {
8397 auto PointeeTy = Ty->getPointeeType();
8398 auto ExprPointeeTy = E->getType()->getPointeeType();
8399 if (!PointeeTy.isNull() &&
8400 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8401 CK = CK_AddressSpaceConversion;
8402 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8403 CK = CK_AddressSpaceConversion;
8404 }
8405
8406 return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8407}
8408
8409ExprResult InitializationSequence::Perform(Sema &S,
8410 const InitializedEntity &Entity,
8411 const InitializationKind &Kind,
8412 MultiExprArg Args,
8413 QualType *ResultType) {
8414 if (Failed()) {
8415 Diagnose(S, Entity, Kind, Args);
8416 return ExprError();
8417 }
8418 if (!ZeroInitializationFixit.empty()) {
8419 const Decl *D = Entity.getDecl();
8420 const auto *VD = dyn_cast_or_null<VarDecl>(D);
8421 QualType DestType = Entity.getType();
8422
8423 // The initialization would have succeeded with this fixit. Since the fixit
8424 // is on the error, we need to build a valid AST in this case, so this isn't
8425 // handled in the Failed() branch above.
8426 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8427 // Use a more useful diagnostic for constexpr variables.
8428 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8429 << VD
8430 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8431 ZeroInitializationFixit);
8432 } else {
8433 unsigned DiagID = diag::err_default_init_const;
8434 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8435 DiagID = diag::ext_default_init_const;
8436
8437 S.Diag(Kind.getLocation(), DiagID)
8438 << DestType << (bool)DestType->getAs<RecordType>()
8439 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8440 ZeroInitializationFixit);
8441 }
8442 }
8443
8444 if (getKind() == DependentSequence) {
8445 // If the declaration is a non-dependent, incomplete array type
8446 // that has an initializer, then its type will be completed once
8447 // the initializer is instantiated.
8448 if (ResultType && !Entity.getType()->isDependentType() &&
8449 Args.size() == 1) {
8450 QualType DeclType = Entity.getType();
8451 if (const IncompleteArrayType *ArrayT
8452 = S.Context.getAsIncompleteArrayType(DeclType)) {
8453 // FIXME: We don't currently have the ability to accurately
8454 // compute the length of an initializer list without
8455 // performing full type-checking of the initializer list
8456 // (since we have to determine where braces are implicitly
8457 // introduced and such). So, we fall back to making the array
8458 // type a dependently-sized array type with no specified
8459 // bound.
8460 if (isa<InitListExpr>((Expr *)Args[0])) {
8461 SourceRange Brackets;
8462
8463 // Scavange the location of the brackets from the entity, if we can.
8464 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8465 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8466 TypeLoc TL = TInfo->getTypeLoc();
8467 if (IncompleteArrayTypeLoc ArrayLoc =
8468 TL.getAs<IncompleteArrayTypeLoc>())
8469 Brackets = ArrayLoc.getBracketsRange();
8470 }
8471 }
8472
8473 *ResultType
8474 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8475 /*NumElts=*/nullptr,
8476 ArrayT->getSizeModifier(),
8477 ArrayT->getIndexTypeCVRQualifiers(),
8478 Brackets);
8479 }
8480
8481 }
8482 }
8483 if (Kind.getKind() == InitializationKind::IK_Direct &&
8484 !Kind.isExplicitCast()) {
8485 // Rebuild the ParenListExpr.
8486 SourceRange ParenRange = Kind.getParenOrBraceRange();
8487 return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8488 Args);
8489 }
8490 assert(Kind.getKind() == InitializationKind::IK_Copy ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "clang/lib/Sema/SemaInit.cpp", 8492, __extension__ __PRETTY_FUNCTION__
))
8491 Kind.isExplicitCast() ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "clang/lib/Sema/SemaInit.cpp", 8492, __extension__ __PRETTY_FUNCTION__
))
8492 Kind.getKind() == InitializationKind::IK_DirectList)(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind
::IK_DirectList) ? void (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList"
, "clang/lib/Sema/SemaInit.cpp", 8492, __extension__ __PRETTY_FUNCTION__
))
;
8493 return ExprResult(Args[0]);
8494 }
8495
8496 // No steps means no initialization.
8497 if (Steps.empty())
8498 return ExprResult((Expr *)nullptr);
8499
8500 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8501 Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8502 !Entity.isParamOrTemplateParamKind()) {
8503 // Produce a C++98 compatibility warning if we are initializing a reference
8504 // from an initializer list. For parameters, we produce a better warning
8505 // elsewhere.
8506 Expr *Init = Args[0];
8507 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8508 << Init->getSourceRange();
8509 }
8510
8511 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8512 QualType ETy = Entity.getType();
8513 bool HasGlobalAS = ETy.hasAddressSpace() &&
8514 ETy.getAddressSpace() == LangAS::opencl_global;
8515
8516 if (S.getLangOpts().OpenCLVersion >= 200 &&
8517 ETy->isAtomicType() && !HasGlobalAS &&
8518 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8519 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8520 << 1
8521 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8522 return ExprError();
8523 }
8524
8525 QualType DestType = Entity.getType().getNonReferenceType();
8526 // FIXME: Ugly hack around the fact that Entity.getType() is not
8527 // the same as Entity.getDecl()->getType() in cases involving type merging,
8528 // and we want latter when it makes sense.
8529 if (ResultType)
8530 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8531 Entity.getType();
8532
8533 ExprResult CurInit((Expr *)nullptr);
8534 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8535
8536 // HLSL allows vector initialization to function like list initialization, but
8537 // use the syntax of a C++-like constructor.
8538 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8539 isa<InitListExpr>(Args[0]);
8540 (void)IsHLSLVectorInit;
8541
8542 // For initialization steps that start with a single initializer,
8543 // grab the only argument out the Args and place it into the "current"
8544 // initializer.
8545 switch (Steps.front().Kind) {
8546 case SK_ResolveAddressOfOverloadedFunction:
8547 case SK_CastDerivedToBasePRValue:
8548 case SK_CastDerivedToBaseXValue:
8549 case SK_CastDerivedToBaseLValue:
8550 case SK_BindReference:
8551 case SK_BindReferenceToTemporary:
8552 case SK_FinalCopy:
8553 case SK_ExtraneousCopyToTemporary:
8554 case SK_UserConversion:
8555 case SK_QualificationConversionLValue:
8556 case SK_QualificationConversionXValue:
8557 case SK_QualificationConversionPRValue:
8558 case SK_FunctionReferenceConversion:
8559 case SK_AtomicConversion:
8560 case SK_ConversionSequence:
8561 case SK_ConversionSequenceNoNarrowing:
8562 case SK_ListInitialization:
8563 case SK_UnwrapInitList:
8564 case SK_RewrapInitList:
8565 case SK_CAssignment:
8566 case SK_StringInit:
8567 case SK_ObjCObjectConversion:
8568 case SK_ArrayLoopIndex:
8569 case SK_ArrayLoopInit:
8570 case SK_ArrayInit:
8571 case SK_GNUArrayInit:
8572 case SK_ParenthesizedArrayInit:
8573 case SK_PassByIndirectCopyRestore:
8574 case SK_PassByIndirectRestore:
8575 case SK_ProduceObjCObject:
8576 case SK_StdInitializerList:
8577 case SK_OCLSamplerInit:
8578 case SK_OCLZeroOpaqueType: {
8579 assert(Args.size() == 1 || IsHLSLVectorInit)(static_cast <bool> (Args.size() == 1 || IsHLSLVectorInit
) ? void (0) : __assert_fail ("Args.size() == 1 || IsHLSLVectorInit"
, "clang/lib/Sema/SemaInit.cpp", 8579, __extension__ __PRETTY_FUNCTION__
))
;
8580 CurInit = Args[0];
8581 if (!CurInit.get()) return ExprError();
8582 break;
8583 }
8584
8585 case SK_ConstructorInitialization:
8586 case SK_ConstructorInitializationFromList:
8587 case SK_StdInitializerListConstructorCall:
8588 case SK_ZeroInitialization:
8589 case SK_ParenthesizedListInit:
8590 break;
8591 }
8592
8593 // Promote from an unevaluated context to an unevaluated list context in
8594 // C++11 list-initialization; we need to instantiate entities usable in
8595 // constant expressions here in order to perform narrowing checks =(
8596 EnterExpressionEvaluationContext Evaluated(
8597 S, EnterExpressionEvaluationContext::InitList,
8598 CurInit.get() && isa<InitListExpr>(CurInit.get()));
8599
8600 // C++ [class.abstract]p2:
8601 // no objects of an abstract class can be created except as subobjects
8602 // of a class derived from it
8603 auto checkAbstractType = [&](QualType T) -> bool {
8604 if (Entity.getKind() == InitializedEntity::EK_Base ||
8605 Entity.getKind() == InitializedEntity::EK_Delegating)
8606 return false;
8607 return S.RequireNonAbstractType(Kind.getLocation(), T,
8608 diag::err_allocation_of_abstract_type);
8609 };
8610
8611 // Walk through the computed steps for the initialization sequence,
8612 // performing the specified conversions along the way.
8613 bool ConstructorInitRequiresZeroInit = false;
8614 for (step_iterator Step = step_begin(), StepEnd = step_end();
8615 Step != StepEnd; ++Step) {
8616 if (CurInit.isInvalid())
8617 return ExprError();
8618
8619 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8620
8621 switch (Step->Kind) {
8622 case SK_ResolveAddressOfOverloadedFunction:
8623 // Overload resolution determined which function invoke; update the
8624 // initializer to reflect that choice.
8625 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
8626 if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8627 return ExprError();
8628 CurInit = S.FixOverloadedFunctionReference(CurInit,
8629 Step->Function.FoundDecl,
8630 Step->Function.Function);
8631 // We might get back another placeholder expression if we resolved to a
8632 // builtin.
8633 if (!CurInit.isInvalid())
8634 CurInit = S.CheckPlaceholderExpr(CurInit.get());
8635 break;
8636
8637 case SK_CastDerivedToBasePRValue:
8638 case SK_CastDerivedToBaseXValue:
8639 case SK_CastDerivedToBaseLValue: {
8640 // We have a derived-to-base cast that produces either an rvalue or an
8641 // lvalue. Perform that cast.
8642
8643 CXXCastPath BasePath;
8644
8645 // Casts to inaccessible base classes are allowed with C-style casts.
8646 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8647 if (S.CheckDerivedToBaseConversion(
8648 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8649 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8650 return ExprError();
8651
8652 ExprValueKind VK =
8653 Step->Kind == SK_CastDerivedToBaseLValue
8654 ? VK_LValue
8655 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8656 : VK_PRValue);
8657 CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8658 CK_DerivedToBase, CurInit.get(),
8659 &BasePath, VK, FPOptionsOverride());
8660 break;
8661 }
8662
8663 case SK_BindReference:
8664 // Reference binding does not have any corresponding ASTs.
8665
8666 // Check exception specifications
8667 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8668 return ExprError();
8669
8670 // We don't check for e.g. function pointers here, since address
8671 // availability checks should only occur when the function first decays
8672 // into a pointer or reference.
8673 if (CurInit.get()->getType()->isFunctionProtoType()) {
8674 if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8675 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8676 if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8677 DRE->getBeginLoc()))
8678 return ExprError();
8679 }
8680 }
8681 }
8682
8683 CheckForNullPointerDereference(S, CurInit.get());
8684 break;
8685
8686 case SK_BindReferenceToTemporary: {
8687 // Make sure the "temporary" is actually an rvalue.
8688 assert(CurInit.get()->isPRValue() && "not a temporary")(static_cast <bool> (CurInit.get()->isPRValue() &&
"not a temporary") ? void (0) : __assert_fail ("CurInit.get()->isPRValue() && \"not a temporary\""
, "clang/lib/Sema/SemaInit.cpp", 8688, __extension__ __PRETTY_FUNCTION__
))
;
8689
8690 // Check exception specifications
8691 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8692 return ExprError();
8693
8694 QualType MTETy = Step->Type;
8695
8696 // When this is an incomplete array type (such as when this is
8697 // initializing an array of unknown bounds from an init list), use THAT
8698 // type instead so that we propagate the array bounds.
8699 if (MTETy->isIncompleteArrayType() &&
8700 !CurInit.get()->getType()->isIncompleteArrayType() &&
8701 S.Context.hasSameType(
8702 MTETy->getPointeeOrArrayElementType(),
8703 CurInit.get()->getType()->getPointeeOrArrayElementType()))
8704 MTETy = CurInit.get()->getType();
8705
8706 // Materialize the temporary into memory.
8707 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8708 MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8709 CurInit = MTE;
8710
8711 // If we're extending this temporary to automatic storage duration -- we
8712 // need to register its cleanup during the full-expression's cleanups.
8713 if (MTE->getStorageDuration() == SD_Automatic &&
8714 MTE->getType().isDestructedType())
8715 S.Cleanup.setExprNeedsCleanups(true);
8716 break;
8717 }
8718
8719 case SK_FinalCopy:
8720 if (checkAbstractType(Step->Type))
8721 return ExprError();
8722
8723 // If the overall initialization is initializing a temporary, we already
8724 // bound our argument if it was necessary to do so. If not (if we're
8725 // ultimately initializing a non-temporary), our argument needs to be
8726 // bound since it's initializing a function parameter.
8727 // FIXME: This is a mess. Rationalize temporary destruction.
8728 if (!shouldBindAsTemporary(Entity))
8729 CurInit = S.MaybeBindToTemporary(CurInit.get());
8730 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8731 /*IsExtraneousCopy=*/false);
8732 break;
8733
8734 case SK_ExtraneousCopyToTemporary:
8735 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8736 /*IsExtraneousCopy=*/true);
8737 break;
8738
8739 case SK_UserConversion: {
8740 // We have a user-defined conversion that invokes either a constructor
8741 // or a conversion function.
8742 CastKind CastKind;
8743 FunctionDecl *Fn = Step->Function.Function;
8744 DeclAccessPair FoundFn = Step->Function.FoundDecl;
8745 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8746 bool CreatedObject = false;
8747 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8748 // Build a call to the selected constructor.
8749 SmallVector<Expr*, 8> ConstructorArgs;
8750 SourceLocation Loc = CurInit.get()->getBeginLoc();
8751
8752 // Determine the arguments required to actually perform the constructor
8753 // call.
8754 Expr *Arg = CurInit.get();
8755 if (S.CompleteConstructorCall(Constructor, Step->Type,
8756 MultiExprArg(&Arg, 1), Loc,
8757 ConstructorArgs))
8758 return ExprError();
8759
8760 // Build an expression that constructs a temporary.
8761 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type,
8762 FoundFn, Constructor,
8763 ConstructorArgs,
8764 HadMultipleCandidates,
8765 /*ListInit*/ false,
8766 /*StdInitListInit*/ false,
8767 /*ZeroInit*/ false,
8768 CXXConstructExpr::CK_Complete,
8769 SourceRange());
8770 if (CurInit.isInvalid())
8771 return ExprError();
8772
8773 S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8774 Entity);
8775 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8776 return ExprError();
8777
8778 CastKind = CK_ConstructorConversion;
8779 CreatedObject = true;
8780 } else {
8781 // Build a call to the conversion function.
8782 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8783 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8784 FoundFn);
8785 if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8786 return ExprError();
8787
8788 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8789 HadMultipleCandidates);
8790 if (CurInit.isInvalid())
8791 return ExprError();
8792
8793 CastKind = CK_UserDefinedConversion;
8794 CreatedObject = Conversion->getReturnType()->isRecordType();
8795 }
8796
8797 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8798 return ExprError();
8799
8800 CurInit = ImplicitCastExpr::Create(
8801 S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8802 CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8803
8804 if (shouldBindAsTemporary(Entity))
8805 // The overall entity is temporary, so this expression should be
8806 // destroyed at the end of its full-expression.
8807 CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8808 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8809 // The object outlasts the full-expression, but we need to prepare for
8810 // a destructor being run on it.
8811 // FIXME: It makes no sense to do this here. This should happen
8812 // regardless of how we initialized the entity.
8813 QualType T = CurInit.get()->getType();
8814 if (const RecordType *Record = T->getAs<RecordType>()) {
8815 CXXDestructorDecl *Destructor
8816 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8817 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8818 S.PDiag(diag::err_access_dtor_temp) << T);
8819 S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8820 if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8821 return ExprError();
8822 }
8823 }
8824 break;
8825 }
8826
8827 case SK_QualificationConversionLValue:
8828 case SK_QualificationConversionXValue:
8829 case SK_QualificationConversionPRValue: {
8830 // Perform a qualification conversion; these can never go wrong.
8831 ExprValueKind VK =
8832 Step->Kind == SK_QualificationConversionLValue
8833 ? VK_LValue
8834 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8835 : VK_PRValue);
8836 CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8837 break;
8838 }
8839
8840 case SK_FunctionReferenceConversion:
8841 assert(CurInit.get()->isLValue() &&(static_cast <bool> (CurInit.get()->isLValue() &&
"function reference should be lvalue") ? void (0) : __assert_fail
("CurInit.get()->isLValue() && \"function reference should be lvalue\""
, "clang/lib/Sema/SemaInit.cpp", 8842, __extension__ __PRETTY_FUNCTION__
))
8842 "function reference should be lvalue")(static_cast <bool> (CurInit.get()->isLValue() &&
"function reference should be lvalue") ? void (0) : __assert_fail
("CurInit.get()->isLValue() && \"function reference should be lvalue\""
, "clang/lib/Sema/SemaInit.cpp", 8842, __extension__ __PRETTY_FUNCTION__
))
;
8843 CurInit =
8844 S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8845 break;
8846
8847 case SK_AtomicConversion: {
8848 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic")(static_cast <bool> (CurInit.get()->isPRValue() &&
"cannot convert glvalue to atomic") ? void (0) : __assert_fail
("CurInit.get()->isPRValue() && \"cannot convert glvalue to atomic\""
, "clang/lib/Sema/SemaInit.cpp", 8848, __extension__ __PRETTY_FUNCTION__
))
;
8849 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8850 CK_NonAtomicToAtomic, VK_PRValue);
8851 break;
8852 }
8853
8854 case SK_ConversionSequence:
8855 case SK_ConversionSequenceNoNarrowing: {
8856 if (const auto *FromPtrType =
8857 CurInit.get()->getType()->getAs<PointerType>()) {
8858 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8859 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8860 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8861 // Do not check static casts here because they are checked earlier
8862 // in Sema::ActOnCXXNamedCast()
8863 if (!Kind.isStaticCast()) {
8864 S.Diag(CurInit.get()->getExprLoc(),
8865 diag::warn_noderef_to_dereferenceable_pointer)
8866 << CurInit.get()->getSourceRange();
8867 }
8868 }
8869 }
8870 }
8871
8872 Sema::CheckedConversionKind CCK
8873 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
8874 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
8875 : Kind.isExplicitCast()? Sema::CCK_OtherCast
8876 : Sema::CCK_ImplicitConversion;
8877 ExprResult CurInitExprRes =
8878 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
8879 getAssignmentAction(Entity), CCK);
8880 if (CurInitExprRes.isInvalid())
8881 return ExprError();
8882
8883 S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
8884
8885 CurInit = CurInitExprRes;
8886
8887 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
8888 S.getLangOpts().CPlusPlus)
8889 DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
8890 CurInit.get());
8891
8892 break;
8893 }
8894
8895 case SK_ListInitialization: {
8896 if (checkAbstractType(Step->Type))
8897 return ExprError();
8898
8899 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
8900 // If we're not initializing the top-level entity, we need to create an
8901 // InitializeTemporary entity for our target type.
8902 QualType Ty = Step->Type;
8903 bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
8904 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
8905 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
8906 InitListChecker PerformInitList(S, InitEntity,
8907 InitList, Ty, /*VerifyOnly=*/false,
8908 /*TreatUnavailableAsInvalid=*/false);
8909 if (PerformInitList.HadError())
8910 return ExprError();
8911
8912 // Hack: We must update *ResultType if available in order to set the
8913 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8914 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8915 if (ResultType &&
8916 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8917 if ((*ResultType)->isRValueReferenceType())
8918 Ty = S.Context.getRValueReferenceType(Ty);
8919 else if ((*ResultType)->isLValueReferenceType())
8920 Ty = S.Context.getLValueReferenceType(Ty,
8921 (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8922 *ResultType = Ty;
8923 }
8924
8925 InitListExpr *StructuredInitList =
8926 PerformInitList.getFullyStructuredList();
8927 CurInit.get();
8928 CurInit = shouldBindAsTemporary(InitEntity)
8929 ? S.MaybeBindToTemporary(StructuredInitList)
8930 : StructuredInitList;
8931 break;
8932 }
8933
8934 case SK_ConstructorInitializationFromList: {
8935 if (checkAbstractType(Step->Type))
8936 return ExprError();
8937
8938 // When an initializer list is passed for a parameter of type "reference
8939 // to object", we don't get an EK_Temporary entity, but instead an
8940 // EK_Parameter entity with reference type.
8941 // FIXME: This is a hack. What we really should do is create a user
8942 // conversion step for this case, but this makes it considerably more
8943 // complicated. For now, this will do.
8944 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8945 Entity.getType().getNonReferenceType());
8946 bool UseTemporary = Entity.getType()->isReferenceType();
8947 assert(Args.size() == 1 && "expected a single argument for list init")(static_cast <bool> (Args.size() == 1 && "expected a single argument for list init"
) ? void (0) : __assert_fail ("Args.size() == 1 && \"expected a single argument for list init\""
, "clang/lib/Sema/SemaInit.cpp", 8947, __extension__ __PRETTY_FUNCTION__
))
;
8948 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
8949 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
8950 << InitList->getSourceRange();
8951 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8952 CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
8953 Entity,
8954 Kind, Arg, *Step,
8955 ConstructorInitRequiresZeroInit,
8956 /*IsListInitialization*/true,
8957 /*IsStdInitListInit*/false,
8958 InitList->getLBraceLoc(),
8959 InitList->getRBraceLoc());
8960 break;
8961 }
8962
8963 case SK_UnwrapInitList:
8964 CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
8965 break;
8966
8967 case SK_RewrapInitList: {
8968 Expr *E = CurInit.get();
8969 InitListExpr *Syntactic = Step->WrappingSyntacticList;
8970 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
8971 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
8972 ILE->setSyntacticForm(Syntactic);
8973 ILE->setType(E->getType());
8974 ILE->setValueKind(E->getValueKind());
8975 CurInit = ILE;
8976 break;
8977 }
8978
8979 case SK_ConstructorInitialization:
8980 case SK_StdInitializerListConstructorCall: {
8981 if (checkAbstractType(Step->Type))
8982 return ExprError();
8983
8984 // When an initializer list is passed for a parameter of type "reference
8985 // to object", we don't get an EK_Temporary entity, but instead an
8986 // EK_Parameter entity with reference type.
8987 // FIXME: This is a hack. What we really should do is create a user
8988 // conversion step for this case, but this makes it considerably more
8989 // complicated. For now, this will do.
8990 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8991 Entity.getType().getNonReferenceType());
8992 bool UseTemporary = Entity.getType()->isReferenceType();
8993 bool IsStdInitListInit =
8994 Step->Kind == SK_StdInitializerListConstructorCall;
8995 Expr *Source = CurInit.get();
8996 SourceRange Range = Kind.hasParenOrBraceRange()
8997 ? Kind.getParenOrBraceRange()
8998 : SourceRange();
8999 CurInit = PerformConstructorInitialization(
9000 S, UseTemporary ? TempEntity : Entity, Kind,
9001 Source ? MultiExprArg(Source) : Args, *Step,
9002 ConstructorInitRequiresZeroInit,
9003 /*IsListInitialization*/ IsStdInitListInit,
9004 /*IsStdInitListInitialization*/ IsStdInitListInit,
9005 /*LBraceLoc*/ Range.getBegin(),
9006 /*RBraceLoc*/ Range.getEnd());
9007 break;
9008 }
9009
9010 case SK_ZeroInitialization: {
9011 step_iterator NextStep = Step;
9012 ++NextStep;
9013 if (NextStep != StepEnd &&
9014 (NextStep->Kind == SK_ConstructorInitialization ||
9015 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9016 // The need for zero-initialization is recorded directly into
9017 // the call to the object's constructor within the next step.
9018 ConstructorInitRequiresZeroInit = true;
9019 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9020 S.getLangOpts().CPlusPlus &&
9021 !Kind.isImplicitValueInit()) {
9022 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9023 if (!TSInfo)
9024 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
9025 Kind.getRange().getBegin());
9026
9027 CurInit = new (S.Context) CXXScalarValueInitExpr(
9028 Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9029 Kind.getRange().getEnd());
9030 } else {
9031 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9032 }
9033 break;
9034 }
9035
9036 case SK_CAssignment: {
9037 QualType SourceType = CurInit.get()->getType();
9038
9039 // Save off the initial CurInit in case we need to emit a diagnostic
9040 ExprResult InitialCurInit = CurInit;
9041 ExprResult Result = CurInit;
9042 Sema::AssignConvertType ConvTy =
9043 S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
9044 Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
9045 if (Result.isInvalid())
9046 return ExprError();
9047 CurInit = Result;
9048
9049 // If this is a call, allow conversion to a transparent union.
9050 ExprResult CurInitExprRes = CurInit;
9051 if (ConvTy != Sema::Compatible &&
9052 Entity.isParameterKind() &&
9053 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
9054 == Sema::Compatible)
9055 ConvTy = Sema::Compatible;
9056 if (CurInitExprRes.isInvalid())
9057 return ExprError();
9058 CurInit = CurInitExprRes;
9059
9060 bool Complained;
9061 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9062 Step->Type, SourceType,
9063 InitialCurInit.get(),
9064 getAssignmentAction(Entity, true),
9065 &Complained)) {
9066 PrintInitLocationNote(S, Entity);
9067 return ExprError();
9068 } else if (Complained)
9069 PrintInitLocationNote(S, Entity);
9070 break;
9071 }
9072
9073 case SK_StringInit: {
9074 QualType Ty = Step->Type;
9075 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9076 CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9077 S.Context.getAsArrayType(Ty), S);
9078 break;
9079 }
9080
9081 case SK_ObjCObjectConversion:
9082 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9083 CK_ObjCObjectLValueCast,
9084 CurInit.get()->getValueKind());
9085 break;
9086
9087 case SK_ArrayLoopIndex: {
9088 Expr *Cur = CurInit.get();
9089 Expr *BaseExpr = new (S.Context)
9090 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9091 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9092 Expr *IndexExpr =
9093 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
9094 CurInit = S.CreateBuiltinArraySubscriptExpr(
9095 BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9096 ArrayLoopCommonExprs.push_back(BaseExpr);
9097 break;
9098 }
9099
9100 case SK_ArrayLoopInit: {
9101 assert(!ArrayLoopCommonExprs.empty() &&(static_cast <bool> (!ArrayLoopCommonExprs.empty() &&
"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void (
0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\""
, "clang/lib/Sema/SemaInit.cpp", 9102, __extension__ __PRETTY_FUNCTION__
))
9102 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit")(static_cast <bool> (!ArrayLoopCommonExprs.empty() &&
"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit") ? void (
0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\""
, "clang/lib/Sema/SemaInit.cpp", 9102, __extension__ __PRETTY_FUNCTION__
))
;
9103 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9104 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9105 CurInit.get());
9106 break;
9107 }
9108
9109 case SK_GNUArrayInit:
9110 // Okay: we checked everything before creating this step. Note that
9111 // this is a GNU extension.
9112 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9113 << Step->Type << CurInit.get()->getType()
9114 << CurInit.get()->getSourceRange();
9115 updateGNUCompoundLiteralRValue(CurInit.get());
9116 [[fallthrough]];
9117 case SK_ArrayInit:
9118 // If the destination type is an incomplete array type, update the
9119 // type accordingly.
9120 if (ResultType) {
9121 if (const IncompleteArrayType *IncompleteDest
9122 = S.Context.getAsIncompleteArrayType(Step->Type)) {
9123 if (const ConstantArrayType *ConstantSource
9124 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9125 *ResultType = S.Context.getConstantArrayType(
9126 IncompleteDest->getElementType(),
9127 ConstantSource->getSize(),
9128 ConstantSource->getSizeExpr(),
9129 ArrayType::Normal, 0);
9130 }
9131 }
9132 }
9133 break;
9134
9135 case SK_ParenthesizedArrayInit:
9136 // Okay: we checked everything before creating this step. Note that
9137 // this is a GNU extension.
9138 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9139 << CurInit.get()->getSourceRange();
9140 break;
9141
9142 case SK_PassByIndirectCopyRestore:
9143 case SK_PassByIndirectRestore:
9144 checkIndirectCopyRestoreSource(S, CurInit.get());
9145 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9146 CurInit.get(), Step->Type,
9147 Step->Kind == SK_PassByIndirectCopyRestore);
9148 break;
9149
9150 case SK_ProduceObjCObject:
9151 CurInit = ImplicitCastExpr::Create(
9152 S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9153 VK_PRValue, FPOptionsOverride());
9154 break;
9155
9156 case SK_StdInitializerList: {
9157 S.Diag(CurInit.get()->getExprLoc(),
9158 diag::warn_cxx98_compat_initializer_list_init)
9159 << CurInit.get()->getSourceRange();
9160
9161 // Materialize the temporary into memory.
9162 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
9163 CurInit.get()->getType(), CurInit.get(),
9164 /*BoundToLvalueReference=*/false);
9165
9166 // Wrap it in a construction of a std::initializer_list<T>.
9167 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9168
9169 // Bind the result, in case the library has given initializer_list a
9170 // non-trivial destructor.
9171 if (shouldBindAsTemporary(Entity))
9172 CurInit = S.MaybeBindToTemporary(CurInit.get());
9173 break;
9174 }
9175
9176 case SK_OCLSamplerInit: {
9177 // Sampler initialization have 5 cases:
9178 // 1. function argument passing
9179 // 1a. argument is a file-scope variable
9180 // 1b. argument is a function-scope variable
9181 // 1c. argument is one of caller function's parameters
9182 // 2. variable initialization
9183 // 2a. initializing a file-scope variable
9184 // 2b. initializing a function-scope variable
9185 //
9186 // For file-scope variables, since they cannot be initialized by function
9187 // call of __translate_sampler_initializer in LLVM IR, their references
9188 // need to be replaced by a cast from their literal initializers to
9189 // sampler type. Since sampler variables can only be used in function
9190 // calls as arguments, we only need to replace them when handling the
9191 // argument passing.
9192 assert(Step->Type->isSamplerT() &&(static_cast <bool> (Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.") ? void (0) : __assert_fail
("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\""
, "clang/lib/Sema/SemaInit.cpp", 9193, __extension__ __PRETTY_FUNCTION__
))
9193 "Sampler initialization on non-sampler type.")(static_cast <bool> (Step->Type->isSamplerT() &&
"Sampler initialization on non-sampler type.") ? void (0) : __assert_fail
("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\""
, "clang/lib/Sema/SemaInit.cpp", 9193, __extension__ __PRETTY_FUNCTION__
))
;
9194 Expr *Init = CurInit.get()->IgnoreParens();
9195 QualType SourceType = Init->getType();
9196 // Case 1
9197 if (Entity.isParameterKind()) {
9198 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9199 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9200 << SourceType;
9201 break;
9202 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9203 auto Var = cast<VarDecl>(DRE->getDecl());
9204 // Case 1b and 1c
9205 // No cast from integer to sampler is needed.
9206 if (!Var->hasGlobalStorage()) {
9207 CurInit = ImplicitCastExpr::Create(
9208 S.Context, Step->Type, CK_LValueToRValue, Init,
9209 /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9210 break;
9211 }
9212 // Case 1a
9213 // For function call with a file-scope sampler variable as argument,
9214 // get the integer literal.
9215 // Do not diagnose if the file-scope variable does not have initializer
9216 // since this has already been diagnosed when parsing the variable
9217 // declaration.
9218 if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9219 break;
9220 Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9221 Var->getInit()))->getSubExpr();
9222 SourceType = Init->getType();
9223 }
9224 } else {
9225 // Case 2
9226 // Check initializer is 32 bit integer constant.
9227 // If the initializer is taken from global variable, do not diagnose since
9228 // this has already been done when parsing the variable declaration.
9229 if (!Init->isConstantInitializer(S.Context, false))
9230 break;
9231
9232 if (!SourceType->isIntegerType() ||
9233 32 != S.Context.getIntWidth(SourceType)) {
9234 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9235 << SourceType;
9236 break;
9237 }
9238
9239 Expr::EvalResult EVResult;
9240 Init->EvaluateAsInt(EVResult, S.Context);
9241 llvm::APSInt Result = EVResult.Val.getInt();
9242 const uint64_t SamplerValue = Result.getLimitedValue();
9243 // 32-bit value of sampler's initializer is interpreted as
9244 // bit-field with the following structure:
9245 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9246 // |31 6|5 4|3 1| 0|
9247 // This structure corresponds to enum values of sampler properties
9248 // defined in SPIR spec v1.2 and also opencl-c.h
9249 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9250 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9251 if (FilterMode != 1 && FilterMode != 2 &&
9252 !S.getOpenCLOptions().isAvailableOption(
9253 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9254 S.Diag(Kind.getLocation(),
9255 diag::warn_sampler_initializer_invalid_bits)
9256 << "Filter Mode";
9257 if (AddressingMode > 4)
9258 S.Diag(Kind.getLocation(),
9259 diag::warn_sampler_initializer_invalid_bits)
9260 << "Addressing Mode";
9261 }
9262
9263 // Cases 1a, 2a and 2b
9264 // Insert cast from integer to sampler.
9265 CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
9266 CK_IntToOCLSampler);
9267 break;
9268 }
9269 case SK_OCLZeroOpaqueType: {
9270 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||(static_cast <bool> ((Step->Type->isEventT() || Step
->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType
()) && "Wrong type for initialization of OpenCL opaque type."
) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\""
, "clang/lib/Sema/SemaInit.cpp", 9272, __extension__ __PRETTY_FUNCTION__
))
9271 Step->Type->isOCLIntelSubgroupAVCType()) &&(static_cast <bool> ((Step->Type->isEventT() || Step
->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType
()) && "Wrong type for initialization of OpenCL opaque type."
) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\""
, "clang/lib/Sema/SemaInit.cpp", 9272, __extension__ __PRETTY_FUNCTION__
))
9272 "Wrong type for initialization of OpenCL opaque type.")(static_cast <bool> ((Step->Type->isEventT() || Step
->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType
()) && "Wrong type for initialization of OpenCL opaque type."
) ? void (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\""
, "clang/lib/Sema/SemaInit.cpp", 9272, __extension__ __PRETTY_FUNCTION__
))
;
9273
9274 CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9275 CK_ZeroToOCLOpaqueType,
9276 CurInit.get()->getValueKind());
9277 break;
9278 }
9279 case SK_ParenthesizedListInit: {
9280 CurInit = nullptr;
9281 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9282 /*VerifyOnly=*/false, &CurInit);
9283 if (CurInit.get() && ResultType)
9284 *ResultType = CurInit.get()->getType();
9285 if (shouldBindAsTemporary(Entity))
9286 CurInit = S.MaybeBindToTemporary(CurInit.get());
9287 break;
9288 }
9289 }
9290 }
9291
9292 // Check whether the initializer has a shorter lifetime than the initialized
9293 // entity, and if not, either lifetime-extend or warn as appropriate.
9294 if (auto *Init = CurInit.get())
9295 S.checkInitializerLifetime(Entity, Init);
9296
9297 // Diagnose non-fatal problems with the completed initialization.
9298 if (InitializedEntity::EntityKind EK = Entity.getKind();
9299 (EK == InitializedEntity::EK_Member ||
9300 EK == InitializedEntity::EK_ParenAggInitMember) &&
9301 cast<FieldDecl>(Entity.getDecl())->isBitField())
9302 S.CheckBitFieldInitialization(Kind.getLocation(),
9303 cast<FieldDecl>(Entity.getDecl()),
9304 CurInit.get());
9305
9306 // Check for std::move on construction.
9307 if (const Expr *E = CurInit.get()) {
9308 CheckMoveOnConstruction(S, E,
9309 Entity.getKind() == InitializedEntity::EK_Result);
9310 }
9311
9312 return CurInit;
9313}
9314
9315/// Somewhere within T there is an uninitialized reference subobject.
9316/// Dig it out and diagnose it.
9317static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
9318 QualType T) {
9319 if (T->isReferenceType()) {
9320 S.Diag(Loc, diag::err_reference_without_init)
9321 << T.getNonReferenceType();
9322 return true;
9323 }
9324
9325 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
9326 if (!RD || !RD->hasUninitializedReferenceMember())
9327 return false;
9328
9329 for (const auto *FI : RD->fields()) {
9330 if (FI->isUnnamedBitfield())
9331 continue;
9332
9333 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9334 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9335 return true;
9336 }
9337 }
9338
9339 for (const auto &BI : RD->bases()) {
9340 if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9341 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9342 return true;
9343 }
9344 }
9345
9346 return false;
9347}
9348
9349
9350//===----------------------------------------------------------------------===//
9351// Diagnose initialization failures
9352//===----------------------------------------------------------------------===//
9353
9354/// Emit notes associated with an initialization that failed due to a
9355/// "simple" conversion failure.
9356static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9357 Expr *op) {
9358 QualType destType = entity.getType();
9359 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9360 op->getType()->isObjCObjectPointerType()) {
9361
9362 // Emit a possible note about the conversion failing because the
9363 // operand is a message send with a related result type.
9364 S.EmitRelatedResultTypeNote(op);
9365
9366 // Emit a possible note about a return failing because we're
9367 // expecting a related result type.
9368 if (entity.getKind() == InitializedEntity::EK_Result)
9369 S.EmitRelatedResultTypeNoteForReturn(destType);
9370 }
9371 QualType fromType = op->getType();
9372 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9373 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9374 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9375 auto *destDecl = destType->getPointeeCXXRecordDecl();
9376 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9377 destDecl->getDeclKind() == Decl::CXXRecord &&
9378 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9379 !fromDecl->hasDefinition() &&
9380 destPointeeType.getQualifiers().compatiblyIncludes(
9381 fromPointeeType.getQualifiers()))
9382 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9383 << S.getASTContext().getTagDeclType(fromDecl)
9384 << S.getASTContext().getTagDeclType(destDecl);
9385}
9386
9387static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9388 InitListExpr *InitList) {
9389 QualType DestType = Entity.getType();
9390
9391 QualType E;
9392 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9393 QualType ArrayType = S.Context.getConstantArrayType(
9394 E.withConst(),
9395 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9396 InitList->getNumInits()),
9397 nullptr, clang::ArrayType::Normal, 0);
9398 InitializedEntity HiddenArray =
9399 InitializedEntity::InitializeTemporary(ArrayType);
9400 return diagnoseListInit(S, HiddenArray, InitList);
9401 }
9402
9403 if (DestType->isReferenceType()) {
9404 // A list-initialization failure for a reference means that we tried to
9405 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9406 // inner initialization failed.
9407 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9408 diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
9409 SourceLocation Loc = InitList->getBeginLoc();
9410 if (auto *D = Entity.getDecl())
9411 Loc = D->getLocation();
9412 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9413 return;
9414 }
9415
9416 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9417 /*VerifyOnly=*/false,
9418 /*TreatUnavailableAsInvalid=*/false);
9419 assert(DiagnoseInitList.HadError() &&(static_cast <bool> (DiagnoseInitList.HadError() &&
"Inconsistent init list check result.") ? void (0) : __assert_fail
("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\""
, "clang/lib/Sema/SemaInit.cpp", 9420, __extension__ __PRETTY_FUNCTION__
))
9420 "Inconsistent init list check result.")(static_cast <bool> (DiagnoseInitList.HadError() &&
"Inconsistent init list check result.") ? void (0) : __assert_fail
("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\""
, "clang/lib/Sema/SemaInit.cpp", 9420, __extension__ __PRETTY_FUNCTION__
))
;
9421}
9422
9423bool InitializationSequence::Diagnose(Sema &S,
9424 const InitializedEntity &Entity,
9425 const InitializationKind &Kind,
9426 ArrayRef<Expr *> Args) {
9427 if (!Failed())
9428 return false;
9429
9430 // When we want to diagnose only one element of a braced-init-list,
9431 // we need to factor it out.
9432 Expr *OnlyArg;
9433 if (Args.size() == 1) {
9434 auto *List = dyn_cast<InitListExpr>(Args[0]);
9435 if (List && List->getNumInits() == 1)
9436 OnlyArg = List->getInit(0);
9437 else
9438 OnlyArg = Args[0];
9439 }
9440 else
9441 OnlyArg = nullptr;
9442
9443 QualType DestType = Entity.getType();
9444 switch (Failure) {
9445 case FK_TooManyInitsForReference:
9446 // FIXME: Customize for the initialized entity?
9447 if (Args.empty()) {
9448 // Dig out the reference subobject which is uninitialized and diagnose it.
9449 // If this is value-initialization, this could be nested some way within
9450 // the target type.
9451 assert(Kind.getKind() == InitializationKind::IK_Value ||(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail
("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()"
, "clang/lib/Sema/SemaInit.cpp", 9452, __extension__ __PRETTY_FUNCTION__
))
9452 DestType->isReferenceType())(static_cast <bool> (Kind.getKind() == InitializationKind
::IK_Value || DestType->isReferenceType()) ? void (0) : __assert_fail
("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()"
, "clang/lib/Sema/SemaInit.cpp", 9452, __extension__ __PRETTY_FUNCTION__
))
;
9453 bool Diagnosed =
9454 DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9455 assert(Diagnosed && "couldn't find uninitialized reference to diagnose")(static_cast <bool> (Diagnosed && "couldn't find uninitialized reference to diagnose"
) ? void (0) : __assert_fail ("Diagnosed && \"couldn't find uninitialized reference to diagnose\""
, "clang/lib/Sema/SemaInit.cpp", 9455, __extension__ __PRETTY_FUNCTION__
))
;
9456 (void)Diagnosed;
9457 } else // FIXME: diagnostic below could be better!
9458 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9459 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9460 break;
9461 case FK_ParenthesizedListInitForReference:
9462 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9463 << 1 << Entity.getType() << Args[0]->getSourceRange();
9464 break;
9465
9466 case FK_ArrayNeedsInitList:
9467 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9468 break;
9469 case FK_ArrayNeedsInitListOrStringLiteral:
9470 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9471 break;
9472 case FK_ArrayNeedsInitListOrWideStringLiteral:
9473 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9474 break;
9475 case FK_NarrowStringIntoWideCharArray:
9476 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9477 break;
9478 case FK_WideStringIntoCharArray:
9479 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9480 break;
9481 case FK_IncompatWideStringIntoWideChar:
9482 S.Diag(Kind.getLocation(),
9483 diag::err_array_init_incompat_wide_string_into_wchar);
9484 break;
9485 case FK_PlainStringIntoUTF8Char:
9486 S.Diag(Kind.getLocation(),
9487 diag::err_array_init_plain_string_into_char8_t);
9488 S.Diag(Args.front()->getBeginLoc(),
9489 diag::note_array_init_plain_string_into_char8_t)
9490 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9491 break;
9492 case FK_UTF8StringIntoPlainChar:
9493 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9494 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9495 break;
9496 case FK_ArrayTypeMismatch:
9497 case FK_NonConstantArrayInit:
9498 S.Diag(Kind.getLocation(),
9499 (Failure == FK_ArrayTypeMismatch
9500 ? diag::err_array_init_different_type
9501 : diag::err_array_init_non_constant_array))
9502 << DestType.getNonReferenceType()
9503 << OnlyArg->getType()
9504 << Args[0]->getSourceRange();
9505 break;
9506
9507 case FK_VariableLengthArrayHasInitializer:
9508 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9509 << Args[0]->getSourceRange();
9510 break;
9511
9512 case FK_AddressOfOverloadFailed: {
9513 DeclAccessPair Found;
9514 S.ResolveAddressOfOverloadedFunction(OnlyArg,
9515 DestType.getNonReferenceType(),
9516 true,
9517 Found);
9518 break;
9519 }
9520
9521 case FK_AddressOfUnaddressableFunction: {
9522 auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9523 S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9524 OnlyArg->getBeginLoc());
9525 break;
9526 }
9527
9528 case FK_ReferenceInitOverloadFailed:
9529 case FK_UserConversionOverloadFailed:
9530 switch (FailedOverloadResult) {
9531 case OR_Ambiguous:
9532
9533 FailedCandidateSet.NoteCandidates(
9534 PartialDiagnosticAt(
9535 Kind.getLocation(),
9536 Failure == FK_UserConversionOverloadFailed
9537 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9538 << OnlyArg->getType() << DestType
9539 << Args[0]->getSourceRange())
9540 : (S.PDiag(diag::err_ref_init_ambiguous)
9541 << DestType << OnlyArg->getType()
9542 << Args[0]->getSourceRange())),
9543 S, OCD_AmbiguousCandidates, Args);
9544 break;
9545
9546 case OR_No_Viable_Function: {
9547 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9548 if (!S.RequireCompleteType(Kind.getLocation(),
9549 DestType.getNonReferenceType(),
9550 diag::err_typecheck_nonviable_condition_incomplete,
9551 OnlyArg->getType(), Args[0]->getSourceRange()))
9552 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9553 << (Entity.getKind() == InitializedEntity::EK_Result)
9554 << OnlyArg->getType() << Args[0]->getSourceRange()
9555 << DestType.getNonReferenceType();
9556
9557 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9558 break;
9559 }
9560 case OR_Deleted: {
9561 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9562 << OnlyArg->getType() << DestType.getNonReferenceType()
9563 << Args[0]->getSourceRange();
9564 OverloadCandidateSet::iterator Best;
9565 OverloadingResult Ovl
9566 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9567 if (Ovl == OR_Deleted) {
9568 S.NoteDeletedFunction(Best->Function);
9569 } else {
9570 llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?"
, "clang/lib/Sema/SemaInit.cpp", 9570)
;
9571 }
9572 break;
9573 }
9574
9575 case OR_Success:
9576 llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!",
"clang/lib/Sema/SemaInit.cpp", 9576)
;
9577 }
9578 break;
9579
9580 case FK_NonConstLValueReferenceBindingToTemporary:
9581 if (isa<InitListExpr>(Args[0])) {
9582 S.Diag(Kind.getLocation(),
9583 diag::err_lvalue_reference_bind_to_initlist)
9584 << DestType.getNonReferenceType().isVolatileQualified()
9585 << DestType.getNonReferenceType()
9586 << Args[0]->getSourceRange();
9587 break;
9588 }
9589 [[fallthrough]];
9590
9591 case FK_NonConstLValueReferenceBindingToUnrelated:
9592 S.Diag(Kind.getLocation(),
9593 Failure == FK_NonConstLValueReferenceBindingToTemporary
9594 ? diag::err_lvalue_reference_bind_to_temporary
9595 : diag::err_lvalue_reference_bind_to_unrelated)
9596 << DestType.getNonReferenceType().isVolatileQualified()
9597 << DestType.getNonReferenceType()
9598 << OnlyArg->getType()
9599 << Args[0]->getSourceRange();
9600 break;
9601
9602 case FK_NonConstLValueReferenceBindingToBitfield: {
9603 // We don't necessarily have an unambiguous source bit-field.
9604 FieldDecl *BitField = Args[0]->getSourceBitField();
9605 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9606 << DestType.isVolatileQualified()
9607 << (BitField ? BitField->getDeclName() : DeclarationName())
9608 << (BitField != nullptr)
9609 << Args[0]->getSourceRange();
9610 if (BitField)
9611 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9612 break;
9613 }
9614
9615 case FK_NonConstLValueReferenceBindingToVectorElement:
9616 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9617 << DestType.isVolatileQualified()
9618 << Args[0]->getSourceRange();
9619 break;
9620
9621 case FK_NonConstLValueReferenceBindingToMatrixElement:
9622 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9623 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9624 break;
9625
9626 case FK_RValueReferenceBindingToLValue:
9627 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9628 << DestType.getNonReferenceType() << OnlyArg->getType()
9629 << Args[0]->getSourceRange();
9630 break;
9631
9632 case FK_ReferenceAddrspaceMismatchTemporary:
9633 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9634 << DestType << Args[0]->getSourceRange();
9635 break;
9636
9637 case FK_ReferenceInitDropsQualifiers: {
9638 QualType SourceType = OnlyArg->getType();
9639 QualType NonRefType = DestType.getNonReferenceType();
9640 Qualifiers DroppedQualifiers =
9641 SourceType.getQualifiers() - NonRefType.getQualifiers();
9642
9643 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9644 SourceType.getQualifiers()))
9645 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9646 << NonRefType << SourceType << 1 /*addr space*/
9647 << Args[0]->getSourceRange();
9648 else if (DroppedQualifiers.hasQualifiers())
9649 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9650 << NonRefType << SourceType << 0 /*cv quals*/
9651 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9652 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9653 else
9654 // FIXME: Consider decomposing the type and explaining which qualifiers
9655 // were dropped where, or on which level a 'const' is missing, etc.
9656 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9657 << NonRefType << SourceType << 2 /*incompatible quals*/
9658 << Args[0]->getSourceRange();
9659 break;
9660 }
9661
9662 case FK_ReferenceInitFailed:
9663 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9664 << DestType.getNonReferenceType()
9665 << DestType.getNonReferenceType()->isIncompleteType()
9666 << OnlyArg->isLValue()
9667 << OnlyArg->getType()
9668 << Args[0]->getSourceRange();
9669 emitBadConversionNotes(S, Entity, Args[0]);
9670 break;
9671
9672 case FK_ConversionFailed: {
9673 QualType FromType = OnlyArg->getType();
9674 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9675 << (int)Entity.getKind()
9676 << DestType
9677 << OnlyArg->isLValue()
9678 << FromType
9679 << Args[0]->getSourceRange();
9680 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9681 S.Diag(Kind.getLocation(), PDiag);
9682 emitBadConversionNotes(S, Entity, Args[0]);
9683 break;
9684 }
9685
9686 case FK_ConversionFromPropertyFailed:
9687 // No-op. This error has already been reported.
9688 break;
9689
9690 case FK_TooManyInitsForScalar: {
9691 SourceRange R;
9692
9693 auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9694 if (InitList && InitList->getNumInits() >= 1) {
9695 R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9696 } else {
9697 assert(Args.size() > 1 && "Expected multiple initializers!")(static_cast <bool> (Args.size() > 1 && "Expected multiple initializers!"
) ? void (0) : __assert_fail ("Args.size() > 1 && \"Expected multiple initializers!\""
, "clang/lib/Sema/SemaInit.cpp", 9697, __extension__ __PRETTY_FUNCTION__
))
;
9698 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9699 }
9700
9701 R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9702 if (Kind.isCStyleOrFunctionalCast())
9703 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9704 << R;
9705 else
9706 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9707 << /*scalar=*/2 << R;
9708 break;
9709 }
9710
9711 case FK_ParenthesizedListInitForScalar:
9712 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9713 << 0 << Entity.getType() << Args[0]->getSourceRange();
9714 break;
9715
9716 case FK_ReferenceBindingToInitList:
9717 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9718 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9719 break;
9720
9721 case FK_InitListBadDestinationType:
9722 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9723 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9724 break;
9725
9726 case FK_ListConstructorOverloadFailed:
9727 case FK_ConstructorOverloadFailed: {
9728 SourceRange ArgsRange;
9729 if (Args.size())
9730 ArgsRange =
9731 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9732
9733 if (Failure == FK_ListConstructorOverloadFailed) {
9734 assert(Args.size() == 1 &&(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\""
, "clang/lib/Sema/SemaInit.cpp", 9735, __extension__ __PRETTY_FUNCTION__
))
9735 "List construction from other than 1 argument.")(static_cast <bool> (Args.size() == 1 && "List construction from other than 1 argument."
) ? void (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\""
, "clang/lib/Sema/SemaInit.cpp", 9735, __extension__ __PRETTY_FUNCTION__
))
;
9736 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9737 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9738 }
9739
9740 // FIXME: Using "DestType" for the entity we're printing is probably
9741 // bad.
9742 switch (FailedOverloadResult) {
9743 case OR_Ambiguous:
9744 FailedCandidateSet.NoteCandidates(
9745 PartialDiagnosticAt(Kind.getLocation(),
9746 S.PDiag(diag::err_ovl_ambiguous_init)
9747 << DestType << ArgsRange),
9748 S, OCD_AmbiguousCandidates, Args);
9749 break;
9750
9751 case OR_No_Viable_Function:
9752 if (Kind.getKind() == InitializationKind::IK_Default &&
9753 (Entity.getKind() == InitializedEntity::EK_Base ||
9754 Entity.getKind() == InitializedEntity::EK_Member ||
9755 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9756 isa<CXXConstructorDecl>(S.CurContext)) {
9757 // This is implicit default initialization of a member or
9758 // base within a constructor. If no viable function was
9759 // found, notify the user that they need to explicitly
9760 // initialize this base/member.
9761 CXXConstructorDecl *Constructor
9762 = cast<CXXConstructorDecl>(S.CurContext);
9763 const CXXRecordDecl *InheritedFrom = nullptr;
9764 if (auto Inherited = Constructor->getInheritedConstructor())
9765 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9766 if (Entity.getKind() == InitializedEntity::EK_Base) {
9767 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9768 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9769 << S.Context.getTypeDeclType(Constructor->getParent())
9770 << /*base=*/0
9771 << Entity.getType()
9772 << InheritedFrom;
9773
9774 RecordDecl *BaseDecl
9775 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9776 ->getDecl();
9777 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9778 << S.Context.getTagDeclType(BaseDecl);
9779 } else {
9780 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9781 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9782 << S.Context.getTypeDeclType(Constructor->getParent())
9783 << /*member=*/1
9784 << Entity.getName()
9785 << InheritedFrom;
9786 S.Diag(Entity.getDecl()->getLocation(),
9787 diag::note_member_declared_at);
9788
9789 if (const RecordType *Record
9790 = Entity.getType()->getAs<RecordType>())
9791 S.Diag(Record->getDecl()->getLocation(),
9792 diag::note_previous_decl)
9793 << S.Context.getTagDeclType(Record->getDecl());
9794 }
9795 break;
9796 }
9797
9798 FailedCandidateSet.NoteCandidates(
9799 PartialDiagnosticAt(
9800 Kind.getLocation(),
9801 S.PDiag(diag::err_ovl_no_viable_function_in_init)
9802 << DestType << ArgsRange),
9803 S, OCD_AllCandidates, Args);
9804 break;
9805
9806 case OR_Deleted: {
9807 OverloadCandidateSet::iterator Best;
9808 OverloadingResult Ovl
9809 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9810 if (Ovl != OR_Deleted) {
9811 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9812 << DestType << ArgsRange;
9813 llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?"
, "clang/lib/Sema/SemaInit.cpp", 9813)
;
9814 break;
9815 }
9816
9817 // If this is a defaulted or implicitly-declared function, then
9818 // it was implicitly deleted. Make it clear that the deletion was
9819 // implicit.
9820 if (S.isImplicitlyDeleted(Best->Function))
9821 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9822 << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9823 << DestType << ArgsRange;
9824 else
9825 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9826 << DestType << ArgsRange;
9827
9828 S.NoteDeletedFunction(Best->Function);
9829 break;
9830 }
9831
9832 case OR_Success:
9833 llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!",
"clang/lib/Sema/SemaInit.cpp", 9833)
;
9834 }
9835 }
9836 break;
9837
9838 case FK_DefaultInitOfConst:
9839 if (Entity.getKind() == InitializedEntity::EK_Member &&
9840 isa<CXXConstructorDecl>(S.CurContext)) {
9841 // This is implicit default-initialization of a const member in
9842 // a constructor. Complain that it needs to be explicitly
9843 // initialized.
9844 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9845 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9846 << (Constructor->getInheritedConstructor() ? 2 :
9847 Constructor->isImplicit() ? 1 : 0)
9848 << S.Context.getTypeDeclType(Constructor->getParent())
9849 << /*const=*/1
9850 << Entity.getName();
9851 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9852 << Entity.getName();
9853 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9854 VD && VD->isConstexpr()) {
9855 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9856 << VD;
9857 } else {
9858 S.Diag(Kind.getLocation(), diag::err_default_init_const)
9859 << DestType << (bool)DestType->getAs<RecordType>();
9860 }
9861 break;
9862
9863 case FK_Incomplete:
9864 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9865 diag::err_init_incomplete_type);
9866 break;
9867
9868 case FK_ListInitializationFailed: {
9869 // Run the init list checker again to emit diagnostics.
9870 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9871 diagnoseListInit(S, Entity, InitList);
9872 break;
9873 }
9874
9875 case FK_PlaceholderType: {
9876 // FIXME: Already diagnosed!
9877 break;
9878 }
9879
9880 case FK_ExplicitConstructor: {
9881 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9882 << Args[0]->getSourceRange();
9883 OverloadCandidateSet::iterator Best;
9884 OverloadingResult Ovl
9885 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9886 (void)Ovl;
9887 assert(Ovl == OR_Success && "Inconsistent overload resolution")(static_cast <bool> (Ovl == OR_Success && "Inconsistent overload resolution"
) ? void (0) : __assert_fail ("Ovl == OR_Success && \"Inconsistent overload resolution\""
, "clang/lib/Sema/SemaInit.cpp", 9887, __extension__ __PRETTY_FUNCTION__
))
;
9888 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
9889 S.Diag(CtorDecl->getLocation(),
9890 diag::note_explicit_ctor_deduction_guide_here) << false;
9891 break;
9892 }
9893
9894 case FK_ParenthesizedListInitFailed:
9895 TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9896 /*VerifyOnly=*/false);
9897 break;
9898
9899 case FK_DesignatedInitForNonAggregate:
9900 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9901 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
9902 << Entity.getType() << InitList->getSourceRange();
9903 break;
9904 }
9905
9906 PrintInitLocationNote(S, Entity);
9907 return true;
9908}
9909
9910void InitializationSequence::dump(raw_ostream &OS) const {
9911 switch (SequenceKind) {
9912 case FailedSequence: {
9913 OS << "Failed sequence: ";
9914 switch (Failure) {
9915 case FK_TooManyInitsForReference:
9916 OS << "too many initializers for reference";
9917 break;
9918
9919 case FK_ParenthesizedListInitForReference:
9920 OS << "parenthesized list init for reference";
9921 break;
9922
9923 case FK_ArrayNeedsInitList:
9924 OS << "array requires initializer list";
9925 break;
9926
9927 case FK_AddressOfUnaddressableFunction:
9928 OS << "address of unaddressable function was taken";
9929 break;
9930
9931 case FK_ArrayNeedsInitListOrStringLiteral:
9932 OS << "array requires initializer list or string literal";
9933 break;
9934
9935 case FK_ArrayNeedsInitListOrWideStringLiteral:
9936 OS << "array requires initializer list or wide string literal";
9937 break;
9938
9939 case FK_NarrowStringIntoWideCharArray:
9940 OS << "narrow string into wide char array";
9941 break;
9942
9943 case FK_WideStringIntoCharArray:
9944 OS << "wide string into char array";
9945 break;
9946
9947 case FK_IncompatWideStringIntoWideChar:
9948 OS << "incompatible wide string into wide char array";
9949 break;
9950
9951 case FK_PlainStringIntoUTF8Char:
9952 OS << "plain string literal into char8_t array";
9953 break;
9954
9955 case FK_UTF8StringIntoPlainChar:
9956 OS << "u8 string literal into char array";
9957 break;
9958
9959 case FK_ArrayTypeMismatch:
9960 OS << "array type mismatch";
9961 break;
9962
9963 case FK_NonConstantArrayInit:
9964 OS << "non-constant array initializer";
9965 break;
9966
9967 case FK_AddressOfOverloadFailed:
9968 OS << "address of overloaded function failed";
9969 break;
9970
9971 case FK_ReferenceInitOverloadFailed:
9972 OS << "overload resolution for reference initialization failed";
9973 break;
9974
9975 case FK_NonConstLValueReferenceBindingToTemporary:
9976 OS << "non-const lvalue reference bound to temporary";
9977 break;
9978
9979 case FK_NonConstLValueReferenceBindingToBitfield:
9980 OS << "non-const lvalue reference bound to bit-field";
9981 break;
9982
9983 case FK_NonConstLValueReferenceBindingToVectorElement:
9984 OS << "non-const lvalue reference bound to vector element";
9985 break;
9986
9987 case FK_NonConstLValueReferenceBindingToMatrixElement:
9988 OS << "non-const lvalue reference bound to matrix element";
9989 break;
9990
9991 case FK_NonConstLValueReferenceBindingToUnrelated:
9992 OS << "non-const lvalue reference bound to unrelated type";
9993 break;
9994
9995 case FK_RValueReferenceBindingToLValue:
9996 OS << "rvalue reference bound to an lvalue";
9997 break;
9998
9999 case FK_ReferenceInitDropsQualifiers:
10000 OS << "reference initialization drops qualifiers";
10001 break;
10002
10003 case FK_ReferenceAddrspaceMismatchTemporary:
10004 OS << "reference with mismatching address space bound to temporary";
10005 break;
10006
10007 case FK_ReferenceInitFailed:
10008 OS << "reference initialization failed";
10009 break;
10010
10011 case FK_ConversionFailed:
10012 OS << "conversion failed";
10013 break;
10014
10015 case FK_ConversionFromPropertyFailed:
10016 OS << "conversion from property failed";
10017 break;
10018
10019 case FK_TooManyInitsForScalar:
10020 OS << "too many initializers for scalar";
10021 break;
10022
10023 case FK_ParenthesizedListInitForScalar:
10024 OS << "parenthesized list init for reference";
10025 break;
10026
10027 case FK_ReferenceBindingToInitList:
10028 OS << "referencing binding to initializer list";
10029 break;
10030
10031 case FK_InitListBadDestinationType:
10032 OS << "initializer list for non-aggregate, non-scalar type";
10033 break;
10034
10035 case FK_UserConversionOverloadFailed:
10036 OS << "overloading failed for user-defined conversion";
10037 break;
10038
10039 case FK_ConstructorOverloadFailed:
10040 OS << "constructor overloading failed";
10041 break;
10042
10043 case FK_DefaultInitOfConst:
10044 OS << "default initialization of a const variable";
10045 break;
10046
10047 case FK_Incomplete:
10048 OS << "initialization of incomplete type";
10049 break;
10050
10051 case FK_ListInitializationFailed:
10052 OS << "list initialization checker failure";
10053 break;
10054
10055 case FK_VariableLengthArrayHasInitializer:
10056 OS << "variable length array has an initializer";
10057 break;
10058
10059 case FK_PlaceholderType:
10060 OS << "initializer expression isn't contextually valid";
10061 break;
10062
10063 case FK_ListConstructorOverloadFailed:
10064 OS << "list constructor overloading failed";
10065 break;
10066
10067 case FK_ExplicitConstructor:
10068 OS << "list copy initialization chose explicit constructor";
10069 break;
10070
10071 case FK_ParenthesizedListInitFailed:
10072 OS << "parenthesized list initialization failed";
10073 break;
10074
10075 case FK_DesignatedInitForNonAggregate:
10076 OS << "designated initializer for non-aggregate type";
10077 break;
10078 }
10079 OS << '\n';
10080 return;
10081 }
10082
10083 case DependentSequence:
10084 OS << "Dependent sequence\n";
10085 return;
10086
10087 case NormalSequence:
10088 OS << "Normal sequence: ";
10089 break;
10090 }
10091
10092 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10093 if (S != step_begin()) {
10094 OS << " -> ";
10095 }
10096
10097 switch (S->Kind) {
10098 case SK_ResolveAddressOfOverloadedFunction:
10099 OS << "resolve address of overloaded function";
10100 break;
10101
10102 case SK_CastDerivedToBasePRValue:
10103 OS << "derived-to-base (prvalue)";
10104 break;
10105
10106 case SK_CastDerivedToBaseXValue:
10107 OS << "derived-to-base (xvalue)";
10108 break;
10109
10110 case SK_CastDerivedToBaseLValue:
10111 OS << "derived-to-base (lvalue)";
10112 break;
10113
10114 case SK_BindReference:
10115 OS << "bind reference to lvalue";
10116 break;
10117
10118 case SK_BindReferenceToTemporary:
10119 OS << "bind reference to a temporary";
10120 break;
10121
10122 case SK_FinalCopy:
10123 OS << "final copy in class direct-initialization";
10124 break;
10125
10126 case SK_ExtraneousCopyToTemporary:
10127 OS << "extraneous C++03 copy to temporary";
10128 break;
10129
10130 case SK_UserConversion:
10131 OS << "user-defined conversion via " << *S->Function.Function;
10132 break;
10133
10134 case SK_QualificationConversionPRValue:
10135 OS << "qualification conversion (prvalue)";
10136 break;
10137
10138 case SK_QualificationConversionXValue:
10139 OS << "qualification conversion (xvalue)";
10140 break;
10141
10142 case SK_QualificationConversionLValue:
10143 OS << "qualification conversion (lvalue)";
10144 break;
10145
10146 case SK_FunctionReferenceConversion:
10147 OS << "function reference conversion";
10148 break;
10149
10150 case SK_AtomicConversion:
10151 OS << "non-atomic-to-atomic conversion";
10152 break;
10153
10154 case SK_ConversionSequence:
10155 OS << "implicit conversion sequence (";
10156 S->ICS->dump(); // FIXME: use OS
10157 OS << ")";
10158 break;
10159
10160 case SK_ConversionSequenceNoNarrowing:
10161 OS << "implicit conversion sequence with narrowing prohibited (";
10162 S->ICS->dump(); // FIXME: use OS
10163 OS << ")";
10164 break;
10165
10166 case SK_ListInitialization:
10167 OS << "list aggregate initialization";
10168 break;
10169
10170 case SK_UnwrapInitList:
10171 OS << "unwrap reference initializer list";
10172 break;
10173
10174 case SK_RewrapInitList:
10175 OS << "rewrap reference initializer list";
10176 break;
10177
10178 case SK_ConstructorInitialization:
10179 OS << "constructor initialization";
10180 break;
10181
10182 case SK_ConstructorInitializationFromList:
10183 OS << "list initialization via constructor";
10184 break;
10185
10186 case SK_ZeroInitialization:
10187 OS << "zero initialization";
10188 break;
10189
10190 case SK_CAssignment:
10191 OS << "C assignment";
10192 break;
10193
10194 case SK_StringInit:
10195 OS << "string initialization";
10196 break;
10197
10198 case SK_ObjCObjectConversion:
10199 OS << "Objective-C object conversion";
10200 break;
10201
10202 case SK_ArrayLoopIndex:
10203 OS << "indexing for array initialization loop";
10204 break;
10205
10206 case SK_ArrayLoopInit:
10207 OS << "array initialization loop";
10208 break;
10209
10210 case SK_ArrayInit:
10211 OS << "array initialization";
10212 break;
10213
10214 case SK_GNUArrayInit:
10215 OS << "array initialization (GNU extension)";
10216 break;
10217
10218 case SK_ParenthesizedArrayInit:
10219 OS << "parenthesized array initialization";
10220 break;
10221
10222 case SK_PassByIndirectCopyRestore:
10223 OS << "pass by indirect copy and restore";
10224 break;
10225
10226 case SK_PassByIndirectRestore:
10227 OS << "pass by indirect restore";
10228 break;
10229
10230 case SK_ProduceObjCObject:
10231 OS << "Objective-C object retension";
10232 break;
10233
10234 case SK_StdInitializerList:
10235 OS << "std::initializer_list from initializer list";
10236 break;
10237
10238 case SK_StdInitializerListConstructorCall:
10239 OS << "list initialization from std::initializer_list";
10240 break;
10241
10242 case SK_OCLSamplerInit:
10243 OS << "OpenCL sampler_t from integer constant";
10244 break;
10245
10246 case SK_OCLZeroOpaqueType:
10247 OS << "OpenCL opaque type from zero";
10248 break;
10249 case SK_ParenthesizedListInit:
10250 OS << "initialization from a parenthesized list of values";
10251 break;
10252 }
10253
10254 OS << " [" << S->Type << ']';
10255 }
10256
10257 OS << '\n';
10258}
10259
10260void InitializationSequence::dump() const {
10261 dump(llvm::errs());
10262}
10263
10264static bool NarrowingErrs(const LangOptions &L) {
10265 return L.CPlusPlus11 &&
10266 (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015));
10267}
10268
10269static void DiagnoseNarrowingInInitList(Sema &S,
10270 const ImplicitConversionSequence &ICS,
10271 QualType PreNarrowingType,
10272 QualType EntityType,
10273 const Expr *PostInit) {
10274 const StandardConversionSequence *SCS = nullptr;
10275 switch (ICS.getKind()) {
10276 case ImplicitConversionSequence::StandardConversion:
10277 SCS = &ICS.Standard;
10278 break;
10279 case ImplicitConversionSequence::UserDefinedConversion:
10280 SCS = &ICS.UserDefined.After;
10281 break;
10282 case ImplicitConversionSequence::AmbiguousConversion:
10283 case ImplicitConversionSequence::StaticObjectArgumentConversion:
10284 case ImplicitConversionSequence::EllipsisConversion:
10285 case ImplicitConversionSequence::BadConversion:
10286 return;
10287 }
10288
10289 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10290 APValue ConstantValue;
10291 QualType ConstantType;
10292 switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10293 ConstantType)) {
10294 case NK_Not_Narrowing:
10295 case NK_Dependent_Narrowing:
10296 // No narrowing occurred.
10297 return;
10298
10299 case NK_Type_Narrowing:
10300 // This was a floating-to-integer conversion, which is always considered a
10301 // narrowing conversion even if the value is a constant and can be
10302 // represented exactly as an integer.
10303 S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
10304 ? diag::ext_init_list_type_narrowing
10305 : diag::warn_init_list_type_narrowing)
10306 << PostInit->getSourceRange()
10307 << PreNarrowingType.getLocalUnqualifiedType()
10308 << EntityType.getLocalUnqualifiedType();
10309 break;
10310
10311 case NK_Constant_Narrowing:
10312 // A constant value was narrowed.
10313 S.Diag(PostInit->getBeginLoc(),
10314 NarrowingErrs(S.getLangOpts())
10315 ? diag::ext_init_list_constant_narrowing
10316 : diag::warn_init_list_constant_narrowing)
10317 << PostInit->getSourceRange()
10318 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10319 << EntityType.getLocalUnqualifiedType();
10320 break;
10321
10322 case NK_Variable_Narrowing:
10323 // A variable's value may have been narrowed.
10324 S.Diag(PostInit->getBeginLoc(),
10325 NarrowingErrs(S.getLangOpts())
10326 ? diag::ext_init_list_variable_narrowing
10327 : diag::warn_init_list_variable_narrowing)
10328 << PostInit->getSourceRange()
10329 << PreNarrowingType.getLocalUnqualifiedType()
10330 << EntityType.getLocalUnqualifiedType();
10331 break;
10332 }
10333
10334 SmallString<128> StaticCast;
10335 llvm::raw_svector_ostream OS(StaticCast);
10336 OS << "static_cast<";
10337 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10338 // It's important to use the typedef's name if there is one so that the
10339 // fixit doesn't break code using types like int64_t.
10340 //
10341 // FIXME: This will break if the typedef requires qualification. But
10342 // getQualifiedNameAsString() includes non-machine-parsable components.
10343 OS << *TT->getDecl();
10344 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10345 OS << BT->getName(S.getLangOpts());
10346 else {
10347 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10348 // with a broken cast.
10349 return;
10350 }
10351 OS << ">(";
10352 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10353 << PostInit->getSourceRange()
10354 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10355 << FixItHint::CreateInsertion(
10356 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10357}
10358
10359//===----------------------------------------------------------------------===//
10360// Initialization helper functions
10361//===----------------------------------------------------------------------===//
10362bool
10363Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10364 ExprResult Init) {
10365 if (Init.isInvalid())
10366 return false;
10367
10368 Expr *InitE = Init.get();
10369 assert(InitE && "No initialization expression")(static_cast <bool> (InitE && "No initialization expression"
) ? void (0) : __assert_fail ("InitE && \"No initialization expression\""
, "clang/lib/Sema/SemaInit.cpp", 10369, __extension__ __PRETTY_FUNCTION__
))
;
10370
10371 InitializationKind Kind =
10372 InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
10373 InitializationSequence Seq(*this, Entity, Kind, InitE);
10374 return !Seq.Failed();
10375}
10376
10377ExprResult
10378Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10379 SourceLocation EqualLoc,
10380 ExprResult Init,
10381 bool TopLevelOfInitList,
10382 bool AllowExplicit) {
10383 if (Init.isInvalid())
10384 return ExprError();
10385
10386 Expr *InitE = Init.get();
10387 assert(InitE && "No initialization expression?")(static_cast <bool> (InitE && "No initialization expression?"
) ? void (0) : __assert_fail ("InitE && \"No initialization expression?\""
, "clang/lib/Sema/SemaInit.cpp", 10387, __extension__ __PRETTY_FUNCTION__
))
;
10388
10389 if (EqualLoc.isInvalid())
10390 EqualLoc = InitE->getBeginLoc();
10391
10392 InitializationKind Kind = InitializationKind::CreateCopy(
10393 InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10394 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10395
10396 // Prevent infinite recursion when performing parameter copy-initialization.
10397 const bool ShouldTrackCopy =
10398 Entity.isParameterKind() && Seq.isConstructorInitialization();
10399 if (ShouldTrackCopy) {
10400 if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10401 Seq.SetOverloadFailure(
10402 InitializationSequence::FK_ConstructorOverloadFailed,
10403 OR_No_Viable_Function);
10404
10405 // Try to give a meaningful diagnostic note for the problematic
10406 // constructor.
10407 const auto LastStep = Seq.step_end() - 1;
10408 assert(LastStep->Kind ==(static_cast <bool> (LastStep->Kind == InitializationSequence
::SK_ConstructorInitialization) ? void (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization"
, "clang/lib/Sema/SemaInit.cpp", 10409, __extension__ __PRETTY_FUNCTION__
))
10409 InitializationSequence::SK_ConstructorInitialization)(static_cast <bool> (LastStep->Kind == InitializationSequence
::SK_ConstructorInitialization) ? void (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization"
, "clang/lib/Sema/SemaInit.cpp", 10409, __extension__ __PRETTY_FUNCTION__
))
;
10410 const FunctionDecl *Function = LastStep->Function.Function;
10411 auto Candidate =
10412 llvm::find_if(Seq.getFailedCandidateSet(),
10413 [Function](const OverloadCandidate &Candidate) -> bool {
10414 return Candidate.Viable &&
10415 Candidate.Function == Function &&
10416 Candidate.Conversions.size() > 0;
10417 });
10418 if (Candidate != Seq.getFailedCandidateSet().end() &&
10419 Function->getNumParams() > 0) {
10420 Candidate->Viable = false;
10421 Candidate->FailureKind = ovl_fail_bad_conversion;
10422 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
10423 InitE,
10424 Function->getParamDecl(0)->getType());
10425 }
10426 }
10427 CurrentParameterCopyTypes.push_back(Entity.getType());
10428 }
10429
10430 ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10431
10432 if (ShouldTrackCopy)
10433 CurrentParameterCopyTypes.pop_back();
10434
10435 return Result;
10436}
10437
10438/// Determine whether RD is, or is derived from, a specialization of CTD.
10439static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10440 ClassTemplateDecl *CTD) {
10441 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10442 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10443 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10444 };
10445 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10446}
10447
10448QualType Sema::DeduceTemplateSpecializationFromInitializer(
10449 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10450 const InitializationKind &Kind, MultiExprArg Inits) {
10451 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10452 TSInfo->getType()->getContainedDeducedType());
10453 assert(DeducedTST && "not a deduced template specialization type")(static_cast <bool> (DeducedTST && "not a deduced template specialization type"
) ? void (0) : __assert_fail ("DeducedTST && \"not a deduced template specialization type\""
, "clang/lib/Sema/SemaInit.cpp", 10453, __extension__ __PRETTY_FUNCTION__
))
;
10454
10455 auto TemplateName = DeducedTST->getTemplateName();
10456 if (TemplateName.isDependent())
10457 return SubstAutoTypeDependent(TSInfo->getType());
10458
10459 // We can only perform deduction for class templates.
10460 auto *Template =
10461 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10462 if (!Template) {
10463 Diag(Kind.getLocation(),
10464 diag::err_deduced_non_class_template_specialization_type)
10465 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10466 if (auto *TD = TemplateName.getAsTemplateDecl())
10467 Diag(TD->getLocation(), diag::note_template_decl_here);
10468 return QualType();
10469 }
10470
10471 // Can't deduce from dependent arguments.
10472 if (Expr::hasAnyTypeDependentArguments(Inits)) {
10473 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10474 diag::warn_cxx14_compat_class_template_argument_deduction)
10475 << TSInfo->getTypeLoc().getSourceRange() << 0;
10476 return SubstAutoTypeDependent(TSInfo->getType());
10477 }
10478
10479 // FIXME: Perform "exact type" matching first, per CWG discussion?
10480 // Or implement this via an implied 'T(T) -> T' deduction guide?
10481
10482 // FIXME: Do we need/want a std::initializer_list<T> special case?
10483
10484 // Look up deduction guides, including those synthesized from constructors.
10485 //
10486 // C++1z [over.match.class.deduct]p1:
10487 // A set of functions and function templates is formed comprising:
10488 // - For each constructor of the class template designated by the
10489 // template-name, a function template [...]
10490 // - For each deduction-guide, a function or function template [...]
10491 DeclarationNameInfo NameInfo(
10492 Context.DeclarationNames.getCXXDeductionGuideName(Template),
10493 TSInfo->getTypeLoc().getEndLoc());
10494 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10495 LookupQualifiedName(Guides, Template->getDeclContext());
10496
10497 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10498 // clear on this, but they're not found by name so access does not apply.
10499 Guides.suppressDiagnostics();
10500
10501 // Figure out if this is list-initialization.
10502 InitListExpr *ListInit =
10503 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10504 ? dyn_cast<InitListExpr>(Inits[0])
10505 : nullptr;
10506
10507 // C++1z [over.match.class.deduct]p1:
10508 // Initialization and overload resolution are performed as described in
10509 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10510 // (as appropriate for the type of initialization performed) for an object
10511 // of a hypothetical class type, where the selected functions and function
10512 // templates are considered to be the constructors of that class type
10513 //
10514 // Since we know we're initializing a class type of a type unrelated to that
10515 // of the initializer, this reduces to something fairly reasonable.
10516 OverloadCandidateSet Candidates(Kind.getLocation(),
10517 OverloadCandidateSet::CSK_Normal);
10518 OverloadCandidateSet::iterator Best;
10519
10520 bool HasAnyDeductionGuide = false;
10521 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10522
10523 auto tryToResolveOverload =
10524 [&](bool OnlyListConstructors) -> OverloadingResult {
10525 Candidates.clear(OverloadCandidateSet::CSK_Normal);
10526 HasAnyDeductionGuide = false;
10527
10528 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10529 NamedDecl *D = (*I)->getUnderlyingDecl();
10530 if (D->isInvalidDecl())
10531 continue;
10532
10533 auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10534 auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>(
10535 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10536 if (!GD)
10537 continue;
10538
10539 if (!GD->isImplicit())
10540 HasAnyDeductionGuide = true;
10541
10542 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10543 // For copy-initialization, the candidate functions are all the
10544 // converting constructors (12.3.1) of that class.
10545 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10546 // The converting constructors of T are candidate functions.
10547 if (!AllowExplicit) {
10548 // Overload resolution checks whether the deduction guide is declared
10549 // explicit for us.
10550
10551 // When looking for a converting constructor, deduction guides that
10552 // could never be called with one argument are not interesting to
10553 // check or note.
10554 if (GD->getMinRequiredArguments() > 1 ||
10555 (GD->getNumParams() == 0 && !GD->isVariadic()))
10556 continue;
10557 }
10558
10559 // C++ [over.match.list]p1.1: (first phase list initialization)
10560 // Initially, the candidate functions are the initializer-list
10561 // constructors of the class T
10562 if (OnlyListConstructors && !isInitListConstructor(GD))
10563 continue;
10564
10565 // C++ [over.match.list]p1.2: (second phase list initialization)
10566 // the candidate functions are all the constructors of the class T
10567 // C++ [over.match.ctor]p1: (all other cases)
10568 // the candidate functions are all the constructors of the class of
10569 // the object being initialized
10570
10571 // C++ [over.best.ics]p4:
10572 // When [...] the constructor [...] is a candidate by
10573 // - [over.match.copy] (in all cases)
10574 // FIXME: The "second phase of [over.match.list] case can also
10575 // theoretically happen here, but it's not clear whether we can
10576 // ever have a parameter of the right type.
10577 bool SuppressUserConversions = Kind.isCopyInit();
10578
10579 if (TD)
10580 AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr,
10581 Inits, Candidates, SuppressUserConversions,
10582 /*PartialOverloading*/ false,
10583 AllowExplicit);
10584 else
10585 AddOverloadCandidate(GD, I.getPair(), Inits, Candidates,
10586 SuppressUserConversions,
10587 /*PartialOverloading*/ false, AllowExplicit);
10588 }
10589 return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10590 };
10591
10592 OverloadingResult Result = OR_No_Viable_Function;
10593
10594 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10595 // try initializer-list constructors.
10596 if (ListInit) {
10597 bool TryListConstructors = true;
10598
10599 // Try list constructors unless the list is empty and the class has one or
10600 // more default constructors, in which case those constructors win.
10601 if (!ListInit->getNumInits()) {
10602 for (NamedDecl *D : Guides) {
10603 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10604 if (FD && FD->getMinRequiredArguments() == 0) {
10605 TryListConstructors = false;
10606 break;
10607 }
10608 }
10609 } else if (ListInit->getNumInits() == 1) {
10610 // C++ [over.match.class.deduct]:
10611 // As an exception, the first phase in [over.match.list] (considering
10612 // initializer-list constructors) is omitted if the initializer list
10613 // consists of a single expression of type cv U, where U is a
10614 // specialization of C or a class derived from a specialization of C.
10615 Expr *E = ListInit->getInit(0);
10616 auto *RD = E->getType()->getAsCXXRecordDecl();
10617 if (!isa<InitListExpr>(E) && RD &&
10618 isCompleteType(Kind.getLocation(), E->getType()) &&
10619 isOrIsDerivedFromSpecializationOf(RD, Template))
10620 TryListConstructors = false;
10621 }
10622
10623 if (TryListConstructors)
10624 Result = tryToResolveOverload(/*OnlyListConstructor*/true);
10625 // Then unwrap the initializer list and try again considering all
10626 // constructors.
10627 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10628 }
10629
10630 // If list-initialization fails, or if we're doing any other kind of
10631 // initialization, we (eventually) consider constructors.
10632 if (Result == OR_No_Viable_Function)
10633 Result = tryToResolveOverload(/*OnlyListConstructor*/false);
10634
10635 switch (Result) {
10636 case OR_Ambiguous:
10637 // FIXME: For list-initialization candidates, it'd usually be better to
10638 // list why they were not viable when given the initializer list itself as
10639 // an argument.
10640 Candidates.NoteCandidates(
10641 PartialDiagnosticAt(
10642 Kind.getLocation(),
10643 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10644 << TemplateName),
10645 *this, OCD_AmbiguousCandidates, Inits);
10646 return QualType();
10647
10648 case OR_No_Viable_Function: {
10649 CXXRecordDecl *Primary =
10650 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10651 bool Complete =
10652 isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10653 Candidates.NoteCandidates(
10654 PartialDiagnosticAt(
10655 Kind.getLocation(),
10656 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10657 : diag::err_deduced_class_template_incomplete)
10658 << TemplateName << !Guides.empty()),
10659 *this, OCD_AllCandidates, Inits);
10660 return QualType();
10661 }
10662
10663 case OR_Deleted: {
10664 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10665 << TemplateName;
10666 NoteDeletedFunction(Best->Function);
10667 return QualType();
10668 }
10669
10670 case OR_Success:
10671 // C++ [over.match.list]p1:
10672 // In copy-list-initialization, if an explicit constructor is chosen, the
10673 // initialization is ill-formed.
10674 if (Kind.isCopyInit() && ListInit &&
10675 cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10676 bool IsDeductionGuide = !Best->Function->isImplicit();
10677 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10678 << TemplateName << IsDeductionGuide;
10679 Diag(Best->Function->getLocation(),
10680 diag::note_explicit_ctor_deduction_guide_here)
10681 << IsDeductionGuide;
10682 return QualType();
10683 }
10684
10685 // Make sure we didn't select an unusable deduction guide, and mark it
10686 // as referenced.
10687 DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10688 MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10689 break;
10690 }
10691
10692 // C++ [dcl.type.class.deduct]p1:
10693 // The placeholder is replaced by the return type of the function selected
10694 // by overload resolution for class template deduction.
10695 QualType DeducedType =
10696 SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10697 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10698 diag::warn_cxx14_compat_class_template_argument_deduction)
10699 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10700
10701 // Warn if CTAD was used on a type that does not have any user-defined
10702 // deduction guides.
10703 if (!HasAnyDeductionGuide) {
10704 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10705 diag::warn_ctad_maybe_unsupported)
10706 << TemplateName;
10707 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10708 }
10709
10710 return DeducedType;
10711}