Bug Summary

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