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