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