Bug Summary

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