Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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