Bug Summary

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