Bug Summary

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