File: | clang/lib/Sema/SemaInit.cpp |
Warning: | line 5897, 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/TargetInfo.h" | ||||||||||
21 | #include "clang/Sema/Designator.h" | ||||||||||
22 | #include "clang/Sema/Initialization.h" | ||||||||||
23 | #include "clang/Sema/Lookup.h" | ||||||||||
24 | #include "clang/Sema/SemaInternal.h" | ||||||||||
25 | #include "llvm/ADT/APInt.h" | ||||||||||
26 | #include "llvm/ADT/SmallString.h" | ||||||||||
27 | #include "llvm/Support/ErrorHandling.h" | ||||||||||
28 | #include "llvm/Support/raw_ostream.h" | ||||||||||
29 | |||||||||||
30 | using namespace clang; | ||||||||||
31 | |||||||||||
32 | //===----------------------------------------------------------------------===// | ||||||||||
33 | // Sema Initialization Checking | ||||||||||
34 | //===----------------------------------------------------------------------===// | ||||||||||
35 | |||||||||||
36 | /// Check whether T is compatible with a wide character type (wchar_t, | ||||||||||
37 | /// char16_t or char32_t). | ||||||||||
38 | static bool IsWideCharCompatible(QualType T, ASTContext &Context) { | ||||||||||
39 | if (Context.typesAreCompatible(Context.getWideCharType(), T)) | ||||||||||
40 | return true; | ||||||||||
41 | if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { | ||||||||||
42 | return Context.typesAreCompatible(Context.Char16Ty, T) || | ||||||||||
43 | Context.typesAreCompatible(Context.Char32Ty, T); | ||||||||||
44 | } | ||||||||||
45 | return false; | ||||||||||
46 | } | ||||||||||
47 | |||||||||||
48 | enum StringInitFailureKind { | ||||||||||
49 | SIF_None, | ||||||||||
50 | SIF_NarrowStringIntoWideChar, | ||||||||||
51 | SIF_WideStringIntoChar, | ||||||||||
52 | SIF_IncompatWideStringIntoWideChar, | ||||||||||
53 | SIF_UTF8StringIntoPlainChar, | ||||||||||
54 | SIF_PlainStringIntoUTF8Char, | ||||||||||
55 | SIF_Other | ||||||||||
56 | }; | ||||||||||
57 | |||||||||||
58 | /// Check whether the array of type AT can be initialized by the Init | ||||||||||
59 | /// expression by means of string initialization. Returns SIF_None if so, | ||||||||||
60 | /// otherwise returns a StringInitFailureKind that describes why the | ||||||||||
61 | /// initialization would not work. | ||||||||||
62 | static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, | ||||||||||
63 | ASTContext &Context) { | ||||||||||
64 | if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT)) | ||||||||||
65 | return SIF_Other; | ||||||||||
66 | |||||||||||
67 | // See if this is a string literal or @encode. | ||||||||||
68 | Init = Init->IgnoreParens(); | ||||||||||
69 | |||||||||||
70 | // Handle @encode, which is a narrow string. | ||||||||||
71 | if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType()) | ||||||||||
72 | return SIF_None; | ||||||||||
73 | |||||||||||
74 | // Otherwise we can only handle string literals. | ||||||||||
75 | StringLiteral *SL = dyn_cast<StringLiteral>(Init); | ||||||||||
76 | if (!SL) | ||||||||||
77 | return SIF_Other; | ||||||||||
78 | |||||||||||
79 | const QualType ElemTy = | ||||||||||
80 | Context.getCanonicalType(AT->getElementType()).getUnqualifiedType(); | ||||||||||
81 | |||||||||||
82 | switch (SL->getKind()) { | ||||||||||
83 | case StringLiteral::UTF8: | ||||||||||
84 | // char8_t array can be initialized with a UTF-8 string. | ||||||||||
85 | if (ElemTy->isChar8Type()) | ||||||||||
86 | return SIF_None; | ||||||||||
87 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
88 | case StringLiteral::Ascii: | ||||||||||
89 | // char array can be initialized with a narrow string. | ||||||||||
90 | // Only allow char x[] = "foo"; not char x[] = L"foo"; | ||||||||||
91 | if (ElemTy->isCharType()) | ||||||||||
92 | return (SL->getKind() == StringLiteral::UTF8 && | ||||||||||
93 | Context.getLangOpts().Char8) | ||||||||||
94 | ? SIF_UTF8StringIntoPlainChar | ||||||||||
95 | : SIF_None; | ||||||||||
96 | if (ElemTy->isChar8Type()) | ||||||||||
97 | return SIF_PlainStringIntoUTF8Char; | ||||||||||
98 | if (IsWideCharCompatible(ElemTy, Context)) | ||||||||||
99 | return SIF_NarrowStringIntoWideChar; | ||||||||||
100 | return SIF_Other; | ||||||||||
101 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: | ||||||||||
102 | // "An array with element type compatible with a qualified or unqualified | ||||||||||
103 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide | ||||||||||
104 | // string literal with the corresponding encoding prefix (L, u, or U, | ||||||||||
105 | // respectively), optionally enclosed in braces. | ||||||||||
106 | case StringLiteral::UTF16: | ||||||||||
107 | if (Context.typesAreCompatible(Context.Char16Ty, ElemTy)) | ||||||||||
108 | return SIF_None; | ||||||||||
109 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | ||||||||||
110 | return SIF_WideStringIntoChar; | ||||||||||
111 | if (IsWideCharCompatible(ElemTy, Context)) | ||||||||||
112 | return SIF_IncompatWideStringIntoWideChar; | ||||||||||
113 | return SIF_Other; | ||||||||||
114 | case StringLiteral::UTF32: | ||||||||||
115 | if (Context.typesAreCompatible(Context.Char32Ty, ElemTy)) | ||||||||||
116 | return SIF_None; | ||||||||||
117 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | ||||||||||
118 | return SIF_WideStringIntoChar; | ||||||||||
119 | if (IsWideCharCompatible(ElemTy, Context)) | ||||||||||
120 | return SIF_IncompatWideStringIntoWideChar; | ||||||||||
121 | return SIF_Other; | ||||||||||
122 | case StringLiteral::Wide: | ||||||||||
123 | if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy)) | ||||||||||
124 | return SIF_None; | ||||||||||
125 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) | ||||||||||
126 | return SIF_WideStringIntoChar; | ||||||||||
127 | if (IsWideCharCompatible(ElemTy, Context)) | ||||||||||
128 | return SIF_IncompatWideStringIntoWideChar; | ||||||||||
129 | return SIF_Other; | ||||||||||
130 | } | ||||||||||
131 | |||||||||||
132 | llvm_unreachable("missed a StringLiteral kind?")::llvm::llvm_unreachable_internal("missed a StringLiteral kind?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 132); | ||||||||||
133 | } | ||||||||||
134 | |||||||||||
135 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, | ||||||||||
136 | ASTContext &Context) { | ||||||||||
137 | const ArrayType *arrayType = Context.getAsArrayType(declType); | ||||||||||
138 | if (!arrayType) | ||||||||||
139 | return SIF_Other; | ||||||||||
140 | return IsStringInit(init, arrayType, Context); | ||||||||||
141 | } | ||||||||||
142 | |||||||||||
143 | /// Update the type of a string literal, including any surrounding parentheses, | ||||||||||
144 | /// to match the type of the object which it is initializing. | ||||||||||
145 | static void updateStringLiteralType(Expr *E, QualType Ty) { | ||||||||||
146 | while (true) { | ||||||||||
147 | E->setType(Ty); | ||||||||||
148 | E->setValueKind(VK_RValue); | ||||||||||
149 | if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E)) { | ||||||||||
150 | break; | ||||||||||
151 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | ||||||||||
152 | E = PE->getSubExpr(); | ||||||||||
153 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | ||||||||||
154 | assert(UO->getOpcode() == UO_Extension)((UO->getOpcode() == UO_Extension) ? static_cast<void> (0) : __assert_fail ("UO->getOpcode() == UO_Extension", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 154, __PRETTY_FUNCTION__)); | ||||||||||
155 | E = UO->getSubExpr(); | ||||||||||
156 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | ||||||||||
157 | E = GSE->getResultExpr(); | ||||||||||
158 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | ||||||||||
159 | E = CE->getChosenSubExpr(); | ||||||||||
160 | } else { | ||||||||||
161 | llvm_unreachable("unexpected expr in string literal init")::llvm::llvm_unreachable_internal("unexpected expr in string literal init" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 161); | ||||||||||
162 | } | ||||||||||
163 | } | ||||||||||
164 | } | ||||||||||
165 | |||||||||||
166 | /// Fix a compound literal initializing an array so it's correctly marked | ||||||||||
167 | /// as an rvalue. | ||||||||||
168 | static void updateGNUCompoundLiteralRValue(Expr *E) { | ||||||||||
169 | while (true) { | ||||||||||
170 | E->setValueKind(VK_RValue); | ||||||||||
171 | if (isa<CompoundLiteralExpr>(E)) { | ||||||||||
172 | break; | ||||||||||
173 | } else if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | ||||||||||
174 | E = PE->getSubExpr(); | ||||||||||
175 | } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { | ||||||||||
176 | assert(UO->getOpcode() == UO_Extension)((UO->getOpcode() == UO_Extension) ? static_cast<void> (0) : __assert_fail ("UO->getOpcode() == UO_Extension", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 176, __PRETTY_FUNCTION__)); | ||||||||||
177 | E = UO->getSubExpr(); | ||||||||||
178 | } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) { | ||||||||||
179 | E = GSE->getResultExpr(); | ||||||||||
180 | } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) { | ||||||||||
181 | E = CE->getChosenSubExpr(); | ||||||||||
182 | } else { | ||||||||||
183 | llvm_unreachable("unexpected expr in array compound literal init")::llvm::llvm_unreachable_internal("unexpected expr in array compound literal init" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 183); | ||||||||||
184 | } | ||||||||||
185 | } | ||||||||||
186 | } | ||||||||||
187 | |||||||||||
188 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, | ||||||||||
189 | Sema &S) { | ||||||||||
190 | // Get the length of the string as parsed. | ||||||||||
191 | auto *ConstantArrayTy = | ||||||||||
192 | cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe()); | ||||||||||
193 | uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue(); | ||||||||||
194 | |||||||||||
195 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { | ||||||||||
196 | // C99 6.7.8p14. We have an array of character type with unknown size | ||||||||||
197 | // being initialized to a string literal. | ||||||||||
198 | llvm::APInt ConstVal(32, StrLength); | ||||||||||
199 | // Return a new array type (C99 6.7.8p22). | ||||||||||
200 | DeclT = S.Context.getConstantArrayType(IAT->getElementType(), | ||||||||||
201 | ConstVal, nullptr, | ||||||||||
202 | ArrayType::Normal, 0); | ||||||||||
203 | updateStringLiteralType(Str, DeclT); | ||||||||||
204 | return; | ||||||||||
205 | } | ||||||||||
206 | |||||||||||
207 | const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); | ||||||||||
208 | |||||||||||
209 | // We have an array of character type with known size. However, | ||||||||||
210 | // the size may be smaller or larger than the string we are initializing. | ||||||||||
211 | // FIXME: Avoid truncation for 64-bit length strings. | ||||||||||
212 | if (S.getLangOpts().CPlusPlus) { | ||||||||||
213 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) { | ||||||||||
214 | // For Pascal strings it's OK to strip off the terminating null character, | ||||||||||
215 | // so the example below is valid: | ||||||||||
216 | // | ||||||||||
217 | // unsigned char a[2] = "\pa"; | ||||||||||
218 | if (SL->isPascal()) | ||||||||||
219 | StrLength--; | ||||||||||
220 | } | ||||||||||
221 | |||||||||||
222 | // [dcl.init.string]p2 | ||||||||||
223 | if (StrLength > CAT->getSize().getZExtValue()) | ||||||||||
224 | S.Diag(Str->getBeginLoc(), | ||||||||||
225 | diag::err_initializer_string_for_char_array_too_long) | ||||||||||
226 | << Str->getSourceRange(); | ||||||||||
227 | } else { | ||||||||||
228 | // C99 6.7.8p14. | ||||||||||
229 | if (StrLength-1 > CAT->getSize().getZExtValue()) | ||||||||||
230 | S.Diag(Str->getBeginLoc(), | ||||||||||
231 | diag::ext_initializer_string_for_char_array_too_long) | ||||||||||
232 | << Str->getSourceRange(); | ||||||||||
233 | } | ||||||||||
234 | |||||||||||
235 | // Set the type to the actual size that we are initializing. If we have | ||||||||||
236 | // something like: | ||||||||||
237 | // char x[1] = "foo"; | ||||||||||
238 | // then this will set the string literal's type to char[1]. | ||||||||||
239 | updateStringLiteralType(Str, DeclT); | ||||||||||
240 | } | ||||||||||
241 | |||||||||||
242 | //===----------------------------------------------------------------------===// | ||||||||||
243 | // Semantic checking for initializer lists. | ||||||||||
244 | //===----------------------------------------------------------------------===// | ||||||||||
245 | |||||||||||
246 | namespace { | ||||||||||
247 | |||||||||||
248 | /// Semantic checking for initializer lists. | ||||||||||
249 | /// | ||||||||||
250 | /// The InitListChecker class contains a set of routines that each | ||||||||||
251 | /// handle the initialization of a certain kind of entity, e.g., | ||||||||||
252 | /// arrays, vectors, struct/union types, scalars, etc. The | ||||||||||
253 | /// InitListChecker itself performs a recursive walk of the subobject | ||||||||||
254 | /// structure of the type to be initialized, while stepping through | ||||||||||
255 | /// the initializer list one element at a time. The IList and Index | ||||||||||
256 | /// parameters to each of the Check* routines contain the active | ||||||||||
257 | /// (syntactic) initializer list and the index into that initializer | ||||||||||
258 | /// list that represents the current initializer. Each routine is | ||||||||||
259 | /// responsible for moving that Index forward as it consumes elements. | ||||||||||
260 | /// | ||||||||||
261 | /// Each Check* routine also has a StructuredList/StructuredIndex | ||||||||||
262 | /// arguments, which contains the current "structured" (semantic) | ||||||||||
263 | /// initializer list and the index into that initializer list where we | ||||||||||
264 | /// are copying initializers as we map them over to the semantic | ||||||||||
265 | /// list. Once we have completed our recursive walk of the subobject | ||||||||||
266 | /// structure, we will have constructed a full semantic initializer | ||||||||||
267 | /// list. | ||||||||||
268 | /// | ||||||||||
269 | /// C99 designators cause changes in the initializer list traversal, | ||||||||||
270 | /// because they make the initialization "jump" into a specific | ||||||||||
271 | /// subobject and then continue the initialization from that | ||||||||||
272 | /// point. CheckDesignatedInitializer() recursively steps into the | ||||||||||
273 | /// designated subobject and manages backing out the recursion to | ||||||||||
274 | /// initialize the subobjects after the one designated. | ||||||||||
275 | /// | ||||||||||
276 | /// If an initializer list contains any designators, we build a placeholder | ||||||||||
277 | /// structured list even in 'verify only' mode, so that we can track which | ||||||||||
278 | /// elements need 'empty' initializtion. | ||||||||||
279 | class InitListChecker { | ||||||||||
280 | Sema &SemaRef; | ||||||||||
281 | bool hadError = false; | ||||||||||
282 | bool VerifyOnly; // No diagnostics. | ||||||||||
283 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. | ||||||||||
284 | bool InOverloadResolution; | ||||||||||
285 | InitListExpr *FullyStructuredList = nullptr; | ||||||||||
286 | NoInitExpr *DummyExpr = nullptr; | ||||||||||
287 | |||||||||||
288 | NoInitExpr *getDummyInit() { | ||||||||||
289 | if (!DummyExpr) | ||||||||||
290 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); | ||||||||||
291 | return DummyExpr; | ||||||||||
292 | } | ||||||||||
293 | |||||||||||
294 | void CheckImplicitInitList(const InitializedEntity &Entity, | ||||||||||
295 | InitListExpr *ParentIList, QualType T, | ||||||||||
296 | unsigned &Index, InitListExpr *StructuredList, | ||||||||||
297 | unsigned &StructuredIndex); | ||||||||||
298 | void CheckExplicitInitList(const InitializedEntity &Entity, | ||||||||||
299 | InitListExpr *IList, QualType &T, | ||||||||||
300 | InitListExpr *StructuredList, | ||||||||||
301 | bool TopLevelObject = false); | ||||||||||
302 | void CheckListElementTypes(const InitializedEntity &Entity, | ||||||||||
303 | InitListExpr *IList, QualType &DeclType, | ||||||||||
304 | bool SubobjectIsDesignatorContext, | ||||||||||
305 | unsigned &Index, | ||||||||||
306 | InitListExpr *StructuredList, | ||||||||||
307 | unsigned &StructuredIndex, | ||||||||||
308 | bool TopLevelObject = false); | ||||||||||
309 | void CheckSubElementType(const InitializedEntity &Entity, | ||||||||||
310 | InitListExpr *IList, QualType ElemType, | ||||||||||
311 | unsigned &Index, | ||||||||||
312 | InitListExpr *StructuredList, | ||||||||||
313 | unsigned &StructuredIndex); | ||||||||||
314 | void CheckComplexType(const InitializedEntity &Entity, | ||||||||||
315 | InitListExpr *IList, QualType DeclType, | ||||||||||
316 | unsigned &Index, | ||||||||||
317 | InitListExpr *StructuredList, | ||||||||||
318 | unsigned &StructuredIndex); | ||||||||||
319 | void CheckScalarType(const InitializedEntity &Entity, | ||||||||||
320 | InitListExpr *IList, QualType DeclType, | ||||||||||
321 | unsigned &Index, | ||||||||||
322 | InitListExpr *StructuredList, | ||||||||||
323 | unsigned &StructuredIndex); | ||||||||||
324 | void CheckReferenceType(const InitializedEntity &Entity, | ||||||||||
325 | InitListExpr *IList, QualType DeclType, | ||||||||||
326 | unsigned &Index, | ||||||||||
327 | InitListExpr *StructuredList, | ||||||||||
328 | unsigned &StructuredIndex); | ||||||||||
329 | void CheckVectorType(const InitializedEntity &Entity, | ||||||||||
330 | InitListExpr *IList, QualType DeclType, unsigned &Index, | ||||||||||
331 | InitListExpr *StructuredList, | ||||||||||
332 | unsigned &StructuredIndex); | ||||||||||
333 | void CheckStructUnionTypes(const InitializedEntity &Entity, | ||||||||||
334 | InitListExpr *IList, QualType DeclType, | ||||||||||
335 | CXXRecordDecl::base_class_range Bases, | ||||||||||
336 | RecordDecl::field_iterator Field, | ||||||||||
337 | bool SubobjectIsDesignatorContext, unsigned &Index, | ||||||||||
338 | InitListExpr *StructuredList, | ||||||||||
339 | unsigned &StructuredIndex, | ||||||||||
340 | bool TopLevelObject = false); | ||||||||||
341 | void CheckArrayType(const InitializedEntity &Entity, | ||||||||||
342 | InitListExpr *IList, QualType &DeclType, | ||||||||||
343 | llvm::APSInt elementIndex, | ||||||||||
344 | bool SubobjectIsDesignatorContext, unsigned &Index, | ||||||||||
345 | InitListExpr *StructuredList, | ||||||||||
346 | unsigned &StructuredIndex); | ||||||||||
347 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, | ||||||||||
348 | InitListExpr *IList, DesignatedInitExpr *DIE, | ||||||||||
349 | unsigned DesigIdx, | ||||||||||
350 | QualType &CurrentObjectType, | ||||||||||
351 | RecordDecl::field_iterator *NextField, | ||||||||||
352 | llvm::APSInt *NextElementIndex, | ||||||||||
353 | unsigned &Index, | ||||||||||
354 | InitListExpr *StructuredList, | ||||||||||
355 | unsigned &StructuredIndex, | ||||||||||
356 | bool FinishSubobjectInit, | ||||||||||
357 | bool TopLevelObject); | ||||||||||
358 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | ||||||||||
359 | QualType CurrentObjectType, | ||||||||||
360 | InitListExpr *StructuredList, | ||||||||||
361 | unsigned StructuredIndex, | ||||||||||
362 | SourceRange InitRange, | ||||||||||
363 | bool IsFullyOverwritten = false); | ||||||||||
364 | void UpdateStructuredListElement(InitListExpr *StructuredList, | ||||||||||
365 | unsigned &StructuredIndex, | ||||||||||
366 | Expr *expr); | ||||||||||
367 | InitListExpr *createInitListExpr(QualType CurrentObjectType, | ||||||||||
368 | SourceRange InitRange, | ||||||||||
369 | unsigned ExpectedNumInits); | ||||||||||
370 | int numArrayElements(QualType DeclType); | ||||||||||
371 | int numStructUnionElements(QualType DeclType); | ||||||||||
372 | |||||||||||
373 | ExprResult PerformEmptyInit(SourceLocation Loc, | ||||||||||
374 | const InitializedEntity &Entity); | ||||||||||
375 | |||||||||||
376 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. | ||||||||||
377 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, | ||||||||||
378 | bool FullyOverwritten = true) { | ||||||||||
379 | // Overriding an initializer via a designator is valid with C99 designated | ||||||||||
380 | // initializers, but ill-formed with C++20 designated initializers. | ||||||||||
381 | unsigned DiagID = SemaRef.getLangOpts().CPlusPlus | ||||||||||
382 | ? diag::ext_initializer_overrides | ||||||||||
383 | : diag::warn_initializer_overrides; | ||||||||||
384 | |||||||||||
385 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { | ||||||||||
386 | // In overload resolution, we have to strictly enforce the rules, and so | ||||||||||
387 | // don't allow any overriding of prior initializers. This matters for a | ||||||||||
388 | // case such as: | ||||||||||
389 | // | ||||||||||
390 | // union U { int a, b; }; | ||||||||||
391 | // struct S { int a, b; }; | ||||||||||
392 | // void f(U), f(S); | ||||||||||
393 | // | ||||||||||
394 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For | ||||||||||
395 | // consistency, we disallow all overriding of prior initializers in | ||||||||||
396 | // overload resolution, not only overriding of union members. | ||||||||||
397 | hadError = true; | ||||||||||
398 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { | ||||||||||
399 | // If we'll be keeping around the old initializer but overwriting part of | ||||||||||
400 | // the object it initialized, and that object is not trivially | ||||||||||
401 | // destructible, this can leak. Don't allow that, not even as an | ||||||||||
402 | // extension. | ||||||||||
403 | // | ||||||||||
404 | // FIXME: It might be reasonable to allow this in cases where the part of | ||||||||||
405 | // the initializer that we're overriding has trivial destruction. | ||||||||||
406 | DiagID = diag::err_initializer_overrides_destructed; | ||||||||||
407 | } else if (!OldInit->getSourceRange().isValid()) { | ||||||||||
408 | // We need to check on source range validity because the previous | ||||||||||
409 | // initializer does not have to be an explicit initializer. e.g., | ||||||||||
410 | // | ||||||||||
411 | // struct P { int a, b; }; | ||||||||||
412 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; | ||||||||||
413 | // | ||||||||||
414 | // There is an overwrite taking place because the first braced initializer | ||||||||||
415 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). | ||||||||||
416 | // | ||||||||||
417 | // Such overwrites are harmless, so we don't diagnose them. (Note that in | ||||||||||
418 | // C++, this cannot be reached unless we've already seen and diagnosed a | ||||||||||
419 | // different conformance issue, such as a mixture of designated and | ||||||||||
420 | // non-designated initializers or a multi-level designator.) | ||||||||||
421 | return; | ||||||||||
422 | } | ||||||||||
423 | |||||||||||
424 | if (!VerifyOnly) { | ||||||||||
425 | SemaRef.Diag(NewInitRange.getBegin(), DiagID) | ||||||||||
426 | << NewInitRange << FullyOverwritten << OldInit->getType(); | ||||||||||
427 | SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer) | ||||||||||
428 | << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten) | ||||||||||
429 | << OldInit->getSourceRange(); | ||||||||||
430 | } | ||||||||||
431 | } | ||||||||||
432 | |||||||||||
433 | // Explanation on the "FillWithNoInit" mode: | ||||||||||
434 | // | ||||||||||
435 | // Assume we have the following definitions (Case#1): | ||||||||||
436 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; | ||||||||||
437 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; | ||||||||||
438 | // | ||||||||||
439 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the | ||||||||||
440 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". | ||||||||||
441 | // | ||||||||||
442 | // But if we have (Case#2): | ||||||||||
443 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; | ||||||||||
444 | // | ||||||||||
445 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the | ||||||||||
446 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". | ||||||||||
447 | // | ||||||||||
448 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" | ||||||||||
449 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty | ||||||||||
450 | // initializers but with special "NoInitExpr" place holders, which tells the | ||||||||||
451 | // CodeGen not to generate any initializers for these parts. | ||||||||||
452 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, | ||||||||||
453 | const InitializedEntity &ParentEntity, | ||||||||||
454 | InitListExpr *ILE, bool &RequiresSecondPass, | ||||||||||
455 | bool FillWithNoInit); | ||||||||||
456 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | ||||||||||
457 | const InitializedEntity &ParentEntity, | ||||||||||
458 | InitListExpr *ILE, bool &RequiresSecondPass, | ||||||||||
459 | bool FillWithNoInit = false); | ||||||||||
460 | void FillInEmptyInitializations(const InitializedEntity &Entity, | ||||||||||
461 | InitListExpr *ILE, bool &RequiresSecondPass, | ||||||||||
462 | InitListExpr *OuterILE, unsigned OuterIndex, | ||||||||||
463 | bool FillWithNoInit = false); | ||||||||||
464 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, | ||||||||||
465 | Expr *InitExpr, FieldDecl *Field, | ||||||||||
466 | bool TopLevelObject); | ||||||||||
467 | void CheckEmptyInitializable(const InitializedEntity &Entity, | ||||||||||
468 | SourceLocation Loc); | ||||||||||
469 | |||||||||||
470 | public: | ||||||||||
471 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, | ||||||||||
472 | QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid, | ||||||||||
473 | bool InOverloadResolution = false); | ||||||||||
474 | bool HadError() { return hadError; } | ||||||||||
475 | |||||||||||
476 | // Retrieves the fully-structured initializer list used for | ||||||||||
477 | // semantic analysis and code generation. | ||||||||||
478 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } | ||||||||||
479 | }; | ||||||||||
480 | |||||||||||
481 | } // end anonymous namespace | ||||||||||
482 | |||||||||||
483 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, | ||||||||||
484 | const InitializedEntity &Entity) { | ||||||||||
485 | InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc, | ||||||||||
486 | true); | ||||||||||
487 | MultiExprArg SubInit; | ||||||||||
488 | Expr *InitExpr; | ||||||||||
489 | InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc); | ||||||||||
490 | |||||||||||
491 | // C++ [dcl.init.aggr]p7: | ||||||||||
492 | // If there are fewer initializer-clauses in the list than there are | ||||||||||
493 | // members in the aggregate, then each member not explicitly initialized | ||||||||||
494 | // ... | ||||||||||
495 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && | ||||||||||
496 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); | ||||||||||
497 | if (EmptyInitList) { | ||||||||||
498 | // C++1y / DR1070: | ||||||||||
499 | // shall be initialized [...] from an empty initializer list. | ||||||||||
500 | // | ||||||||||
501 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 | ||||||||||
502 | // does not have useful semantics for initialization from an init list. | ||||||||||
503 | // We treat this as copy-initialization, because aggregate initialization | ||||||||||
504 | // always performs copy-initialization on its elements. | ||||||||||
505 | // | ||||||||||
506 | // Only do this if we're initializing a class type, to avoid filling in | ||||||||||
507 | // the initializer list where possible. | ||||||||||
508 | InitExpr = VerifyOnly ? &DummyInitList : new (SemaRef.Context) | ||||||||||
509 | InitListExpr(SemaRef.Context, Loc, None, Loc); | ||||||||||
510 | InitExpr->setType(SemaRef.Context.VoidTy); | ||||||||||
511 | SubInit = InitExpr; | ||||||||||
512 | Kind = InitializationKind::CreateCopy(Loc, Loc); | ||||||||||
513 | } else { | ||||||||||
514 | // C++03: | ||||||||||
515 | // shall be value-initialized. | ||||||||||
516 | } | ||||||||||
517 | |||||||||||
518 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); | ||||||||||
519 | // libstdc++4.6 marks the vector default constructor as explicit in | ||||||||||
520 | // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case. | ||||||||||
521 | // stlport does so too. Look for std::__debug for libstdc++, and for | ||||||||||
522 | // std:: for stlport. This is effectively a compiler-side implementation of | ||||||||||
523 | // LWG2193. | ||||||||||
524 | if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() == | ||||||||||
525 | InitializationSequence::FK_ExplicitConstructor) { | ||||||||||
526 | OverloadCandidateSet::iterator Best; | ||||||||||
527 | OverloadingResult O = | ||||||||||
528 | InitSeq.getFailedCandidateSet() | ||||||||||
529 | .BestViableFunction(SemaRef, Kind.getLocation(), Best); | ||||||||||
530 | (void)O; | ||||||||||
531 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 531, __PRETTY_FUNCTION__)); | ||||||||||
532 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | ||||||||||
533 | CXXRecordDecl *R = CtorDecl->getParent(); | ||||||||||
534 | |||||||||||
535 | if (CtorDecl->getMinRequiredArguments() == 0 && | ||||||||||
536 | CtorDecl->isExplicit() && R->getDeclName() && | ||||||||||
537 | SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) { | ||||||||||
538 | bool IsInStd = false; | ||||||||||
539 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext()); | ||||||||||
540 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) { | ||||||||||
541 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND)) | ||||||||||
542 | IsInStd = true; | ||||||||||
543 | } | ||||||||||
544 | |||||||||||
545 | if (IsInStd && llvm::StringSwitch<bool>(R->getName()) | ||||||||||
546 | .Cases("basic_string", "deque", "forward_list", true) | ||||||||||
547 | .Cases("list", "map", "multimap", "multiset", true) | ||||||||||
548 | .Cases("priority_queue", "queue", "set", "stack", true) | ||||||||||
549 | .Cases("unordered_map", "unordered_set", "vector", true) | ||||||||||
550 | .Default(false)) { | ||||||||||
551 | InitSeq.InitializeFrom( | ||||||||||
552 | SemaRef, Entity, | ||||||||||
553 | InitializationKind::CreateValue(Loc, Loc, Loc, true), | ||||||||||
554 | MultiExprArg(), /*TopLevelOfInitList=*/false, | ||||||||||
555 | TreatUnavailableAsInvalid); | ||||||||||
556 | // Emit a warning for this. System header warnings aren't shown | ||||||||||
557 | // by default, but people working on system headers should see it. | ||||||||||
558 | if (!VerifyOnly) { | ||||||||||
559 | SemaRef.Diag(CtorDecl->getLocation(), | ||||||||||
560 | diag::warn_invalid_initializer_from_system_header); | ||||||||||
561 | if (Entity.getKind() == InitializedEntity::EK_Member) | ||||||||||
562 | SemaRef.Diag(Entity.getDecl()->getLocation(), | ||||||||||
563 | diag::note_used_in_initialization_here); | ||||||||||
564 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) | ||||||||||
565 | SemaRef.Diag(Loc, diag::note_used_in_initialization_here); | ||||||||||
566 | } | ||||||||||
567 | } | ||||||||||
568 | } | ||||||||||
569 | } | ||||||||||
570 | if (!InitSeq) { | ||||||||||
571 | if (!VerifyOnly) { | ||||||||||
572 | InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit); | ||||||||||
573 | if (Entity.getKind() == InitializedEntity::EK_Member) | ||||||||||
574 | SemaRef.Diag(Entity.getDecl()->getLocation(), | ||||||||||
575 | diag::note_in_omitted_aggregate_initializer) | ||||||||||
576 | << /*field*/1 << Entity.getDecl(); | ||||||||||
577 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { | ||||||||||
578 | bool IsTrailingArrayNewMember = | ||||||||||
579 | Entity.getParent() && | ||||||||||
580 | Entity.getParent()->isVariableLengthArrayNew(); | ||||||||||
581 | SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer) | ||||||||||
582 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) | ||||||||||
583 | << Entity.getElementIndex(); | ||||||||||
584 | } | ||||||||||
585 | } | ||||||||||
586 | hadError = true; | ||||||||||
587 | return ExprError(); | ||||||||||
588 | } | ||||||||||
589 | |||||||||||
590 | return VerifyOnly ? ExprResult() | ||||||||||
591 | : InitSeq.Perform(SemaRef, Entity, Kind, SubInit); | ||||||||||
592 | } | ||||||||||
593 | |||||||||||
594 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, | ||||||||||
595 | SourceLocation Loc) { | ||||||||||
596 | // If we're building a fully-structured list, we'll check this at the end | ||||||||||
597 | // once we know which elements are actually initialized. Otherwise, we know | ||||||||||
598 | // that there are no designators so we can just check now. | ||||||||||
599 | if (FullyStructuredList) | ||||||||||
600 | return; | ||||||||||
601 | PerformEmptyInit(Loc, Entity); | ||||||||||
602 | } | ||||||||||
603 | |||||||||||
604 | void InitListChecker::FillInEmptyInitForBase( | ||||||||||
605 | unsigned Init, const CXXBaseSpecifier &Base, | ||||||||||
606 | const InitializedEntity &ParentEntity, InitListExpr *ILE, | ||||||||||
607 | bool &RequiresSecondPass, bool FillWithNoInit) { | ||||||||||
608 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | ||||||||||
609 | SemaRef.Context, &Base, false, &ParentEntity); | ||||||||||
610 | |||||||||||
611 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { | ||||||||||
612 | ExprResult BaseInit = FillWithNoInit | ||||||||||
613 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) | ||||||||||
614 | : PerformEmptyInit(ILE->getEndLoc(), BaseEntity); | ||||||||||
615 | if (BaseInit.isInvalid()) { | ||||||||||
616 | hadError = true; | ||||||||||
617 | return; | ||||||||||
618 | } | ||||||||||
619 | |||||||||||
620 | if (!VerifyOnly) { | ||||||||||
621 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 621, __PRETTY_FUNCTION__)); | ||||||||||
622 | ILE->setInit(Init, BaseInit.getAs<Expr>()); | ||||||||||
623 | } | ||||||||||
624 | } else if (InitListExpr *InnerILE = | ||||||||||
625 | dyn_cast<InitListExpr>(ILE->getInit(Init))) { | ||||||||||
626 | FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass, | ||||||||||
627 | ILE, Init, FillWithNoInit); | ||||||||||
628 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | ||||||||||
629 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | ||||||||||
630 | FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(), | ||||||||||
631 | RequiresSecondPass, ILE, Init, | ||||||||||
632 | /*FillWithNoInit =*/true); | ||||||||||
633 | } | ||||||||||
634 | } | ||||||||||
635 | |||||||||||
636 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, | ||||||||||
637 | const InitializedEntity &ParentEntity, | ||||||||||
638 | InitListExpr *ILE, | ||||||||||
639 | bool &RequiresSecondPass, | ||||||||||
640 | bool FillWithNoInit) { | ||||||||||
641 | SourceLocation Loc = ILE->getEndLoc(); | ||||||||||
642 | unsigned NumInits = ILE->getNumInits(); | ||||||||||
643 | InitializedEntity MemberEntity | ||||||||||
644 | = InitializedEntity::InitializeMember(Field, &ParentEntity); | ||||||||||
645 | |||||||||||
646 | if (Init >= NumInits || !ILE->getInit(Init)) { | ||||||||||
647 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) | ||||||||||
648 | if (!RType->getDecl()->isUnion()) | ||||||||||
649 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 650, __PRETTY_FUNCTION__)) | ||||||||||
650 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 650, __PRETTY_FUNCTION__)); | ||||||||||
651 | |||||||||||
652 | if (FillWithNoInit) { | ||||||||||
653 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 653, __PRETTY_FUNCTION__)); | ||||||||||
654 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); | ||||||||||
655 | if (Init < NumInits) | ||||||||||
656 | ILE->setInit(Init, Filler); | ||||||||||
657 | else | ||||||||||
658 | ILE->updateInit(SemaRef.Context, Init, Filler); | ||||||||||
659 | return; | ||||||||||
660 | } | ||||||||||
661 | // C++1y [dcl.init.aggr]p7: | ||||||||||
662 | // If there are fewer initializer-clauses in the list than there are | ||||||||||
663 | // members in the aggregate, then each member not explicitly initialized | ||||||||||
664 | // shall be initialized from its brace-or-equal-initializer [...] | ||||||||||
665 | if (Field->hasInClassInitializer()) { | ||||||||||
666 | if (VerifyOnly) | ||||||||||
667 | return; | ||||||||||
668 | |||||||||||
669 | ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); | ||||||||||
670 | if (DIE.isInvalid()) { | ||||||||||
671 | hadError = true; | ||||||||||
672 | return; | ||||||||||
673 | } | ||||||||||
674 | SemaRef.checkInitializerLifetime(MemberEntity, DIE.get()); | ||||||||||
675 | if (Init < NumInits) | ||||||||||
676 | ILE->setInit(Init, DIE.get()); | ||||||||||
677 | else { | ||||||||||
678 | ILE->updateInit(SemaRef.Context, Init, DIE.get()); | ||||||||||
679 | RequiresSecondPass = true; | ||||||||||
680 | } | ||||||||||
681 | return; | ||||||||||
682 | } | ||||||||||
683 | |||||||||||
684 | if (Field->getType()->isReferenceType()) { | ||||||||||
685 | if (!VerifyOnly) { | ||||||||||
686 | // C++ [dcl.init.aggr]p9: | ||||||||||
687 | // If an incomplete or empty initializer-list leaves a | ||||||||||
688 | // member of reference type uninitialized, the program is | ||||||||||
689 | // ill-formed. | ||||||||||
690 | SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized) | ||||||||||
691 | << Field->getType() | ||||||||||
692 | << ILE->getSyntacticForm()->getSourceRange(); | ||||||||||
693 | SemaRef.Diag(Field->getLocation(), | ||||||||||
694 | diag::note_uninit_reference_member); | ||||||||||
695 | } | ||||||||||
696 | hadError = true; | ||||||||||
697 | return; | ||||||||||
698 | } | ||||||||||
699 | |||||||||||
700 | ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity); | ||||||||||
701 | if (MemberInit.isInvalid()) { | ||||||||||
702 | hadError = true; | ||||||||||
703 | return; | ||||||||||
704 | } | ||||||||||
705 | |||||||||||
706 | if (hadError || VerifyOnly) { | ||||||||||
707 | // Do nothing | ||||||||||
708 | } else if (Init < NumInits) { | ||||||||||
709 | ILE->setInit(Init, MemberInit.getAs<Expr>()); | ||||||||||
710 | } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) { | ||||||||||
711 | // Empty initialization requires a constructor call, so | ||||||||||
712 | // extend the initializer list to include the constructor | ||||||||||
713 | // call and make a note that we'll need to take another pass | ||||||||||
714 | // through the initializer list. | ||||||||||
715 | ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>()); | ||||||||||
716 | RequiresSecondPass = true; | ||||||||||
717 | } | ||||||||||
718 | } else if (InitListExpr *InnerILE | ||||||||||
719 | = dyn_cast<InitListExpr>(ILE->getInit(Init))) { | ||||||||||
720 | FillInEmptyInitializations(MemberEntity, InnerILE, | ||||||||||
721 | RequiresSecondPass, ILE, Init, FillWithNoInit); | ||||||||||
722 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | ||||||||||
723 | dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) { | ||||||||||
724 | FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(), | ||||||||||
725 | RequiresSecondPass, ILE, Init, | ||||||||||
726 | /*FillWithNoInit =*/true); | ||||||||||
727 | } | ||||||||||
728 | } | ||||||||||
729 | |||||||||||
730 | /// Recursively replaces NULL values within the given initializer list | ||||||||||
731 | /// with expressions that perform value-initialization of the | ||||||||||
732 | /// appropriate type, and finish off the InitListExpr formation. | ||||||||||
733 | void | ||||||||||
734 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, | ||||||||||
735 | InitListExpr *ILE, | ||||||||||
736 | bool &RequiresSecondPass, | ||||||||||
737 | InitListExpr *OuterILE, | ||||||||||
738 | unsigned OuterIndex, | ||||||||||
739 | bool FillWithNoInit) { | ||||||||||
740 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 741, __PRETTY_FUNCTION__)) | ||||||||||
741 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 741, __PRETTY_FUNCTION__)); | ||||||||||
742 | |||||||||||
743 | // We don't need to do any checks when just filling NoInitExprs; that can't | ||||||||||
744 | // fail. | ||||||||||
745 | if (FillWithNoInit && VerifyOnly) | ||||||||||
746 | return; | ||||||||||
747 | |||||||||||
748 | // If this is a nested initializer list, we might have changed its contents | ||||||||||
749 | // (and therefore some of its properties, such as instantiation-dependence) | ||||||||||
750 | // while filling it in. Inform the outer initializer list so that its state | ||||||||||
751 | // can be updated to match. | ||||||||||
752 | // FIXME: We should fully build the inner initializers before constructing | ||||||||||
753 | // the outer InitListExpr instead of mutating AST nodes after they have | ||||||||||
754 | // been used as subexpressions of other nodes. | ||||||||||
755 | struct UpdateOuterILEWithUpdatedInit { | ||||||||||
756 | InitListExpr *Outer; | ||||||||||
757 | unsigned OuterIndex; | ||||||||||
758 | ~UpdateOuterILEWithUpdatedInit() { | ||||||||||
759 | if (Outer) | ||||||||||
760 | Outer->setInit(OuterIndex, Outer->getInit(OuterIndex)); | ||||||||||
761 | } | ||||||||||
762 | } UpdateOuterRAII = {OuterILE, OuterIndex}; | ||||||||||
763 | |||||||||||
764 | // A transparent ILE is not performing aggregate initialization and should | ||||||||||
765 | // not be filled in. | ||||||||||
766 | if (ILE->isTransparent()) | ||||||||||
767 | return; | ||||||||||
768 | |||||||||||
769 | if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { | ||||||||||
770 | const RecordDecl *RDecl = RType->getDecl(); | ||||||||||
771 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) | ||||||||||
772 | FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), | ||||||||||
773 | Entity, ILE, RequiresSecondPass, FillWithNoInit); | ||||||||||
774 | else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) && | ||||||||||
775 | cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) { | ||||||||||
776 | for (auto *Field : RDecl->fields()) { | ||||||||||
777 | if (Field->hasInClassInitializer()) { | ||||||||||
778 | FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass, | ||||||||||
779 | FillWithNoInit); | ||||||||||
780 | break; | ||||||||||
781 | } | ||||||||||
782 | } | ||||||||||
783 | } else { | ||||||||||
784 | // The fields beyond ILE->getNumInits() are default initialized, so in | ||||||||||
785 | // order to leave them uninitialized, the ILE is expanded and the extra | ||||||||||
786 | // fields are then filled with NoInitExpr. | ||||||||||
787 | unsigned NumElems = numStructUnionElements(ILE->getType()); | ||||||||||
788 | if (RDecl->hasFlexibleArrayMember()) | ||||||||||
789 | ++NumElems; | ||||||||||
790 | if (!VerifyOnly && ILE->getNumInits() < NumElems) | ||||||||||
791 | ILE->resizeInits(SemaRef.Context, NumElems); | ||||||||||
792 | |||||||||||
793 | unsigned Init = 0; | ||||||||||
794 | |||||||||||
795 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) { | ||||||||||
796 | for (auto &Base : CXXRD->bases()) { | ||||||||||
797 | if (hadError) | ||||||||||
798 | return; | ||||||||||
799 | |||||||||||
800 | FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass, | ||||||||||
801 | FillWithNoInit); | ||||||||||
802 | ++Init; | ||||||||||
803 | } | ||||||||||
804 | } | ||||||||||
805 | |||||||||||
806 | for (auto *Field : RDecl->fields()) { | ||||||||||
807 | if (Field->isUnnamedBitfield()) | ||||||||||
808 | continue; | ||||||||||
809 | |||||||||||
810 | if (hadError) | ||||||||||
811 | return; | ||||||||||
812 | |||||||||||
813 | FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass, | ||||||||||
814 | FillWithNoInit); | ||||||||||
815 | if (hadError) | ||||||||||
816 | return; | ||||||||||
817 | |||||||||||
818 | ++Init; | ||||||||||
819 | |||||||||||
820 | // Only look at the first initialization of a union. | ||||||||||
821 | if (RDecl->isUnion()) | ||||||||||
822 | break; | ||||||||||
823 | } | ||||||||||
824 | } | ||||||||||
825 | |||||||||||
826 | return; | ||||||||||
827 | } | ||||||||||
828 | |||||||||||
829 | QualType ElementType; | ||||||||||
830 | |||||||||||
831 | InitializedEntity ElementEntity = Entity; | ||||||||||
832 | unsigned NumInits = ILE->getNumInits(); | ||||||||||
833 | unsigned NumElements = NumInits; | ||||||||||
834 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) { | ||||||||||
835 | ElementType = AType->getElementType(); | ||||||||||
836 | if (const auto *CAType = dyn_cast<ConstantArrayType>(AType)) | ||||||||||
837 | NumElements = CAType->getSize().getZExtValue(); | ||||||||||
838 | // For an array new with an unknown bound, ask for one additional element | ||||||||||
839 | // in order to populate the array filler. | ||||||||||
840 | if (Entity.isVariableLengthArrayNew()) | ||||||||||
841 | ++NumElements; | ||||||||||
842 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | ||||||||||
843 | 0, Entity); | ||||||||||
844 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { | ||||||||||
845 | ElementType = VType->getElementType(); | ||||||||||
846 | NumElements = VType->getNumElements(); | ||||||||||
847 | ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context, | ||||||||||
848 | 0, Entity); | ||||||||||
849 | } else | ||||||||||
850 | ElementType = ILE->getType(); | ||||||||||
851 | |||||||||||
852 | bool SkipEmptyInitChecks = false; | ||||||||||
853 | for (unsigned Init = 0; Init != NumElements; ++Init) { | ||||||||||
854 | if (hadError) | ||||||||||
855 | return; | ||||||||||
856 | |||||||||||
857 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || | ||||||||||
858 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement) | ||||||||||
859 | ElementEntity.setElementIndex(Init); | ||||||||||
860 | |||||||||||
861 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) | ||||||||||
862 | return; | ||||||||||
863 | |||||||||||
864 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); | ||||||||||
865 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) | ||||||||||
866 | ILE->setInit(Init, ILE->getArrayFiller()); | ||||||||||
867 | else if (!InitExpr && !ILE->hasArrayFiller()) { | ||||||||||
868 | // In VerifyOnly mode, there's no point performing empty initialization | ||||||||||
869 | // more than once. | ||||||||||
870 | if (SkipEmptyInitChecks) | ||||||||||
871 | continue; | ||||||||||
872 | |||||||||||
873 | Expr *Filler = nullptr; | ||||||||||
874 | |||||||||||
875 | if (FillWithNoInit) | ||||||||||
876 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); | ||||||||||
877 | else { | ||||||||||
878 | ExprResult ElementInit = | ||||||||||
879 | PerformEmptyInit(ILE->getEndLoc(), ElementEntity); | ||||||||||
880 | if (ElementInit.isInvalid()) { | ||||||||||
881 | hadError = true; | ||||||||||
882 | return; | ||||||||||
883 | } | ||||||||||
884 | |||||||||||
885 | Filler = ElementInit.getAs<Expr>(); | ||||||||||
886 | } | ||||||||||
887 | |||||||||||
888 | if (hadError) { | ||||||||||
889 | // Do nothing | ||||||||||
890 | } else if (VerifyOnly) { | ||||||||||
891 | SkipEmptyInitChecks = true; | ||||||||||
892 | } else if (Init < NumInits) { | ||||||||||
893 | // For arrays, just set the expression used for value-initialization | ||||||||||
894 | // of the "holes" in the array. | ||||||||||
895 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) | ||||||||||
896 | ILE->setArrayFiller(Filler); | ||||||||||
897 | else | ||||||||||
898 | ILE->setInit(Init, Filler); | ||||||||||
899 | } else { | ||||||||||
900 | // For arrays, just set the expression used for value-initialization | ||||||||||
901 | // of the rest of elements and exit. | ||||||||||
902 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { | ||||||||||
903 | ILE->setArrayFiller(Filler); | ||||||||||
904 | return; | ||||||||||
905 | } | ||||||||||
906 | |||||||||||
907 | if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) { | ||||||||||
908 | // Empty initialization requires a constructor call, so | ||||||||||
909 | // extend the initializer list to include the constructor | ||||||||||
910 | // call and make a note that we'll need to take another pass | ||||||||||
911 | // through the initializer list. | ||||||||||
912 | ILE->updateInit(SemaRef.Context, Init, Filler); | ||||||||||
913 | RequiresSecondPass = true; | ||||||||||
914 | } | ||||||||||
915 | } | ||||||||||
916 | } else if (InitListExpr *InnerILE | ||||||||||
917 | = dyn_cast_or_null<InitListExpr>(InitExpr)) { | ||||||||||
918 | FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass, | ||||||||||
919 | ILE, Init, FillWithNoInit); | ||||||||||
920 | } else if (DesignatedInitUpdateExpr *InnerDIUE = | ||||||||||
921 | dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) { | ||||||||||
922 | FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(), | ||||||||||
923 | RequiresSecondPass, ILE, Init, | ||||||||||
924 | /*FillWithNoInit =*/true); | ||||||||||
925 | } | ||||||||||
926 | } | ||||||||||
927 | } | ||||||||||
928 | |||||||||||
929 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { | ||||||||||
930 | for (const Stmt *Init : *IL) | ||||||||||
931 | if (Init && isa<DesignatedInitExpr>(Init)) | ||||||||||
932 | return true; | ||||||||||
933 | return false; | ||||||||||
934 | } | ||||||||||
935 | |||||||||||
936 | InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity, | ||||||||||
937 | InitListExpr *IL, QualType &T, bool VerifyOnly, | ||||||||||
938 | bool TreatUnavailableAsInvalid, | ||||||||||
939 | bool InOverloadResolution) | ||||||||||
940 | : SemaRef(S), VerifyOnly(VerifyOnly), | ||||||||||
941 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), | ||||||||||
942 | InOverloadResolution(InOverloadResolution) { | ||||||||||
943 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { | ||||||||||
944 | FullyStructuredList = | ||||||||||
945 | createInitListExpr(T, IL->getSourceRange(), IL->getNumInits()); | ||||||||||
946 | |||||||||||
947 | // FIXME: Check that IL isn't already the semantic form of some other | ||||||||||
948 | // InitListExpr. If it is, we'd create a broken AST. | ||||||||||
949 | if (!VerifyOnly) | ||||||||||
950 | FullyStructuredList->setSyntacticForm(IL); | ||||||||||
951 | } | ||||||||||
952 | |||||||||||
953 | CheckExplicitInitList(Entity, IL, T, FullyStructuredList, | ||||||||||
954 | /*TopLevelObject=*/true); | ||||||||||
955 | |||||||||||
956 | if (!hadError && FullyStructuredList) { | ||||||||||
957 | bool RequiresSecondPass = false; | ||||||||||
958 | FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass, | ||||||||||
959 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); | ||||||||||
960 | if (RequiresSecondPass && !hadError) | ||||||||||
961 | FillInEmptyInitializations(Entity, FullyStructuredList, | ||||||||||
962 | RequiresSecondPass, nullptr, 0); | ||||||||||
963 | } | ||||||||||
964 | } | ||||||||||
965 | |||||||||||
966 | int InitListChecker::numArrayElements(QualType DeclType) { | ||||||||||
967 | // FIXME: use a proper constant | ||||||||||
968 | int maxElements = 0x7FFFFFFF; | ||||||||||
969 | if (const ConstantArrayType *CAT = | ||||||||||
970 | SemaRef.Context.getAsConstantArrayType(DeclType)) { | ||||||||||
971 | maxElements = static_cast<int>(CAT->getSize().getZExtValue()); | ||||||||||
972 | } | ||||||||||
973 | return maxElements; | ||||||||||
974 | } | ||||||||||
975 | |||||||||||
976 | int InitListChecker::numStructUnionElements(QualType DeclType) { | ||||||||||
977 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | ||||||||||
978 | int InitializableMembers = 0; | ||||||||||
979 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl)) | ||||||||||
980 | InitializableMembers += CXXRD->getNumBases(); | ||||||||||
981 | for (const auto *Field : structDecl->fields()) | ||||||||||
982 | if (!Field->isUnnamedBitfield()) | ||||||||||
983 | ++InitializableMembers; | ||||||||||
984 | |||||||||||
985 | if (structDecl->isUnion()) | ||||||||||
986 | return std::min(InitializableMembers, 1); | ||||||||||
987 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); | ||||||||||
988 | } | ||||||||||
989 | |||||||||||
990 | /// Determine whether Entity is an entity for which it is idiomatic to elide | ||||||||||
991 | /// the braces in aggregate initialization. | ||||||||||
992 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { | ||||||||||
993 | // Recursive initialization of the one and only field within an aggregate | ||||||||||
994 | // class is considered idiomatic. This case arises in particular for | ||||||||||
995 | // initialization of std::array, where the C++ standard suggests the idiom of | ||||||||||
996 | // | ||||||||||
997 | // std::array<T, N> arr = {1, 2, 3}; | ||||||||||
998 | // | ||||||||||
999 | // (where std::array is an aggregate struct containing a single array field. | ||||||||||
1000 | |||||||||||
1001 | // FIXME: Should aggregate initialization of a struct with a single | ||||||||||
1002 | // base class and no members also suppress the warning? | ||||||||||
1003 | if (Entity.getKind() != InitializedEntity::EK_Member || !Entity.getParent()) | ||||||||||
1004 | return false; | ||||||||||
1005 | |||||||||||
1006 | auto *ParentRD = | ||||||||||
1007 | Entity.getParent()->getType()->castAs<RecordType>()->getDecl(); | ||||||||||
1008 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) | ||||||||||
1009 | if (CXXRD->getNumBases()) | ||||||||||
1010 | return false; | ||||||||||
1011 | |||||||||||
1012 | auto FieldIt = ParentRD->field_begin(); | ||||||||||
1013 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1014, __PRETTY_FUNCTION__)) | ||||||||||
1014 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1014, __PRETTY_FUNCTION__)); | ||||||||||
1015 | return ++FieldIt == ParentRD->field_end(); | ||||||||||
1016 | } | ||||||||||
1017 | |||||||||||
1018 | /// Check whether the range of the initializer \p ParentIList from element | ||||||||||
1019 | /// \p Index onwards can be used to initialize an object of type \p T. Update | ||||||||||
1020 | /// \p Index to indicate how many elements of the list were consumed. | ||||||||||
1021 | /// | ||||||||||
1022 | /// This also fills in \p StructuredList, from element \p StructuredIndex | ||||||||||
1023 | /// onwards, with the fully-braced, desugared form of the initialization. | ||||||||||
1024 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, | ||||||||||
1025 | InitListExpr *ParentIList, | ||||||||||
1026 | QualType T, unsigned &Index, | ||||||||||
1027 | InitListExpr *StructuredList, | ||||||||||
1028 | unsigned &StructuredIndex) { | ||||||||||
1029 | int maxElements = 0; | ||||||||||
1030 | |||||||||||
1031 | if (T->isArrayType()) | ||||||||||
1032 | maxElements = numArrayElements(T); | ||||||||||
1033 | else if (T->isRecordType()) | ||||||||||
1034 | maxElements = numStructUnionElements(T); | ||||||||||
1035 | else if (T->isVectorType()) | ||||||||||
1036 | maxElements = T->castAs<VectorType>()->getNumElements(); | ||||||||||
1037 | else | ||||||||||
1038 | llvm_unreachable("CheckImplicitInitList(): Illegal type")::llvm::llvm_unreachable_internal("CheckImplicitInitList(): Illegal type" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1038); | ||||||||||
1039 | |||||||||||
1040 | if (maxElements == 0) { | ||||||||||
1041 | if (!VerifyOnly) | ||||||||||
1042 | SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(), | ||||||||||
1043 | diag::err_implicit_empty_initializer); | ||||||||||
1044 | ++Index; | ||||||||||
1045 | hadError = true; | ||||||||||
1046 | return; | ||||||||||
1047 | } | ||||||||||
1048 | |||||||||||
1049 | // Build a structured initializer list corresponding to this subobject. | ||||||||||
1050 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( | ||||||||||
1051 | ParentIList, Index, T, StructuredList, StructuredIndex, | ||||||||||
1052 | SourceRange(ParentIList->getInit(Index)->getBeginLoc(), | ||||||||||
1053 | ParentIList->getSourceRange().getEnd())); | ||||||||||
1054 | unsigned StructuredSubobjectInitIndex = 0; | ||||||||||
1055 | |||||||||||
1056 | // Check the element types and build the structural subobject. | ||||||||||
1057 | unsigned StartIndex = Index; | ||||||||||
1058 | CheckListElementTypes(Entity, ParentIList, T, | ||||||||||
1059 | /*SubobjectIsDesignatorContext=*/false, Index, | ||||||||||
1060 | StructuredSubobjectInitList, | ||||||||||
1061 | StructuredSubobjectInitIndex); | ||||||||||
1062 | |||||||||||
1063 | if (StructuredSubobjectInitList) { | ||||||||||
1064 | StructuredSubobjectInitList->setType(T); | ||||||||||
1065 | |||||||||||
1066 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); | ||||||||||
1067 | // Update the structured sub-object initializer so that it's ending | ||||||||||
1068 | // range corresponds with the end of the last initializer it used. | ||||||||||
1069 | if (EndIndex < ParentIList->getNumInits() && | ||||||||||
1070 | ParentIList->getInit(EndIndex)) { | ||||||||||
1071 | SourceLocation EndLoc | ||||||||||
1072 | = ParentIList->getInit(EndIndex)->getSourceRange().getEnd(); | ||||||||||
1073 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); | ||||||||||
1074 | } | ||||||||||
1075 | |||||||||||
1076 | // Complain about missing braces. | ||||||||||
1077 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && | ||||||||||
1078 | !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) && | ||||||||||
1079 | !isIdiomaticBraceElisionEntity(Entity)) { | ||||||||||
1080 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | ||||||||||
1081 | diag::warn_missing_braces) | ||||||||||
1082 | << StructuredSubobjectInitList->getSourceRange() | ||||||||||
1083 | << FixItHint::CreateInsertion( | ||||||||||
1084 | StructuredSubobjectInitList->getBeginLoc(), "{") | ||||||||||
1085 | << FixItHint::CreateInsertion( | ||||||||||
1086 | SemaRef.getLocForEndOfToken( | ||||||||||
1087 | StructuredSubobjectInitList->getEndLoc()), | ||||||||||
1088 | "}"); | ||||||||||
1089 | } | ||||||||||
1090 | |||||||||||
1091 | // Warn if this type won't be an aggregate in future versions of C++. | ||||||||||
1092 | auto *CXXRD = T->getAsCXXRecordDecl(); | ||||||||||
1093 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { | ||||||||||
1094 | SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(), | ||||||||||
1095 | diag::warn_cxx2a_compat_aggregate_init_with_ctors) | ||||||||||
1096 | << StructuredSubobjectInitList->getSourceRange() << T; | ||||||||||
1097 | } | ||||||||||
1098 | } | ||||||||||
1099 | } | ||||||||||
1100 | |||||||||||
1101 | /// Warn that \p Entity was of scalar type and was initialized by a | ||||||||||
1102 | /// single-element braced initializer list. | ||||||||||
1103 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, | ||||||||||
1104 | SourceRange Braces) { | ||||||||||
1105 | // Don't warn during template instantiation. If the initialization was | ||||||||||
1106 | // non-dependent, we warned during the initial parse; otherwise, the | ||||||||||
1107 | // type might not be scalar in some uses of the template. | ||||||||||
1108 | if (S.inTemplateInstantiation()) | ||||||||||
1109 | return; | ||||||||||
1110 | |||||||||||
1111 | unsigned DiagID = 0; | ||||||||||
1112 | |||||||||||
1113 | switch (Entity.getKind()) { | ||||||||||
1114 | case InitializedEntity::EK_VectorElement: | ||||||||||
1115 | case InitializedEntity::EK_ComplexElement: | ||||||||||
1116 | case InitializedEntity::EK_ArrayElement: | ||||||||||
1117 | case InitializedEntity::EK_Parameter: | ||||||||||
1118 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||||||||
1119 | case InitializedEntity::EK_Result: | ||||||||||
1120 | // Extra braces here are suspicious. | ||||||||||
1121 | DiagID = diag::warn_braces_around_scalar_init; | ||||||||||
1122 | break; | ||||||||||
1123 | |||||||||||
1124 | case InitializedEntity::EK_Member: | ||||||||||
1125 | // Warn on aggregate initialization but not on ctor init list or | ||||||||||
1126 | // default member initializer. | ||||||||||
1127 | if (Entity.getParent()) | ||||||||||
1128 | DiagID = diag::warn_braces_around_scalar_init; | ||||||||||
1129 | break; | ||||||||||
1130 | |||||||||||
1131 | case InitializedEntity::EK_Variable: | ||||||||||
1132 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
1133 | // No warning, might be direct-list-initialization. | ||||||||||
1134 | // FIXME: Should we warn for copy-list-initialization in these cases? | ||||||||||
1135 | break; | ||||||||||
1136 | |||||||||||
1137 | case InitializedEntity::EK_New: | ||||||||||
1138 | case InitializedEntity::EK_Temporary: | ||||||||||
1139 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
1140 | // No warning, braces are part of the syntax of the underlying construct. | ||||||||||
1141 | break; | ||||||||||
1142 | |||||||||||
1143 | case InitializedEntity::EK_RelatedResult: | ||||||||||
1144 | // No warning, we already warned when initializing the result. | ||||||||||
1145 | break; | ||||||||||
1146 | |||||||||||
1147 | case InitializedEntity::EK_Exception: | ||||||||||
1148 | case InitializedEntity::EK_Base: | ||||||||||
1149 | case InitializedEntity::EK_Delegating: | ||||||||||
1150 | case InitializedEntity::EK_BlockElement: | ||||||||||
1151 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||||||||
1152 | case InitializedEntity::EK_Binding: | ||||||||||
1153 | case InitializedEntity::EK_StmtExprResult: | ||||||||||
1154 | llvm_unreachable("unexpected braced scalar init")::llvm::llvm_unreachable_internal("unexpected braced scalar init" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1154); | ||||||||||
1155 | } | ||||||||||
1156 | |||||||||||
1157 | if (DiagID) { | ||||||||||
1158 | S.Diag(Braces.getBegin(), DiagID) | ||||||||||
1159 | << Braces | ||||||||||
1160 | << FixItHint::CreateRemoval(Braces.getBegin()) | ||||||||||
1161 | << FixItHint::CreateRemoval(Braces.getEnd()); | ||||||||||
1162 | } | ||||||||||
1163 | } | ||||||||||
1164 | |||||||||||
1165 | /// Check whether the initializer \p IList (that was written with explicit | ||||||||||
1166 | /// braces) can be used to initialize an object of type \p T. | ||||||||||
1167 | /// | ||||||||||
1168 | /// This also fills in \p StructuredList with the fully-braced, desugared | ||||||||||
1169 | /// form of the initialization. | ||||||||||
1170 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, | ||||||||||
1171 | InitListExpr *IList, QualType &T, | ||||||||||
1172 | InitListExpr *StructuredList, | ||||||||||
1173 | bool TopLevelObject) { | ||||||||||
1174 | unsigned Index = 0, StructuredIndex = 0; | ||||||||||
1175 | CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true, | ||||||||||
1176 | Index, StructuredList, StructuredIndex, TopLevelObject); | ||||||||||
1177 | if (StructuredList) { | ||||||||||
1178 | QualType ExprTy = T; | ||||||||||
1179 | if (!ExprTy->isArrayType()) | ||||||||||
1180 | ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context); | ||||||||||
1181 | if (!VerifyOnly) | ||||||||||
1182 | IList->setType(ExprTy); | ||||||||||
1183 | StructuredList->setType(ExprTy); | ||||||||||
1184 | } | ||||||||||
1185 | if (hadError) | ||||||||||
1186 | return; | ||||||||||
1187 | |||||||||||
1188 | // Don't complain for incomplete types, since we'll get an error elsewhere. | ||||||||||
1189 | if (Index < IList->getNumInits() && !T->isIncompleteType()) { | ||||||||||
1190 | // We have leftover initializers | ||||||||||
1191 | bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus || | ||||||||||
1192 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); | ||||||||||
1193 | hadError = ExtraInitsIsError; | ||||||||||
1194 | if (VerifyOnly) { | ||||||||||
1195 | return; | ||||||||||
1196 | } else if (StructuredIndex == 1 && | ||||||||||
1197 | IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) == | ||||||||||
1198 | SIF_None) { | ||||||||||
1199 | unsigned DK = | ||||||||||
1200 | ExtraInitsIsError | ||||||||||
1201 | ? diag::err_excess_initializers_in_char_array_initializer | ||||||||||
1202 | : diag::ext_excess_initializers_in_char_array_initializer; | ||||||||||
1203 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | ||||||||||
1204 | << IList->getInit(Index)->getSourceRange(); | ||||||||||
1205 | } else { | ||||||||||
1206 | int initKind = T->isArrayType() ? 0 : | ||||||||||
1207 | T->isVectorType() ? 1 : | ||||||||||
1208 | T->isScalarType() ? 2 : | ||||||||||
1209 | T->isUnionType() ? 3 : | ||||||||||
1210 | 4; | ||||||||||
1211 | |||||||||||
1212 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers | ||||||||||
1213 | : diag::ext_excess_initializers; | ||||||||||
1214 | SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK) | ||||||||||
1215 | << initKind << IList->getInit(Index)->getSourceRange(); | ||||||||||
1216 | } | ||||||||||
1217 | } | ||||||||||
1218 | |||||||||||
1219 | if (!VerifyOnly) { | ||||||||||
1220 | if (T->isScalarType() && IList->getNumInits() == 1 && | ||||||||||
1221 | !isa<InitListExpr>(IList->getInit(0))) | ||||||||||
1222 | warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange()); | ||||||||||
1223 | |||||||||||
1224 | // Warn if this is a class type that won't be an aggregate in future | ||||||||||
1225 | // versions of C++. | ||||||||||
1226 | auto *CXXRD = T->getAsCXXRecordDecl(); | ||||||||||
1227 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { | ||||||||||
1228 | // Don't warn if there's an equivalent default constructor that would be | ||||||||||
1229 | // used instead. | ||||||||||
1230 | bool HasEquivCtor = false; | ||||||||||
1231 | if (IList->getNumInits() == 0) { | ||||||||||
1232 | auto *CD = SemaRef.LookupDefaultConstructor(CXXRD); | ||||||||||
1233 | HasEquivCtor = CD && !CD->isDeleted(); | ||||||||||
1234 | } | ||||||||||
1235 | |||||||||||
1236 | if (!HasEquivCtor) { | ||||||||||
1237 | SemaRef.Diag(IList->getBeginLoc(), | ||||||||||
1238 | diag::warn_cxx2a_compat_aggregate_init_with_ctors) | ||||||||||
1239 | << IList->getSourceRange() << T; | ||||||||||
1240 | } | ||||||||||
1241 | } | ||||||||||
1242 | } | ||||||||||
1243 | } | ||||||||||
1244 | |||||||||||
1245 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, | ||||||||||
1246 | InitListExpr *IList, | ||||||||||
1247 | QualType &DeclType, | ||||||||||
1248 | bool SubobjectIsDesignatorContext, | ||||||||||
1249 | unsigned &Index, | ||||||||||
1250 | InitListExpr *StructuredList, | ||||||||||
1251 | unsigned &StructuredIndex, | ||||||||||
1252 | bool TopLevelObject) { | ||||||||||
1253 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { | ||||||||||
1254 | // Explicitly braced initializer for complex type can be real+imaginary | ||||||||||
1255 | // parts. | ||||||||||
1256 | CheckComplexType(Entity, IList, DeclType, Index, | ||||||||||
1257 | StructuredList, StructuredIndex); | ||||||||||
1258 | } else if (DeclType->isScalarType()) { | ||||||||||
1259 | CheckScalarType(Entity, IList, DeclType, Index, | ||||||||||
1260 | StructuredList, StructuredIndex); | ||||||||||
1261 | } else if (DeclType->isVectorType()) { | ||||||||||
1262 | CheckVectorType(Entity, IList, DeclType, Index, | ||||||||||
1263 | StructuredList, StructuredIndex); | ||||||||||
1264 | } else if (DeclType->isRecordType()) { | ||||||||||
1265 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1266, __PRETTY_FUNCTION__)) | ||||||||||
1266 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1266, __PRETTY_FUNCTION__)); | ||||||||||
1267 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | ||||||||||
1268 | auto Bases = | ||||||||||
1269 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | ||||||||||
1270 | CXXRecordDecl::base_class_iterator()); | ||||||||||
1271 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) | ||||||||||
1272 | Bases = CXXRD->bases(); | ||||||||||
1273 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(), | ||||||||||
1274 | SubobjectIsDesignatorContext, Index, StructuredList, | ||||||||||
1275 | StructuredIndex, TopLevelObject); | ||||||||||
1276 | } else if (DeclType->isArrayType()) { | ||||||||||
1277 | llvm::APSInt Zero( | ||||||||||
1278 | SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()), | ||||||||||
1279 | false); | ||||||||||
1280 | CheckArrayType(Entity, IList, DeclType, Zero, | ||||||||||
1281 | SubobjectIsDesignatorContext, Index, | ||||||||||
1282 | StructuredList, StructuredIndex); | ||||||||||
1283 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { | ||||||||||
1284 | // This type is invalid, issue a diagnostic. | ||||||||||
1285 | ++Index; | ||||||||||
1286 | if (!VerifyOnly) | ||||||||||
1287 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | ||||||||||
1288 | << DeclType; | ||||||||||
1289 | hadError = true; | ||||||||||
1290 | } else if (DeclType->isReferenceType()) { | ||||||||||
1291 | CheckReferenceType(Entity, IList, DeclType, Index, | ||||||||||
1292 | StructuredList, StructuredIndex); | ||||||||||
1293 | } else if (DeclType->isObjCObjectType()) { | ||||||||||
1294 | if (!VerifyOnly) | ||||||||||
1295 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType; | ||||||||||
1296 | hadError = true; | ||||||||||
1297 | } else if (DeclType->isOCLIntelSubgroupAVCType()) { | ||||||||||
1298 | // Checks for scalar type are sufficient for these types too. | ||||||||||
1299 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | ||||||||||
1300 | StructuredIndex); | ||||||||||
1301 | } else { | ||||||||||
1302 | if (!VerifyOnly) | ||||||||||
1303 | SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type) | ||||||||||
1304 | << DeclType; | ||||||||||
1305 | hadError = true; | ||||||||||
1306 | } | ||||||||||
1307 | } | ||||||||||
1308 | |||||||||||
1309 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, | ||||||||||
1310 | InitListExpr *IList, | ||||||||||
1311 | QualType ElemType, | ||||||||||
1312 | unsigned &Index, | ||||||||||
1313 | InitListExpr *StructuredList, | ||||||||||
1314 | unsigned &StructuredIndex) { | ||||||||||
1315 | Expr *expr = IList->getInit(Index); | ||||||||||
1316 | |||||||||||
1317 | if (ElemType->isReferenceType()) | ||||||||||
1318 | return CheckReferenceType(Entity, IList, ElemType, Index, | ||||||||||
1319 | StructuredList, StructuredIndex); | ||||||||||
1320 | |||||||||||
1321 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) { | ||||||||||
1322 | if (SubInitList->getNumInits() == 1 && | ||||||||||
1323 | IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) == | ||||||||||
1324 | SIF_None) { | ||||||||||
1325 | // FIXME: It would be more faithful and no less correct to include an | ||||||||||
1326 | // InitListExpr in the semantic form of the initializer list in this case. | ||||||||||
1327 | expr = SubInitList->getInit(0); | ||||||||||
1328 | } | ||||||||||
1329 | // Nested aggregate initialization and C++ initialization are handled later. | ||||||||||
1330 | } else if (isa<ImplicitValueInitExpr>(expr)) { | ||||||||||
1331 | // This happens during template instantiation when we see an InitListExpr | ||||||||||
1332 | // that we've already checked once. | ||||||||||
1333 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1334, __PRETTY_FUNCTION__)) | ||||||||||
1334 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1334, __PRETTY_FUNCTION__)); | ||||||||||
1335 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | ||||||||||
1336 | ++Index; | ||||||||||
1337 | return; | ||||||||||
1338 | } | ||||||||||
1339 | |||||||||||
1340 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) { | ||||||||||
1341 | // C++ [dcl.init.aggr]p2: | ||||||||||
1342 | // Each member is copy-initialized from the corresponding | ||||||||||
1343 | // initializer-clause. | ||||||||||
1344 | |||||||||||
1345 | // FIXME: Better EqualLoc? | ||||||||||
1346 | InitializationKind Kind = | ||||||||||
1347 | InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation()); | ||||||||||
1348 | |||||||||||
1349 | // Vector elements can be initialized from other vectors in which case | ||||||||||
1350 | // we need initialization entity with a type of a vector (and not a vector | ||||||||||
1351 | // element!) initializing multiple vector elements. | ||||||||||
1352 | auto TmpEntity = | ||||||||||
1353 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) | ||||||||||
1354 | ? InitializedEntity::InitializeTemporary(ElemType) | ||||||||||
1355 | : Entity; | ||||||||||
1356 | |||||||||||
1357 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, | ||||||||||
1358 | /*TopLevelOfInitList*/ true); | ||||||||||
1359 | |||||||||||
1360 | // C++14 [dcl.init.aggr]p13: | ||||||||||
1361 | // If the assignment-expression can initialize a member, the member is | ||||||||||
1362 | // initialized. Otherwise [...] brace elision is assumed | ||||||||||
1363 | // | ||||||||||
1364 | // Brace elision is never performed if the element is not an | ||||||||||
1365 | // assignment-expression. | ||||||||||
1366 | if (Seq || isa<InitListExpr>(expr)) { | ||||||||||
1367 | if (!VerifyOnly) { | ||||||||||
1368 | ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr); | ||||||||||
1369 | if (Result.isInvalid()) | ||||||||||
1370 | hadError = true; | ||||||||||
1371 | |||||||||||
1372 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||||||||
1373 | Result.getAs<Expr>()); | ||||||||||
1374 | } else if (!Seq) { | ||||||||||
1375 | hadError = true; | ||||||||||
1376 | } else if (StructuredList) { | ||||||||||
1377 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||||||||
1378 | getDummyInit()); | ||||||||||
1379 | } | ||||||||||
1380 | ++Index; | ||||||||||
1381 | return; | ||||||||||
1382 | } | ||||||||||
1383 | |||||||||||
1384 | // Fall through for subaggregate initialization | ||||||||||
1385 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { | ||||||||||
1386 | // FIXME: Need to handle atomic aggregate types with implicit init lists. | ||||||||||
1387 | return CheckScalarType(Entity, IList, ElemType, Index, | ||||||||||
1388 | StructuredList, StructuredIndex); | ||||||||||
1389 | } else if (const ArrayType *arrayType = | ||||||||||
1390 | SemaRef.Context.getAsArrayType(ElemType)) { | ||||||||||
1391 | // arrayType can be incomplete if we're initializing a flexible | ||||||||||
1392 | // array member. There's nothing we can do with the completed | ||||||||||
1393 | // type here, though. | ||||||||||
1394 | |||||||||||
1395 | if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) { | ||||||||||
1396 | // FIXME: Should we do this checking in verify-only mode? | ||||||||||
1397 | if (!VerifyOnly) | ||||||||||
1398 | CheckStringInit(expr, ElemType, arrayType, SemaRef); | ||||||||||
1399 | if (StructuredList) | ||||||||||
1400 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | ||||||||||
1401 | ++Index; | ||||||||||
1402 | return; | ||||||||||
1403 | } | ||||||||||
1404 | |||||||||||
1405 | // Fall through for subaggregate initialization. | ||||||||||
1406 | |||||||||||
1407 | } else { | ||||||||||
1408 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1409, __PRETTY_FUNCTION__)) | ||||||||||
1409 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1409, __PRETTY_FUNCTION__)); | ||||||||||
1410 | |||||||||||
1411 | // C99 6.7.8p13: | ||||||||||
1412 | // | ||||||||||
1413 | // The initializer for a structure or union object that has | ||||||||||
1414 | // automatic storage duration shall be either an initializer | ||||||||||
1415 | // list as described below, or a single expression that has | ||||||||||
1416 | // compatible structure or union type. In the latter case, the | ||||||||||
1417 | // initial value of the object, including unnamed members, is | ||||||||||
1418 | // that of the expression. | ||||||||||
1419 | ExprResult ExprRes = expr; | ||||||||||
1420 | if (SemaRef.CheckSingleAssignmentConstraints( | ||||||||||
1421 | ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) { | ||||||||||
1422 | if (ExprRes.isInvalid()) | ||||||||||
1423 | hadError = true; | ||||||||||
1424 | else { | ||||||||||
1425 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get()); | ||||||||||
1426 | if (ExprRes.isInvalid()) | ||||||||||
1427 | hadError = true; | ||||||||||
1428 | } | ||||||||||
1429 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||||||||
1430 | ExprRes.getAs<Expr>()); | ||||||||||
1431 | ++Index; | ||||||||||
1432 | return; | ||||||||||
1433 | } | ||||||||||
1434 | ExprRes.get(); | ||||||||||
1435 | // Fall through for subaggregate initialization | ||||||||||
1436 | } | ||||||||||
1437 | |||||||||||
1438 | // C++ [dcl.init.aggr]p12: | ||||||||||
1439 | // | ||||||||||
1440 | // [...] Otherwise, if the member is itself a non-empty | ||||||||||
1441 | // subaggregate, brace elision is assumed and the initializer is | ||||||||||
1442 | // considered for the initialization of the first member of | ||||||||||
1443 | // the subaggregate. | ||||||||||
1444 | // OpenCL vector initializer is handled elsewhere. | ||||||||||
1445 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || | ||||||||||
1446 | ElemType->isAggregateType()) { | ||||||||||
1447 | CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList, | ||||||||||
1448 | StructuredIndex); | ||||||||||
1449 | ++StructuredIndex; | ||||||||||
1450 | } else { | ||||||||||
1451 | if (!VerifyOnly) { | ||||||||||
1452 | // We cannot initialize this element, so let PerformCopyInitialization | ||||||||||
1453 | // produce the appropriate diagnostic. We already checked that this | ||||||||||
1454 | // initialization will fail. | ||||||||||
1455 | ExprResult Copy = | ||||||||||
1456 | SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr, | ||||||||||
1457 | /*TopLevelOfInitList=*/true); | ||||||||||
1458 | (void)Copy; | ||||||||||
1459 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1460, __PRETTY_FUNCTION__)) | ||||||||||
1460 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1460, __PRETTY_FUNCTION__)); | ||||||||||
1461 | } | ||||||||||
1462 | hadError = true; | ||||||||||
1463 | ++Index; | ||||||||||
1464 | ++StructuredIndex; | ||||||||||
1465 | } | ||||||||||
1466 | } | ||||||||||
1467 | |||||||||||
1468 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, | ||||||||||
1469 | InitListExpr *IList, QualType DeclType, | ||||||||||
1470 | unsigned &Index, | ||||||||||
1471 | InitListExpr *StructuredList, | ||||||||||
1472 | unsigned &StructuredIndex) { | ||||||||||
1473 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1473, __PRETTY_FUNCTION__)); | ||||||||||
1474 | |||||||||||
1475 | // As an extension, clang supports complex initializers, which initialize | ||||||||||
1476 | // a complex number component-wise. When an explicit initializer list for | ||||||||||
1477 | // a complex number contains two two initializers, this extension kicks in: | ||||||||||
1478 | // it exepcts the initializer list to contain two elements convertible to | ||||||||||
1479 | // the element type of the complex type. The first element initializes | ||||||||||
1480 | // the real part, and the second element intitializes the imaginary part. | ||||||||||
1481 | |||||||||||
1482 | if (IList->getNumInits() != 2) | ||||||||||
1483 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, | ||||||||||
1484 | StructuredIndex); | ||||||||||
1485 | |||||||||||
1486 | // This is an extension in C. (The builtin _Complex type does not exist | ||||||||||
1487 | // in the C++ standard.) | ||||||||||
1488 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) | ||||||||||
1489 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init) | ||||||||||
1490 | << IList->getSourceRange(); | ||||||||||
1491 | |||||||||||
1492 | // Initialize the complex number. | ||||||||||
1493 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); | ||||||||||
1494 | InitializedEntity ElementEntity = | ||||||||||
1495 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||||||||
1496 | |||||||||||
1497 | for (unsigned i = 0; i < 2; ++i) { | ||||||||||
1498 | ElementEntity.setElementIndex(Index); | ||||||||||
1499 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||||||||
1500 | StructuredList, StructuredIndex); | ||||||||||
1501 | } | ||||||||||
1502 | } | ||||||||||
1503 | |||||||||||
1504 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, | ||||||||||
1505 | InitListExpr *IList, QualType DeclType, | ||||||||||
1506 | unsigned &Index, | ||||||||||
1507 | InitListExpr *StructuredList, | ||||||||||
1508 | unsigned &StructuredIndex) { | ||||||||||
1509 | if (Index >= IList->getNumInits()) { | ||||||||||
1510 | if (!VerifyOnly) | ||||||||||
1511 | SemaRef.Diag(IList->getBeginLoc(), | ||||||||||
1512 | SemaRef.getLangOpts().CPlusPlus11 | ||||||||||
1513 | ? diag::warn_cxx98_compat_empty_scalar_initializer | ||||||||||
1514 | : diag::err_empty_scalar_initializer) | ||||||||||
1515 | << IList->getSourceRange(); | ||||||||||
1516 | hadError = !SemaRef.getLangOpts().CPlusPlus11; | ||||||||||
1517 | ++Index; | ||||||||||
1518 | ++StructuredIndex; | ||||||||||
1519 | return; | ||||||||||
1520 | } | ||||||||||
1521 | |||||||||||
1522 | Expr *expr = IList->getInit(Index); | ||||||||||
1523 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) { | ||||||||||
1524 | // FIXME: This is invalid, and accepting it causes overload resolution | ||||||||||
1525 | // to pick the wrong overload in some corner cases. | ||||||||||
1526 | if (!VerifyOnly) | ||||||||||
1527 | SemaRef.Diag(SubIList->getBeginLoc(), | ||||||||||
1528 | diag::ext_many_braces_around_scalar_init) | ||||||||||
1529 | << SubIList->getSourceRange(); | ||||||||||
1530 | |||||||||||
1531 | CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList, | ||||||||||
1532 | StructuredIndex); | ||||||||||
1533 | return; | ||||||||||
1534 | } else if (isa<DesignatedInitExpr>(expr)) { | ||||||||||
1535 | if (!VerifyOnly) | ||||||||||
1536 | SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init) | ||||||||||
1537 | << DeclType << expr->getSourceRange(); | ||||||||||
1538 | hadError = true; | ||||||||||
1539 | ++Index; | ||||||||||
1540 | ++StructuredIndex; | ||||||||||
1541 | return; | ||||||||||
1542 | } | ||||||||||
1543 | |||||||||||
1544 | ExprResult Result; | ||||||||||
1545 | if (VerifyOnly) { | ||||||||||
1546 | if (SemaRef.CanPerformCopyInitialization(Entity, expr)) | ||||||||||
1547 | Result = getDummyInit(); | ||||||||||
1548 | else | ||||||||||
1549 | Result = ExprError(); | ||||||||||
1550 | } else { | ||||||||||
1551 | Result = | ||||||||||
1552 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | ||||||||||
1553 | /*TopLevelOfInitList=*/true); | ||||||||||
1554 | } | ||||||||||
1555 | |||||||||||
1556 | Expr *ResultExpr = nullptr; | ||||||||||
1557 | |||||||||||
1558 | if (Result.isInvalid()) | ||||||||||
1559 | hadError = true; // types weren't compatible. | ||||||||||
1560 | else { | ||||||||||
1561 | ResultExpr = Result.getAs<Expr>(); | ||||||||||
1562 | |||||||||||
1563 | if (ResultExpr != expr && !VerifyOnly) { | ||||||||||
1564 | // The type was promoted, update initializer list. | ||||||||||
1565 | // FIXME: Why are we updating the syntactic init list? | ||||||||||
1566 | IList->setInit(Index, ResultExpr); | ||||||||||
1567 | } | ||||||||||
1568 | } | ||||||||||
1569 | if (hadError) | ||||||||||
1570 | ++StructuredIndex; | ||||||||||
1571 | else | ||||||||||
1572 | UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr); | ||||||||||
1573 | ++Index; | ||||||||||
1574 | } | ||||||||||
1575 | |||||||||||
1576 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, | ||||||||||
1577 | InitListExpr *IList, QualType DeclType, | ||||||||||
1578 | unsigned &Index, | ||||||||||
1579 | InitListExpr *StructuredList, | ||||||||||
1580 | unsigned &StructuredIndex) { | ||||||||||
1581 | if (Index >= IList->getNumInits()) { | ||||||||||
1582 | // FIXME: It would be wonderful if we could point at the actual member. In | ||||||||||
1583 | // general, it would be useful to pass location information down the stack, | ||||||||||
1584 | // so that we know the location (or decl) of the "current object" being | ||||||||||
1585 | // initialized. | ||||||||||
1586 | if (!VerifyOnly) | ||||||||||
1587 | SemaRef.Diag(IList->getBeginLoc(), | ||||||||||
1588 | diag::err_init_reference_member_uninitialized) | ||||||||||
1589 | << DeclType << IList->getSourceRange(); | ||||||||||
1590 | hadError = true; | ||||||||||
1591 | ++Index; | ||||||||||
1592 | ++StructuredIndex; | ||||||||||
1593 | return; | ||||||||||
1594 | } | ||||||||||
1595 | |||||||||||
1596 | Expr *expr = IList->getInit(Index); | ||||||||||
1597 | if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) { | ||||||||||
1598 | if (!VerifyOnly) | ||||||||||
1599 | SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list) | ||||||||||
1600 | << DeclType << IList->getSourceRange(); | ||||||||||
1601 | hadError = true; | ||||||||||
1602 | ++Index; | ||||||||||
1603 | ++StructuredIndex; | ||||||||||
1604 | return; | ||||||||||
1605 | } | ||||||||||
1606 | |||||||||||
1607 | ExprResult Result; | ||||||||||
1608 | if (VerifyOnly) { | ||||||||||
1609 | if (SemaRef.CanPerformCopyInitialization(Entity,expr)) | ||||||||||
1610 | Result = getDummyInit(); | ||||||||||
1611 | else | ||||||||||
1612 | Result = ExprError(); | ||||||||||
1613 | } else { | ||||||||||
1614 | Result = | ||||||||||
1615 | SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr, | ||||||||||
1616 | /*TopLevelOfInitList=*/true); | ||||||||||
1617 | } | ||||||||||
1618 | |||||||||||
1619 | if (Result.isInvalid()) | ||||||||||
1620 | hadError = true; | ||||||||||
1621 | |||||||||||
1622 | expr = Result.getAs<Expr>(); | ||||||||||
1623 | // FIXME: Why are we updating the syntactic init list? | ||||||||||
1624 | if (!VerifyOnly) | ||||||||||
1625 | IList->setInit(Index, expr); | ||||||||||
1626 | |||||||||||
1627 | if (hadError) | ||||||||||
1628 | ++StructuredIndex; | ||||||||||
1629 | else | ||||||||||
1630 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); | ||||||||||
1631 | ++Index; | ||||||||||
1632 | } | ||||||||||
1633 | |||||||||||
1634 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, | ||||||||||
1635 | InitListExpr *IList, QualType DeclType, | ||||||||||
1636 | unsigned &Index, | ||||||||||
1637 | InitListExpr *StructuredList, | ||||||||||
1638 | unsigned &StructuredIndex) { | ||||||||||
1639 | const VectorType *VT = DeclType->castAs<VectorType>(); | ||||||||||
1640 | unsigned maxElements = VT->getNumElements(); | ||||||||||
1641 | unsigned numEltsInit = 0; | ||||||||||
1642 | QualType elementType = VT->getElementType(); | ||||||||||
1643 | |||||||||||
1644 | if (Index >= IList->getNumInits()) { | ||||||||||
1645 | // Make sure the element type can be value-initialized. | ||||||||||
1646 | CheckEmptyInitializable( | ||||||||||
1647 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | ||||||||||
1648 | IList->getEndLoc()); | ||||||||||
1649 | return; | ||||||||||
1650 | } | ||||||||||
1651 | |||||||||||
1652 | if (!SemaRef.getLangOpts().OpenCL) { | ||||||||||
1653 | // If the initializing element is a vector, try to copy-initialize | ||||||||||
1654 | // instead of breaking it apart (which is doomed to failure anyway). | ||||||||||
1655 | Expr *Init = IList->getInit(Index); | ||||||||||
1656 | if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) { | ||||||||||
1657 | ExprResult Result; | ||||||||||
1658 | if (VerifyOnly) { | ||||||||||
1659 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) | ||||||||||
1660 | Result = getDummyInit(); | ||||||||||
1661 | else | ||||||||||
1662 | Result = ExprError(); | ||||||||||
1663 | } else { | ||||||||||
1664 | Result = | ||||||||||
1665 | SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init, | ||||||||||
1666 | /*TopLevelOfInitList=*/true); | ||||||||||
1667 | } | ||||||||||
1668 | |||||||||||
1669 | Expr *ResultExpr = nullptr; | ||||||||||
1670 | if (Result.isInvalid()) | ||||||||||
1671 | hadError = true; // types weren't compatible. | ||||||||||
1672 | else { | ||||||||||
1673 | ResultExpr = Result.getAs<Expr>(); | ||||||||||
1674 | |||||||||||
1675 | if (ResultExpr != Init && !VerifyOnly) { | ||||||||||
1676 | // The type was promoted, update initializer list. | ||||||||||
1677 | // FIXME: Why are we updating the syntactic init list? | ||||||||||
1678 | IList->setInit(Index, ResultExpr); | ||||||||||
1679 | } | ||||||||||
1680 | } | ||||||||||
1681 | if (hadError) | ||||||||||
1682 | ++StructuredIndex; | ||||||||||
1683 | else | ||||||||||
1684 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||||||||
1685 | ResultExpr); | ||||||||||
1686 | ++Index; | ||||||||||
1687 | return; | ||||||||||
1688 | } | ||||||||||
1689 | |||||||||||
1690 | InitializedEntity ElementEntity = | ||||||||||
1691 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||||||||
1692 | |||||||||||
1693 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { | ||||||||||
1694 | // Don't attempt to go past the end of the init list | ||||||||||
1695 | if (Index >= IList->getNumInits()) { | ||||||||||
1696 | CheckEmptyInitializable(ElementEntity, IList->getEndLoc()); | ||||||||||
1697 | break; | ||||||||||
1698 | } | ||||||||||
1699 | |||||||||||
1700 | ElementEntity.setElementIndex(Index); | ||||||||||
1701 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||||||||
1702 | StructuredList, StructuredIndex); | ||||||||||
1703 | } | ||||||||||
1704 | |||||||||||
1705 | if (VerifyOnly) | ||||||||||
1706 | return; | ||||||||||
1707 | |||||||||||
1708 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); | ||||||||||
1709 | const VectorType *T = Entity.getType()->castAs<VectorType>(); | ||||||||||
1710 | if (isBigEndian && (T->getVectorKind() == VectorType::NeonVector || | ||||||||||
1711 | T->getVectorKind() == VectorType::NeonPolyVector)) { | ||||||||||
1712 | // The ability to use vector initializer lists is a GNU vector extension | ||||||||||
1713 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little | ||||||||||
1714 | // endian machines it works fine, however on big endian machines it | ||||||||||
1715 | // exhibits surprising behaviour: | ||||||||||
1716 | // | ||||||||||
1717 | // uint32x2_t x = {42, 64}; | ||||||||||
1718 | // return vget_lane_u32(x, 0); // Will return 64. | ||||||||||
1719 | // | ||||||||||
1720 | // Because of this, explicitly call out that it is non-portable. | ||||||||||
1721 | // | ||||||||||
1722 | SemaRef.Diag(IList->getBeginLoc(), | ||||||||||
1723 | diag::warn_neon_vector_initializer_non_portable); | ||||||||||
1724 | |||||||||||
1725 | const char *typeCode; | ||||||||||
1726 | unsigned typeSize = SemaRef.Context.getTypeSize(elementType); | ||||||||||
1727 | |||||||||||
1728 | if (elementType->isFloatingType()) | ||||||||||
1729 | typeCode = "f"; | ||||||||||
1730 | else if (elementType->isSignedIntegerType()) | ||||||||||
1731 | typeCode = "s"; | ||||||||||
1732 | else if (elementType->isUnsignedIntegerType()) | ||||||||||
1733 | typeCode = "u"; | ||||||||||
1734 | else | ||||||||||
1735 | llvm_unreachable("Invalid element type!")::llvm::llvm_unreachable_internal("Invalid element type!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 1735); | ||||||||||
1736 | |||||||||||
1737 | SemaRef.Diag(IList->getBeginLoc(), | ||||||||||
1738 | SemaRef.Context.getTypeSize(VT) > 64 | ||||||||||
1739 | ? diag::note_neon_vector_initializer_non_portable_q | ||||||||||
1740 | : diag::note_neon_vector_initializer_non_portable) | ||||||||||
1741 | << typeCode << typeSize; | ||||||||||
1742 | } | ||||||||||
1743 | |||||||||||
1744 | return; | ||||||||||
1745 | } | ||||||||||
1746 | |||||||||||
1747 | InitializedEntity ElementEntity = | ||||||||||
1748 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||||||||
1749 | |||||||||||
1750 | // OpenCL initializers allows vectors to be constructed from vectors. | ||||||||||
1751 | for (unsigned i = 0; i < maxElements; ++i) { | ||||||||||
1752 | // Don't attempt to go past the end of the init list | ||||||||||
1753 | if (Index >= IList->getNumInits()) | ||||||||||
1754 | break; | ||||||||||
1755 | |||||||||||
1756 | ElementEntity.setElementIndex(Index); | ||||||||||
1757 | |||||||||||
1758 | QualType IType = IList->getInit(Index)->getType(); | ||||||||||
1759 | if (!IType->isVectorType()) { | ||||||||||
1760 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||||||||
1761 | StructuredList, StructuredIndex); | ||||||||||
1762 | ++numEltsInit; | ||||||||||
1763 | } else { | ||||||||||
1764 | QualType VecType; | ||||||||||
1765 | const VectorType *IVT = IType->castAs<VectorType>(); | ||||||||||
1766 | unsigned numIElts = IVT->getNumElements(); | ||||||||||
1767 | |||||||||||
1768 | if (IType->isExtVectorType()) | ||||||||||
1769 | VecType = SemaRef.Context.getExtVectorType(elementType, numIElts); | ||||||||||
1770 | else | ||||||||||
1771 | VecType = SemaRef.Context.getVectorType(elementType, numIElts, | ||||||||||
1772 | IVT->getVectorKind()); | ||||||||||
1773 | CheckSubElementType(ElementEntity, IList, VecType, Index, | ||||||||||
1774 | StructuredList, StructuredIndex); | ||||||||||
1775 | numEltsInit += numIElts; | ||||||||||
1776 | } | ||||||||||
1777 | } | ||||||||||
1778 | |||||||||||
1779 | // OpenCL requires all elements to be initialized. | ||||||||||
1780 | if (numEltsInit != maxElements) { | ||||||||||
1781 | if (!VerifyOnly) | ||||||||||
1782 | SemaRef.Diag(IList->getBeginLoc(), | ||||||||||
1783 | diag::err_vector_incorrect_num_initializers) | ||||||||||
1784 | << (numEltsInit < maxElements) << maxElements << numEltsInit; | ||||||||||
1785 | hadError = true; | ||||||||||
1786 | } | ||||||||||
1787 | } | ||||||||||
1788 | |||||||||||
1789 | /// Check if the type of a class element has an accessible destructor, and marks | ||||||||||
1790 | /// it referenced. Returns true if we shouldn't form a reference to the | ||||||||||
1791 | /// destructor. | ||||||||||
1792 | /// | ||||||||||
1793 | /// Aggregate initialization requires a class element's destructor be | ||||||||||
1794 | /// accessible per 11.6.1 [dcl.init.aggr]: | ||||||||||
1795 | /// | ||||||||||
1796 | /// The destructor for each element of class type is potentially invoked | ||||||||||
1797 | /// (15.4 [class.dtor]) from the context where the aggregate initialization | ||||||||||
1798 | /// occurs. | ||||||||||
1799 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, | ||||||||||
1800 | Sema &SemaRef) { | ||||||||||
1801 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); | ||||||||||
1802 | if (!CXXRD) | ||||||||||
1803 | return false; | ||||||||||
1804 | |||||||||||
1805 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD); | ||||||||||
1806 | SemaRef.CheckDestructorAccess(Loc, Destructor, | ||||||||||
1807 | SemaRef.PDiag(diag::err_access_dtor_temp) | ||||||||||
1808 | << ElementType); | ||||||||||
1809 | SemaRef.MarkFunctionReferenced(Loc, Destructor); | ||||||||||
1810 | return SemaRef.DiagnoseUseOfDecl(Destructor, Loc); | ||||||||||
1811 | } | ||||||||||
1812 | |||||||||||
1813 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, | ||||||||||
1814 | InitListExpr *IList, QualType &DeclType, | ||||||||||
1815 | llvm::APSInt elementIndex, | ||||||||||
1816 | bool SubobjectIsDesignatorContext, | ||||||||||
1817 | unsigned &Index, | ||||||||||
1818 | InitListExpr *StructuredList, | ||||||||||
1819 | unsigned &StructuredIndex) { | ||||||||||
1820 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType); | ||||||||||
1821 | |||||||||||
1822 | if (!VerifyOnly) { | ||||||||||
1823 | if (checkDestructorReference(arrayType->getElementType(), | ||||||||||
1824 | IList->getEndLoc(), SemaRef)) { | ||||||||||
1825 | hadError = true; | ||||||||||
1826 | return; | ||||||||||
1827 | } | ||||||||||
1828 | } | ||||||||||
1829 | |||||||||||
1830 | // Check for the special-case of initializing an array with a string. | ||||||||||
1831 | if (Index < IList->getNumInits()) { | ||||||||||
1832 | if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) == | ||||||||||
1833 | SIF_None) { | ||||||||||
1834 | // We place the string literal directly into the resulting | ||||||||||
1835 | // initializer list. This is the only place where the structure | ||||||||||
1836 | // of the structured initializer list doesn't match exactly, | ||||||||||
1837 | // because doing so would involve allocating one character | ||||||||||
1838 | // constant for each string. | ||||||||||
1839 | // FIXME: Should we do these checks in verify-only mode too? | ||||||||||
1840 | if (!VerifyOnly) | ||||||||||
1841 | CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef); | ||||||||||
1842 | if (StructuredList) { | ||||||||||
1843 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||||||||
1844 | IList->getInit(Index)); | ||||||||||
1845 | StructuredList->resizeInits(SemaRef.Context, StructuredIndex); | ||||||||||
1846 | } | ||||||||||
1847 | ++Index; | ||||||||||
1848 | return; | ||||||||||
1849 | } | ||||||||||
1850 | } | ||||||||||
1851 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) { | ||||||||||
1852 | // Check for VLAs; in standard C it would be possible to check this | ||||||||||
1853 | // earlier, but I don't know where clang accepts VLAs (gcc accepts | ||||||||||
1854 | // them in all sorts of strange places). | ||||||||||
1855 | if (!VerifyOnly) | ||||||||||
1856 | SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(), | ||||||||||
1857 | diag::err_variable_object_no_init) | ||||||||||
1858 | << VAT->getSizeExpr()->getSourceRange(); | ||||||||||
1859 | hadError = true; | ||||||||||
1860 | ++Index; | ||||||||||
1861 | ++StructuredIndex; | ||||||||||
1862 | return; | ||||||||||
1863 | } | ||||||||||
1864 | |||||||||||
1865 | // We might know the maximum number of elements in advance. | ||||||||||
1866 | llvm::APSInt maxElements(elementIndex.getBitWidth(), | ||||||||||
1867 | elementIndex.isUnsigned()); | ||||||||||
1868 | bool maxElementsKnown = false; | ||||||||||
1869 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) { | ||||||||||
1870 | maxElements = CAT->getSize(); | ||||||||||
1871 | elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth()); | ||||||||||
1872 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | ||||||||||
1873 | maxElementsKnown = true; | ||||||||||
1874 | } | ||||||||||
1875 | |||||||||||
1876 | QualType elementType = arrayType->getElementType(); | ||||||||||
1877 | while (Index < IList->getNumInits()) { | ||||||||||
1878 | Expr *Init = IList->getInit(Index); | ||||||||||
1879 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | ||||||||||
1880 | // If we're not the subobject that matches up with the '{' for | ||||||||||
1881 | // the designator, we shouldn't be handling the | ||||||||||
1882 | // designator. Return immediately. | ||||||||||
1883 | if (!SubobjectIsDesignatorContext) | ||||||||||
1884 | return; | ||||||||||
1885 | |||||||||||
1886 | // Handle this designated initializer. elementIndex will be | ||||||||||
1887 | // updated to be the next array element we'll initialize. | ||||||||||
1888 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | ||||||||||
1889 | DeclType, nullptr, &elementIndex, Index, | ||||||||||
1890 | StructuredList, StructuredIndex, true, | ||||||||||
1891 | false)) { | ||||||||||
1892 | hadError = true; | ||||||||||
1893 | continue; | ||||||||||
1894 | } | ||||||||||
1895 | |||||||||||
1896 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) | ||||||||||
1897 | maxElements = maxElements.extend(elementIndex.getBitWidth()); | ||||||||||
1898 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) | ||||||||||
1899 | elementIndex = elementIndex.extend(maxElements.getBitWidth()); | ||||||||||
1900 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); | ||||||||||
1901 | |||||||||||
1902 | // If the array is of incomplete type, keep track of the number of | ||||||||||
1903 | // elements in the initializer. | ||||||||||
1904 | if (!maxElementsKnown && elementIndex > maxElements) | ||||||||||
1905 | maxElements = elementIndex; | ||||||||||
1906 | |||||||||||
1907 | continue; | ||||||||||
1908 | } | ||||||||||
1909 | |||||||||||
1910 | // If we know the maximum number of elements, and we've already | ||||||||||
1911 | // hit it, stop consuming elements in the initializer list. | ||||||||||
1912 | if (maxElementsKnown && elementIndex == maxElements) | ||||||||||
1913 | break; | ||||||||||
1914 | |||||||||||
1915 | InitializedEntity ElementEntity = | ||||||||||
1916 | InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex, | ||||||||||
1917 | Entity); | ||||||||||
1918 | // Check this element. | ||||||||||
1919 | CheckSubElementType(ElementEntity, IList, elementType, Index, | ||||||||||
1920 | StructuredList, StructuredIndex); | ||||||||||
1921 | ++elementIndex; | ||||||||||
1922 | |||||||||||
1923 | // If the array is of incomplete type, keep track of the number of | ||||||||||
1924 | // elements in the initializer. | ||||||||||
1925 | if (!maxElementsKnown && elementIndex > maxElements) | ||||||||||
1926 | maxElements = elementIndex; | ||||||||||
1927 | } | ||||||||||
1928 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { | ||||||||||
1929 | // If this is an incomplete array type, the actual type needs to | ||||||||||
1930 | // be calculated here. | ||||||||||
1931 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); | ||||||||||
1932 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { | ||||||||||
1933 | // Sizing an array implicitly to zero is not allowed by ISO C, | ||||||||||
1934 | // but is supported by GNU. | ||||||||||
1935 | SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size); | ||||||||||
1936 | } | ||||||||||
1937 | |||||||||||
1938 | DeclType = SemaRef.Context.getConstantArrayType( | ||||||||||
1939 | elementType, maxElements, nullptr, ArrayType::Normal, 0); | ||||||||||
1940 | } | ||||||||||
1941 | if (!hadError) { | ||||||||||
1942 | // If there are any members of the array that get value-initialized, check | ||||||||||
1943 | // that is possible. That happens if we know the bound and don't have | ||||||||||
1944 | // enough elements, or if we're performing an array new with an unknown | ||||||||||
1945 | // bound. | ||||||||||
1946 | if ((maxElementsKnown && elementIndex < maxElements) || | ||||||||||
1947 | Entity.isVariableLengthArrayNew()) | ||||||||||
1948 | CheckEmptyInitializable( | ||||||||||
1949 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity), | ||||||||||
1950 | IList->getEndLoc()); | ||||||||||
1951 | } | ||||||||||
1952 | } | ||||||||||
1953 | |||||||||||
1954 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, | ||||||||||
1955 | Expr *InitExpr, | ||||||||||
1956 | FieldDecl *Field, | ||||||||||
1957 | bool TopLevelObject) { | ||||||||||
1958 | // Handle GNU flexible array initializers. | ||||||||||
1959 | unsigned FlexArrayDiag; | ||||||||||
1960 | if (isa<InitListExpr>(InitExpr) && | ||||||||||
1961 | cast<InitListExpr>(InitExpr)->getNumInits() == 0) { | ||||||||||
1962 | // Empty flexible array init always allowed as an extension | ||||||||||
1963 | FlexArrayDiag = diag::ext_flexible_array_init; | ||||||||||
1964 | } else if (SemaRef.getLangOpts().CPlusPlus) { | ||||||||||
1965 | // Disallow flexible array init in C++; it is not required for gcc | ||||||||||
1966 | // compatibility, and it needs work to IRGen correctly in general. | ||||||||||
1967 | FlexArrayDiag = diag::err_flexible_array_init; | ||||||||||
1968 | } else if (!TopLevelObject) { | ||||||||||
1969 | // Disallow flexible array init on non-top-level object | ||||||||||
1970 | FlexArrayDiag = diag::err_flexible_array_init; | ||||||||||
1971 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { | ||||||||||
1972 | // Disallow flexible array init on anything which is not a variable. | ||||||||||
1973 | FlexArrayDiag = diag::err_flexible_array_init; | ||||||||||
1974 | } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) { | ||||||||||
1975 | // Disallow flexible array init on local variables. | ||||||||||
1976 | FlexArrayDiag = diag::err_flexible_array_init; | ||||||||||
1977 | } else { | ||||||||||
1978 | // Allow other cases. | ||||||||||
1979 | FlexArrayDiag = diag::ext_flexible_array_init; | ||||||||||
1980 | } | ||||||||||
1981 | |||||||||||
1982 | if (!VerifyOnly) { | ||||||||||
1983 | SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag) | ||||||||||
1984 | << InitExpr->getBeginLoc(); | ||||||||||
1985 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | ||||||||||
1986 | << Field; | ||||||||||
1987 | } | ||||||||||
1988 | |||||||||||
1989 | return FlexArrayDiag != diag::ext_flexible_array_init; | ||||||||||
1990 | } | ||||||||||
1991 | |||||||||||
1992 | void InitListChecker::CheckStructUnionTypes( | ||||||||||
1993 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, | ||||||||||
1994 | CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field, | ||||||||||
1995 | bool SubobjectIsDesignatorContext, unsigned &Index, | ||||||||||
1996 | InitListExpr *StructuredList, unsigned &StructuredIndex, | ||||||||||
1997 | bool TopLevelObject) { | ||||||||||
1998 | RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl(); | ||||||||||
1999 | |||||||||||
2000 | // If the record is invalid, some of it's members are invalid. To avoid | ||||||||||
2001 | // confusion, we forgo checking the intializer for the entire record. | ||||||||||
2002 | if (structDecl->isInvalidDecl()) { | ||||||||||
2003 | // Assume it was supposed to consume a single initializer. | ||||||||||
2004 | ++Index; | ||||||||||
2005 | hadError = true; | ||||||||||
2006 | return; | ||||||||||
2007 | } | ||||||||||
2008 | |||||||||||
2009 | if (DeclType->isUnionType() && IList->getNumInits() == 0) { | ||||||||||
2010 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | ||||||||||
2011 | |||||||||||
2012 | if (!VerifyOnly) | ||||||||||
2013 | for (FieldDecl *FD : RD->fields()) { | ||||||||||
2014 | QualType ET = SemaRef.Context.getBaseElementType(FD->getType()); | ||||||||||
2015 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | ||||||||||
2016 | hadError = true; | ||||||||||
2017 | return; | ||||||||||
2018 | } | ||||||||||
2019 | } | ||||||||||
2020 | |||||||||||
2021 | // If there's a default initializer, use it. | ||||||||||
2022 | if (isa<CXXRecordDecl>(RD) && | ||||||||||
2023 | cast<CXXRecordDecl>(RD)->hasInClassInitializer()) { | ||||||||||
2024 | if (!StructuredList) | ||||||||||
2025 | return; | ||||||||||
2026 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | ||||||||||
2027 | Field != FieldEnd; ++Field) { | ||||||||||
2028 | if (Field->hasInClassInitializer()) { | ||||||||||
2029 | StructuredList->setInitializedFieldInUnion(*Field); | ||||||||||
2030 | // FIXME: Actually build a CXXDefaultInitExpr? | ||||||||||
2031 | return; | ||||||||||
2032 | } | ||||||||||
2033 | } | ||||||||||
2034 | } | ||||||||||
2035 | |||||||||||
2036 | // Value-initialize the first member of the union that isn't an unnamed | ||||||||||
2037 | // bitfield. | ||||||||||
2038 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); | ||||||||||
2039 | Field != FieldEnd; ++Field) { | ||||||||||
2040 | if (!Field->isUnnamedBitfield()) { | ||||||||||
2041 | CheckEmptyInitializable( | ||||||||||
2042 | InitializedEntity::InitializeMember(*Field, &Entity), | ||||||||||
2043 | IList->getEndLoc()); | ||||||||||
2044 | if (StructuredList) | ||||||||||
2045 | StructuredList->setInitializedFieldInUnion(*Field); | ||||||||||
2046 | break; | ||||||||||
2047 | } | ||||||||||
2048 | } | ||||||||||
2049 | return; | ||||||||||
2050 | } | ||||||||||
2051 | |||||||||||
2052 | bool InitializedSomething = false; | ||||||||||
2053 | |||||||||||
2054 | // If we have any base classes, they are initialized prior to the fields. | ||||||||||
2055 | for (auto &Base : Bases) { | ||||||||||
2056 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr; | ||||||||||
2057 | |||||||||||
2058 | // Designated inits always initialize fields, so if we see one, all | ||||||||||
2059 | // remaining base classes have no explicit initializer. | ||||||||||
2060 | if (Init && isa<DesignatedInitExpr>(Init)) | ||||||||||
2061 | Init = nullptr; | ||||||||||
2062 | |||||||||||
2063 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); | ||||||||||
2064 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( | ||||||||||
2065 | SemaRef.Context, &Base, false, &Entity); | ||||||||||
2066 | if (Init) { | ||||||||||
2067 | CheckSubElementType(BaseEntity, IList, Base.getType(), Index, | ||||||||||
2068 | StructuredList, StructuredIndex); | ||||||||||
2069 | InitializedSomething = true; | ||||||||||
2070 | } else { | ||||||||||
2071 | CheckEmptyInitializable(BaseEntity, InitLoc); | ||||||||||
2072 | } | ||||||||||
2073 | |||||||||||
2074 | if (!VerifyOnly) | ||||||||||
2075 | if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) { | ||||||||||
2076 | hadError = true; | ||||||||||
2077 | return; | ||||||||||
2078 | } | ||||||||||
2079 | } | ||||||||||
2080 | |||||||||||
2081 | // If structDecl is a forward declaration, this loop won't do | ||||||||||
2082 | // anything except look at designated initializers; That's okay, | ||||||||||
2083 | // because an error should get printed out elsewhere. It might be | ||||||||||
2084 | // worthwhile to skip over the rest of the initializer, though. | ||||||||||
2085 | RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl(); | ||||||||||
2086 | RecordDecl::field_iterator FieldEnd = RD->field_end(); | ||||||||||
2087 | bool CheckForMissingFields = | ||||||||||
2088 | !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); | ||||||||||
2089 | bool HasDesignatedInit = false; | ||||||||||
2090 | |||||||||||
2091 | while (Index < IList->getNumInits()) { | ||||||||||
2092 | Expr *Init = IList->getInit(Index); | ||||||||||
2093 | SourceLocation InitLoc = Init->getBeginLoc(); | ||||||||||
2094 | |||||||||||
2095 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) { | ||||||||||
2096 | // If we're not the subobject that matches up with the '{' for | ||||||||||
2097 | // the designator, we shouldn't be handling the | ||||||||||
2098 | // designator. Return immediately. | ||||||||||
2099 | if (!SubobjectIsDesignatorContext) | ||||||||||
2100 | return; | ||||||||||
2101 | |||||||||||
2102 | HasDesignatedInit = true; | ||||||||||
2103 | |||||||||||
2104 | // Handle this designated initializer. Field will be updated to | ||||||||||
2105 | // the next field that we'll be initializing. | ||||||||||
2106 | if (CheckDesignatedInitializer(Entity, IList, DIE, 0, | ||||||||||
2107 | DeclType, &Field, nullptr, Index, | ||||||||||
2108 | StructuredList, StructuredIndex, | ||||||||||
2109 | true, TopLevelObject)) | ||||||||||
2110 | hadError = true; | ||||||||||
2111 | else if (!VerifyOnly) { | ||||||||||
2112 | // Find the field named by the designated initializer. | ||||||||||
2113 | RecordDecl::field_iterator F = RD->field_begin(); | ||||||||||
2114 | while (std::next(F) != Field) | ||||||||||
2115 | ++F; | ||||||||||
2116 | QualType ET = SemaRef.Context.getBaseElementType(F->getType()); | ||||||||||
2117 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | ||||||||||
2118 | hadError = true; | ||||||||||
2119 | return; | ||||||||||
2120 | } | ||||||||||
2121 | } | ||||||||||
2122 | |||||||||||
2123 | InitializedSomething = true; | ||||||||||
2124 | |||||||||||
2125 | // Disable check for missing fields when designators are used. | ||||||||||
2126 | // This matches gcc behaviour. | ||||||||||
2127 | CheckForMissingFields = false; | ||||||||||
2128 | continue; | ||||||||||
2129 | } | ||||||||||
2130 | |||||||||||
2131 | if (Field == FieldEnd) { | ||||||||||
2132 | // We've run out of fields. We're done. | ||||||||||
2133 | break; | ||||||||||
2134 | } | ||||||||||
2135 | |||||||||||
2136 | // We've already initialized a member of a union. We're done. | ||||||||||
2137 | if (InitializedSomething && DeclType->isUnionType()) | ||||||||||
2138 | break; | ||||||||||
2139 | |||||||||||
2140 | // If we've hit the flexible array member at the end, we're done. | ||||||||||
2141 | if (Field->getType()->isIncompleteArrayType()) | ||||||||||
2142 | break; | ||||||||||
2143 | |||||||||||
2144 | if (Field->isUnnamedBitfield()) { | ||||||||||
2145 | // Don't initialize unnamed bitfields, e.g. "int : 20;" | ||||||||||
2146 | ++Field; | ||||||||||
2147 | continue; | ||||||||||
2148 | } | ||||||||||
2149 | |||||||||||
2150 | // Make sure we can use this declaration. | ||||||||||
2151 | bool InvalidUse; | ||||||||||
2152 | if (VerifyOnly) | ||||||||||
2153 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | ||||||||||
2154 | else | ||||||||||
2155 | InvalidUse = SemaRef.DiagnoseUseOfDecl( | ||||||||||
2156 | *Field, IList->getInit(Index)->getBeginLoc()); | ||||||||||
2157 | if (InvalidUse) { | ||||||||||
2158 | ++Index; | ||||||||||
2159 | ++Field; | ||||||||||
2160 | hadError = true; | ||||||||||
2161 | continue; | ||||||||||
2162 | } | ||||||||||
2163 | |||||||||||
2164 | if (!VerifyOnly) { | ||||||||||
2165 | QualType ET = SemaRef.Context.getBaseElementType(Field->getType()); | ||||||||||
2166 | if (checkDestructorReference(ET, InitLoc, SemaRef)) { | ||||||||||
2167 | hadError = true; | ||||||||||
2168 | return; | ||||||||||
2169 | } | ||||||||||
2170 | } | ||||||||||
2171 | |||||||||||
2172 | InitializedEntity MemberEntity = | ||||||||||
2173 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||||||||
2174 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | ||||||||||
2175 | StructuredList, StructuredIndex); | ||||||||||
2176 | InitializedSomething = true; | ||||||||||
2177 | |||||||||||
2178 | if (DeclType->isUnionType() && StructuredList) { | ||||||||||
2179 | // Initialize the first field within the union. | ||||||||||
2180 | StructuredList->setInitializedFieldInUnion(*Field); | ||||||||||
2181 | } | ||||||||||
2182 | |||||||||||
2183 | ++Field; | ||||||||||
2184 | } | ||||||||||
2185 | |||||||||||
2186 | // Emit warnings for missing struct field initializers. | ||||||||||
2187 | if (!VerifyOnly && InitializedSomething && CheckForMissingFields && | ||||||||||
2188 | Field != FieldEnd && !Field->getType()->isIncompleteArrayType() && | ||||||||||
2189 | !DeclType->isUnionType()) { | ||||||||||
2190 | // It is possible we have one or more unnamed bitfields remaining. | ||||||||||
2191 | // Find first (if any) named field and emit warning. | ||||||||||
2192 | for (RecordDecl::field_iterator it = Field, end = RD->field_end(); | ||||||||||
2193 | it != end; ++it) { | ||||||||||
2194 | if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) { | ||||||||||
2195 | SemaRef.Diag(IList->getSourceRange().getEnd(), | ||||||||||
2196 | diag::warn_missing_field_initializers) << *it; | ||||||||||
2197 | break; | ||||||||||
2198 | } | ||||||||||
2199 | } | ||||||||||
2200 | } | ||||||||||
2201 | |||||||||||
2202 | // Check that any remaining fields can be value-initialized if we're not | ||||||||||
2203 | // building a structured list. (If we are, we'll check this later.) | ||||||||||
2204 | if (!StructuredList && Field != FieldEnd && !DeclType->isUnionType() && | ||||||||||
2205 | !Field->getType()->isIncompleteArrayType()) { | ||||||||||
2206 | for (; Field != FieldEnd && !hadError; ++Field) { | ||||||||||
2207 | if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer()) | ||||||||||
2208 | CheckEmptyInitializable( | ||||||||||
2209 | InitializedEntity::InitializeMember(*Field, &Entity), | ||||||||||
2210 | IList->getEndLoc()); | ||||||||||
2211 | } | ||||||||||
2212 | } | ||||||||||
2213 | |||||||||||
2214 | // Check that the types of the remaining fields have accessible destructors. | ||||||||||
2215 | if (!VerifyOnly) { | ||||||||||
2216 | // If the initializer expression has a designated initializer, check the | ||||||||||
2217 | // elements for which a designated initializer is not provided too. | ||||||||||
2218 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() | ||||||||||
2219 | : Field; | ||||||||||
2220 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { | ||||||||||
2221 | QualType ET = SemaRef.Context.getBaseElementType(I->getType()); | ||||||||||
2222 | if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) { | ||||||||||
2223 | hadError = true; | ||||||||||
2224 | return; | ||||||||||
2225 | } | ||||||||||
2226 | } | ||||||||||
2227 | } | ||||||||||
2228 | |||||||||||
2229 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || | ||||||||||
2230 | Index >= IList->getNumInits()) | ||||||||||
2231 | return; | ||||||||||
2232 | |||||||||||
2233 | if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field, | ||||||||||
2234 | TopLevelObject)) { | ||||||||||
2235 | hadError = true; | ||||||||||
2236 | ++Index; | ||||||||||
2237 | return; | ||||||||||
2238 | } | ||||||||||
2239 | |||||||||||
2240 | InitializedEntity MemberEntity = | ||||||||||
2241 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||||||||
2242 | |||||||||||
2243 | if (isa<InitListExpr>(IList->getInit(Index))) | ||||||||||
2244 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | ||||||||||
2245 | StructuredList, StructuredIndex); | ||||||||||
2246 | else | ||||||||||
2247 | CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index, | ||||||||||
2248 | StructuredList, StructuredIndex); | ||||||||||
2249 | } | ||||||||||
2250 | |||||||||||
2251 | /// Expand a field designator that refers to a member of an | ||||||||||
2252 | /// anonymous struct or union into a series of field designators that | ||||||||||
2253 | /// refers to the field within the appropriate subobject. | ||||||||||
2254 | /// | ||||||||||
2255 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, | ||||||||||
2256 | DesignatedInitExpr *DIE, | ||||||||||
2257 | unsigned DesigIdx, | ||||||||||
2258 | IndirectFieldDecl *IndirectField) { | ||||||||||
2259 | typedef DesignatedInitExpr::Designator Designator; | ||||||||||
2260 | |||||||||||
2261 | // Build the replacement designators. | ||||||||||
2262 | SmallVector<Designator, 4> Replacements; | ||||||||||
2263 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), | ||||||||||
2264 | PE = IndirectField->chain_end(); PI != PE; ++PI) { | ||||||||||
2265 | if (PI + 1 == PE) | ||||||||||
2266 | Replacements.push_back(Designator((IdentifierInfo *)nullptr, | ||||||||||
2267 | DIE->getDesignator(DesigIdx)->getDotLoc(), | ||||||||||
2268 | DIE->getDesignator(DesigIdx)->getFieldLoc())); | ||||||||||
2269 | else | ||||||||||
2270 | Replacements.push_back(Designator((IdentifierInfo *)nullptr, | ||||||||||
2271 | SourceLocation(), SourceLocation())); | ||||||||||
2272 | assert(isa<FieldDecl>(*PI))((isa<FieldDecl>(*PI)) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(*PI)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 2272, __PRETTY_FUNCTION__)); | ||||||||||
2273 | Replacements.back().setField(cast<FieldDecl>(*PI)); | ||||||||||
2274 | } | ||||||||||
2275 | |||||||||||
2276 | // Expand the current designator into the set of replacement | ||||||||||
2277 | // designators, so we have a full subobject path down to where the | ||||||||||
2278 | // member of the anonymous struct/union is actually stored. | ||||||||||
2279 | DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0], | ||||||||||
2280 | &Replacements[0] + Replacements.size()); | ||||||||||
2281 | } | ||||||||||
2282 | |||||||||||
2283 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, | ||||||||||
2284 | DesignatedInitExpr *DIE) { | ||||||||||
2285 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; | ||||||||||
2286 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); | ||||||||||
2287 | for (unsigned I = 0; I < NumIndexExprs; ++I) | ||||||||||
2288 | IndexExprs[I] = DIE->getSubExpr(I + 1); | ||||||||||
2289 | return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(), | ||||||||||
2290 | IndexExprs, | ||||||||||
2291 | DIE->getEqualOrColonLoc(), | ||||||||||
2292 | DIE->usesGNUSyntax(), DIE->getInit()); | ||||||||||
2293 | } | ||||||||||
2294 | |||||||||||
2295 | namespace { | ||||||||||
2296 | |||||||||||
2297 | // Callback to only accept typo corrections that are for field members of | ||||||||||
2298 | // the given struct or union. | ||||||||||
2299 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { | ||||||||||
2300 | public: | ||||||||||
2301 | explicit FieldInitializerValidatorCCC(RecordDecl *RD) | ||||||||||
2302 | : Record(RD) {} | ||||||||||
2303 | |||||||||||
2304 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||||||
2305 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); | ||||||||||
2306 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record); | ||||||||||
2307 | } | ||||||||||
2308 | |||||||||||
2309 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||||||
2310 | return std::make_unique<FieldInitializerValidatorCCC>(*this); | ||||||||||
2311 | } | ||||||||||
2312 | |||||||||||
2313 | private: | ||||||||||
2314 | RecordDecl *Record; | ||||||||||
2315 | }; | ||||||||||
2316 | |||||||||||
2317 | } // end anonymous namespace | ||||||||||
2318 | |||||||||||
2319 | /// Check the well-formedness of a C99 designated initializer. | ||||||||||
2320 | /// | ||||||||||
2321 | /// Determines whether the designated initializer @p DIE, which | ||||||||||
2322 | /// resides at the given @p Index within the initializer list @p | ||||||||||
2323 | /// IList, is well-formed for a current object of type @p DeclType | ||||||||||
2324 | /// (C99 6.7.8). The actual subobject that this designator refers to | ||||||||||
2325 | /// within the current subobject is returned in either | ||||||||||
2326 | /// @p NextField or @p NextElementIndex (whichever is appropriate). | ||||||||||
2327 | /// | ||||||||||
2328 | /// @param IList The initializer list in which this designated | ||||||||||
2329 | /// initializer occurs. | ||||||||||
2330 | /// | ||||||||||
2331 | /// @param DIE The designated initializer expression. | ||||||||||
2332 | /// | ||||||||||
2333 | /// @param DesigIdx The index of the current designator. | ||||||||||
2334 | /// | ||||||||||
2335 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), | ||||||||||
2336 | /// into which the designation in @p DIE should refer. | ||||||||||
2337 | /// | ||||||||||
2338 | /// @param NextField If non-NULL and the first designator in @p DIE is | ||||||||||
2339 | /// a field, this will be set to the field declaration corresponding | ||||||||||
2340 | /// to the field named by the designator. On input, this is expected to be | ||||||||||
2341 | /// the next field that would be initialized in the absence of designation, | ||||||||||
2342 | /// if the complete object being initialized is a struct. | ||||||||||
2343 | /// | ||||||||||
2344 | /// @param NextElementIndex If non-NULL and the first designator in @p | ||||||||||
2345 | /// DIE is an array designator or GNU array-range designator, this | ||||||||||
2346 | /// will be set to the last index initialized by this designator. | ||||||||||
2347 | /// | ||||||||||
2348 | /// @param Index Index into @p IList where the designated initializer | ||||||||||
2349 | /// @p DIE occurs. | ||||||||||
2350 | /// | ||||||||||
2351 | /// @param StructuredList The initializer list expression that | ||||||||||
2352 | /// describes all of the subobject initializers in the order they'll | ||||||||||
2353 | /// actually be initialized. | ||||||||||
2354 | /// | ||||||||||
2355 | /// @returns true if there was an error, false otherwise. | ||||||||||
2356 | bool | ||||||||||
2357 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, | ||||||||||
2358 | InitListExpr *IList, | ||||||||||
2359 | DesignatedInitExpr *DIE, | ||||||||||
2360 | unsigned DesigIdx, | ||||||||||
2361 | QualType &CurrentObjectType, | ||||||||||
2362 | RecordDecl::field_iterator *NextField, | ||||||||||
2363 | llvm::APSInt *NextElementIndex, | ||||||||||
2364 | unsigned &Index, | ||||||||||
2365 | InitListExpr *StructuredList, | ||||||||||
2366 | unsigned &StructuredIndex, | ||||||||||
2367 | bool FinishSubobjectInit, | ||||||||||
2368 | bool TopLevelObject) { | ||||||||||
2369 | if (DesigIdx == DIE->size()) { | ||||||||||
2370 | // C++20 designated initialization can result in direct-list-initialization | ||||||||||
2371 | // of the designated subobject. This is the only way that we can end up | ||||||||||
2372 | // performing direct initialization as part of aggregate initialization, so | ||||||||||
2373 | // it needs special handling. | ||||||||||
2374 | if (DIE->isDirectInit()) { | ||||||||||
2375 | Expr *Init = DIE->getInit(); | ||||||||||
2376 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 2377, __PRETTY_FUNCTION__)) | ||||||||||
2377 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 2377, __PRETTY_FUNCTION__)); | ||||||||||
2378 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||||||||
2379 | DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc()); | ||||||||||
2380 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, | ||||||||||
2381 | /*TopLevelOfInitList*/ true); | ||||||||||
2382 | if (StructuredList) { | ||||||||||
2383 | ExprResult Result = VerifyOnly | ||||||||||
2384 | ? getDummyInit() | ||||||||||
2385 | : Seq.Perform(SemaRef, Entity, Kind, Init); | ||||||||||
2386 | UpdateStructuredListElement(StructuredList, StructuredIndex, | ||||||||||
2387 | Result.get()); | ||||||||||
2388 | } | ||||||||||
2389 | ++Index; | ||||||||||
2390 | return !Seq; | ||||||||||
2391 | } | ||||||||||
2392 | |||||||||||
2393 | // Check the actual initialization for the designated object type. | ||||||||||
2394 | bool prevHadError = hadError; | ||||||||||
2395 | |||||||||||
2396 | // Temporarily remove the designator expression from the | ||||||||||
2397 | // initializer list that the child calls see, so that we don't try | ||||||||||
2398 | // to re-process the designator. | ||||||||||
2399 | unsigned OldIndex = Index; | ||||||||||
2400 | IList->setInit(OldIndex, DIE->getInit()); | ||||||||||
2401 | |||||||||||
2402 | CheckSubElementType(Entity, IList, CurrentObjectType, Index, | ||||||||||
2403 | StructuredList, StructuredIndex); | ||||||||||
2404 | |||||||||||
2405 | // Restore the designated initializer expression in the syntactic | ||||||||||
2406 | // form of the initializer list. | ||||||||||
2407 | if (IList->getInit(OldIndex) != DIE->getInit()) | ||||||||||
2408 | DIE->setInit(IList->getInit(OldIndex)); | ||||||||||
2409 | IList->setInit(OldIndex, DIE); | ||||||||||
2410 | |||||||||||
2411 | return hadError && !prevHadError; | ||||||||||
2412 | } | ||||||||||
2413 | |||||||||||
2414 | DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx); | ||||||||||
2415 | bool IsFirstDesignator = (DesigIdx == 0); | ||||||||||
2416 | if (IsFirstDesignator ? FullyStructuredList : StructuredList) { | ||||||||||
2417 | // Determine the structural initializer list that corresponds to the | ||||||||||
2418 | // current subobject. | ||||||||||
2419 | if (IsFirstDesignator) | ||||||||||
2420 | StructuredList = FullyStructuredList; | ||||||||||
2421 | else { | ||||||||||
2422 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? | ||||||||||
2423 | StructuredList->getInit(StructuredIndex) : nullptr; | ||||||||||
2424 | if (!ExistingInit && StructuredList->hasArrayFiller()) | ||||||||||
2425 | ExistingInit = StructuredList->getArrayFiller(); | ||||||||||
2426 | |||||||||||
2427 | if (!ExistingInit) | ||||||||||
2428 | StructuredList = getStructuredSubobjectInit( | ||||||||||
2429 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, | ||||||||||
2430 | SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | ||||||||||
2431 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit)) | ||||||||||
2432 | StructuredList = Result; | ||||||||||
2433 | else { | ||||||||||
2434 | // We are creating an initializer list that initializes the | ||||||||||
2435 | // subobjects of the current object, but there was already an | ||||||||||
2436 | // initialization that completely initialized the current | ||||||||||
2437 | // subobject, e.g., by a compound literal: | ||||||||||
2438 | // | ||||||||||
2439 | // struct X { int a, b; }; | ||||||||||
2440 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | ||||||||||
2441 | // | ||||||||||
2442 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | ||||||||||
2443 | // designated initializer re-initializes only its current object | ||||||||||
2444 | // subobject [0].b. | ||||||||||
2445 | diagnoseInitOverride(ExistingInit, | ||||||||||
2446 | SourceRange(D->getBeginLoc(), DIE->getEndLoc()), | ||||||||||
2447 | /*FullyOverwritten=*/false); | ||||||||||
2448 | |||||||||||
2449 | if (!VerifyOnly) { | ||||||||||
2450 | if (DesignatedInitUpdateExpr *E = | ||||||||||
2451 | dyn_cast<DesignatedInitUpdateExpr>(ExistingInit)) | ||||||||||
2452 | StructuredList = E->getUpdater(); | ||||||||||
2453 | else { | ||||||||||
2454 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) | ||||||||||
2455 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), | ||||||||||
2456 | ExistingInit, DIE->getEndLoc()); | ||||||||||
2457 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE); | ||||||||||
2458 | StructuredList = DIUE->getUpdater(); | ||||||||||
2459 | } | ||||||||||
2460 | } else { | ||||||||||
2461 | // We don't need to track the structured representation of a | ||||||||||
2462 | // designated init update of an already-fully-initialized object in | ||||||||||
2463 | // verify-only mode. The only reason we would need the structure is | ||||||||||
2464 | // to determine where the uninitialized "holes" are, and in this | ||||||||||
2465 | // case, we know there aren't any and we can't introduce any. | ||||||||||
2466 | StructuredList = nullptr; | ||||||||||
2467 | } | ||||||||||
2468 | } | ||||||||||
2469 | } | ||||||||||
2470 | } | ||||||||||
2471 | |||||||||||
2472 | if (D->isFieldDesignator()) { | ||||||||||
2473 | // C99 6.7.8p7: | ||||||||||
2474 | // | ||||||||||
2475 | // If a designator has the form | ||||||||||
2476 | // | ||||||||||
2477 | // . identifier | ||||||||||
2478 | // | ||||||||||
2479 | // then the current object (defined below) shall have | ||||||||||
2480 | // structure or union type and the identifier shall be the | ||||||||||
2481 | // name of a member of that type. | ||||||||||
2482 | const RecordType *RT = CurrentObjectType->getAs<RecordType>(); | ||||||||||
2483 | if (!RT) { | ||||||||||
2484 | SourceLocation Loc = D->getDotLoc(); | ||||||||||
2485 | if (Loc.isInvalid()) | ||||||||||
2486 | Loc = D->getFieldLoc(); | ||||||||||
2487 | if (!VerifyOnly) | ||||||||||
2488 | SemaRef.Diag(Loc, diag::err_field_designator_non_aggr) | ||||||||||
2489 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; | ||||||||||
2490 | ++Index; | ||||||||||
2491 | return true; | ||||||||||
2492 | } | ||||||||||
2493 | |||||||||||
2494 | FieldDecl *KnownField = D->getField(); | ||||||||||
2495 | if (!KnownField) { | ||||||||||
2496 | IdentifierInfo *FieldName = D->getFieldName(); | ||||||||||
2497 | DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName); | ||||||||||
2498 | for (NamedDecl *ND : Lookup) { | ||||||||||
2499 | if (auto *FD = dyn_cast<FieldDecl>(ND)) { | ||||||||||
2500 | KnownField = FD; | ||||||||||
2501 | break; | ||||||||||
2502 | } | ||||||||||
2503 | if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) { | ||||||||||
2504 | // In verify mode, don't modify the original. | ||||||||||
2505 | if (VerifyOnly) | ||||||||||
2506 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); | ||||||||||
2507 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD); | ||||||||||
2508 | D = DIE->getDesignator(DesigIdx); | ||||||||||
2509 | KnownField = cast<FieldDecl>(*IFD->chain_begin()); | ||||||||||
2510 | break; | ||||||||||
2511 | } | ||||||||||
2512 | } | ||||||||||
2513 | if (!KnownField) { | ||||||||||
2514 | if (VerifyOnly) { | ||||||||||
2515 | ++Index; | ||||||||||
2516 | return true; // No typo correction when just trying this out. | ||||||||||
2517 | } | ||||||||||
2518 | |||||||||||
2519 | // Name lookup found something, but it wasn't a field. | ||||||||||
2520 | if (!Lookup.empty()) { | ||||||||||
2521 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield) | ||||||||||
2522 | << FieldName; | ||||||||||
2523 | SemaRef.Diag(Lookup.front()->getLocation(), | ||||||||||
2524 | diag::note_field_designator_found); | ||||||||||
2525 | ++Index; | ||||||||||
2526 | return true; | ||||||||||
2527 | } | ||||||||||
2528 | |||||||||||
2529 | // Name lookup didn't find anything. | ||||||||||
2530 | // Determine whether this was a typo for another field name. | ||||||||||
2531 | FieldInitializerValidatorCCC CCC(RT->getDecl()); | ||||||||||
2532 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( | ||||||||||
2533 | DeclarationNameInfo(FieldName, D->getFieldLoc()), | ||||||||||
2534 | Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC, | ||||||||||
2535 | Sema::CTK_ErrorRecovery, RT->getDecl())) { | ||||||||||
2536 | SemaRef.diagnoseTypo( | ||||||||||
2537 | Corrected, | ||||||||||
2538 | SemaRef.PDiag(diag::err_field_designator_unknown_suggest) | ||||||||||
2539 | << FieldName << CurrentObjectType); | ||||||||||
2540 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); | ||||||||||
2541 | hadError = true; | ||||||||||
2542 | } else { | ||||||||||
2543 | // Typo correction didn't find anything. | ||||||||||
2544 | SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown) | ||||||||||
2545 | << FieldName << CurrentObjectType; | ||||||||||
2546 | ++Index; | ||||||||||
2547 | return true; | ||||||||||
2548 | } | ||||||||||
2549 | } | ||||||||||
2550 | } | ||||||||||
2551 | |||||||||||
2552 | unsigned NumBases = 0; | ||||||||||
2553 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) | ||||||||||
2554 | NumBases = CXXRD->getNumBases(); | ||||||||||
2555 | |||||||||||
2556 | unsigned FieldIndex = NumBases; | ||||||||||
2557 | |||||||||||
2558 | for (auto *FI : RT->getDecl()->fields()) { | ||||||||||
2559 | if (FI->isUnnamedBitfield()) | ||||||||||
2560 | continue; | ||||||||||
2561 | if (declaresSameEntity(KnownField, FI)) { | ||||||||||
2562 | KnownField = FI; | ||||||||||
2563 | break; | ||||||||||
2564 | } | ||||||||||
2565 | ++FieldIndex; | ||||||||||
2566 | } | ||||||||||
2567 | |||||||||||
2568 | RecordDecl::field_iterator Field = | ||||||||||
2569 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); | ||||||||||
2570 | |||||||||||
2571 | // All of the fields of a union are located at the same place in | ||||||||||
2572 | // the initializer list. | ||||||||||
2573 | if (RT->getDecl()->isUnion()) { | ||||||||||
2574 | FieldIndex = 0; | ||||||||||
2575 | if (StructuredList) { | ||||||||||
2576 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); | ||||||||||
2577 | if (CurrentField && !declaresSameEntity(CurrentField, *Field)) { | ||||||||||
2578 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 2579, __PRETTY_FUNCTION__)) | ||||||||||
2579 | && "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 2579, __PRETTY_FUNCTION__)); | ||||||||||
2580 | |||||||||||
2581 | Expr *ExistingInit = StructuredList->getInit(0); | ||||||||||
2582 | if (ExistingInit) { | ||||||||||
2583 | // We're about to throw away an initializer, emit warning. | ||||||||||
2584 | diagnoseInitOverride( | ||||||||||
2585 | ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc())); | ||||||||||
2586 | } | ||||||||||
2587 | |||||||||||
2588 | // remove existing initializer | ||||||||||
2589 | StructuredList->resizeInits(SemaRef.Context, 0); | ||||||||||
2590 | StructuredList->setInitializedFieldInUnion(nullptr); | ||||||||||
2591 | } | ||||||||||
2592 | |||||||||||
2593 | StructuredList->setInitializedFieldInUnion(*Field); | ||||||||||
2594 | } | ||||||||||
2595 | } | ||||||||||
2596 | |||||||||||
2597 | // Make sure we can use this declaration. | ||||||||||
2598 | bool InvalidUse; | ||||||||||
2599 | if (VerifyOnly) | ||||||||||
2600 | InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid); | ||||||||||
2601 | else | ||||||||||
2602 | InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc()); | ||||||||||
2603 | if (InvalidUse) { | ||||||||||
2604 | ++Index; | ||||||||||
2605 | return true; | ||||||||||
2606 | } | ||||||||||
2607 | |||||||||||
2608 | // C++20 [dcl.init.list]p3: | ||||||||||
2609 | // The ordered identifiers in the designators of the designated- | ||||||||||
2610 | // initializer-list shall form a subsequence of the ordered identifiers | ||||||||||
2611 | // in the direct non-static data members of T. | ||||||||||
2612 | // | ||||||||||
2613 | // Note that this is not a condition on forming the aggregate | ||||||||||
2614 | // initialization, only on actually performing initialization, | ||||||||||
2615 | // so it is not checked in VerifyOnly mode. | ||||||||||
2616 | // | ||||||||||
2617 | // FIXME: This is the only reordering diagnostic we produce, and it only | ||||||||||
2618 | // catches cases where we have a top-level field designator that jumps | ||||||||||
2619 | // backwards. This is the only such case that is reachable in an | ||||||||||
2620 | // otherwise-valid C++20 program, so is the only case that's required for | ||||||||||
2621 | // conformance, but for consistency, we should diagnose all the other | ||||||||||
2622 | // cases where a designator takes us backwards too. | ||||||||||
2623 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && | ||||||||||
2624 | NextField && | ||||||||||
2625 | (*NextField == RT->getDecl()->field_end() || | ||||||||||
2626 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { | ||||||||||
2627 | // Find the field that we just initialized. | ||||||||||
2628 | FieldDecl *PrevField = nullptr; | ||||||||||
2629 | for (auto FI = RT->getDecl()->field_begin(); | ||||||||||
2630 | FI != RT->getDecl()->field_end(); ++FI) { | ||||||||||
2631 | if (FI->isUnnamedBitfield()) | ||||||||||
2632 | continue; | ||||||||||
2633 | if (*NextField != RT->getDecl()->field_end() && | ||||||||||
2634 | declaresSameEntity(*FI, **NextField)) | ||||||||||
2635 | break; | ||||||||||
2636 | PrevField = *FI; | ||||||||||
2637 | } | ||||||||||
2638 | |||||||||||
2639 | if (PrevField && | ||||||||||
2640 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { | ||||||||||
2641 | SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered) | ||||||||||
2642 | << KnownField << PrevField << DIE->getSourceRange(); | ||||||||||
2643 | |||||||||||
2644 | unsigned OldIndex = NumBases + PrevField->getFieldIndex(); | ||||||||||
2645 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { | ||||||||||
2646 | if (Expr *PrevInit = StructuredList->getInit(OldIndex)) { | ||||||||||
2647 | SemaRef.Diag(PrevInit->getBeginLoc(), | ||||||||||
2648 | diag::note_previous_field_init) | ||||||||||
2649 | << PrevField << PrevInit->getSourceRange(); | ||||||||||
2650 | } | ||||||||||
2651 | } | ||||||||||
2652 | } | ||||||||||
2653 | } | ||||||||||
2654 | |||||||||||
2655 | |||||||||||
2656 | // Update the designator with the field declaration. | ||||||||||
2657 | if (!VerifyOnly) | ||||||||||
2658 | D->setField(*Field); | ||||||||||
2659 | |||||||||||
2660 | // Make sure that our non-designated initializer list has space | ||||||||||
2661 | // for a subobject corresponding to this field. | ||||||||||
2662 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) | ||||||||||
2663 | StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1); | ||||||||||
2664 | |||||||||||
2665 | // This designator names a flexible array member. | ||||||||||
2666 | if (Field->getType()->isIncompleteArrayType()) { | ||||||||||
2667 | bool Invalid = false; | ||||||||||
2668 | if ((DesigIdx + 1) != DIE->size()) { | ||||||||||
2669 | // We can't designate an object within the flexible array | ||||||||||
2670 | // member (because GCC doesn't allow it). | ||||||||||
2671 | if (!VerifyOnly) { | ||||||||||
2672 | DesignatedInitExpr::Designator *NextD | ||||||||||
2673 | = DIE->getDesignator(DesigIdx + 1); | ||||||||||
2674 | SemaRef.Diag(NextD->getBeginLoc(), | ||||||||||
2675 | diag::err_designator_into_flexible_array_member) | ||||||||||
2676 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); | ||||||||||
2677 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | ||||||||||
2678 | << *Field; | ||||||||||
2679 | } | ||||||||||
2680 | Invalid = true; | ||||||||||
2681 | } | ||||||||||
2682 | |||||||||||
2683 | if (!hadError && !isa<InitListExpr>(DIE->getInit()) && | ||||||||||
2684 | !isa<StringLiteral>(DIE->getInit())) { | ||||||||||
2685 | // The initializer is not an initializer list. | ||||||||||
2686 | if (!VerifyOnly) { | ||||||||||
2687 | SemaRef.Diag(DIE->getInit()->getBeginLoc(), | ||||||||||
2688 | diag::err_flexible_array_init_needs_braces) | ||||||||||
2689 | << DIE->getInit()->getSourceRange(); | ||||||||||
2690 | SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member) | ||||||||||
2691 | << *Field; | ||||||||||
2692 | } | ||||||||||
2693 | Invalid = true; | ||||||||||
2694 | } | ||||||||||
2695 | |||||||||||
2696 | // Check GNU flexible array initializer. | ||||||||||
2697 | if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field, | ||||||||||
2698 | TopLevelObject)) | ||||||||||
2699 | Invalid = true; | ||||||||||
2700 | |||||||||||
2701 | if (Invalid) { | ||||||||||
2702 | ++Index; | ||||||||||
2703 | return true; | ||||||||||
2704 | } | ||||||||||
2705 | |||||||||||
2706 | // Initialize the array. | ||||||||||
2707 | bool prevHadError = hadError; | ||||||||||
2708 | unsigned newStructuredIndex = FieldIndex; | ||||||||||
2709 | unsigned OldIndex = Index; | ||||||||||
2710 | IList->setInit(Index, DIE->getInit()); | ||||||||||
2711 | |||||||||||
2712 | InitializedEntity MemberEntity = | ||||||||||
2713 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||||||||
2714 | CheckSubElementType(MemberEntity, IList, Field->getType(), Index, | ||||||||||
2715 | StructuredList, newStructuredIndex); | ||||||||||
2716 | |||||||||||
2717 | IList->setInit(OldIndex, DIE); | ||||||||||
2718 | if (hadError && !prevHadError) { | ||||||||||
2719 | ++Field; | ||||||||||
2720 | ++FieldIndex; | ||||||||||
2721 | if (NextField) | ||||||||||
2722 | *NextField = Field; | ||||||||||
2723 | StructuredIndex = FieldIndex; | ||||||||||
2724 | return true; | ||||||||||
2725 | } | ||||||||||
2726 | } else { | ||||||||||
2727 | // Recurse to check later designated subobjects. | ||||||||||
2728 | QualType FieldType = Field->getType(); | ||||||||||
2729 | unsigned newStructuredIndex = FieldIndex; | ||||||||||
2730 | |||||||||||
2731 | InitializedEntity MemberEntity = | ||||||||||
2732 | InitializedEntity::InitializeMember(*Field, &Entity); | ||||||||||
2733 | if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1, | ||||||||||
2734 | FieldType, nullptr, nullptr, Index, | ||||||||||
2735 | StructuredList, newStructuredIndex, | ||||||||||
2736 | FinishSubobjectInit, false)) | ||||||||||
2737 | return true; | ||||||||||
2738 | } | ||||||||||
2739 | |||||||||||
2740 | // Find the position of the next field to be initialized in this | ||||||||||
2741 | // subobject. | ||||||||||
2742 | ++Field; | ||||||||||
2743 | ++FieldIndex; | ||||||||||
2744 | |||||||||||
2745 | // If this the first designator, our caller will continue checking | ||||||||||
2746 | // the rest of this struct/class/union subobject. | ||||||||||
2747 | if (IsFirstDesignator) { | ||||||||||
2748 | if (NextField) | ||||||||||
2749 | *NextField = Field; | ||||||||||
2750 | StructuredIndex = FieldIndex; | ||||||||||
2751 | return false; | ||||||||||
2752 | } | ||||||||||
2753 | |||||||||||
2754 | if (!FinishSubobjectInit) | ||||||||||
2755 | return false; | ||||||||||
2756 | |||||||||||
2757 | // We've already initialized something in the union; we're done. | ||||||||||
2758 | if (RT->getDecl()->isUnion()) | ||||||||||
2759 | return hadError; | ||||||||||
2760 | |||||||||||
2761 | // Check the remaining fields within this class/struct/union subobject. | ||||||||||
2762 | bool prevHadError = hadError; | ||||||||||
2763 | |||||||||||
2764 | auto NoBases = | ||||||||||
2765 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), | ||||||||||
2766 | CXXRecordDecl::base_class_iterator()); | ||||||||||
2767 | CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field, | ||||||||||
2768 | false, Index, StructuredList, FieldIndex); | ||||||||||
2769 | return hadError && !prevHadError; | ||||||||||
2770 | } | ||||||||||
2771 | |||||||||||
2772 | // C99 6.7.8p6: | ||||||||||
2773 | // | ||||||||||
2774 | // If a designator has the form | ||||||||||
2775 | // | ||||||||||
2776 | // [ constant-expression ] | ||||||||||
2777 | // | ||||||||||
2778 | // then the current object (defined below) shall have array | ||||||||||
2779 | // type and the expression shall be an integer constant | ||||||||||
2780 | // expression. If the array is of unknown size, any | ||||||||||
2781 | // nonnegative value is valid. | ||||||||||
2782 | // | ||||||||||
2783 | // Additionally, cope with the GNU extension that permits | ||||||||||
2784 | // designators of the form | ||||||||||
2785 | // | ||||||||||
2786 | // [ constant-expression ... constant-expression ] | ||||||||||
2787 | const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType); | ||||||||||
2788 | if (!AT) { | ||||||||||
2789 | if (!VerifyOnly) | ||||||||||
2790 | SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array) | ||||||||||
2791 | << CurrentObjectType; | ||||||||||
2792 | ++Index; | ||||||||||
2793 | return true; | ||||||||||
2794 | } | ||||||||||
2795 | |||||||||||
2796 | Expr *IndexExpr = nullptr; | ||||||||||
2797 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; | ||||||||||
2798 | if (D->isArrayDesignator()) { | ||||||||||
2799 | IndexExpr = DIE->getArrayIndex(*D); | ||||||||||
2800 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context); | ||||||||||
2801 | DesignatedEndIndex = DesignatedStartIndex; | ||||||||||
2802 | } else { | ||||||||||
2803 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 2803, __PRETTY_FUNCTION__)); | ||||||||||
2804 | |||||||||||
2805 | DesignatedStartIndex = | ||||||||||
2806 | DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context); | ||||||||||
2807 | DesignatedEndIndex = | ||||||||||
2808 | DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context); | ||||||||||
2809 | IndexExpr = DIE->getArrayRangeEnd(*D); | ||||||||||
2810 | |||||||||||
2811 | // Codegen can't handle evaluating array range designators that have side | ||||||||||
2812 | // effects, because we replicate the AST value for each initialized element. | ||||||||||
2813 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple | ||||||||||
2814 | // elements with something that has a side effect, so codegen can emit an | ||||||||||
2815 | // "error unsupported" error instead of miscompiling the app. | ||||||||||
2816 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& | ||||||||||
2817 | DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly) | ||||||||||
2818 | FullyStructuredList->sawArrayRangeDesignator(); | ||||||||||
2819 | } | ||||||||||
2820 | |||||||||||
2821 | if (isa<ConstantArrayType>(AT)) { | ||||||||||
2822 | llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false); | ||||||||||
2823 | DesignatedStartIndex | ||||||||||
2824 | = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth()); | ||||||||||
2825 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); | ||||||||||
2826 | DesignatedEndIndex | ||||||||||
2827 | = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth()); | ||||||||||
2828 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); | ||||||||||
2829 | if (DesignatedEndIndex >= MaxElements) { | ||||||||||
2830 | if (!VerifyOnly) | ||||||||||
2831 | SemaRef.Diag(IndexExpr->getBeginLoc(), | ||||||||||
2832 | diag::err_array_designator_too_large) | ||||||||||
2833 | << DesignatedEndIndex.toString(10) << MaxElements.toString(10) | ||||||||||
2834 | << IndexExpr->getSourceRange(); | ||||||||||
2835 | ++Index; | ||||||||||
2836 | return true; | ||||||||||
2837 | } | ||||||||||
2838 | } else { | ||||||||||
2839 | unsigned DesignatedIndexBitWidth = | ||||||||||
2840 | ConstantArrayType::getMaxSizeBits(SemaRef.Context); | ||||||||||
2841 | DesignatedStartIndex = | ||||||||||
2842 | DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth); | ||||||||||
2843 | DesignatedEndIndex = | ||||||||||
2844 | DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth); | ||||||||||
2845 | DesignatedStartIndex.setIsUnsigned(true); | ||||||||||
2846 | DesignatedEndIndex.setIsUnsigned(true); | ||||||||||
2847 | } | ||||||||||
2848 | |||||||||||
2849 | bool IsStringLiteralInitUpdate = | ||||||||||
2850 | StructuredList && StructuredList->isStringLiteralInit(); | ||||||||||
2851 | if (IsStringLiteralInitUpdate && VerifyOnly) { | ||||||||||
2852 | // We're just verifying an update to a string literal init. We don't need | ||||||||||
2853 | // to split the string up into individual characters to do that. | ||||||||||
2854 | StructuredList = nullptr; | ||||||||||
2855 | } else if (IsStringLiteralInitUpdate) { | ||||||||||
2856 | // We're modifying a string literal init; we have to decompose the string | ||||||||||
2857 | // so we can modify the individual characters. | ||||||||||
2858 | ASTContext &Context = SemaRef.Context; | ||||||||||
2859 | Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens(); | ||||||||||
2860 | |||||||||||
2861 | // Compute the character type | ||||||||||
2862 | QualType CharTy = AT->getElementType(); | ||||||||||
2863 | |||||||||||
2864 | // Compute the type of the integer literals. | ||||||||||
2865 | QualType PromotedCharTy = CharTy; | ||||||||||
2866 | if (CharTy->isPromotableIntegerType()) | ||||||||||
2867 | PromotedCharTy = Context.getPromotedIntegerType(CharTy); | ||||||||||
2868 | unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy); | ||||||||||
2869 | |||||||||||
2870 | if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) { | ||||||||||
2871 | // Get the length of the string. | ||||||||||
2872 | uint64_t StrLen = SL->getLength(); | ||||||||||
2873 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | ||||||||||
2874 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | ||||||||||
2875 | StructuredList->resizeInits(Context, StrLen); | ||||||||||
2876 | |||||||||||
2877 | // Build a literal for each character in the string, and put them into | ||||||||||
2878 | // the init list. | ||||||||||
2879 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | ||||||||||
2880 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); | ||||||||||
2881 | Expr *Init = new (Context) IntegerLiteral( | ||||||||||
2882 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | ||||||||||
2883 | if (CharTy != PromotedCharTy) | ||||||||||
2884 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | ||||||||||
2885 | Init, nullptr, VK_RValue); | ||||||||||
2886 | StructuredList->updateInit(Context, i, Init); | ||||||||||
2887 | } | ||||||||||
2888 | } else { | ||||||||||
2889 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr); | ||||||||||
2890 | std::string Str; | ||||||||||
2891 | Context.getObjCEncodingForType(E->getEncodedType(), Str); | ||||||||||
2892 | |||||||||||
2893 | // Get the length of the string. | ||||||||||
2894 | uint64_t StrLen = Str.size(); | ||||||||||
2895 | if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen)) | ||||||||||
2896 | StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue(); | ||||||||||
2897 | StructuredList->resizeInits(Context, StrLen); | ||||||||||
2898 | |||||||||||
2899 | // Build a literal for each character in the string, and put them into | ||||||||||
2900 | // the init list. | ||||||||||
2901 | for (unsigned i = 0, e = StrLen; i != e; ++i) { | ||||||||||
2902 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); | ||||||||||
2903 | Expr *Init = new (Context) IntegerLiteral( | ||||||||||
2904 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); | ||||||||||
2905 | if (CharTy != PromotedCharTy) | ||||||||||
2906 | Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast, | ||||||||||
2907 | Init, nullptr, VK_RValue); | ||||||||||
2908 | StructuredList->updateInit(Context, i, Init); | ||||||||||
2909 | } | ||||||||||
2910 | } | ||||||||||
2911 | } | ||||||||||
2912 | |||||||||||
2913 | // Make sure that our non-designated initializer list has space | ||||||||||
2914 | // for a subobject corresponding to this array element. | ||||||||||
2915 | if (StructuredList && | ||||||||||
2916 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) | ||||||||||
2917 | StructuredList->resizeInits(SemaRef.Context, | ||||||||||
2918 | DesignatedEndIndex.getZExtValue() + 1); | ||||||||||
2919 | |||||||||||
2920 | // Repeatedly perform subobject initializations in the range | ||||||||||
2921 | // [DesignatedStartIndex, DesignatedEndIndex]. | ||||||||||
2922 | |||||||||||
2923 | // Move to the next designator | ||||||||||
2924 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); | ||||||||||
2925 | unsigned OldIndex = Index; | ||||||||||
2926 | |||||||||||
2927 | InitializedEntity ElementEntity = | ||||||||||
2928 | InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity); | ||||||||||
2929 | |||||||||||
2930 | while (DesignatedStartIndex <= DesignatedEndIndex) { | ||||||||||
2931 | // Recurse to check later designated subobjects. | ||||||||||
2932 | QualType ElementType = AT->getElementType(); | ||||||||||
2933 | Index = OldIndex; | ||||||||||
2934 | |||||||||||
2935 | ElementEntity.setElementIndex(ElementIndex); | ||||||||||
2936 | if (CheckDesignatedInitializer( | ||||||||||
2937 | ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr, | ||||||||||
2938 | nullptr, Index, StructuredList, ElementIndex, | ||||||||||
2939 | FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), | ||||||||||
2940 | false)) | ||||||||||
2941 | return true; | ||||||||||
2942 | |||||||||||
2943 | // Move to the next index in the array that we'll be initializing. | ||||||||||
2944 | ++DesignatedStartIndex; | ||||||||||
2945 | ElementIndex = DesignatedStartIndex.getZExtValue(); | ||||||||||
2946 | } | ||||||||||
2947 | |||||||||||
2948 | // If this the first designator, our caller will continue checking | ||||||||||
2949 | // the rest of this array subobject. | ||||||||||
2950 | if (IsFirstDesignator) { | ||||||||||
2951 | if (NextElementIndex) | ||||||||||
2952 | *NextElementIndex = DesignatedStartIndex; | ||||||||||
2953 | StructuredIndex = ElementIndex; | ||||||||||
2954 | return false; | ||||||||||
2955 | } | ||||||||||
2956 | |||||||||||
2957 | if (!FinishSubobjectInit) | ||||||||||
2958 | return false; | ||||||||||
2959 | |||||||||||
2960 | // Check the remaining elements within this array subobject. | ||||||||||
2961 | bool prevHadError = hadError; | ||||||||||
2962 | CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex, | ||||||||||
2963 | /*SubobjectIsDesignatorContext=*/false, Index, | ||||||||||
2964 | StructuredList, ElementIndex); | ||||||||||
2965 | return hadError && !prevHadError; | ||||||||||
2966 | } | ||||||||||
2967 | |||||||||||
2968 | // Get the structured initializer list for a subobject of type | ||||||||||
2969 | // @p CurrentObjectType. | ||||||||||
2970 | InitListExpr * | ||||||||||
2971 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, | ||||||||||
2972 | QualType CurrentObjectType, | ||||||||||
2973 | InitListExpr *StructuredList, | ||||||||||
2974 | unsigned StructuredIndex, | ||||||||||
2975 | SourceRange InitRange, | ||||||||||
2976 | bool IsFullyOverwritten) { | ||||||||||
2977 | if (!StructuredList) | ||||||||||
2978 | return nullptr; | ||||||||||
2979 | |||||||||||
2980 | Expr *ExistingInit = nullptr; | ||||||||||
2981 | if (StructuredIndex < StructuredList->getNumInits()) | ||||||||||
2982 | ExistingInit = StructuredList->getInit(StructuredIndex); | ||||||||||
2983 | |||||||||||
2984 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit)) | ||||||||||
2985 | // There might have already been initializers for subobjects of the current | ||||||||||
2986 | // object, but a subsequent initializer list will overwrite the entirety | ||||||||||
2987 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., | ||||||||||
2988 | // | ||||||||||
2989 | // struct P { char x[6]; }; | ||||||||||
2990 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; | ||||||||||
2991 | // | ||||||||||
2992 | // The first designated initializer is ignored, and l.x is just "f". | ||||||||||
2993 | if (!IsFullyOverwritten) | ||||||||||
2994 | return Result; | ||||||||||
2995 | |||||||||||
2996 | if (ExistingInit) { | ||||||||||
2997 | // We are creating an initializer list that initializes the | ||||||||||
2998 | // subobjects of the current object, but there was already an | ||||||||||
2999 | // initialization that completely initialized the current | ||||||||||
3000 | // subobject: | ||||||||||
3001 | // | ||||||||||
3002 | // struct X { int a, b; }; | ||||||||||
3003 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; | ||||||||||
3004 | // | ||||||||||
3005 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, | ||||||||||
3006 | // designated initializer overwrites the [0].b initializer | ||||||||||
3007 | // from the prior initialization. | ||||||||||
3008 | // | ||||||||||
3009 | // When the existing initializer is an expression rather than an | ||||||||||
3010 | // initializer list, we cannot decompose and update it in this way. | ||||||||||
3011 | // For example: | ||||||||||
3012 | // | ||||||||||
3013 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; | ||||||||||
3014 | // | ||||||||||
3015 | // This case is handled by CheckDesignatedInitializer. | ||||||||||
3016 | diagnoseInitOverride(ExistingInit, InitRange); | ||||||||||
3017 | } | ||||||||||
3018 | |||||||||||
3019 | unsigned ExpectedNumInits = 0; | ||||||||||
3020 | if (Index < IList->getNumInits()) { | ||||||||||
3021 | if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index))) | ||||||||||
3022 | ExpectedNumInits = Init->getNumInits(); | ||||||||||
3023 | else | ||||||||||
3024 | ExpectedNumInits = IList->getNumInits() - Index; | ||||||||||
3025 | } | ||||||||||
3026 | |||||||||||
3027 | InitListExpr *Result = | ||||||||||
3028 | createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits); | ||||||||||
3029 | |||||||||||
3030 | // Link this new initializer list into the structured initializer | ||||||||||
3031 | // lists. | ||||||||||
3032 | StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result); | ||||||||||
3033 | return Result; | ||||||||||
3034 | } | ||||||||||
3035 | |||||||||||
3036 | InitListExpr * | ||||||||||
3037 | InitListChecker::createInitListExpr(QualType CurrentObjectType, | ||||||||||
3038 | SourceRange InitRange, | ||||||||||
3039 | unsigned ExpectedNumInits) { | ||||||||||
3040 | InitListExpr *Result | ||||||||||
3041 | = new (SemaRef.Context) InitListExpr(SemaRef.Context, | ||||||||||
3042 | InitRange.getBegin(), None, | ||||||||||
3043 | InitRange.getEnd()); | ||||||||||
3044 | |||||||||||
3045 | QualType ResultType = CurrentObjectType; | ||||||||||
3046 | if (!ResultType->isArrayType()) | ||||||||||
3047 | ResultType = ResultType.getNonLValueExprType(SemaRef.Context); | ||||||||||
3048 | Result->setType(ResultType); | ||||||||||
3049 | |||||||||||
3050 | // Pre-allocate storage for the structured initializer list. | ||||||||||
3051 | unsigned NumElements = 0; | ||||||||||
3052 | |||||||||||
3053 | if (const ArrayType *AType | ||||||||||
3054 | = SemaRef.Context.getAsArrayType(CurrentObjectType)) { | ||||||||||
3055 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) { | ||||||||||
3056 | NumElements = CAType->getSize().getZExtValue(); | ||||||||||
3057 | // Simple heuristic so that we don't allocate a very large | ||||||||||
3058 | // initializer with many empty entries at the end. | ||||||||||
3059 | if (NumElements > ExpectedNumInits) | ||||||||||
3060 | NumElements = 0; | ||||||||||
3061 | } | ||||||||||
3062 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { | ||||||||||
3063 | NumElements = VType->getNumElements(); | ||||||||||
3064 | } else if (CurrentObjectType->isRecordType()) { | ||||||||||
3065 | NumElements = numStructUnionElements(CurrentObjectType); | ||||||||||
3066 | } | ||||||||||
3067 | |||||||||||
3068 | Result->reserveInits(SemaRef.Context, NumElements); | ||||||||||
3069 | |||||||||||
3070 | return Result; | ||||||||||
3071 | } | ||||||||||
3072 | |||||||||||
3073 | /// Update the initializer at index @p StructuredIndex within the | ||||||||||
3074 | /// structured initializer list to the value @p expr. | ||||||||||
3075 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, | ||||||||||
3076 | unsigned &StructuredIndex, | ||||||||||
3077 | Expr *expr) { | ||||||||||
3078 | // No structured initializer list to update | ||||||||||
3079 | if (!StructuredList) | ||||||||||
3080 | return; | ||||||||||
3081 | |||||||||||
3082 | if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context, | ||||||||||
3083 | StructuredIndex, expr)) { | ||||||||||
3084 | // This initializer overwrites a previous initializer. Warn. | ||||||||||
3085 | diagnoseInitOverride(PrevInit, expr->getSourceRange()); | ||||||||||
3086 | } | ||||||||||
3087 | |||||||||||
3088 | ++StructuredIndex; | ||||||||||
3089 | } | ||||||||||
3090 | |||||||||||
3091 | /// Determine whether we can perform aggregate initialization for the purposes | ||||||||||
3092 | /// of overload resolution. | ||||||||||
3093 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( | ||||||||||
3094 | const InitializedEntity &Entity, InitListExpr *From) { | ||||||||||
3095 | QualType Type = Entity.getType(); | ||||||||||
3096 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, | ||||||||||
3097 | /*TreatUnavailableAsInvalid=*/false, | ||||||||||
3098 | /*InOverloadResolution=*/true); | ||||||||||
3099 | return !Check.HadError(); | ||||||||||
3100 | } | ||||||||||
3101 | |||||||||||
3102 | /// Check that the given Index expression is a valid array designator | ||||||||||
3103 | /// value. This is essentially just a wrapper around | ||||||||||
3104 | /// VerifyIntegerConstantExpression that also checks for negative values | ||||||||||
3105 | /// and produces a reasonable diagnostic if there is a | ||||||||||
3106 | /// failure. Returns the index expression, possibly with an implicit cast | ||||||||||
3107 | /// added, on success. If everything went okay, Value will receive the | ||||||||||
3108 | /// value of the constant expression. | ||||||||||
3109 | static ExprResult | ||||||||||
3110 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { | ||||||||||
3111 | SourceLocation Loc = Index->getBeginLoc(); | ||||||||||
3112 | |||||||||||
3113 | // Make sure this is an integer constant expression. | ||||||||||
3114 | ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value); | ||||||||||
3115 | if (Result.isInvalid()) | ||||||||||
3116 | return Result; | ||||||||||
3117 | |||||||||||
3118 | if (Value.isSigned() && Value.isNegative()) | ||||||||||
3119 | return S.Diag(Loc, diag::err_array_designator_negative) | ||||||||||
3120 | << Value.toString(10) << Index->getSourceRange(); | ||||||||||
3121 | |||||||||||
3122 | Value.setIsUnsigned(true); | ||||||||||
3123 | return Result; | ||||||||||
3124 | } | ||||||||||
3125 | |||||||||||
3126 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, | ||||||||||
3127 | SourceLocation EqualOrColonLoc, | ||||||||||
3128 | bool GNUSyntax, | ||||||||||
3129 | ExprResult Init) { | ||||||||||
3130 | typedef DesignatedInitExpr::Designator ASTDesignator; | ||||||||||
3131 | |||||||||||
3132 | bool Invalid = false; | ||||||||||
3133 | SmallVector<ASTDesignator, 32> Designators; | ||||||||||
3134 | SmallVector<Expr *, 32> InitExpressions; | ||||||||||
3135 | |||||||||||
3136 | // Build designators and check array designator expressions. | ||||||||||
3137 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { | ||||||||||
3138 | const Designator &D = Desig.getDesignator(Idx); | ||||||||||
3139 | switch (D.getKind()) { | ||||||||||
3140 | case Designator::FieldDesignator: | ||||||||||
3141 | Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(), | ||||||||||
3142 | D.getFieldLoc())); | ||||||||||
3143 | break; | ||||||||||
3144 | |||||||||||
3145 | case Designator::ArrayDesignator: { | ||||||||||
3146 | Expr *Index = static_cast<Expr *>(D.getArrayIndex()); | ||||||||||
3147 | llvm::APSInt IndexValue; | ||||||||||
3148 | if (!Index->isTypeDependent() && !Index->isValueDependent()) | ||||||||||
3149 | Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get(); | ||||||||||
3150 | if (!Index) | ||||||||||
3151 | Invalid = true; | ||||||||||
3152 | else { | ||||||||||
3153 | Designators.push_back(ASTDesignator(InitExpressions.size(), | ||||||||||
3154 | D.getLBracketLoc(), | ||||||||||
3155 | D.getRBracketLoc())); | ||||||||||
3156 | InitExpressions.push_back(Index); | ||||||||||
3157 | } | ||||||||||
3158 | break; | ||||||||||
3159 | } | ||||||||||
3160 | |||||||||||
3161 | case Designator::ArrayRangeDesignator: { | ||||||||||
3162 | Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart()); | ||||||||||
3163 | Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd()); | ||||||||||
3164 | llvm::APSInt StartValue; | ||||||||||
3165 | llvm::APSInt EndValue; | ||||||||||
3166 | bool StartDependent = StartIndex->isTypeDependent() || | ||||||||||
3167 | StartIndex->isValueDependent(); | ||||||||||
3168 | bool EndDependent = EndIndex->isTypeDependent() || | ||||||||||
3169 | EndIndex->isValueDependent(); | ||||||||||
3170 | if (!StartDependent) | ||||||||||
3171 | StartIndex = | ||||||||||
3172 | CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get(); | ||||||||||
3173 | if (!EndDependent) | ||||||||||
3174 | EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get(); | ||||||||||
3175 | |||||||||||
3176 | if (!StartIndex || !EndIndex) | ||||||||||
3177 | Invalid = true; | ||||||||||
3178 | else { | ||||||||||
3179 | // Make sure we're comparing values with the same bit width. | ||||||||||
3180 | if (StartDependent || EndDependent) { | ||||||||||
3181 | // Nothing to compute. | ||||||||||
3182 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) | ||||||||||
3183 | EndValue = EndValue.extend(StartValue.getBitWidth()); | ||||||||||
3184 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) | ||||||||||
3185 | StartValue = StartValue.extend(EndValue.getBitWidth()); | ||||||||||
3186 | |||||||||||
3187 | if (!StartDependent && !EndDependent && EndValue < StartValue) { | ||||||||||
3188 | Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range) | ||||||||||
3189 | << StartValue.toString(10) << EndValue.toString(10) | ||||||||||
3190 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); | ||||||||||
3191 | Invalid = true; | ||||||||||
3192 | } else { | ||||||||||
3193 | Designators.push_back(ASTDesignator(InitExpressions.size(), | ||||||||||
3194 | D.getLBracketLoc(), | ||||||||||
3195 | D.getEllipsisLoc(), | ||||||||||
3196 | D.getRBracketLoc())); | ||||||||||
3197 | InitExpressions.push_back(StartIndex); | ||||||||||
3198 | InitExpressions.push_back(EndIndex); | ||||||||||
3199 | } | ||||||||||
3200 | } | ||||||||||
3201 | break; | ||||||||||
3202 | } | ||||||||||
3203 | } | ||||||||||
3204 | } | ||||||||||
3205 | |||||||||||
3206 | if (Invalid || Init.isInvalid()) | ||||||||||
3207 | return ExprError(); | ||||||||||
3208 | |||||||||||
3209 | // Clear out the expressions within the designation. | ||||||||||
3210 | Desig.ClearExprs(*this); | ||||||||||
3211 | |||||||||||
3212 | return DesignatedInitExpr::Create(Context, Designators, InitExpressions, | ||||||||||
3213 | EqualOrColonLoc, GNUSyntax, | ||||||||||
3214 | Init.getAs<Expr>()); | ||||||||||
3215 | } | ||||||||||
3216 | |||||||||||
3217 | //===----------------------------------------------------------------------===// | ||||||||||
3218 | // Initialization entity | ||||||||||
3219 | //===----------------------------------------------------------------------===// | ||||||||||
3220 | |||||||||||
3221 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, | ||||||||||
3222 | const InitializedEntity &Parent) | ||||||||||
3223 | : Parent(&Parent), Index(Index) | ||||||||||
3224 | { | ||||||||||
3225 | if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) { | ||||||||||
3226 | Kind = EK_ArrayElement; | ||||||||||
3227 | Type = AT->getElementType(); | ||||||||||
3228 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { | ||||||||||
3229 | Kind = EK_VectorElement; | ||||||||||
3230 | Type = VT->getElementType(); | ||||||||||
3231 | } else { | ||||||||||
3232 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); | ||||||||||
3233 | assert(CT && "Unexpected type")((CT && "Unexpected type") ? static_cast<void> ( 0) : __assert_fail ("CT && \"Unexpected type\"", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3233, __PRETTY_FUNCTION__)); | ||||||||||
3234 | Kind = EK_ComplexElement; | ||||||||||
3235 | Type = CT->getElementType(); | ||||||||||
3236 | } | ||||||||||
3237 | } | ||||||||||
3238 | |||||||||||
3239 | InitializedEntity | ||||||||||
3240 | InitializedEntity::InitializeBase(ASTContext &Context, | ||||||||||
3241 | const CXXBaseSpecifier *Base, | ||||||||||
3242 | bool IsInheritedVirtualBase, | ||||||||||
3243 | const InitializedEntity *Parent) { | ||||||||||
3244 | InitializedEntity Result; | ||||||||||
3245 | Result.Kind = EK_Base; | ||||||||||
3246 | Result.Parent = Parent; | ||||||||||
3247 | Result.Base = reinterpret_cast<uintptr_t>(Base); | ||||||||||
3248 | if (IsInheritedVirtualBase) | ||||||||||
3249 | Result.Base |= 0x01; | ||||||||||
3250 | |||||||||||
3251 | Result.Type = Base->getType(); | ||||||||||
3252 | return Result; | ||||||||||
3253 | } | ||||||||||
3254 | |||||||||||
3255 | DeclarationName InitializedEntity::getName() const { | ||||||||||
3256 | switch (getKind()) { | ||||||||||
3257 | case EK_Parameter: | ||||||||||
3258 | case EK_Parameter_CF_Audited: { | ||||||||||
3259 | ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); | ||||||||||
3260 | return (D ? D->getDeclName() : DeclarationName()); | ||||||||||
3261 | } | ||||||||||
3262 | |||||||||||
3263 | case EK_Variable: | ||||||||||
3264 | case EK_Member: | ||||||||||
3265 | case EK_Binding: | ||||||||||
3266 | return Variable.VariableOrMember->getDeclName(); | ||||||||||
3267 | |||||||||||
3268 | case EK_LambdaCapture: | ||||||||||
3269 | return DeclarationName(Capture.VarID); | ||||||||||
3270 | |||||||||||
3271 | case EK_Result: | ||||||||||
3272 | case EK_StmtExprResult: | ||||||||||
3273 | case EK_Exception: | ||||||||||
3274 | case EK_New: | ||||||||||
3275 | case EK_Temporary: | ||||||||||
3276 | case EK_Base: | ||||||||||
3277 | case EK_Delegating: | ||||||||||
3278 | case EK_ArrayElement: | ||||||||||
3279 | case EK_VectorElement: | ||||||||||
3280 | case EK_ComplexElement: | ||||||||||
3281 | case EK_BlockElement: | ||||||||||
3282 | case EK_LambdaToBlockConversionBlockElement: | ||||||||||
3283 | case EK_CompoundLiteralInit: | ||||||||||
3284 | case EK_RelatedResult: | ||||||||||
3285 | return DeclarationName(); | ||||||||||
3286 | } | ||||||||||
3287 | |||||||||||
3288 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3288); | ||||||||||
3289 | } | ||||||||||
3290 | |||||||||||
3291 | ValueDecl *InitializedEntity::getDecl() const { | ||||||||||
3292 | switch (getKind()) { | ||||||||||
3293 | case EK_Variable: | ||||||||||
3294 | case EK_Member: | ||||||||||
3295 | case EK_Binding: | ||||||||||
3296 | return Variable.VariableOrMember; | ||||||||||
3297 | |||||||||||
3298 | case EK_Parameter: | ||||||||||
3299 | case EK_Parameter_CF_Audited: | ||||||||||
3300 | return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1); | ||||||||||
3301 | |||||||||||
3302 | case EK_Result: | ||||||||||
3303 | case EK_StmtExprResult: | ||||||||||
3304 | case EK_Exception: | ||||||||||
3305 | case EK_New: | ||||||||||
3306 | case EK_Temporary: | ||||||||||
3307 | case EK_Base: | ||||||||||
3308 | case EK_Delegating: | ||||||||||
3309 | case EK_ArrayElement: | ||||||||||
3310 | case EK_VectorElement: | ||||||||||
3311 | case EK_ComplexElement: | ||||||||||
3312 | case EK_BlockElement: | ||||||||||
3313 | case EK_LambdaToBlockConversionBlockElement: | ||||||||||
3314 | case EK_LambdaCapture: | ||||||||||
3315 | case EK_CompoundLiteralInit: | ||||||||||
3316 | case EK_RelatedResult: | ||||||||||
3317 | return nullptr; | ||||||||||
3318 | } | ||||||||||
3319 | |||||||||||
3320 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3320); | ||||||||||
3321 | } | ||||||||||
3322 | |||||||||||
3323 | bool InitializedEntity::allowsNRVO() const { | ||||||||||
3324 | switch (getKind()) { | ||||||||||
3325 | case EK_Result: | ||||||||||
3326 | case EK_Exception: | ||||||||||
3327 | return LocAndNRVO.NRVO; | ||||||||||
3328 | |||||||||||
3329 | case EK_StmtExprResult: | ||||||||||
3330 | case EK_Variable: | ||||||||||
3331 | case EK_Parameter: | ||||||||||
3332 | case EK_Parameter_CF_Audited: | ||||||||||
3333 | case EK_Member: | ||||||||||
3334 | case EK_Binding: | ||||||||||
3335 | case EK_New: | ||||||||||
3336 | case EK_Temporary: | ||||||||||
3337 | case EK_CompoundLiteralInit: | ||||||||||
3338 | case EK_Base: | ||||||||||
3339 | case EK_Delegating: | ||||||||||
3340 | case EK_ArrayElement: | ||||||||||
3341 | case EK_VectorElement: | ||||||||||
3342 | case EK_ComplexElement: | ||||||||||
3343 | case EK_BlockElement: | ||||||||||
3344 | case EK_LambdaToBlockConversionBlockElement: | ||||||||||
3345 | case EK_LambdaCapture: | ||||||||||
3346 | case EK_RelatedResult: | ||||||||||
3347 | break; | ||||||||||
3348 | } | ||||||||||
3349 | |||||||||||
3350 | return false; | ||||||||||
3351 | } | ||||||||||
3352 | |||||||||||
3353 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { | ||||||||||
3354 | assert(getParent() != this)((getParent() != this) ? static_cast<void> (0) : __assert_fail ("getParent() != this", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3354, __PRETTY_FUNCTION__)); | ||||||||||
3355 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; | ||||||||||
3356 | for (unsigned I = 0; I != Depth; ++I) | ||||||||||
3357 | OS << "`-"; | ||||||||||
3358 | |||||||||||
3359 | switch (getKind()) { | ||||||||||
3360 | case EK_Variable: OS << "Variable"; break; | ||||||||||
3361 | case EK_Parameter: OS << "Parameter"; break; | ||||||||||
3362 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter"; | ||||||||||
3363 | break; | ||||||||||
3364 | case EK_Result: OS << "Result"; break; | ||||||||||
3365 | case EK_StmtExprResult: OS << "StmtExprResult"; break; | ||||||||||
3366 | case EK_Exception: OS << "Exception"; break; | ||||||||||
3367 | case EK_Member: OS << "Member"; break; | ||||||||||
3368 | case EK_Binding: OS << "Binding"; break; | ||||||||||
3369 | case EK_New: OS << "New"; break; | ||||||||||
3370 | case EK_Temporary: OS << "Temporary"; break; | ||||||||||
3371 | case EK_CompoundLiteralInit: OS << "CompoundLiteral";break; | ||||||||||
3372 | case EK_RelatedResult: OS << "RelatedResult"; break; | ||||||||||
3373 | case EK_Base: OS << "Base"; break; | ||||||||||
3374 | case EK_Delegating: OS << "Delegating"; break; | ||||||||||
3375 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; | ||||||||||
3376 | case EK_VectorElement: OS << "VectorElement " << Index; break; | ||||||||||
3377 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; | ||||||||||
3378 | case EK_BlockElement: OS << "Block"; break; | ||||||||||
3379 | case EK_LambdaToBlockConversionBlockElement: | ||||||||||
3380 | OS << "Block (lambda)"; | ||||||||||
3381 | break; | ||||||||||
3382 | case EK_LambdaCapture: | ||||||||||
3383 | OS << "LambdaCapture "; | ||||||||||
3384 | OS << DeclarationName(Capture.VarID); | ||||||||||
3385 | break; | ||||||||||
3386 | } | ||||||||||
3387 | |||||||||||
3388 | if (auto *D = getDecl()) { | ||||||||||
3389 | OS << " "; | ||||||||||
3390 | D->printQualifiedName(OS); | ||||||||||
3391 | } | ||||||||||
3392 | |||||||||||
3393 | OS << " '" << getType().getAsString() << "'\n"; | ||||||||||
3394 | |||||||||||
3395 | return Depth + 1; | ||||||||||
3396 | } | ||||||||||
3397 | |||||||||||
3398 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void InitializedEntity::dump() const { | ||||||||||
3399 | dumpImpl(llvm::errs()); | ||||||||||
3400 | } | ||||||||||
3401 | |||||||||||
3402 | //===----------------------------------------------------------------------===// | ||||||||||
3403 | // Initialization sequence | ||||||||||
3404 | //===----------------------------------------------------------------------===// | ||||||||||
3405 | |||||||||||
3406 | void InitializationSequence::Step::Destroy() { | ||||||||||
3407 | switch (Kind) { | ||||||||||
3408 | case SK_ResolveAddressOfOverloadedFunction: | ||||||||||
3409 | case SK_CastDerivedToBaseRValue: | ||||||||||
3410 | case SK_CastDerivedToBaseXValue: | ||||||||||
3411 | case SK_CastDerivedToBaseLValue: | ||||||||||
3412 | case SK_BindReference: | ||||||||||
3413 | case SK_BindReferenceToTemporary: | ||||||||||
3414 | case SK_FinalCopy: | ||||||||||
3415 | case SK_ExtraneousCopyToTemporary: | ||||||||||
3416 | case SK_UserConversion: | ||||||||||
3417 | case SK_QualificationConversionRValue: | ||||||||||
3418 | case SK_QualificationConversionXValue: | ||||||||||
3419 | case SK_QualificationConversionLValue: | ||||||||||
3420 | case SK_AtomicConversion: | ||||||||||
3421 | case SK_ListInitialization: | ||||||||||
3422 | case SK_UnwrapInitList: | ||||||||||
3423 | case SK_RewrapInitList: | ||||||||||
3424 | case SK_ConstructorInitialization: | ||||||||||
3425 | case SK_ConstructorInitializationFromList: | ||||||||||
3426 | case SK_ZeroInitialization: | ||||||||||
3427 | case SK_CAssignment: | ||||||||||
3428 | case SK_StringInit: | ||||||||||
3429 | case SK_ObjCObjectConversion: | ||||||||||
3430 | case SK_ArrayLoopIndex: | ||||||||||
3431 | case SK_ArrayLoopInit: | ||||||||||
3432 | case SK_ArrayInit: | ||||||||||
3433 | case SK_GNUArrayInit: | ||||||||||
3434 | case SK_ParenthesizedArrayInit: | ||||||||||
3435 | case SK_PassByIndirectCopyRestore: | ||||||||||
3436 | case SK_PassByIndirectRestore: | ||||||||||
3437 | case SK_ProduceObjCObject: | ||||||||||
3438 | case SK_StdInitializerList: | ||||||||||
3439 | case SK_StdInitializerListConstructorCall: | ||||||||||
3440 | case SK_OCLSamplerInit: | ||||||||||
3441 | case SK_OCLZeroOpaqueType: | ||||||||||
3442 | break; | ||||||||||
3443 | |||||||||||
3444 | case SK_ConversionSequence: | ||||||||||
3445 | case SK_ConversionSequenceNoNarrowing: | ||||||||||
3446 | delete ICS; | ||||||||||
3447 | } | ||||||||||
3448 | } | ||||||||||
3449 | |||||||||||
3450 | bool InitializationSequence::isDirectReferenceBinding() const { | ||||||||||
3451 | // There can be some lvalue adjustments after the SK_BindReference step. | ||||||||||
3452 | for (auto I = Steps.rbegin(); I != Steps.rend(); ++I) { | ||||||||||
3453 | if (I->Kind == SK_BindReference) | ||||||||||
3454 | return true; | ||||||||||
3455 | if (I->Kind == SK_BindReferenceToTemporary) | ||||||||||
3456 | return false; | ||||||||||
3457 | } | ||||||||||
3458 | return false; | ||||||||||
3459 | } | ||||||||||
3460 | |||||||||||
3461 | bool InitializationSequence::isAmbiguous() const { | ||||||||||
3462 | if (!Failed()) | ||||||||||
3463 | return false; | ||||||||||
3464 | |||||||||||
3465 | switch (getFailureKind()) { | ||||||||||
3466 | case FK_TooManyInitsForReference: | ||||||||||
3467 | case FK_ParenthesizedListInitForReference: | ||||||||||
3468 | case FK_ArrayNeedsInitList: | ||||||||||
3469 | case FK_ArrayNeedsInitListOrStringLiteral: | ||||||||||
3470 | case FK_ArrayNeedsInitListOrWideStringLiteral: | ||||||||||
3471 | case FK_NarrowStringIntoWideCharArray: | ||||||||||
3472 | case FK_WideStringIntoCharArray: | ||||||||||
3473 | case FK_IncompatWideStringIntoWideChar: | ||||||||||
3474 | case FK_PlainStringIntoUTF8Char: | ||||||||||
3475 | case FK_UTF8StringIntoPlainChar: | ||||||||||
3476 | case FK_AddressOfOverloadFailed: // FIXME: Could do better | ||||||||||
3477 | case FK_NonConstLValueReferenceBindingToTemporary: | ||||||||||
3478 | case FK_NonConstLValueReferenceBindingToBitfield: | ||||||||||
3479 | case FK_NonConstLValueReferenceBindingToVectorElement: | ||||||||||
3480 | case FK_NonConstLValueReferenceBindingToUnrelated: | ||||||||||
3481 | case FK_RValueReferenceBindingToLValue: | ||||||||||
3482 | case FK_ReferenceAddrspaceMismatchTemporary: | ||||||||||
3483 | case FK_ReferenceInitDropsQualifiers: | ||||||||||
3484 | case FK_ReferenceInitFailed: | ||||||||||
3485 | case FK_ConversionFailed: | ||||||||||
3486 | case FK_ConversionFromPropertyFailed: | ||||||||||
3487 | case FK_TooManyInitsForScalar: | ||||||||||
3488 | case FK_ParenthesizedListInitForScalar: | ||||||||||
3489 | case FK_ReferenceBindingToInitList: | ||||||||||
3490 | case FK_InitListBadDestinationType: | ||||||||||
3491 | case FK_DefaultInitOfConst: | ||||||||||
3492 | case FK_Incomplete: | ||||||||||
3493 | case FK_ArrayTypeMismatch: | ||||||||||
3494 | case FK_NonConstantArrayInit: | ||||||||||
3495 | case FK_ListInitializationFailed: | ||||||||||
3496 | case FK_VariableLengthArrayHasInitializer: | ||||||||||
3497 | case FK_PlaceholderType: | ||||||||||
3498 | case FK_ExplicitConstructor: | ||||||||||
3499 | case FK_AddressOfUnaddressableFunction: | ||||||||||
3500 | return false; | ||||||||||
3501 | |||||||||||
3502 | case FK_ReferenceInitOverloadFailed: | ||||||||||
3503 | case FK_UserConversionOverloadFailed: | ||||||||||
3504 | case FK_ConstructorOverloadFailed: | ||||||||||
3505 | case FK_ListConstructorOverloadFailed: | ||||||||||
3506 | return FailedOverloadResult == OR_Ambiguous; | ||||||||||
3507 | } | ||||||||||
3508 | |||||||||||
3509 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3509); | ||||||||||
3510 | } | ||||||||||
3511 | |||||||||||
3512 | bool InitializationSequence::isConstructorInitialization() const { | ||||||||||
3513 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; | ||||||||||
3514 | } | ||||||||||
3515 | |||||||||||
3516 | void | ||||||||||
3517 | InitializationSequence | ||||||||||
3518 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, | ||||||||||
3519 | DeclAccessPair Found, | ||||||||||
3520 | bool HadMultipleCandidates) { | ||||||||||
3521 | Step S; | ||||||||||
3522 | S.Kind = SK_ResolveAddressOfOverloadedFunction; | ||||||||||
3523 | S.Type = Function->getType(); | ||||||||||
3524 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | ||||||||||
3525 | S.Function.Function = Function; | ||||||||||
3526 | S.Function.FoundDecl = Found; | ||||||||||
3527 | Steps.push_back(S); | ||||||||||
3528 | } | ||||||||||
3529 | |||||||||||
3530 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, | ||||||||||
3531 | ExprValueKind VK) { | ||||||||||
3532 | Step S; | ||||||||||
3533 | switch (VK) { | ||||||||||
3534 | case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break; | ||||||||||
3535 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; | ||||||||||
3536 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; | ||||||||||
3537 | } | ||||||||||
3538 | S.Type = BaseType; | ||||||||||
3539 | Steps.push_back(S); | ||||||||||
3540 | } | ||||||||||
3541 | |||||||||||
3542 | void InitializationSequence::AddReferenceBindingStep(QualType T, | ||||||||||
3543 | bool BindingTemporary) { | ||||||||||
3544 | Step S; | ||||||||||
3545 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; | ||||||||||
3546 | S.Type = T; | ||||||||||
3547 | Steps.push_back(S); | ||||||||||
3548 | } | ||||||||||
3549 | |||||||||||
3550 | void InitializationSequence::AddFinalCopy(QualType T) { | ||||||||||
3551 | Step S; | ||||||||||
3552 | S.Kind = SK_FinalCopy; | ||||||||||
3553 | S.Type = T; | ||||||||||
3554 | Steps.push_back(S); | ||||||||||
3555 | } | ||||||||||
3556 | |||||||||||
3557 | void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) { | ||||||||||
3558 | Step S; | ||||||||||
3559 | S.Kind = SK_ExtraneousCopyToTemporary; | ||||||||||
3560 | S.Type = T; | ||||||||||
3561 | Steps.push_back(S); | ||||||||||
3562 | } | ||||||||||
3563 | |||||||||||
3564 | void | ||||||||||
3565 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, | ||||||||||
3566 | DeclAccessPair FoundDecl, | ||||||||||
3567 | QualType T, | ||||||||||
3568 | bool HadMultipleCandidates) { | ||||||||||
3569 | Step S; | ||||||||||
3570 | S.Kind = SK_UserConversion; | ||||||||||
3571 | S.Type = T; | ||||||||||
3572 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | ||||||||||
3573 | S.Function.Function = Function; | ||||||||||
3574 | S.Function.FoundDecl = FoundDecl; | ||||||||||
3575 | Steps.push_back(S); | ||||||||||
3576 | } | ||||||||||
3577 | |||||||||||
3578 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, | ||||||||||
3579 | ExprValueKind VK) { | ||||||||||
3580 | Step S; | ||||||||||
3581 | S.Kind = SK_QualificationConversionRValue; // work around a gcc warning | ||||||||||
3582 | switch (VK) { | ||||||||||
3583 | case VK_RValue: | ||||||||||
3584 | S.Kind = SK_QualificationConversionRValue; | ||||||||||
3585 | break; | ||||||||||
3586 | case VK_XValue: | ||||||||||
3587 | S.Kind = SK_QualificationConversionXValue; | ||||||||||
3588 | break; | ||||||||||
3589 | case VK_LValue: | ||||||||||
3590 | S.Kind = SK_QualificationConversionLValue; | ||||||||||
3591 | break; | ||||||||||
3592 | } | ||||||||||
3593 | S.Type = Ty; | ||||||||||
3594 | Steps.push_back(S); | ||||||||||
3595 | } | ||||||||||
3596 | |||||||||||
3597 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { | ||||||||||
3598 | Step S; | ||||||||||
3599 | S.Kind = SK_AtomicConversion; | ||||||||||
3600 | S.Type = Ty; | ||||||||||
3601 | Steps.push_back(S); | ||||||||||
3602 | } | ||||||||||
3603 | |||||||||||
3604 | void InitializationSequence::AddConversionSequenceStep( | ||||||||||
3605 | const ImplicitConversionSequence &ICS, QualType T, | ||||||||||
3606 | bool TopLevelOfInitList) { | ||||||||||
3607 | Step S; | ||||||||||
3608 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing | ||||||||||
3609 | : SK_ConversionSequence; | ||||||||||
3610 | S.Type = T; | ||||||||||
3611 | S.ICS = new ImplicitConversionSequence(ICS); | ||||||||||
3612 | Steps.push_back(S); | ||||||||||
3613 | } | ||||||||||
3614 | |||||||||||
3615 | void InitializationSequence::AddListInitializationStep(QualType T) { | ||||||||||
3616 | Step S; | ||||||||||
3617 | S.Kind = SK_ListInitialization; | ||||||||||
3618 | S.Type = T; | ||||||||||
3619 | Steps.push_back(S); | ||||||||||
3620 | } | ||||||||||
3621 | |||||||||||
3622 | void InitializationSequence::AddConstructorInitializationStep( | ||||||||||
3623 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, | ||||||||||
3624 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { | ||||||||||
3625 | Step S; | ||||||||||
3626 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall | ||||||||||
3627 | : SK_ConstructorInitializationFromList | ||||||||||
3628 | : SK_ConstructorInitialization; | ||||||||||
3629 | S.Type = T; | ||||||||||
3630 | S.Function.HadMultipleCandidates = HadMultipleCandidates; | ||||||||||
3631 | S.Function.Function = Constructor; | ||||||||||
3632 | S.Function.FoundDecl = FoundDecl; | ||||||||||
3633 | Steps.push_back(S); | ||||||||||
3634 | } | ||||||||||
3635 | |||||||||||
3636 | void InitializationSequence::AddZeroInitializationStep(QualType T) { | ||||||||||
3637 | Step S; | ||||||||||
3638 | S.Kind = SK_ZeroInitialization; | ||||||||||
3639 | S.Type = T; | ||||||||||
3640 | Steps.push_back(S); | ||||||||||
3641 | } | ||||||||||
3642 | |||||||||||
3643 | void InitializationSequence::AddCAssignmentStep(QualType T) { | ||||||||||
3644 | Step S; | ||||||||||
3645 | S.Kind = SK_CAssignment; | ||||||||||
3646 | S.Type = T; | ||||||||||
3647 | Steps.push_back(S); | ||||||||||
3648 | } | ||||||||||
3649 | |||||||||||
3650 | void InitializationSequence::AddStringInitStep(QualType T) { | ||||||||||
3651 | Step S; | ||||||||||
3652 | S.Kind = SK_StringInit; | ||||||||||
3653 | S.Type = T; | ||||||||||
3654 | Steps.push_back(S); | ||||||||||
3655 | } | ||||||||||
3656 | |||||||||||
3657 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { | ||||||||||
3658 | Step S; | ||||||||||
3659 | S.Kind = SK_ObjCObjectConversion; | ||||||||||
3660 | S.Type = T; | ||||||||||
3661 | Steps.push_back(S); | ||||||||||
3662 | } | ||||||||||
3663 | |||||||||||
3664 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { | ||||||||||
3665 | Step S; | ||||||||||
3666 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; | ||||||||||
3667 | S.Type = T; | ||||||||||
3668 | Steps.push_back(S); | ||||||||||
3669 | } | ||||||||||
3670 | |||||||||||
3671 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { | ||||||||||
3672 | Step S; | ||||||||||
3673 | S.Kind = SK_ArrayLoopIndex; | ||||||||||
3674 | S.Type = EltT; | ||||||||||
3675 | Steps.insert(Steps.begin(), S); | ||||||||||
3676 | |||||||||||
3677 | S.Kind = SK_ArrayLoopInit; | ||||||||||
3678 | S.Type = T; | ||||||||||
3679 | Steps.push_back(S); | ||||||||||
3680 | } | ||||||||||
3681 | |||||||||||
3682 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { | ||||||||||
3683 | Step S; | ||||||||||
3684 | S.Kind = SK_ParenthesizedArrayInit; | ||||||||||
3685 | S.Type = T; | ||||||||||
3686 | Steps.push_back(S); | ||||||||||
3687 | } | ||||||||||
3688 | |||||||||||
3689 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, | ||||||||||
3690 | bool shouldCopy) { | ||||||||||
3691 | Step s; | ||||||||||
3692 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore | ||||||||||
3693 | : SK_PassByIndirectRestore); | ||||||||||
3694 | s.Type = type; | ||||||||||
3695 | Steps.push_back(s); | ||||||||||
3696 | } | ||||||||||
3697 | |||||||||||
3698 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { | ||||||||||
3699 | Step S; | ||||||||||
3700 | S.Kind = SK_ProduceObjCObject; | ||||||||||
3701 | S.Type = T; | ||||||||||
3702 | Steps.push_back(S); | ||||||||||
3703 | } | ||||||||||
3704 | |||||||||||
3705 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { | ||||||||||
3706 | Step S; | ||||||||||
3707 | S.Kind = SK_StdInitializerList; | ||||||||||
3708 | S.Type = T; | ||||||||||
3709 | Steps.push_back(S); | ||||||||||
3710 | } | ||||||||||
3711 | |||||||||||
3712 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { | ||||||||||
3713 | Step S; | ||||||||||
3714 | S.Kind = SK_OCLSamplerInit; | ||||||||||
3715 | S.Type = T; | ||||||||||
3716 | Steps.push_back(S); | ||||||||||
3717 | } | ||||||||||
3718 | |||||||||||
3719 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { | ||||||||||
3720 | Step S; | ||||||||||
3721 | S.Kind = SK_OCLZeroOpaqueType; | ||||||||||
3722 | S.Type = T; | ||||||||||
3723 | Steps.push_back(S); | ||||||||||
3724 | } | ||||||||||
3725 | |||||||||||
3726 | void InitializationSequence::RewrapReferenceInitList(QualType T, | ||||||||||
3727 | InitListExpr *Syntactic) { | ||||||||||
3728 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3729, __PRETTY_FUNCTION__)) | ||||||||||
3729 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3729, __PRETTY_FUNCTION__)); | ||||||||||
3730 | Step S; | ||||||||||
3731 | S.Kind = SK_UnwrapInitList; | ||||||||||
3732 | S.Type = Syntactic->getInit(0)->getType(); | ||||||||||
3733 | Steps.insert(Steps.begin(), S); | ||||||||||
3734 | |||||||||||
3735 | S.Kind = SK_RewrapInitList; | ||||||||||
3736 | S.Type = T; | ||||||||||
3737 | S.WrappingSyntacticList = Syntactic; | ||||||||||
3738 | Steps.push_back(S); | ||||||||||
3739 | } | ||||||||||
3740 | |||||||||||
3741 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, | ||||||||||
3742 | OverloadingResult Result) { | ||||||||||
3743 | setSequenceKind(FailedSequence); | ||||||||||
3744 | this->Failure = Failure; | ||||||||||
3745 | this->FailedOverloadResult = Result; | ||||||||||
3746 | } | ||||||||||
3747 | |||||||||||
3748 | //===----------------------------------------------------------------------===// | ||||||||||
3749 | // Attempt initialization | ||||||||||
3750 | //===----------------------------------------------------------------------===// | ||||||||||
3751 | |||||||||||
3752 | /// Tries to add a zero initializer. Returns true if that worked. | ||||||||||
3753 | static bool | ||||||||||
3754 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, | ||||||||||
3755 | const InitializedEntity &Entity) { | ||||||||||
3756 | if (Entity.getKind() != InitializedEntity::EK_Variable) | ||||||||||
3757 | return false; | ||||||||||
3758 | |||||||||||
3759 | VarDecl *VD = cast<VarDecl>(Entity.getDecl()); | ||||||||||
3760 | if (VD->getInit() || VD->getEndLoc().isMacroID()) | ||||||||||
3761 | return false; | ||||||||||
3762 | |||||||||||
3763 | QualType VariableTy = VD->getType().getCanonicalType(); | ||||||||||
3764 | SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); | ||||||||||
3765 | std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); | ||||||||||
3766 | if (!Init.empty()) { | ||||||||||
3767 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||||||||
3768 | Sequence.SetZeroInitializationFixit(Init, Loc); | ||||||||||
3769 | return true; | ||||||||||
3770 | } | ||||||||||
3771 | return false; | ||||||||||
3772 | } | ||||||||||
3773 | |||||||||||
3774 | static void MaybeProduceObjCObject(Sema &S, | ||||||||||
3775 | InitializationSequence &Sequence, | ||||||||||
3776 | const InitializedEntity &Entity) { | ||||||||||
3777 | if (!S.getLangOpts().ObjCAutoRefCount) return; | ||||||||||
3778 | |||||||||||
3779 | /// When initializing a parameter, produce the value if it's marked | ||||||||||
3780 | /// __attribute__((ns_consumed)). | ||||||||||
3781 | if (Entity.isParameterKind()) { | ||||||||||
3782 | if (!Entity.isParameterConsumed()) | ||||||||||
3783 | return; | ||||||||||
3784 | |||||||||||
3785 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3786, __PRETTY_FUNCTION__)) | ||||||||||
3786 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3786, __PRETTY_FUNCTION__)); | ||||||||||
3787 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | ||||||||||
3788 | |||||||||||
3789 | /// When initializing a return value, if the return type is a | ||||||||||
3790 | /// retainable type, then returns need to immediately retain the | ||||||||||
3791 | /// object. If an autorelease is required, it will be done at the | ||||||||||
3792 | /// last instant. | ||||||||||
3793 | } else if (Entity.getKind() == InitializedEntity::EK_Result || | ||||||||||
3794 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { | ||||||||||
3795 | if (!Entity.getType()->isObjCRetainableType()) | ||||||||||
3796 | return; | ||||||||||
3797 | |||||||||||
3798 | Sequence.AddProduceObjCObjectStep(Entity.getType()); | ||||||||||
3799 | } | ||||||||||
3800 | } | ||||||||||
3801 | |||||||||||
3802 | static void TryListInitialization(Sema &S, | ||||||||||
3803 | const InitializedEntity &Entity, | ||||||||||
3804 | const InitializationKind &Kind, | ||||||||||
3805 | InitListExpr *InitList, | ||||||||||
3806 | InitializationSequence &Sequence, | ||||||||||
3807 | bool TreatUnavailableAsInvalid); | ||||||||||
3808 | |||||||||||
3809 | /// When initializing from init list via constructor, handle | ||||||||||
3810 | /// initialization of an object of type std::initializer_list<T>. | ||||||||||
3811 | /// | ||||||||||
3812 | /// \return true if we have handled initialization of an object of type | ||||||||||
3813 | /// std::initializer_list<T>, false otherwise. | ||||||||||
3814 | static bool TryInitializerListConstruction(Sema &S, | ||||||||||
3815 | InitListExpr *List, | ||||||||||
3816 | QualType DestType, | ||||||||||
3817 | InitializationSequence &Sequence, | ||||||||||
3818 | bool TreatUnavailableAsInvalid) { | ||||||||||
3819 | QualType E; | ||||||||||
3820 | if (!S.isStdInitializerList(DestType, &E)) | ||||||||||
3821 | return false; | ||||||||||
3822 | |||||||||||
3823 | if (!S.isCompleteType(List->getExprLoc(), E)) { | ||||||||||
3824 | Sequence.setIncompleteTypeFailure(E); | ||||||||||
3825 | return true; | ||||||||||
3826 | } | ||||||||||
3827 | |||||||||||
3828 | // Try initializing a temporary array from the init list. | ||||||||||
3829 | QualType ArrayType = S.Context.getConstantArrayType( | ||||||||||
3830 | E.withConst(), | ||||||||||
3831 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | ||||||||||
3832 | List->getNumInits()), | ||||||||||
3833 | nullptr, clang::ArrayType::Normal, 0); | ||||||||||
3834 | InitializedEntity HiddenArray = | ||||||||||
3835 | InitializedEntity::InitializeTemporary(ArrayType); | ||||||||||
3836 | InitializationKind Kind = InitializationKind::CreateDirectList( | ||||||||||
3837 | List->getExprLoc(), List->getBeginLoc(), List->getEndLoc()); | ||||||||||
3838 | TryListInitialization(S, HiddenArray, Kind, List, Sequence, | ||||||||||
3839 | TreatUnavailableAsInvalid); | ||||||||||
3840 | if (Sequence) | ||||||||||
3841 | Sequence.AddStdInitializerListConstructionStep(DestType); | ||||||||||
3842 | return true; | ||||||||||
3843 | } | ||||||||||
3844 | |||||||||||
3845 | /// Determine if the constructor has the signature of a copy or move | ||||||||||
3846 | /// constructor for the type T of the class in which it was found. That is, | ||||||||||
3847 | /// determine if its first parameter is of type T or reference to (possibly | ||||||||||
3848 | /// cv-qualified) T. | ||||||||||
3849 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, | ||||||||||
3850 | const ConstructorInfo &Info) { | ||||||||||
3851 | if (Info.Constructor->getNumParams() == 0) | ||||||||||
3852 | return false; | ||||||||||
3853 | |||||||||||
3854 | QualType ParmT = | ||||||||||
3855 | Info.Constructor->getParamDecl(0)->getType().getNonReferenceType(); | ||||||||||
3856 | QualType ClassT = | ||||||||||
3857 | Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext())); | ||||||||||
3858 | |||||||||||
3859 | return Ctx.hasSameUnqualifiedType(ParmT, ClassT); | ||||||||||
3860 | } | ||||||||||
3861 | |||||||||||
3862 | static OverloadingResult | ||||||||||
3863 | ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc, | ||||||||||
3864 | MultiExprArg Args, | ||||||||||
3865 | OverloadCandidateSet &CandidateSet, | ||||||||||
3866 | QualType DestType, | ||||||||||
3867 | DeclContext::lookup_result Ctors, | ||||||||||
3868 | OverloadCandidateSet::iterator &Best, | ||||||||||
3869 | bool CopyInitializing, bool AllowExplicit, | ||||||||||
3870 | bool OnlyListConstructors, bool IsListInit, | ||||||||||
3871 | bool SecondStepOfCopyInit = false) { | ||||||||||
3872 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor); | ||||||||||
3873 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | ||||||||||
3874 | |||||||||||
3875 | for (NamedDecl *D : Ctors) { | ||||||||||
3876 | auto Info = getConstructorInfo(D); | ||||||||||
3877 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) | ||||||||||
3878 | continue; | ||||||||||
3879 | |||||||||||
3880 | if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor)) | ||||||||||
3881 | continue; | ||||||||||
3882 | |||||||||||
3883 | // C++11 [over.best.ics]p4: | ||||||||||
3884 | // ... and the constructor or user-defined conversion function is a | ||||||||||
3885 | // candidate by | ||||||||||
3886 | // - 13.3.1.3, when the argument is the temporary in the second step | ||||||||||
3887 | // of a class copy-initialization, or | ||||||||||
3888 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] | ||||||||||
3889 | // - the second phase of 13.3.1.7 when the initializer list has exactly | ||||||||||
3890 | // one element that is itself an initializer list, and the target is | ||||||||||
3891 | // the first parameter of a constructor of class X, and the conversion | ||||||||||
3892 | // is to X or reference to (possibly cv-qualified X), | ||||||||||
3893 | // user-defined conversion sequences are not considered. | ||||||||||
3894 | bool SuppressUserConversions = | ||||||||||
3895 | SecondStepOfCopyInit || | ||||||||||
3896 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) && | ||||||||||
3897 | hasCopyOrMoveCtorParam(S.Context, Info)); | ||||||||||
3898 | |||||||||||
3899 | if (Info.ConstructorTmpl) | ||||||||||
3900 | S.AddTemplateOverloadCandidate( | ||||||||||
3901 | Info.ConstructorTmpl, Info.FoundDecl, | ||||||||||
3902 | /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions, | ||||||||||
3903 | /*PartialOverloading=*/false, AllowExplicit); | ||||||||||
3904 | else { | ||||||||||
3905 | // C++ [over.match.copy]p1: | ||||||||||
3906 | // - When initializing a temporary to be bound to the first parameter | ||||||||||
3907 | // of a constructor [for type T] that takes a reference to possibly | ||||||||||
3908 | // cv-qualified T as its first argument, called with a single | ||||||||||
3909 | // argument in the context of direct-initialization, explicit | ||||||||||
3910 | // conversion functions are also considered. | ||||||||||
3911 | // FIXME: What if a constructor template instantiates to such a signature? | ||||||||||
3912 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && | ||||||||||
3913 | Args.size() == 1 && | ||||||||||
3914 | hasCopyOrMoveCtorParam(S.Context, Info); | ||||||||||
3915 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args, | ||||||||||
3916 | CandidateSet, SuppressUserConversions, | ||||||||||
3917 | /*PartialOverloading=*/false, AllowExplicit, | ||||||||||
3918 | AllowExplicitConv); | ||||||||||
3919 | } | ||||||||||
3920 | } | ||||||||||
3921 | |||||||||||
3922 | // FIXME: Work around a bug in C++17 guaranteed copy elision. | ||||||||||
3923 | // | ||||||||||
3924 | // When initializing an object of class type T by constructor | ||||||||||
3925 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) | ||||||||||
3926 | // from a single expression of class type U, conversion functions of | ||||||||||
3927 | // U that convert to the non-reference type cv T are candidates. | ||||||||||
3928 | // Explicit conversion functions are only candidates during | ||||||||||
3929 | // direct-initialization. | ||||||||||
3930 | // | ||||||||||
3931 | // Note: SecondStepOfCopyInit is only ever true in this case when | ||||||||||
3932 | // evaluating whether to produce a C++98 compatibility warning. | ||||||||||
3933 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && | ||||||||||
3934 | !SecondStepOfCopyInit) { | ||||||||||
3935 | Expr *Initializer = Args[0]; | ||||||||||
3936 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); | ||||||||||
3937 | if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) { | ||||||||||
3938 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); | ||||||||||
3939 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | ||||||||||
3940 | NamedDecl *D = *I; | ||||||||||
3941 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | ||||||||||
3942 | D = D->getUnderlyingDecl(); | ||||||||||
3943 | |||||||||||
3944 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | ||||||||||
3945 | CXXConversionDecl *Conv; | ||||||||||
3946 | if (ConvTemplate) | ||||||||||
3947 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | ||||||||||
3948 | else | ||||||||||
3949 | Conv = cast<CXXConversionDecl>(D); | ||||||||||
3950 | |||||||||||
3951 | if (ConvTemplate) | ||||||||||
3952 | S.AddTemplateConversionCandidate( | ||||||||||
3953 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | ||||||||||
3954 | CandidateSet, AllowExplicit, AllowExplicit, | ||||||||||
3955 | /*AllowResultConversion*/ false); | ||||||||||
3956 | else | ||||||||||
3957 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | ||||||||||
3958 | DestType, CandidateSet, AllowExplicit, | ||||||||||
3959 | AllowExplicit, | ||||||||||
3960 | /*AllowResultConversion*/ false); | ||||||||||
3961 | } | ||||||||||
3962 | } | ||||||||||
3963 | } | ||||||||||
3964 | |||||||||||
3965 | // Perform overload resolution and return the result. | ||||||||||
3966 | return CandidateSet.BestViableFunction(S, DeclLoc, Best); | ||||||||||
3967 | } | ||||||||||
3968 | |||||||||||
3969 | /// Attempt initialization by constructor (C++ [dcl.init]), which | ||||||||||
3970 | /// enumerates the constructors of the initialized entity and performs overload | ||||||||||
3971 | /// resolution to select the best. | ||||||||||
3972 | /// \param DestType The destination class type. | ||||||||||
3973 | /// \param DestArrayType The destination type, which is either DestType or | ||||||||||
3974 | /// a (possibly multidimensional) array of DestType. | ||||||||||
3975 | /// \param IsListInit Is this list-initialization? | ||||||||||
3976 | /// \param IsInitListCopy Is this non-list-initialization resulting from a | ||||||||||
3977 | /// list-initialization from {x} where x is the same | ||||||||||
3978 | /// type as the entity? | ||||||||||
3979 | static void TryConstructorInitialization(Sema &S, | ||||||||||
3980 | const InitializedEntity &Entity, | ||||||||||
3981 | const InitializationKind &Kind, | ||||||||||
3982 | MultiExprArg Args, QualType DestType, | ||||||||||
3983 | QualType DestArrayType, | ||||||||||
3984 | InitializationSequence &Sequence, | ||||||||||
3985 | bool IsListInit = false, | ||||||||||
3986 | bool IsInitListCopy = false) { | ||||||||||
3987 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3990, __PRETTY_FUNCTION__)) | ||||||||||
3988 | (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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3990, __PRETTY_FUNCTION__)) | ||||||||||
3989 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3990, __PRETTY_FUNCTION__)) | ||||||||||
3990 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 3990, __PRETTY_FUNCTION__)); | ||||||||||
3991 | InitListExpr *ILE = | ||||||||||
3992 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr; | ||||||||||
3993 | MultiExprArg UnwrappedArgs = | ||||||||||
3994 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; | ||||||||||
3995 | |||||||||||
3996 | // The type we're constructing needs to be complete. | ||||||||||
3997 | if (!S.isCompleteType(Kind.getLocation(), DestType)) { | ||||||||||
3998 | Sequence.setIncompleteTypeFailure(DestType); | ||||||||||
3999 | return; | ||||||||||
4000 | } | ||||||||||
4001 | |||||||||||
4002 | // C++17 [dcl.init]p17: | ||||||||||
4003 | // - If the initializer expression is a prvalue and the cv-unqualified | ||||||||||
4004 | // version of the source type is the same class as the class of the | ||||||||||
4005 | // destination, the initializer expression is used to initialize the | ||||||||||
4006 | // destination object. | ||||||||||
4007 | // Per DR (no number yet), this does not apply when initializing a base | ||||||||||
4008 | // class or delegating to another constructor from a mem-initializer. | ||||||||||
4009 | // ObjC++: Lambda captured by the block in the lambda to block conversion | ||||||||||
4010 | // should avoid copy elision. | ||||||||||
4011 | if (S.getLangOpts().CPlusPlus17 && | ||||||||||
4012 | Entity.getKind() != InitializedEntity::EK_Base && | ||||||||||
4013 | Entity.getKind() != InitializedEntity::EK_Delegating && | ||||||||||
4014 | Entity.getKind() != | ||||||||||
4015 | InitializedEntity::EK_LambdaToBlockConversionBlockElement && | ||||||||||
4016 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isRValue() && | ||||||||||
4017 | S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) { | ||||||||||
4018 | // Convert qualifications if necessary. | ||||||||||
4019 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | ||||||||||
4020 | if (ILE) | ||||||||||
4021 | Sequence.RewrapReferenceInitList(DestType, ILE); | ||||||||||
4022 | return; | ||||||||||
4023 | } | ||||||||||
4024 | |||||||||||
4025 | const RecordType *DestRecordType = DestType->getAs<RecordType>(); | ||||||||||
4026 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4026, __PRETTY_FUNCTION__)); | ||||||||||
4027 | CXXRecordDecl *DestRecordDecl | ||||||||||
4028 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | ||||||||||
4029 | |||||||||||
4030 | // Build the candidate set directly in the initialization sequence | ||||||||||
4031 | // structure, so that it will persist if we fail. | ||||||||||
4032 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | ||||||||||
4033 | |||||||||||
4034 | // Determine whether we are allowed to call explicit constructors or | ||||||||||
4035 | // explicit conversion operators. | ||||||||||
4036 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; | ||||||||||
4037 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; | ||||||||||
4038 | |||||||||||
4039 | // - Otherwise, if T is a class type, constructors are considered. The | ||||||||||
4040 | // applicable constructors are enumerated, and the best one is chosen | ||||||||||
4041 | // through overload resolution. | ||||||||||
4042 | DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl); | ||||||||||
4043 | |||||||||||
4044 | OverloadingResult Result = OR_No_Viable_Function; | ||||||||||
4045 | OverloadCandidateSet::iterator Best; | ||||||||||
4046 | bool AsInitializerList = false; | ||||||||||
4047 | |||||||||||
4048 | // C++11 [over.match.list]p1, per DR1467: | ||||||||||
4049 | // When objects of non-aggregate type T are list-initialized, such that | ||||||||||
4050 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed | ||||||||||
4051 | // according to the rules in this section, overload resolution selects | ||||||||||
4052 | // the constructor in two phases: | ||||||||||
4053 | // | ||||||||||
4054 | // - Initially, the candidate functions are the initializer-list | ||||||||||
4055 | // constructors of the class T and the argument list consists of the | ||||||||||
4056 | // initializer list as a single argument. | ||||||||||
4057 | if (IsListInit) { | ||||||||||
4058 | AsInitializerList = true; | ||||||||||
4059 | |||||||||||
4060 | // If the initializer list has no elements and T has a default constructor, | ||||||||||
4061 | // the first phase is omitted. | ||||||||||
4062 | if (!(UnwrappedArgs.empty() && DestRecordDecl->hasDefaultConstructor())) | ||||||||||
4063 | Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, | ||||||||||
4064 | CandidateSet, DestType, Ctors, Best, | ||||||||||
4065 | CopyInitialization, AllowExplicit, | ||||||||||
4066 | /*OnlyListConstructors=*/true, | ||||||||||
4067 | IsListInit); | ||||||||||
4068 | } | ||||||||||
4069 | |||||||||||
4070 | // C++11 [over.match.list]p1: | ||||||||||
4071 | // - If no viable initializer-list constructor is found, overload resolution | ||||||||||
4072 | // is performed again, where the candidate functions are all the | ||||||||||
4073 | // constructors of the class T and the argument list consists of the | ||||||||||
4074 | // elements of the initializer list. | ||||||||||
4075 | if (Result == OR_No_Viable_Function) { | ||||||||||
4076 | AsInitializerList = false; | ||||||||||
4077 | Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs, | ||||||||||
4078 | CandidateSet, DestType, Ctors, Best, | ||||||||||
4079 | CopyInitialization, AllowExplicit, | ||||||||||
4080 | /*OnlyListConstructors=*/false, | ||||||||||
4081 | IsListInit); | ||||||||||
4082 | } | ||||||||||
4083 | if (Result) { | ||||||||||
4084 | Sequence.SetOverloadFailure(IsListInit ? | ||||||||||
4085 | InitializationSequence::FK_ListConstructorOverloadFailed : | ||||||||||
4086 | InitializationSequence::FK_ConstructorOverloadFailed, | ||||||||||
4087 | Result); | ||||||||||
4088 | return; | ||||||||||
4089 | } | ||||||||||
4090 | |||||||||||
4091 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | ||||||||||
4092 | |||||||||||
4093 | // In C++17, ResolveConstructorOverload can select a conversion function | ||||||||||
4094 | // instead of a constructor. | ||||||||||
4095 | if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) { | ||||||||||
4096 | // Add the user-defined conversion step that calls the conversion function. | ||||||||||
4097 | QualType ConvType = CD->getConversionType(); | ||||||||||
4098 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4099, __PRETTY_FUNCTION__)) | ||||||||||
4099 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4099, __PRETTY_FUNCTION__)); | ||||||||||
4100 | Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType, | ||||||||||
4101 | HadMultipleCandidates); | ||||||||||
4102 | if (!S.Context.hasSameType(ConvType, DestType)) | ||||||||||
4103 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | ||||||||||
4104 | if (IsListInit) | ||||||||||
4105 | Sequence.RewrapReferenceInitList(Entity.getType(), ILE); | ||||||||||
4106 | return; | ||||||||||
4107 | } | ||||||||||
4108 | |||||||||||
4109 | // C++11 [dcl.init]p6: | ||||||||||
4110 | // If a program calls for the default initialization of an object | ||||||||||
4111 | // of a const-qualified type T, T shall be a class type with a | ||||||||||
4112 | // user-provided default constructor. | ||||||||||
4113 | // C++ core issue 253 proposal: | ||||||||||
4114 | // If the implicit default constructor initializes all subobjects, no | ||||||||||
4115 | // initializer should be required. | ||||||||||
4116 | // The 253 proposal is for example needed to process libstdc++ headers in 5.x. | ||||||||||
4117 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | ||||||||||
4118 | if (Kind.getKind() == InitializationKind::IK_Default && | ||||||||||
4119 | Entity.getType().isConstQualified()) { | ||||||||||
4120 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { | ||||||||||
4121 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | ||||||||||
4122 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | ||||||||||
4123 | return; | ||||||||||
4124 | } | ||||||||||
4125 | } | ||||||||||
4126 | |||||||||||
4127 | // C++11 [over.match.list]p1: | ||||||||||
4128 | // In copy-list-initialization, if an explicit constructor is chosen, the | ||||||||||
4129 | // initializer is ill-formed. | ||||||||||
4130 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { | ||||||||||
4131 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); | ||||||||||
4132 | return; | ||||||||||
4133 | } | ||||||||||
4134 | |||||||||||
4135 | // Add the constructor initialization step. Any cv-qualification conversion is | ||||||||||
4136 | // subsumed by the initialization. | ||||||||||
4137 | Sequence.AddConstructorInitializationStep( | ||||||||||
4138 | Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates, | ||||||||||
4139 | IsListInit | IsInitListCopy, AsInitializerList); | ||||||||||
4140 | } | ||||||||||
4141 | |||||||||||
4142 | static bool | ||||||||||
4143 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, | ||||||||||
4144 | Expr *Initializer, | ||||||||||
4145 | QualType &SourceType, | ||||||||||
4146 | QualType &UnqualifiedSourceType, | ||||||||||
4147 | QualType UnqualifiedTargetType, | ||||||||||
4148 | InitializationSequence &Sequence) { | ||||||||||
4149 | if (S.Context.getCanonicalType(UnqualifiedSourceType) == | ||||||||||
4150 | S.Context.OverloadTy) { | ||||||||||
4151 | DeclAccessPair Found; | ||||||||||
4152 | bool HadMultipleCandidates = false; | ||||||||||
4153 | if (FunctionDecl *Fn | ||||||||||
4154 | = S.ResolveAddressOfOverloadedFunction(Initializer, | ||||||||||
4155 | UnqualifiedTargetType, | ||||||||||
4156 | false, Found, | ||||||||||
4157 | &HadMultipleCandidates)) { | ||||||||||
4158 | Sequence.AddAddressOverloadResolutionStep(Fn, Found, | ||||||||||
4159 | HadMultipleCandidates); | ||||||||||
4160 | SourceType = Fn->getType(); | ||||||||||
4161 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); | ||||||||||
4162 | } else if (!UnqualifiedTargetType->isRecordType()) { | ||||||||||
4163 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||||||||
4164 | return true; | ||||||||||
4165 | } | ||||||||||
4166 | } | ||||||||||
4167 | return false; | ||||||||||
4168 | } | ||||||||||
4169 | |||||||||||
4170 | static void TryReferenceInitializationCore(Sema &S, | ||||||||||
4171 | const InitializedEntity &Entity, | ||||||||||
4172 | const InitializationKind &Kind, | ||||||||||
4173 | Expr *Initializer, | ||||||||||
4174 | QualType cv1T1, QualType T1, | ||||||||||
4175 | Qualifiers T1Quals, | ||||||||||
4176 | QualType cv2T2, QualType T2, | ||||||||||
4177 | Qualifiers T2Quals, | ||||||||||
4178 | InitializationSequence &Sequence); | ||||||||||
4179 | |||||||||||
4180 | static void TryValueInitialization(Sema &S, | ||||||||||
4181 | const InitializedEntity &Entity, | ||||||||||
4182 | const InitializationKind &Kind, | ||||||||||
4183 | InitializationSequence &Sequence, | ||||||||||
4184 | InitListExpr *InitList = nullptr); | ||||||||||
4185 | |||||||||||
4186 | /// Attempt list initialization of a reference. | ||||||||||
4187 | static void TryReferenceListInitialization(Sema &S, | ||||||||||
4188 | const InitializedEntity &Entity, | ||||||||||
4189 | const InitializationKind &Kind, | ||||||||||
4190 | InitListExpr *InitList, | ||||||||||
4191 | InitializationSequence &Sequence, | ||||||||||
4192 | bool TreatUnavailableAsInvalid) { | ||||||||||
4193 | // First, catch C++03 where this isn't possible. | ||||||||||
4194 | if (!S.getLangOpts().CPlusPlus11) { | ||||||||||
4195 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | ||||||||||
4196 | return; | ||||||||||
4197 | } | ||||||||||
4198 | // Can't reference initialize a compound literal. | ||||||||||
4199 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { | ||||||||||
4200 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); | ||||||||||
4201 | return; | ||||||||||
4202 | } | ||||||||||
4203 | |||||||||||
4204 | QualType DestType = Entity.getType(); | ||||||||||
4205 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||||||||
4206 | Qualifiers T1Quals; | ||||||||||
4207 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | ||||||||||
4208 | |||||||||||
4209 | // Reference initialization via an initializer list works thus: | ||||||||||
4210 | // If the initializer list consists of a single element that is | ||||||||||
4211 | // reference-related to the referenced type, bind directly to that element | ||||||||||
4212 | // (possibly creating temporaries). | ||||||||||
4213 | // Otherwise, initialize a temporary with the initializer list and | ||||||||||
4214 | // bind to that. | ||||||||||
4215 | if (InitList->getNumInits() == 1) { | ||||||||||
4216 | Expr *Initializer = InitList->getInit(0); | ||||||||||
4217 | QualType cv2T2 = Initializer->getType(); | ||||||||||
4218 | Qualifiers T2Quals; | ||||||||||
4219 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | ||||||||||
4220 | |||||||||||
4221 | // If this fails, creating a temporary wouldn't work either. | ||||||||||
4222 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | ||||||||||
4223 | T1, Sequence)) | ||||||||||
4224 | return; | ||||||||||
4225 | |||||||||||
4226 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||||||||
4227 | Sema::ReferenceCompareResult RefRelationship | ||||||||||
4228 | = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2); | ||||||||||
4229 | if (RefRelationship >= Sema::Ref_Related) { | ||||||||||
4230 | // Try to bind the reference here. | ||||||||||
4231 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | ||||||||||
4232 | T1Quals, cv2T2, T2, T2Quals, Sequence); | ||||||||||
4233 | if (Sequence) | ||||||||||
4234 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | ||||||||||
4235 | return; | ||||||||||
4236 | } | ||||||||||
4237 | |||||||||||
4238 | // Update the initializer if we've resolved an overloaded function. | ||||||||||
4239 | if (Sequence.step_begin() != Sequence.step_end()) | ||||||||||
4240 | Sequence.RewrapReferenceInitList(cv1T1, InitList); | ||||||||||
4241 | } | ||||||||||
4242 | |||||||||||
4243 | // Not reference-related. Create a temporary and bind to that. | ||||||||||
4244 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1); | ||||||||||
4245 | |||||||||||
4246 | TryListInitialization(S, TempEntity, Kind, InitList, Sequence, | ||||||||||
4247 | TreatUnavailableAsInvalid); | ||||||||||
4248 | if (Sequence) { | ||||||||||
4249 | if (DestType->isRValueReferenceType() || | ||||||||||
4250 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) | ||||||||||
4251 | Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true); | ||||||||||
4252 | else | ||||||||||
4253 | Sequence.SetFailed( | ||||||||||
4254 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); | ||||||||||
4255 | } | ||||||||||
4256 | } | ||||||||||
4257 | |||||||||||
4258 | /// Attempt list initialization (C++0x [dcl.init.list]) | ||||||||||
4259 | static void TryListInitialization(Sema &S, | ||||||||||
4260 | const InitializedEntity &Entity, | ||||||||||
4261 | const InitializationKind &Kind, | ||||||||||
4262 | InitListExpr *InitList, | ||||||||||
4263 | InitializationSequence &Sequence, | ||||||||||
4264 | bool TreatUnavailableAsInvalid) { | ||||||||||
4265 | QualType DestType = Entity.getType(); | ||||||||||
4266 | |||||||||||
4267 | // C++ doesn't allow scalar initialization with more than one argument. | ||||||||||
4268 | // But C99 complex numbers are scalars and it makes sense there. | ||||||||||
4269 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && | ||||||||||
4270 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { | ||||||||||
4271 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); | ||||||||||
4272 | return; | ||||||||||
4273 | } | ||||||||||
4274 | if (DestType->isReferenceType()) { | ||||||||||
4275 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, | ||||||||||
4276 | TreatUnavailableAsInvalid); | ||||||||||
4277 | return; | ||||||||||
4278 | } | ||||||||||
4279 | |||||||||||
4280 | if (DestType->isRecordType() && | ||||||||||
4281 | !S.isCompleteType(InitList->getBeginLoc(), DestType)) { | ||||||||||
4282 | Sequence.setIncompleteTypeFailure(DestType); | ||||||||||
4283 | return; | ||||||||||
4284 | } | ||||||||||
4285 | |||||||||||
4286 | // C++11 [dcl.init.list]p3, per DR1467: | ||||||||||
4287 | // - If T is a class type and the initializer list has a single element of | ||||||||||
4288 | // type cv U, where U is T or a class derived from T, the object is | ||||||||||
4289 | // initialized from that element (by copy-initialization for | ||||||||||
4290 | // copy-list-initialization, or by direct-initialization for | ||||||||||
4291 | // direct-list-initialization). | ||||||||||
4292 | // - Otherwise, if T is a character array and the initializer list has a | ||||||||||
4293 | // single element that is an appropriately-typed string literal | ||||||||||
4294 | // (8.5.2 [dcl.init.string]), initialization is performed as described | ||||||||||
4295 | // in that section. | ||||||||||
4296 | // - Otherwise, if T is an aggregate, [...] (continue below). | ||||||||||
4297 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1) { | ||||||||||
4298 | if (DestType->isRecordType()) { | ||||||||||
4299 | QualType InitType = InitList->getInit(0)->getType(); | ||||||||||
4300 | if (S.Context.hasSameUnqualifiedType(InitType, DestType) || | ||||||||||
4301 | S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) { | ||||||||||
4302 | Expr *InitListAsExpr = InitList; | ||||||||||
4303 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | ||||||||||
4304 | DestType, Sequence, | ||||||||||
4305 | /*InitListSyntax*/false, | ||||||||||
4306 | /*IsInitListCopy*/true); | ||||||||||
4307 | return; | ||||||||||
4308 | } | ||||||||||
4309 | } | ||||||||||
4310 | if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) { | ||||||||||
4311 | Expr *SubInit[1] = {InitList->getInit(0)}; | ||||||||||
4312 | if (!isa<VariableArrayType>(DestAT) && | ||||||||||
4313 | IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) { | ||||||||||
4314 | InitializationKind SubKind = | ||||||||||
4315 | Kind.getKind() == InitializationKind::IK_DirectList | ||||||||||
4316 | ? InitializationKind::CreateDirect(Kind.getLocation(), | ||||||||||
4317 | InitList->getLBraceLoc(), | ||||||||||
4318 | InitList->getRBraceLoc()) | ||||||||||
4319 | : Kind; | ||||||||||
4320 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | ||||||||||
4321 | /*TopLevelOfInitList*/ true, | ||||||||||
4322 | TreatUnavailableAsInvalid); | ||||||||||
4323 | |||||||||||
4324 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if | ||||||||||
4325 | // the element is not an appropriately-typed string literal, in which | ||||||||||
4326 | // case we should proceed as in C++11 (below). | ||||||||||
4327 | if (Sequence) { | ||||||||||
4328 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | ||||||||||
4329 | return; | ||||||||||
4330 | } | ||||||||||
4331 | } | ||||||||||
4332 | } | ||||||||||
4333 | } | ||||||||||
4334 | |||||||||||
4335 | // C++11 [dcl.init.list]p3: | ||||||||||
4336 | // - If T is an aggregate, aggregate initialization is performed. | ||||||||||
4337 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || | ||||||||||
4338 | (S.getLangOpts().CPlusPlus11 && | ||||||||||
4339 | S.isStdInitializerList(DestType, nullptr))) { | ||||||||||
4340 | if (S.getLangOpts().CPlusPlus11) { | ||||||||||
4341 | // - Otherwise, if the initializer list has no elements and T is a | ||||||||||
4342 | // class type with a default constructor, the object is | ||||||||||
4343 | // value-initialized. | ||||||||||
4344 | if (InitList->getNumInits() == 0) { | ||||||||||
4345 | CXXRecordDecl *RD = DestType->getAsCXXRecordDecl(); | ||||||||||
4346 | if (RD->hasDefaultConstructor()) { | ||||||||||
4347 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); | ||||||||||
4348 | return; | ||||||||||
4349 | } | ||||||||||
4350 | } | ||||||||||
4351 | |||||||||||
4352 | // - Otherwise, if T is a specialization of std::initializer_list<E>, | ||||||||||
4353 | // an initializer_list object constructed [...] | ||||||||||
4354 | if (TryInitializerListConstruction(S, InitList, DestType, Sequence, | ||||||||||
4355 | TreatUnavailableAsInvalid)) | ||||||||||
4356 | return; | ||||||||||
4357 | |||||||||||
4358 | // - Otherwise, if T is a class type, constructors are considered. | ||||||||||
4359 | Expr *InitListAsExpr = InitList; | ||||||||||
4360 | TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType, | ||||||||||
4361 | DestType, Sequence, /*InitListSyntax*/true); | ||||||||||
4362 | } else | ||||||||||
4363 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); | ||||||||||
4364 | return; | ||||||||||
4365 | } | ||||||||||
4366 | |||||||||||
4367 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && | ||||||||||
4368 | InitList->getNumInits() == 1) { | ||||||||||
4369 | Expr *E = InitList->getInit(0); | ||||||||||
4370 | |||||||||||
4371 | // - Otherwise, if T is an enumeration with a fixed underlying type, | ||||||||||
4372 | // the initializer-list has a single element v, and the initialization | ||||||||||
4373 | // is direct-list-initialization, the object is initialized with the | ||||||||||
4374 | // value T(v); if a narrowing conversion is required to convert v to | ||||||||||
4375 | // the underlying type of T, the program is ill-formed. | ||||||||||
4376 | auto *ET = DestType->getAs<EnumType>(); | ||||||||||
4377 | if (S.getLangOpts().CPlusPlus17 && | ||||||||||
4378 | Kind.getKind() == InitializationKind::IK_DirectList && | ||||||||||
4379 | ET && ET->getDecl()->isFixed() && | ||||||||||
4380 | !S.Context.hasSameUnqualifiedType(E->getType(), DestType) && | ||||||||||
4381 | (E->getType()->isIntegralOrEnumerationType() || | ||||||||||
4382 | E->getType()->isFloatingType())) { | ||||||||||
4383 | // There are two ways that T(v) can work when T is an enumeration type. | ||||||||||
4384 | // If there is either an implicit conversion sequence from v to T or | ||||||||||
4385 | // a conversion function that can convert from v to T, then we use that. | ||||||||||
4386 | // Otherwise, if v is of integral, enumeration, or floating-point type, | ||||||||||
4387 | // it is converted to the enumeration type via its underlying type. | ||||||||||
4388 | // There is no overlap possible between these two cases (except when the | ||||||||||
4389 | // source value is already of the destination type), and the first | ||||||||||
4390 | // case is handled by the general case for single-element lists below. | ||||||||||
4391 | ImplicitConversionSequence ICS; | ||||||||||
4392 | ICS.setStandard(); | ||||||||||
4393 | ICS.Standard.setAsIdentityConversion(); | ||||||||||
4394 | if (!E->isRValue()) | ||||||||||
4395 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | ||||||||||
4396 | // If E is of a floating-point type, then the conversion is ill-formed | ||||||||||
4397 | // due to narrowing, but go through the motions in order to produce the | ||||||||||
4398 | // right diagnostic. | ||||||||||
4399 | ICS.Standard.Second = E->getType()->isFloatingType() | ||||||||||
4400 | ? ICK_Floating_Integral | ||||||||||
4401 | : ICK_Integral_Conversion; | ||||||||||
4402 | ICS.Standard.setFromType(E->getType()); | ||||||||||
4403 | ICS.Standard.setToType(0, E->getType()); | ||||||||||
4404 | ICS.Standard.setToType(1, DestType); | ||||||||||
4405 | ICS.Standard.setToType(2, DestType); | ||||||||||
4406 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2), | ||||||||||
4407 | /*TopLevelOfInitList*/true); | ||||||||||
4408 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | ||||||||||
4409 | return; | ||||||||||
4410 | } | ||||||||||
4411 | |||||||||||
4412 | // - Otherwise, if the initializer list has a single element of type E | ||||||||||
4413 | // [...references are handled above...], the object or reference is | ||||||||||
4414 | // initialized from that element (by copy-initialization for | ||||||||||
4415 | // copy-list-initialization, or by direct-initialization for | ||||||||||
4416 | // direct-list-initialization); if a narrowing conversion is required | ||||||||||
4417 | // to convert the element to T, the program is ill-formed. | ||||||||||
4418 | // | ||||||||||
4419 | // Per core-24034, this is direct-initialization if we were performing | ||||||||||
4420 | // direct-list-initialization and copy-initialization otherwise. | ||||||||||
4421 | // We can't use InitListChecker for this, because it always performs | ||||||||||
4422 | // copy-initialization. This only matters if we might use an 'explicit' | ||||||||||
4423 | // conversion operator, so we only need to handle the cases where the source | ||||||||||
4424 | // is of record type. | ||||||||||
4425 | if (InitList->getInit(0)->getType()->isRecordType()) { | ||||||||||
4426 | InitializationKind SubKind = | ||||||||||
4427 | Kind.getKind() == InitializationKind::IK_DirectList | ||||||||||
4428 | ? InitializationKind::CreateDirect(Kind.getLocation(), | ||||||||||
4429 | InitList->getLBraceLoc(), | ||||||||||
4430 | InitList->getRBraceLoc()) | ||||||||||
4431 | : Kind; | ||||||||||
4432 | Expr *SubInit[1] = { InitList->getInit(0) }; | ||||||||||
4433 | Sequence.InitializeFrom(S, Entity, SubKind, SubInit, | ||||||||||
4434 | /*TopLevelOfInitList*/true, | ||||||||||
4435 | TreatUnavailableAsInvalid); | ||||||||||
4436 | if (Sequence) | ||||||||||
4437 | Sequence.RewrapReferenceInitList(Entity.getType(), InitList); | ||||||||||
4438 | return; | ||||||||||
4439 | } | ||||||||||
4440 | } | ||||||||||
4441 | |||||||||||
4442 | InitListChecker CheckInitList(S, Entity, InitList, | ||||||||||
4443 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); | ||||||||||
4444 | if (CheckInitList.HadError()) { | ||||||||||
4445 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); | ||||||||||
4446 | return; | ||||||||||
4447 | } | ||||||||||
4448 | |||||||||||
4449 | // Add the list initialization step with the built init list. | ||||||||||
4450 | Sequence.AddListInitializationStep(DestType); | ||||||||||
4451 | } | ||||||||||
4452 | |||||||||||
4453 | /// Try a reference initialization that involves calling a conversion | ||||||||||
4454 | /// function. | ||||||||||
4455 | static OverloadingResult TryRefInitWithConversionFunction( | ||||||||||
4456 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, | ||||||||||
4457 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, | ||||||||||
4458 | InitializationSequence &Sequence) { | ||||||||||
4459 | QualType DestType = Entity.getType(); | ||||||||||
4460 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||||||||
4461 | QualType T1 = cv1T1.getUnqualifiedType(); | ||||||||||
4462 | QualType cv2T2 = Initializer->getType(); | ||||||||||
4463 | QualType T2 = cv2T2.getUnqualifiedType(); | ||||||||||
4464 | |||||||||||
4465 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4466, __PRETTY_FUNCTION__)) | ||||||||||
4466 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4466, __PRETTY_FUNCTION__)); | ||||||||||
4467 | |||||||||||
4468 | // Build the candidate set directly in the initialization sequence | ||||||||||
4469 | // structure, so that it will persist if we fail. | ||||||||||
4470 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | ||||||||||
4471 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | ||||||||||
4472 | |||||||||||
4473 | // Determine whether we are allowed to call explicit conversion operators. | ||||||||||
4474 | // Note that none of [over.match.copy], [over.match.conv], nor | ||||||||||
4475 | // [over.match.ref] permit an explicit constructor to be chosen when | ||||||||||
4476 | // initializing a reference, not even for direct-initialization. | ||||||||||
4477 | bool AllowExplicitCtors = false; | ||||||||||
4478 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); | ||||||||||
4479 | |||||||||||
4480 | const RecordType *T1RecordType = nullptr; | ||||||||||
4481 | if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) && | ||||||||||
4482 | S.isCompleteType(Kind.getLocation(), T1)) { | ||||||||||
4483 | // The type we're converting to is a class type. Enumerate its constructors | ||||||||||
4484 | // to see if there is a suitable conversion. | ||||||||||
4485 | CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl()); | ||||||||||
4486 | |||||||||||
4487 | for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) { | ||||||||||
4488 | auto Info = getConstructorInfo(D); | ||||||||||
4489 | if (!Info.Constructor) | ||||||||||
4490 | continue; | ||||||||||
4491 | |||||||||||
4492 | if (!Info.Constructor->isInvalidDecl() && | ||||||||||
4493 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { | ||||||||||
4494 | if (Info.ConstructorTmpl) | ||||||||||
4495 | S.AddTemplateOverloadCandidate( | ||||||||||
4496 | Info.ConstructorTmpl, Info.FoundDecl, | ||||||||||
4497 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | ||||||||||
4498 | /*SuppressUserConversions=*/true, | ||||||||||
4499 | /*PartialOverloading*/ false, AllowExplicitCtors); | ||||||||||
4500 | else | ||||||||||
4501 | S.AddOverloadCandidate( | ||||||||||
4502 | Info.Constructor, Info.FoundDecl, Initializer, CandidateSet, | ||||||||||
4503 | /*SuppressUserConversions=*/true, | ||||||||||
4504 | /*PartialOverloading*/ false, AllowExplicitCtors); | ||||||||||
4505 | } | ||||||||||
4506 | } | ||||||||||
4507 | } | ||||||||||
4508 | if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl()) | ||||||||||
4509 | return OR_No_Viable_Function; | ||||||||||
4510 | |||||||||||
4511 | const RecordType *T2RecordType = nullptr; | ||||||||||
4512 | if ((T2RecordType = T2->getAs<RecordType>()) && | ||||||||||
4513 | S.isCompleteType(Kind.getLocation(), T2)) { | ||||||||||
4514 | // The type we're converting from is a class type, enumerate its conversion | ||||||||||
4515 | // functions. | ||||||||||
4516 | CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl()); | ||||||||||
4517 | |||||||||||
4518 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); | ||||||||||
4519 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | ||||||||||
4520 | NamedDecl *D = *I; | ||||||||||
4521 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | ||||||||||
4522 | if (isa<UsingShadowDecl>(D)) | ||||||||||
4523 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||||||||
4524 | |||||||||||
4525 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | ||||||||||
4526 | CXXConversionDecl *Conv; | ||||||||||
4527 | if (ConvTemplate) | ||||||||||
4528 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | ||||||||||
4529 | else | ||||||||||
4530 | Conv = cast<CXXConversionDecl>(D); | ||||||||||
4531 | |||||||||||
4532 | // If the conversion function doesn't return a reference type, | ||||||||||
4533 | // it can't be considered for this conversion unless we're allowed to | ||||||||||
4534 | // consider rvalues. | ||||||||||
4535 | // FIXME: Do we need to make sure that we only consider conversion | ||||||||||
4536 | // candidates with reference-compatible results? That might be needed to | ||||||||||
4537 | // break recursion. | ||||||||||
4538 | if ((AllowRValues || | ||||||||||
4539 | Conv->getConversionType()->isLValueReferenceType())) { | ||||||||||
4540 | if (ConvTemplate) | ||||||||||
4541 | S.AddTemplateConversionCandidate( | ||||||||||
4542 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | ||||||||||
4543 | CandidateSet, | ||||||||||
4544 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | ||||||||||
4545 | else | ||||||||||
4546 | S.AddConversionCandidate( | ||||||||||
4547 | Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet, | ||||||||||
4548 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs); | ||||||||||
4549 | } | ||||||||||
4550 | } | ||||||||||
4551 | } | ||||||||||
4552 | if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl()) | ||||||||||
4553 | return OR_No_Viable_Function; | ||||||||||
4554 | |||||||||||
4555 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||||||||
4556 | |||||||||||
4557 | // Perform overload resolution. If it fails, return the failed result. | ||||||||||
4558 | OverloadCandidateSet::iterator Best; | ||||||||||
4559 | if (OverloadingResult Result | ||||||||||
4560 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) | ||||||||||
4561 | return Result; | ||||||||||
4562 | |||||||||||
4563 | FunctionDecl *Function = Best->Function; | ||||||||||
4564 | // This is the overload that will be used for this initialization step if we | ||||||||||
4565 | // use this initialization. Mark it as referenced. | ||||||||||
4566 | Function->setReferenced(); | ||||||||||
4567 | |||||||||||
4568 | // Compute the returned type and value kind of the conversion. | ||||||||||
4569 | QualType cv3T3; | ||||||||||
4570 | if (isa<CXXConversionDecl>(Function)) | ||||||||||
4571 | cv3T3 = Function->getReturnType(); | ||||||||||
4572 | else | ||||||||||
4573 | cv3T3 = T1; | ||||||||||
4574 | |||||||||||
4575 | ExprValueKind VK = VK_RValue; | ||||||||||
4576 | if (cv3T3->isLValueReferenceType()) | ||||||||||
4577 | VK = VK_LValue; | ||||||||||
4578 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) | ||||||||||
4579 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; | ||||||||||
4580 | cv3T3 = cv3T3.getNonLValueExprType(S.Context); | ||||||||||
4581 | |||||||||||
4582 | // Add the user-defined conversion step. | ||||||||||
4583 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | ||||||||||
4584 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3, | ||||||||||
4585 | HadMultipleCandidates); | ||||||||||
4586 | |||||||||||
4587 | // Determine whether we'll need to perform derived-to-base adjustments or | ||||||||||
4588 | // other conversions. | ||||||||||
4589 | Sema::ReferenceConversions RefConv; | ||||||||||
4590 | Sema::ReferenceCompareResult NewRefRelationship = | ||||||||||
4591 | S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv); | ||||||||||
4592 | |||||||||||
4593 | // Add the final conversion sequence, if necessary. | ||||||||||
4594 | if (NewRefRelationship == Sema::Ref_Incompatible) { | ||||||||||
4595 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4596, __PRETTY_FUNCTION__)) | ||||||||||
4596 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4596, __PRETTY_FUNCTION__)); | ||||||||||
4597 | |||||||||||
4598 | ImplicitConversionSequence ICS; | ||||||||||
4599 | ICS.setStandard(); | ||||||||||
4600 | ICS.Standard = Best->FinalConversion; | ||||||||||
4601 | Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2)); | ||||||||||
4602 | |||||||||||
4603 | // Every implicit conversion results in a prvalue, except for a glvalue | ||||||||||
4604 | // derived-to-base conversion, which we handle below. | ||||||||||
4605 | cv3T3 = ICS.Standard.getToType(2); | ||||||||||
4606 | VK = VK_RValue; | ||||||||||
4607 | } | ||||||||||
4608 | |||||||||||
4609 | // If the converted initializer is a prvalue, its type T4 is adjusted to | ||||||||||
4610 | // type "cv1 T4" and the temporary materialization conversion is applied. | ||||||||||
4611 | // | ||||||||||
4612 | // We adjust the cv-qualifications to match the reference regardless of | ||||||||||
4613 | // whether we have a prvalue so that the AST records the change. In this | ||||||||||
4614 | // case, T4 is "cv3 T3". | ||||||||||
4615 | QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers()); | ||||||||||
4616 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) | ||||||||||
4617 | Sequence.AddQualificationConversionStep(cv1T4, VK); | ||||||||||
4618 | Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue); | ||||||||||
4619 | VK = IsLValueRef ? VK_LValue : VK_XValue; | ||||||||||
4620 | |||||||||||
4621 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | ||||||||||
4622 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK); | ||||||||||
4623 | else if (RefConv & Sema::ReferenceConversions::ObjC) | ||||||||||
4624 | Sequence.AddObjCObjectConversionStep(cv1T1); | ||||||||||
4625 | else if (RefConv & Sema::ReferenceConversions::Function) | ||||||||||
4626 | Sequence.AddQualificationConversionStep(cv1T1, VK); | ||||||||||
4627 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | ||||||||||
4628 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | ||||||||||
4629 | Sequence.AddQualificationConversionStep(cv1T1, VK); | ||||||||||
4630 | } | ||||||||||
4631 | |||||||||||
4632 | return OR_Success; | ||||||||||
4633 | } | ||||||||||
4634 | |||||||||||
4635 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | ||||||||||
4636 | const InitializedEntity &Entity, | ||||||||||
4637 | Expr *CurInitExpr); | ||||||||||
4638 | |||||||||||
4639 | /// Attempt reference initialization (C++0x [dcl.init.ref]) | ||||||||||
4640 | static void TryReferenceInitialization(Sema &S, | ||||||||||
4641 | const InitializedEntity &Entity, | ||||||||||
4642 | const InitializationKind &Kind, | ||||||||||
4643 | Expr *Initializer, | ||||||||||
4644 | InitializationSequence &Sequence) { | ||||||||||
4645 | QualType DestType = Entity.getType(); | ||||||||||
4646 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||||||||
4647 | Qualifiers T1Quals; | ||||||||||
4648 | QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals); | ||||||||||
4649 | QualType cv2T2 = Initializer->getType(); | ||||||||||
4650 | Qualifiers T2Quals; | ||||||||||
4651 | QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals); | ||||||||||
4652 | |||||||||||
4653 | // If the initializer is the address of an overloaded function, try | ||||||||||
4654 | // to resolve the overloaded function. If all goes well, T2 is the | ||||||||||
4655 | // type of the resulting function. | ||||||||||
4656 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2, | ||||||||||
4657 | T1, Sequence)) | ||||||||||
4658 | return; | ||||||||||
4659 | |||||||||||
4660 | // Delegate everything else to a subfunction. | ||||||||||
4661 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, | ||||||||||
4662 | T1Quals, cv2T2, T2, T2Quals, Sequence); | ||||||||||
4663 | } | ||||||||||
4664 | |||||||||||
4665 | /// Determine whether an expression is a non-referenceable glvalue (one to | ||||||||||
4666 | /// which a reference can never bind). Attempting to bind a reference to | ||||||||||
4667 | /// such a glvalue will always create a temporary. | ||||||||||
4668 | static bool isNonReferenceableGLValue(Expr *E) { | ||||||||||
4669 | return E->refersToBitField() || E->refersToVectorElement(); | ||||||||||
4670 | } | ||||||||||
4671 | |||||||||||
4672 | /// Reference initialization without resolving overloaded functions. | ||||||||||
4673 | static void TryReferenceInitializationCore(Sema &S, | ||||||||||
4674 | const InitializedEntity &Entity, | ||||||||||
4675 | const InitializationKind &Kind, | ||||||||||
4676 | Expr *Initializer, | ||||||||||
4677 | QualType cv1T1, QualType T1, | ||||||||||
4678 | Qualifiers T1Quals, | ||||||||||
4679 | QualType cv2T2, QualType T2, | ||||||||||
4680 | Qualifiers T2Quals, | ||||||||||
4681 | InitializationSequence &Sequence) { | ||||||||||
4682 | QualType DestType = Entity.getType(); | ||||||||||
4683 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||||||||
4684 | |||||||||||
4685 | // Compute some basic properties of the types and the initializer. | ||||||||||
4686 | bool isLValueRef = DestType->isLValueReferenceType(); | ||||||||||
4687 | bool isRValueRef = !isLValueRef; | ||||||||||
4688 | Expr::Classification InitCategory = Initializer->Classify(S.Context); | ||||||||||
4689 | |||||||||||
4690 | Sema::ReferenceConversions RefConv; | ||||||||||
4691 | Sema::ReferenceCompareResult RefRelationship = | ||||||||||
4692 | S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv); | ||||||||||
4693 | |||||||||||
4694 | // C++0x [dcl.init.ref]p5: | ||||||||||
4695 | // A reference to type "cv1 T1" is initialized by an expression of type | ||||||||||
4696 | // "cv2 T2" as follows: | ||||||||||
4697 | // | ||||||||||
4698 | // - If the reference is an lvalue reference and the initializer | ||||||||||
4699 | // expression | ||||||||||
4700 | // Note the analogous bullet points for rvalue refs to functions. Because | ||||||||||
4701 | // there are no function rvalues in C++, rvalue refs to functions are treated | ||||||||||
4702 | // like lvalue refs. | ||||||||||
4703 | OverloadingResult ConvOvlResult = OR_Success; | ||||||||||
4704 | bool T1Function = T1->isFunctionType(); | ||||||||||
4705 | if (isLValueRef || T1Function) { | ||||||||||
4706 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) && | ||||||||||
4707 | (RefRelationship == Sema::Ref_Compatible || | ||||||||||
4708 | (Kind.isCStyleOrFunctionalCast() && | ||||||||||
4709 | RefRelationship == Sema::Ref_Related))) { | ||||||||||
4710 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is | ||||||||||
4711 | // reference-compatible with "cv2 T2," or | ||||||||||
4712 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | | ||||||||||
4713 | Sema::ReferenceConversions::ObjC)) { | ||||||||||
4714 | // If we're converting the pointee, add any qualifiers first; | ||||||||||
4715 | // these qualifiers must all be top-level, so just convert to "cv1 T2". | ||||||||||
4716 | if (RefConv & (Sema::ReferenceConversions::Qualification)) | ||||||||||
4717 | Sequence.AddQualificationConversionStep( | ||||||||||
4718 | S.Context.getQualifiedType(T2, T1Quals), | ||||||||||
4719 | Initializer->getValueKind()); | ||||||||||
4720 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | ||||||||||
4721 | Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue); | ||||||||||
4722 | else | ||||||||||
4723 | Sequence.AddObjCObjectConversionStep(cv1T1); | ||||||||||
4724 | } else if (RefConv & (Sema::ReferenceConversions::Qualification | | ||||||||||
4725 | Sema::ReferenceConversions::Function)) { | ||||||||||
4726 | // Perform a (possibly multi-level) qualification conversion. | ||||||||||
4727 | // FIXME: Should we use a different step kind for function conversions? | ||||||||||
4728 | Sequence.AddQualificationConversionStep(cv1T1, | ||||||||||
4729 | Initializer->getValueKind()); | ||||||||||
4730 | } | ||||||||||
4731 | |||||||||||
4732 | // We only create a temporary here when binding a reference to a | ||||||||||
4733 | // bit-field or vector element. Those cases are't supposed to be | ||||||||||
4734 | // handled by this bullet, but the outcome is the same either way. | ||||||||||
4735 | Sequence.AddReferenceBindingStep(cv1T1, false); | ||||||||||
4736 | return; | ||||||||||
4737 | } | ||||||||||
4738 | |||||||||||
4739 | // - has a class type (i.e., T2 is a class type), where T1 is not | ||||||||||
4740 | // reference-related to T2, and can be implicitly converted to an | ||||||||||
4741 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible | ||||||||||
4742 | // with "cv3 T3" (this conversion is selected by enumerating the | ||||||||||
4743 | // applicable conversion functions (13.3.1.6) and choosing the best | ||||||||||
4744 | // one through overload resolution (13.3)), | ||||||||||
4745 | // If we have an rvalue ref to function type here, the rhs must be | ||||||||||
4746 | // an rvalue. DR1287 removed the "implicitly" here. | ||||||||||
4747 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && | ||||||||||
4748 | (isLValueRef || InitCategory.isRValue())) { | ||||||||||
4749 | ConvOvlResult = TryRefInitWithConversionFunction( | ||||||||||
4750 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, | ||||||||||
4751 | /*IsLValueRef*/ isLValueRef, Sequence); | ||||||||||
4752 | if (ConvOvlResult == OR_Success) | ||||||||||
4753 | return; | ||||||||||
4754 | if (ConvOvlResult != OR_No_Viable_Function) | ||||||||||
4755 | Sequence.SetOverloadFailure( | ||||||||||
4756 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||||||||
4757 | ConvOvlResult); | ||||||||||
4758 | } | ||||||||||
4759 | } | ||||||||||
4760 | |||||||||||
4761 | // - Otherwise, the reference shall be an lvalue reference to a | ||||||||||
4762 | // non-volatile const type (i.e., cv1 shall be const), or the reference | ||||||||||
4763 | // shall be an rvalue reference. | ||||||||||
4764 | // For address spaces, we interpret this to mean that an addr space | ||||||||||
4765 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". | ||||||||||
4766 | if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() && | ||||||||||
4767 | T1Quals.isAddressSpaceSupersetOf(T2Quals))) { | ||||||||||
4768 | if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | ||||||||||
4769 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||||||||
4770 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | ||||||||||
4771 | Sequence.SetOverloadFailure( | ||||||||||
4772 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||||||||
4773 | ConvOvlResult); | ||||||||||
4774 | else if (!InitCategory.isLValue()) | ||||||||||
4775 | Sequence.SetFailed( | ||||||||||
4776 | T1Quals.isAddressSpaceSupersetOf(T2Quals) | ||||||||||
4777 | ? InitializationSequence:: | ||||||||||
4778 | FK_NonConstLValueReferenceBindingToTemporary | ||||||||||
4779 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||||||||
4780 | else { | ||||||||||
4781 | InitializationSequence::FailureKind FK; | ||||||||||
4782 | switch (RefRelationship) { | ||||||||||
4783 | case Sema::Ref_Compatible: | ||||||||||
4784 | if (Initializer->refersToBitField()) | ||||||||||
4785 | FK = InitializationSequence:: | ||||||||||
4786 | FK_NonConstLValueReferenceBindingToBitfield; | ||||||||||
4787 | else if (Initializer->refersToVectorElement()) | ||||||||||
4788 | FK = InitializationSequence:: | ||||||||||
4789 | FK_NonConstLValueReferenceBindingToVectorElement; | ||||||||||
4790 | else | ||||||||||
4791 | llvm_unreachable("unexpected kind of compatible initializer")::llvm::llvm_unreachable_internal("unexpected kind of compatible initializer" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 4791); | ||||||||||
4792 | break; | ||||||||||
4793 | case Sema::Ref_Related: | ||||||||||
4794 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; | ||||||||||
4795 | break; | ||||||||||
4796 | case Sema::Ref_Incompatible: | ||||||||||
4797 | FK = InitializationSequence:: | ||||||||||
4798 | FK_NonConstLValueReferenceBindingToUnrelated; | ||||||||||
4799 | break; | ||||||||||
4800 | } | ||||||||||
4801 | Sequence.SetFailed(FK); | ||||||||||
4802 | } | ||||||||||
4803 | return; | ||||||||||
4804 | } | ||||||||||
4805 | |||||||||||
4806 | // - If the initializer expression | ||||||||||
4807 | // - is an | ||||||||||
4808 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or | ||||||||||
4809 | // [1z] rvalue (but not a bit-field) or | ||||||||||
4810 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" | ||||||||||
4811 | // | ||||||||||
4812 | // Note: functions are handled above and below rather than here... | ||||||||||
4813 | if (!T1Function && | ||||||||||
4814 | (RefRelationship == Sema::Ref_Compatible || | ||||||||||
4815 | (Kind.isCStyleOrFunctionalCast() && | ||||||||||
4816 | RefRelationship == Sema::Ref_Related)) && | ||||||||||
4817 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) || | ||||||||||
4818 | (InitCategory.isPRValue() && | ||||||||||
4819 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || | ||||||||||
4820 | T2->isArrayType())))) { | ||||||||||
4821 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_RValue; | ||||||||||
4822 | if (InitCategory.isPRValue() && T2->isRecordType()) { | ||||||||||
4823 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the | ||||||||||
4824 | // compiler the freedom to perform a copy here or bind to the | ||||||||||
4825 | // object, while C++0x requires that we bind directly to the | ||||||||||
4826 | // object. Hence, we always bind to the object without making an | ||||||||||
4827 | // extra copy. However, in C++03 requires that we check for the | ||||||||||
4828 | // presence of a suitable copy constructor: | ||||||||||
4829 | // | ||||||||||
4830 | // The constructor that would be used to make the copy shall | ||||||||||
4831 | // be callable whether or not the copy is actually done. | ||||||||||
4832 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) | ||||||||||
4833 | Sequence.AddExtraneousCopyToTemporary(cv2T2); | ||||||||||
4834 | else if (S.getLangOpts().CPlusPlus11) | ||||||||||
4835 | CheckCXX98CompatAccessibleCopy(S, Entity, Initializer); | ||||||||||
4836 | } | ||||||||||
4837 | |||||||||||
4838 | // C++1z [dcl.init.ref]/5.2.1.2: | ||||||||||
4839 | // If the converted initializer is a prvalue, its type T4 is adjusted | ||||||||||
4840 | // to type "cv1 T4" and the temporary materialization conversion is | ||||||||||
4841 | // applied. | ||||||||||
4842 | // Postpone address space conversions to after the temporary materialization | ||||||||||
4843 | // conversion to allow creating temporaries in the alloca address space. | ||||||||||
4844 | auto T1QualsIgnoreAS = T1Quals; | ||||||||||
4845 | auto T2QualsIgnoreAS = T2Quals; | ||||||||||
4846 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | ||||||||||
4847 | T1QualsIgnoreAS.removeAddressSpace(); | ||||||||||
4848 | T2QualsIgnoreAS.removeAddressSpace(); | ||||||||||
4849 | } | ||||||||||
4850 | QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS); | ||||||||||
4851 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) | ||||||||||
4852 | Sequence.AddQualificationConversionStep(cv1T4, ValueKind); | ||||||||||
4853 | Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue); | ||||||||||
4854 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; | ||||||||||
4855 | // Add addr space conversion if required. | ||||||||||
4856 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { | ||||||||||
4857 | auto T4Quals = cv1T4.getQualifiers(); | ||||||||||
4858 | T4Quals.addAddressSpace(T1Quals.getAddressSpace()); | ||||||||||
4859 | QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals); | ||||||||||
4860 | Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind); | ||||||||||
4861 | cv1T4 = cv1T4WithAS; | ||||||||||
4862 | } | ||||||||||
4863 | |||||||||||
4864 | // In any case, the reference is bound to the resulting glvalue (or to | ||||||||||
4865 | // an appropriate base class subobject). | ||||||||||
4866 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) | ||||||||||
4867 | Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind); | ||||||||||
4868 | else if (RefConv & Sema::ReferenceConversions::ObjC) | ||||||||||
4869 | Sequence.AddObjCObjectConversionStep(cv1T1); | ||||||||||
4870 | else if (RefConv & Sema::ReferenceConversions::Qualification) { | ||||||||||
4871 | if (!S.Context.hasSameType(cv1T4, cv1T1)) | ||||||||||
4872 | Sequence.AddQualificationConversionStep(cv1T1, ValueKind); | ||||||||||
4873 | } | ||||||||||
4874 | return; | ||||||||||
4875 | } | ||||||||||
4876 | |||||||||||
4877 | // - has a class type (i.e., T2 is a class type), where T1 is not | ||||||||||
4878 | // reference-related to T2, and can be implicitly converted to an | ||||||||||
4879 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", | ||||||||||
4880 | // where "cv1 T1" is reference-compatible with "cv3 T3", | ||||||||||
4881 | // | ||||||||||
4882 | // DR1287 removes the "implicitly" here. | ||||||||||
4883 | if (T2->isRecordType()) { | ||||||||||
4884 | if (RefRelationship == Sema::Ref_Incompatible) { | ||||||||||
4885 | ConvOvlResult = TryRefInitWithConversionFunction( | ||||||||||
4886 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, | ||||||||||
4887 | /*IsLValueRef*/ isLValueRef, Sequence); | ||||||||||
4888 | if (ConvOvlResult) | ||||||||||
4889 | Sequence.SetOverloadFailure( | ||||||||||
4890 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||||||||
4891 | ConvOvlResult); | ||||||||||
4892 | |||||||||||
4893 | return; | ||||||||||
4894 | } | ||||||||||
4895 | |||||||||||
4896 | if (RefRelationship == Sema::Ref_Compatible && | ||||||||||
4897 | isRValueRef && InitCategory.isLValue()) { | ||||||||||
4898 | Sequence.SetFailed( | ||||||||||
4899 | InitializationSequence::FK_RValueReferenceBindingToLValue); | ||||||||||
4900 | return; | ||||||||||
4901 | } | ||||||||||
4902 | |||||||||||
4903 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||||||||
4904 | return; | ||||||||||
4905 | } | ||||||||||
4906 | |||||||||||
4907 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized | ||||||||||
4908 | // from the initializer expression using the rules for a non-reference | ||||||||||
4909 | // copy-initialization (8.5). The reference is then bound to the | ||||||||||
4910 | // temporary. [...] | ||||||||||
4911 | |||||||||||
4912 | // Ignore address space of reference type at this point and perform address | ||||||||||
4913 | // space conversion after the reference binding step. | ||||||||||
4914 | QualType cv1T1IgnoreAS = | ||||||||||
4915 | T1Quals.hasAddressSpace() | ||||||||||
4916 | ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace()) | ||||||||||
4917 | : cv1T1; | ||||||||||
4918 | |||||||||||
4919 | InitializedEntity TempEntity = | ||||||||||
4920 | InitializedEntity::InitializeTemporary(cv1T1IgnoreAS); | ||||||||||
4921 | |||||||||||
4922 | // FIXME: Why do we use an implicit conversion here rather than trying | ||||||||||
4923 | // copy-initialization? | ||||||||||
4924 | ImplicitConversionSequence ICS | ||||||||||
4925 | = S.TryImplicitConversion(Initializer, TempEntity.getType(), | ||||||||||
4926 | /*SuppressUserConversions=*/false, | ||||||||||
4927 | /*AllowExplicit=*/false, | ||||||||||
4928 | /*FIXME:InOverloadResolution=*/false, | ||||||||||
4929 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | ||||||||||
4930 | /*AllowObjCWritebackConversion=*/false); | ||||||||||
4931 | |||||||||||
4932 | if (ICS.isBad()) { | ||||||||||
4933 | // FIXME: Use the conversion function set stored in ICS to turn | ||||||||||
4934 | // this into an overloading ambiguity diagnostic. However, we need | ||||||||||
4935 | // to keep that set as an OverloadCandidateSet rather than as some | ||||||||||
4936 | // other kind of set. | ||||||||||
4937 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) | ||||||||||
4938 | Sequence.SetOverloadFailure( | ||||||||||
4939 | InitializationSequence::FK_ReferenceInitOverloadFailed, | ||||||||||
4940 | ConvOvlResult); | ||||||||||
4941 | else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) | ||||||||||
4942 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||||||||
4943 | else | ||||||||||
4944 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); | ||||||||||
4945 | return; | ||||||||||
4946 | } else { | ||||||||||
4947 | Sequence.AddConversionSequenceStep(ICS, TempEntity.getType()); | ||||||||||
4948 | } | ||||||||||
4949 | |||||||||||
4950 | // [...] If T1 is reference-related to T2, cv1 must be the | ||||||||||
4951 | // same cv-qualification as, or greater cv-qualification | ||||||||||
4952 | // than, cv2; otherwise, the program is ill-formed. | ||||||||||
4953 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); | ||||||||||
4954 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); | ||||||||||
4955 | if ((RefRelationship == Sema::Ref_Related && | ||||||||||
4956 | (T1CVRQuals | T2CVRQuals) != T1CVRQuals) || | ||||||||||
4957 | !T1Quals.isAddressSpaceSupersetOf(T2Quals)) { | ||||||||||
4958 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); | ||||||||||
4959 | return; | ||||||||||
4960 | } | ||||||||||
4961 | |||||||||||
4962 | // [...] If T1 is reference-related to T2 and the reference is an rvalue | ||||||||||
4963 | // reference, the initializer expression shall not be an lvalue. | ||||||||||
4964 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && | ||||||||||
4965 | InitCategory.isLValue()) { | ||||||||||
4966 | Sequence.SetFailed( | ||||||||||
4967 | InitializationSequence::FK_RValueReferenceBindingToLValue); | ||||||||||
4968 | return; | ||||||||||
4969 | } | ||||||||||
4970 | |||||||||||
4971 | Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true); | ||||||||||
4972 | |||||||||||
4973 | if (T1Quals.hasAddressSpace()) { | ||||||||||
4974 | if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(), | ||||||||||
4975 | LangAS::Default)) { | ||||||||||
4976 | Sequence.SetFailed( | ||||||||||
4977 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); | ||||||||||
4978 | return; | ||||||||||
4979 | } | ||||||||||
4980 | Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue | ||||||||||
4981 | : VK_XValue); | ||||||||||
4982 | } | ||||||||||
4983 | } | ||||||||||
4984 | |||||||||||
4985 | /// Attempt character array initialization from a string literal | ||||||||||
4986 | /// (C++ [dcl.init.string], C99 6.7.8). | ||||||||||
4987 | static void TryStringLiteralInitialization(Sema &S, | ||||||||||
4988 | const InitializedEntity &Entity, | ||||||||||
4989 | const InitializationKind &Kind, | ||||||||||
4990 | Expr *Initializer, | ||||||||||
4991 | InitializationSequence &Sequence) { | ||||||||||
4992 | Sequence.AddStringInitStep(Entity.getType()); | ||||||||||
4993 | } | ||||||||||
4994 | |||||||||||
4995 | /// Attempt value initialization (C++ [dcl.init]p7). | ||||||||||
4996 | static void TryValueInitialization(Sema &S, | ||||||||||
4997 | const InitializedEntity &Entity, | ||||||||||
4998 | const InitializationKind &Kind, | ||||||||||
4999 | InitializationSequence &Sequence, | ||||||||||
5000 | InitListExpr *InitList) { | ||||||||||
5001 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5002, __PRETTY_FUNCTION__)) | ||||||||||
5002 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5002, __PRETTY_FUNCTION__)); | ||||||||||
5003 | |||||||||||
5004 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: | ||||||||||
5005 | // | ||||||||||
5006 | // To value-initialize an object of type T means: | ||||||||||
5007 | QualType T = Entity.getType(); | ||||||||||
5008 | |||||||||||
5009 | // -- if T is an array type, then each element is value-initialized; | ||||||||||
5010 | T = S.Context.getBaseElementType(T); | ||||||||||
5011 | |||||||||||
5012 | if (const RecordType *RT = T->getAs<RecordType>()) { | ||||||||||
5013 | if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { | ||||||||||
5014 | bool NeedZeroInitialization = true; | ||||||||||
5015 | // C++98: | ||||||||||
5016 | // -- if T is a class type (clause 9) with a user-declared constructor | ||||||||||
5017 | // (12.1), then the default constructor for T is called (and the | ||||||||||
5018 | // initialization is ill-formed if T has no accessible default | ||||||||||
5019 | // constructor); | ||||||||||
5020 | // C++11: | ||||||||||
5021 | // -- if T is a class type (clause 9) with either no default constructor | ||||||||||
5022 | // (12.1 [class.ctor]) or a default constructor that is user-provided | ||||||||||
5023 | // or deleted, then the object is default-initialized; | ||||||||||
5024 | // | ||||||||||
5025 | // Note that the C++11 rule is the same as the C++98 rule if there are no | ||||||||||
5026 | // defaulted or deleted constructors, so we just use it unconditionally. | ||||||||||
5027 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl); | ||||||||||
5028 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) | ||||||||||
5029 | NeedZeroInitialization = false; | ||||||||||
5030 | |||||||||||
5031 | // -- if T is a (possibly cv-qualified) non-union class type without a | ||||||||||
5032 | // user-provided or deleted default constructor, then the object is | ||||||||||
5033 | // zero-initialized and, if T has a non-trivial default constructor, | ||||||||||
5034 | // default-initialized; | ||||||||||
5035 | // The 'non-union' here was removed by DR1502. The 'non-trivial default | ||||||||||
5036 | // constructor' part was removed by DR1507. | ||||||||||
5037 | if (NeedZeroInitialization) | ||||||||||
5038 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||||||||
5039 | |||||||||||
5040 | // C++03: | ||||||||||
5041 | // -- if T is a non-union class type without a user-declared constructor, | ||||||||||
5042 | // then every non-static data member and base class component of T is | ||||||||||
5043 | // value-initialized; | ||||||||||
5044 | // [...] A program that calls for [...] value-initialization of an | ||||||||||
5045 | // entity of reference type is ill-formed. | ||||||||||
5046 | // | ||||||||||
5047 | // C++11 doesn't need this handling, because value-initialization does not | ||||||||||
5048 | // occur recursively there, and the implicit default constructor is | ||||||||||
5049 | // defined as deleted in the problematic cases. | ||||||||||
5050 | if (!S.getLangOpts().CPlusPlus11 && | ||||||||||
5051 | ClassDecl->hasUninitializedReferenceMember()) { | ||||||||||
5052 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); | ||||||||||
5053 | return; | ||||||||||
5054 | } | ||||||||||
5055 | |||||||||||
5056 | // If this is list-value-initialization, pass the empty init list on when | ||||||||||
5057 | // building the constructor call. This affects the semantics of a few | ||||||||||
5058 | // things (such as whether an explicit default constructor can be called). | ||||||||||
5059 | Expr *InitListAsExpr = InitList; | ||||||||||
5060 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); | ||||||||||
5061 | bool InitListSyntax = InitList; | ||||||||||
5062 | |||||||||||
5063 | // FIXME: Instead of creating a CXXConstructExpr of array type here, | ||||||||||
5064 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. | ||||||||||
5065 | return TryConstructorInitialization( | ||||||||||
5066 | S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax); | ||||||||||
5067 | } | ||||||||||
5068 | } | ||||||||||
5069 | |||||||||||
5070 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||||||||
5071 | } | ||||||||||
5072 | |||||||||||
5073 | /// Attempt default initialization (C++ [dcl.init]p6). | ||||||||||
5074 | static void TryDefaultInitialization(Sema &S, | ||||||||||
5075 | const InitializedEntity &Entity, | ||||||||||
5076 | const InitializationKind &Kind, | ||||||||||
5077 | InitializationSequence &Sequence) { | ||||||||||
5078 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5078, __PRETTY_FUNCTION__)); | ||||||||||
5079 | |||||||||||
5080 | // C++ [dcl.init]p6: | ||||||||||
5081 | // To default-initialize an object of type T means: | ||||||||||
5082 | // - if T is an array type, each element is default-initialized; | ||||||||||
5083 | QualType DestType = S.Context.getBaseElementType(Entity.getType()); | ||||||||||
5084 | |||||||||||
5085 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default | ||||||||||
5086 | // constructor for T is called (and the initialization is ill-formed if | ||||||||||
5087 | // T has no accessible default constructor); | ||||||||||
5088 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { | ||||||||||
5089 | TryConstructorInitialization(S, Entity, Kind, None, DestType, | ||||||||||
5090 | Entity.getType(), Sequence); | ||||||||||
5091 | return; | ||||||||||
5092 | } | ||||||||||
5093 | |||||||||||
5094 | // - otherwise, no initialization is performed. | ||||||||||
5095 | |||||||||||
5096 | // If a program calls for the default initialization of an object of | ||||||||||
5097 | // a const-qualified type T, T shall be a class type with a user-provided | ||||||||||
5098 | // default constructor. | ||||||||||
5099 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { | ||||||||||
5100 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) | ||||||||||
5101 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); | ||||||||||
5102 | return; | ||||||||||
5103 | } | ||||||||||
5104 | |||||||||||
5105 | // If the destination type has a lifetime property, zero-initialize it. | ||||||||||
5106 | if (DestType.getQualifiers().hasObjCLifetime()) { | ||||||||||
5107 | Sequence.AddZeroInitializationStep(Entity.getType()); | ||||||||||
5108 | return; | ||||||||||
5109 | } | ||||||||||
5110 | } | ||||||||||
5111 | |||||||||||
5112 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), | ||||||||||
5113 | /// which enumerates all conversion functions and performs overload resolution | ||||||||||
5114 | /// to select the best. | ||||||||||
5115 | static void TryUserDefinedConversion(Sema &S, | ||||||||||
5116 | QualType DestType, | ||||||||||
5117 | const InitializationKind &Kind, | ||||||||||
5118 | Expr *Initializer, | ||||||||||
5119 | InitializationSequence &Sequence, | ||||||||||
5120 | bool TopLevelOfInitList) { | ||||||||||
5121 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5121, __PRETTY_FUNCTION__)); | ||||||||||
5122 | QualType SourceType = Initializer->getType(); | ||||||||||
5123 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5124, __PRETTY_FUNCTION__)) | ||||||||||
5124 | "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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5124, __PRETTY_FUNCTION__)); | ||||||||||
5125 | |||||||||||
5126 | // Build the candidate set directly in the initialization sequence | ||||||||||
5127 | // structure, so that it will persist if we fail. | ||||||||||
5128 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); | ||||||||||
5129 | CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); | ||||||||||
5130 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); | ||||||||||
5131 | |||||||||||
5132 | // Determine whether we are allowed to call explicit constructors or | ||||||||||
5133 | // explicit conversion operators. | ||||||||||
5134 | bool AllowExplicit = Kind.AllowExplicit(); | ||||||||||
5135 | |||||||||||
5136 | if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) { | ||||||||||
5137 | // The type we're converting to is a class type. Enumerate its constructors | ||||||||||
5138 | // to see if there is a suitable conversion. | ||||||||||
5139 | CXXRecordDecl *DestRecordDecl | ||||||||||
5140 | = cast<CXXRecordDecl>(DestRecordType->getDecl()); | ||||||||||
5141 | |||||||||||
5142 | // Try to complete the type we're converting to. | ||||||||||
5143 | if (S.isCompleteType(Kind.getLocation(), DestType)) { | ||||||||||
5144 | for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) { | ||||||||||
5145 | auto Info = getConstructorInfo(D); | ||||||||||
5146 | if (!Info.Constructor) | ||||||||||
5147 | continue; | ||||||||||
5148 | |||||||||||
5149 | if (!Info.Constructor->isInvalidDecl() && | ||||||||||
5150 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { | ||||||||||
5151 | if (Info.ConstructorTmpl) | ||||||||||
5152 | S.AddTemplateOverloadCandidate( | ||||||||||
5153 | Info.ConstructorTmpl, Info.FoundDecl, | ||||||||||
5154 | /*ExplicitArgs*/ nullptr, Initializer, CandidateSet, | ||||||||||
5155 | /*SuppressUserConversions=*/true, | ||||||||||
5156 | /*PartialOverloading*/ false, AllowExplicit); | ||||||||||
5157 | else | ||||||||||
5158 | S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, | ||||||||||
5159 | Initializer, CandidateSet, | ||||||||||
5160 | /*SuppressUserConversions=*/true, | ||||||||||
5161 | /*PartialOverloading*/ false, AllowExplicit); | ||||||||||
5162 | } | ||||||||||
5163 | } | ||||||||||
5164 | } | ||||||||||
5165 | } | ||||||||||
5166 | |||||||||||
5167 | SourceLocation DeclLoc = Initializer->getBeginLoc(); | ||||||||||
5168 | |||||||||||
5169 | if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) { | ||||||||||
5170 | // The type we're converting from is a class type, enumerate its conversion | ||||||||||
5171 | // functions. | ||||||||||
5172 | |||||||||||
5173 | // We can only enumerate the conversion functions for a complete type; if | ||||||||||
5174 | // the type isn't complete, simply skip this step. | ||||||||||
5175 | if (S.isCompleteType(DeclLoc, SourceType)) { | ||||||||||
5176 | CXXRecordDecl *SourceRecordDecl | ||||||||||
5177 | = cast<CXXRecordDecl>(SourceRecordType->getDecl()); | ||||||||||
5178 | |||||||||||
5179 | const auto &Conversions = | ||||||||||
5180 | SourceRecordDecl->getVisibleConversionFunctions(); | ||||||||||
5181 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { | ||||||||||
5182 | NamedDecl *D = *I; | ||||||||||
5183 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); | ||||||||||
5184 | if (isa<UsingShadowDecl>(D)) | ||||||||||
5185 | D = cast<UsingShadowDecl>(D)->getTargetDecl(); | ||||||||||
5186 | |||||||||||
5187 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); | ||||||||||
5188 | CXXConversionDecl *Conv; | ||||||||||
5189 | if (ConvTemplate) | ||||||||||
5190 | Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); | ||||||||||
5191 | else | ||||||||||
5192 | Conv = cast<CXXConversionDecl>(D); | ||||||||||
5193 | |||||||||||
5194 | if (ConvTemplate) | ||||||||||
5195 | S.AddTemplateConversionCandidate( | ||||||||||
5196 | ConvTemplate, I.getPair(), ActingDC, Initializer, DestType, | ||||||||||
5197 | CandidateSet, AllowExplicit, AllowExplicit); | ||||||||||
5198 | else | ||||||||||
5199 | S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer, | ||||||||||
5200 | DestType, CandidateSet, AllowExplicit, | ||||||||||
5201 | AllowExplicit); | ||||||||||
5202 | } | ||||||||||
5203 | } | ||||||||||
5204 | } | ||||||||||
5205 | |||||||||||
5206 | // Perform overload resolution. If it fails, return the failed result. | ||||||||||
5207 | OverloadCandidateSet::iterator Best; | ||||||||||
5208 | if (OverloadingResult Result | ||||||||||
5209 | = CandidateSet.BestViableFunction(S, DeclLoc, Best)) { | ||||||||||
5210 | Sequence.SetOverloadFailure( | ||||||||||
5211 | InitializationSequence::FK_UserConversionOverloadFailed, | ||||||||||
5212 | Result); | ||||||||||
5213 | return; | ||||||||||
5214 | } | ||||||||||
5215 | |||||||||||
5216 | FunctionDecl *Function = Best->Function; | ||||||||||
5217 | Function->setReferenced(); | ||||||||||
5218 | bool HadMultipleCandidates = (CandidateSet.size() > 1); | ||||||||||
5219 | |||||||||||
5220 | if (isa<CXXConstructorDecl>(Function)) { | ||||||||||
5221 | // Add the user-defined conversion step. Any cv-qualification conversion is | ||||||||||
5222 | // subsumed by the initialization. Per DR5, the created temporary is of the | ||||||||||
5223 | // cv-unqualified type of the destination. | ||||||||||
5224 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, | ||||||||||
5225 | DestType.getUnqualifiedType(), | ||||||||||
5226 | HadMultipleCandidates); | ||||||||||
5227 | |||||||||||
5228 | // C++14 and before: | ||||||||||
5229 | // - if the function is a constructor, the call initializes a temporary | ||||||||||
5230 | // of the cv-unqualified version of the destination type. The [...] | ||||||||||
5231 | // temporary [...] is then used to direct-initialize, according to the | ||||||||||
5232 | // rules above, the object that is the destination of the | ||||||||||
5233 | // copy-initialization. | ||||||||||
5234 | // Note that this just performs a simple object copy from the temporary. | ||||||||||
5235 | // | ||||||||||
5236 | // C++17: | ||||||||||
5237 | // - if the function is a constructor, the call is a prvalue of the | ||||||||||
5238 | // cv-unqualified version of the destination type whose return object | ||||||||||
5239 | // is initialized by the constructor. The call is used to | ||||||||||
5240 | // direct-initialize, according to the rules above, the object that | ||||||||||
5241 | // is the destination of the copy-initialization. | ||||||||||
5242 | // Therefore we need to do nothing further. | ||||||||||
5243 | // | ||||||||||
5244 | // FIXME: Mark this copy as extraneous. | ||||||||||
5245 | if (!S.getLangOpts().CPlusPlus17) | ||||||||||
5246 | Sequence.AddFinalCopy(DestType); | ||||||||||
5247 | else if (DestType.hasQualifiers()) | ||||||||||
5248 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | ||||||||||
5249 | return; | ||||||||||
5250 | } | ||||||||||
5251 | |||||||||||
5252 | // Add the user-defined conversion step that calls the conversion function. | ||||||||||
5253 | QualType ConvType = Function->getCallResultType(); | ||||||||||
5254 | Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType, | ||||||||||
5255 | HadMultipleCandidates); | ||||||||||
5256 | |||||||||||
5257 | if (ConvType->getAs<RecordType>()) { | ||||||||||
5258 | // The call is used to direct-initialize [...] the object that is the | ||||||||||
5259 | // destination of the copy-initialization. | ||||||||||
5260 | // | ||||||||||
5261 | // In C++17, this does not call a constructor if we enter /17.6.1: | ||||||||||
5262 | // - If the initializer expression is a prvalue and the cv-unqualified | ||||||||||
5263 | // version of the source type is the same as the class of the | ||||||||||
5264 | // destination [... do not make an extra copy] | ||||||||||
5265 | // | ||||||||||
5266 | // FIXME: Mark this copy as extraneous. | ||||||||||
5267 | if (!S.getLangOpts().CPlusPlus17 || | ||||||||||
5268 | Function->getReturnType()->isReferenceType() || | ||||||||||
5269 | !S.Context.hasSameUnqualifiedType(ConvType, DestType)) | ||||||||||
5270 | Sequence.AddFinalCopy(DestType); | ||||||||||
5271 | else if (!S.Context.hasSameType(ConvType, DestType)) | ||||||||||
5272 | Sequence.AddQualificationConversionStep(DestType, VK_RValue); | ||||||||||
5273 | return; | ||||||||||
5274 | } | ||||||||||
5275 | |||||||||||
5276 | // If the conversion following the call to the conversion function | ||||||||||
5277 | // is interesting, add it as a separate step. | ||||||||||
5278 | if (Best->FinalConversion.First || Best->FinalConversion.Second || | ||||||||||
5279 | Best->FinalConversion.Third) { | ||||||||||
5280 | ImplicitConversionSequence ICS; | ||||||||||
5281 | ICS.setStandard(); | ||||||||||
5282 | ICS.Standard = Best->FinalConversion; | ||||||||||
5283 | Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | ||||||||||
5284 | } | ||||||||||
5285 | } | ||||||||||
5286 | |||||||||||
5287 | /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>, | ||||||||||
5288 | /// a function with a pointer return type contains a 'return false;' statement. | ||||||||||
5289 | /// In C++11, 'false' is not a null pointer, so this breaks the build of any | ||||||||||
5290 | /// code using that header. | ||||||||||
5291 | /// | ||||||||||
5292 | /// Work around this by treating 'return false;' as zero-initializing the result | ||||||||||
5293 | /// if it's used in a pointer-returning function in a system header. | ||||||||||
5294 | static bool isLibstdcxxPointerReturnFalseHack(Sema &S, | ||||||||||
5295 | const InitializedEntity &Entity, | ||||||||||
5296 | const Expr *Init) { | ||||||||||
5297 | return S.getLangOpts().CPlusPlus11 && | ||||||||||
5298 | Entity.getKind() == InitializedEntity::EK_Result && | ||||||||||
5299 | Entity.getType()->isPointerType() && | ||||||||||
5300 | isa<CXXBoolLiteralExpr>(Init) && | ||||||||||
5301 | !cast<CXXBoolLiteralExpr>(Init)->getValue() && | ||||||||||
5302 | S.getSourceManager().isInSystemHeader(Init->getExprLoc()); | ||||||||||
5303 | } | ||||||||||
5304 | |||||||||||
5305 | /// The non-zero enum values here are indexes into diagnostic alternatives. | ||||||||||
5306 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; | ||||||||||
5307 | |||||||||||
5308 | /// Determines whether this expression is an acceptable ICR source. | ||||||||||
5309 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, | ||||||||||
5310 | bool isAddressOf, bool &isWeakAccess) { | ||||||||||
5311 | // Skip parens. | ||||||||||
5312 | e = e->IgnoreParens(); | ||||||||||
5313 | |||||||||||
5314 | // Skip address-of nodes. | ||||||||||
5315 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { | ||||||||||
5316 | if (op->getOpcode() == UO_AddrOf) | ||||||||||
5317 | return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true, | ||||||||||
5318 | isWeakAccess); | ||||||||||
5319 | |||||||||||
5320 | // Skip certain casts. | ||||||||||
5321 | } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) { | ||||||||||
5322 | switch (ce->getCastKind()) { | ||||||||||
5323 | case CK_Dependent: | ||||||||||
5324 | case CK_BitCast: | ||||||||||
5325 | case CK_LValueBitCast: | ||||||||||
5326 | case CK_NoOp: | ||||||||||
5327 | return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess); | ||||||||||
5328 | |||||||||||
5329 | case CK_ArrayToPointerDecay: | ||||||||||
5330 | return IIK_nonscalar; | ||||||||||
5331 | |||||||||||
5332 | case CK_NullToPointer: | ||||||||||
5333 | return IIK_okay; | ||||||||||
5334 | |||||||||||
5335 | default: | ||||||||||
5336 | break; | ||||||||||
5337 | } | ||||||||||
5338 | |||||||||||
5339 | // If we have a declaration reference, it had better be a local variable. | ||||||||||
5340 | } else if (isa<DeclRefExpr>(e)) { | ||||||||||
5341 | // set isWeakAccess to true, to mean that there will be an implicit | ||||||||||
5342 | // load which requires a cleanup. | ||||||||||
5343 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||||||
5344 | isWeakAccess = true; | ||||||||||
5345 | |||||||||||
5346 | if (!isAddressOf) return IIK_nonlocal; | ||||||||||
5347 | |||||||||||
5348 | VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl()); | ||||||||||
5349 | if (!var) return IIK_nonlocal; | ||||||||||
5350 | |||||||||||
5351 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); | ||||||||||
5352 | |||||||||||
5353 | // If we have a conditional operator, check both sides. | ||||||||||
5354 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) { | ||||||||||
5355 | if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf, | ||||||||||
5356 | isWeakAccess)) | ||||||||||
5357 | return iik; | ||||||||||
5358 | |||||||||||
5359 | return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess); | ||||||||||
5360 | |||||||||||
5361 | // These are never scalar. | ||||||||||
5362 | } else if (isa<ArraySubscriptExpr>(e)) { | ||||||||||
5363 | return IIK_nonscalar; | ||||||||||
5364 | |||||||||||
5365 | // Otherwise, it needs to be a null pointer constant. | ||||||||||
5366 | } else { | ||||||||||
5367 | return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull) | ||||||||||
5368 | ? IIK_okay : IIK_nonlocal); | ||||||||||
5369 | } | ||||||||||
5370 | |||||||||||
5371 | return IIK_nonlocal; | ||||||||||
5372 | } | ||||||||||
5373 | |||||||||||
5374 | /// Check whether the given expression is a valid operand for an | ||||||||||
5375 | /// indirect copy/restore. | ||||||||||
5376 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { | ||||||||||
5377 | assert(src->isRValue())((src->isRValue()) ? static_cast<void> (0) : __assert_fail ("src->isRValue()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5377, __PRETTY_FUNCTION__)); | ||||||||||
5378 | bool isWeakAccess = false; | ||||||||||
5379 | InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess); | ||||||||||
5380 | // If isWeakAccess to true, there will be an implicit | ||||||||||
5381 | // load which requires a cleanup. | ||||||||||
5382 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) | ||||||||||
5383 | S.Cleanup.setExprNeedsCleanups(true); | ||||||||||
5384 | |||||||||||
5385 | if (iik == IIK_okay) return; | ||||||||||
5386 | |||||||||||
5387 | S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback) | ||||||||||
5388 | << ((unsigned) iik - 1) // shift index into diagnostic explanations | ||||||||||
5389 | << src->getSourceRange(); | ||||||||||
5390 | } | ||||||||||
5391 | |||||||||||
5392 | /// Determine whether we have compatible array types for the | ||||||||||
5393 | /// purposes of GNU by-copy array initialization. | ||||||||||
5394 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, | ||||||||||
5395 | const ArrayType *Source) { | ||||||||||
5396 | // If the source and destination array types are equivalent, we're | ||||||||||
5397 | // done. | ||||||||||
5398 | if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0))) | ||||||||||
5399 | return true; | ||||||||||
5400 | |||||||||||
5401 | // Make sure that the element types are the same. | ||||||||||
5402 | if (!Context.hasSameType(Dest->getElementType(), Source->getElementType())) | ||||||||||
5403 | return false; | ||||||||||
5404 | |||||||||||
5405 | // The only mismatch we allow is when the destination is an | ||||||||||
5406 | // incomplete array type and the source is a constant array type. | ||||||||||
5407 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); | ||||||||||
5408 | } | ||||||||||
5409 | |||||||||||
5410 | static bool tryObjCWritebackConversion(Sema &S, | ||||||||||
5411 | InitializationSequence &Sequence, | ||||||||||
5412 | const InitializedEntity &Entity, | ||||||||||
5413 | Expr *Initializer) { | ||||||||||
5414 | bool ArrayDecay = false; | ||||||||||
5415 | QualType ArgType = Initializer->getType(); | ||||||||||
5416 | QualType ArgPointee; | ||||||||||
5417 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) { | ||||||||||
5418 | ArrayDecay = true; | ||||||||||
5419 | ArgPointee = ArgArrayType->getElementType(); | ||||||||||
5420 | ArgType = S.Context.getPointerType(ArgPointee); | ||||||||||
5421 | } | ||||||||||
5422 | |||||||||||
5423 | // Handle write-back conversion. | ||||||||||
5424 | QualType ConvertedArgType; | ||||||||||
5425 | if (!S.isObjCWritebackConversion(ArgType, Entity.getType(), | ||||||||||
5426 | ConvertedArgType)) | ||||||||||
5427 | return false; | ||||||||||
5428 | |||||||||||
5429 | // We should copy unless we're passing to an argument explicitly | ||||||||||
5430 | // marked 'out'. | ||||||||||
5431 | bool ShouldCopy = true; | ||||||||||
5432 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | ||||||||||
5433 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | ||||||||||
5434 | |||||||||||
5435 | // Do we need an lvalue conversion? | ||||||||||
5436 | if (ArrayDecay || Initializer->isGLValue()) { | ||||||||||
5437 | ImplicitConversionSequence ICS; | ||||||||||
5438 | ICS.setStandard(); | ||||||||||
5439 | ICS.Standard.setAsIdentityConversion(); | ||||||||||
5440 | |||||||||||
5441 | QualType ResultType; | ||||||||||
5442 | if (ArrayDecay) { | ||||||||||
5443 | ICS.Standard.First = ICK_Array_To_Pointer; | ||||||||||
5444 | ResultType = S.Context.getPointerType(ArgPointee); | ||||||||||
5445 | } else { | ||||||||||
5446 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; | ||||||||||
5447 | ResultType = Initializer->getType().getNonLValueExprType(S.Context); | ||||||||||
5448 | } | ||||||||||
5449 | |||||||||||
5450 | Sequence.AddConversionSequenceStep(ICS, ResultType); | ||||||||||
5451 | } | ||||||||||
5452 | |||||||||||
5453 | Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy); | ||||||||||
5454 | return true; | ||||||||||
5455 | } | ||||||||||
5456 | |||||||||||
5457 | static bool TryOCLSamplerInitialization(Sema &S, | ||||||||||
5458 | InitializationSequence &Sequence, | ||||||||||
5459 | QualType DestType, | ||||||||||
5460 | Expr *Initializer) { | ||||||||||
5461 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || | ||||||||||
5462 | (!Initializer->isIntegerConstantExpr(S.Context) && | ||||||||||
5463 | !Initializer->getType()->isSamplerT())) | ||||||||||
5464 | return false; | ||||||||||
5465 | |||||||||||
5466 | Sequence.AddOCLSamplerInitStep(DestType); | ||||||||||
5467 | return true; | ||||||||||
5468 | } | ||||||||||
5469 | |||||||||||
5470 | static bool IsZeroInitializer(Expr *Initializer, Sema &S) { | ||||||||||
5471 | return Initializer->isIntegerConstantExpr(S.getASTContext()) && | ||||||||||
5472 | (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0); | ||||||||||
5473 | } | ||||||||||
5474 | |||||||||||
5475 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, | ||||||||||
5476 | InitializationSequence &Sequence, | ||||||||||
5477 | QualType DestType, | ||||||||||
5478 | Expr *Initializer) { | ||||||||||
5479 | if (!S.getLangOpts().OpenCL) | ||||||||||
5480 | return false; | ||||||||||
5481 | |||||||||||
5482 | // | ||||||||||
5483 | // OpenCL 1.2 spec, s6.12.10 | ||||||||||
5484 | // | ||||||||||
5485 | // The event argument can also be used to associate the | ||||||||||
5486 | // async_work_group_copy with a previous async copy allowing | ||||||||||
5487 | // an event to be shared by multiple async copies; otherwise | ||||||||||
5488 | // event should be zero. | ||||||||||
5489 | // | ||||||||||
5490 | if (DestType->isEventT() || DestType->isQueueT()) { | ||||||||||
5491 | if (!IsZeroInitializer(Initializer, S)) | ||||||||||
5492 | return false; | ||||||||||
5493 | |||||||||||
5494 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | ||||||||||
5495 | return true; | ||||||||||
5496 | } | ||||||||||
5497 | |||||||||||
5498 | // We should allow zero initialization for all types defined in the | ||||||||||
5499 | // cl_intel_device_side_avc_motion_estimation extension, except | ||||||||||
5500 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. | ||||||||||
5501 | if (S.getOpenCLOptions().isEnabled( | ||||||||||
5502 | "cl_intel_device_side_avc_motion_estimation") && | ||||||||||
5503 | DestType->isOCLIntelSubgroupAVCType()) { | ||||||||||
5504 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || | ||||||||||
5505 | DestType->isOCLIntelSubgroupAVCMceResultType()) | ||||||||||
5506 | return false; | ||||||||||
5507 | if (!IsZeroInitializer(Initializer, S)) | ||||||||||
5508 | return false; | ||||||||||
5509 | |||||||||||
5510 | Sequence.AddOCLZeroOpaqueTypeStep(DestType); | ||||||||||
5511 | return true; | ||||||||||
5512 | } | ||||||||||
5513 | |||||||||||
5514 | return false; | ||||||||||
5515 | } | ||||||||||
5516 | |||||||||||
5517 | InitializationSequence::InitializationSequence(Sema &S, | ||||||||||
5518 | const InitializedEntity &Entity, | ||||||||||
5519 | const InitializationKind &Kind, | ||||||||||
5520 | MultiExprArg Args, | ||||||||||
5521 | bool TopLevelOfInitList, | ||||||||||
5522 | bool TreatUnavailableAsInvalid) | ||||||||||
5523 | : FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { | ||||||||||
5524 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, | ||||||||||
5525 | TreatUnavailableAsInvalid); | ||||||||||
5526 | } | ||||||||||
5527 | |||||||||||
5528 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the | ||||||||||
5529 | /// address of that function, this returns true. Otherwise, it returns false. | ||||||||||
5530 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { | ||||||||||
5531 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||||||||
5532 | if (!DRE || !isa<FunctionDecl>(DRE->getDecl())) | ||||||||||
5533 | return false; | ||||||||||
5534 | |||||||||||
5535 | return !S.checkAddressOfFunctionIsAvailable( | ||||||||||
5536 | cast<FunctionDecl>(DRE->getDecl())); | ||||||||||
5537 | } | ||||||||||
5538 | |||||||||||
5539 | /// Determine whether we can perform an elementwise array copy for this kind | ||||||||||
5540 | /// of entity. | ||||||||||
5541 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { | ||||||||||
5542 | switch (Entity.getKind()) { | ||||||||||
5543 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
5544 | // C++ [expr.prim.lambda]p24: | ||||||||||
5545 | // For array members, the array elements are direct-initialized in | ||||||||||
5546 | // increasing subscript order. | ||||||||||
5547 | return true; | ||||||||||
5548 | |||||||||||
5549 | case InitializedEntity::EK_Variable: | ||||||||||
5550 | // C++ [dcl.decomp]p1: | ||||||||||
5551 | // [...] each element is copy-initialized or direct-initialized from the | ||||||||||
5552 | // corresponding element of the assignment-expression [...] | ||||||||||
5553 | return isa<DecompositionDecl>(Entity.getDecl()); | ||||||||||
5554 | |||||||||||
5555 | case InitializedEntity::EK_Member: | ||||||||||
5556 | // C++ [class.copy.ctor]p14: | ||||||||||
5557 | // - if the member is an array, each element is direct-initialized with | ||||||||||
5558 | // the corresponding subobject of x | ||||||||||
5559 | return Entity.isImplicitMemberInitializer(); | ||||||||||
5560 | |||||||||||
5561 | case InitializedEntity::EK_ArrayElement: | ||||||||||
5562 | // All the above cases are intended to apply recursively, even though none | ||||||||||
5563 | // of them actually say that. | ||||||||||
5564 | if (auto *E = Entity.getParent()) | ||||||||||
5565 | return canPerformArrayCopy(*E); | ||||||||||
5566 | break; | ||||||||||
5567 | |||||||||||
5568 | default: | ||||||||||
5569 | break; | ||||||||||
5570 | } | ||||||||||
5571 | |||||||||||
5572 | return false; | ||||||||||
5573 | } | ||||||||||
5574 | |||||||||||
5575 | void InitializationSequence::InitializeFrom(Sema &S, | ||||||||||
5576 | const InitializedEntity &Entity, | ||||||||||
5577 | const InitializationKind &Kind, | ||||||||||
5578 | MultiExprArg Args, | ||||||||||
5579 | bool TopLevelOfInitList, | ||||||||||
5580 | bool TreatUnavailableAsInvalid) { | ||||||||||
5581 | ASTContext &Context = S.Context; | ||||||||||
5582 | |||||||||||
5583 | // Eliminate non-overload placeholder types in the arguments. We | ||||||||||
5584 | // need to do this before checking whether types are dependent | ||||||||||
5585 | // because lowering a pseudo-object expression might well give us | ||||||||||
5586 | // something of dependent type. | ||||||||||
5587 | for (unsigned I = 0, E = Args.size(); I != E; ++I) | ||||||||||
| |||||||||||
5588 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { | ||||||||||
5589 | // FIXME: should we be doing this here? | ||||||||||
5590 | ExprResult result = S.CheckPlaceholderExpr(Args[I]); | ||||||||||
5591 | if (result.isInvalid()) { | ||||||||||
5592 | SetFailed(FK_PlaceholderType); | ||||||||||
5593 | return; | ||||||||||
5594 | } | ||||||||||
5595 | Args[I] = result.get(); | ||||||||||
5596 | } | ||||||||||
5597 | |||||||||||
5598 | // C++0x [dcl.init]p16: | ||||||||||
5599 | // The semantics of initializers are as follows. The destination type is | ||||||||||
5600 | // the type of the object or reference being initialized and the source | ||||||||||
5601 | // type is the type of the initializer expression. The source type is not | ||||||||||
5602 | // defined when the initializer is a braced-init-list or when it is a | ||||||||||
5603 | // parenthesized list of expressions. | ||||||||||
5604 | QualType DestType = Entity.getType(); | ||||||||||
5605 | |||||||||||
5606 | if (DestType->isDependentType() || | ||||||||||
5607 | Expr::hasAnyTypeDependentArguments(Args)) { | ||||||||||
5608 | SequenceKind = DependentSequence; | ||||||||||
5609 | return; | ||||||||||
5610 | } | ||||||||||
5611 | |||||||||||
5612 | // Almost everything is a normal sequence. | ||||||||||
5613 | setSequenceKind(NormalSequence); | ||||||||||
5614 | |||||||||||
5615 | QualType SourceType; | ||||||||||
5616 | Expr *Initializer = nullptr; | ||||||||||
5617 | if (Args.size() == 1) { | ||||||||||
5618 | Initializer = Args[0]; | ||||||||||
5619 | if (S.getLangOpts().ObjC) { | ||||||||||
5620 | if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(), | ||||||||||
5621 | DestType, Initializer->getType(), | ||||||||||
5622 | Initializer) || | ||||||||||
5623 | S.ConversionToObjCStringLiteralCheck(DestType, Initializer)) | ||||||||||
5624 | Args[0] = Initializer; | ||||||||||
5625 | } | ||||||||||
5626 | if (!isa<InitListExpr>(Initializer)) | ||||||||||
5627 | SourceType = Initializer->getType(); | ||||||||||
5628 | } | ||||||||||
5629 | |||||||||||
5630 | // - If the initializer is a (non-parenthesized) braced-init-list, the | ||||||||||
5631 | // object is list-initialized (8.5.4). | ||||||||||
5632 | if (Kind.getKind() != InitializationKind::IK_Direct) { | ||||||||||
5633 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) { | ||||||||||
5634 | TryListInitialization(S, Entity, Kind, InitList, *this, | ||||||||||
5635 | TreatUnavailableAsInvalid); | ||||||||||
5636 | return; | ||||||||||
5637 | } | ||||||||||
5638 | } | ||||||||||
5639 | |||||||||||
5640 | // - If the destination type is a reference type, see 8.5.3. | ||||||||||
5641 | if (DestType->isReferenceType()) { | ||||||||||
5642 | // C++0x [dcl.init.ref]p1: | ||||||||||
5643 | // A variable declared to be a T& or T&&, that is, "reference to type T" | ||||||||||
5644 | // (8.3.2), shall be initialized by an object, or function, of type T or | ||||||||||
5645 | // by an object that can be converted into a T. | ||||||||||
5646 | // (Therefore, multiple arguments are not permitted.) | ||||||||||
5647 | if (Args.size() != 1) | ||||||||||
5648 | SetFailed(FK_TooManyInitsForReference); | ||||||||||
5649 | // C++17 [dcl.init.ref]p5: | ||||||||||
5650 | // A reference [...] is initialized by an expression [...] as follows: | ||||||||||
5651 | // If the initializer is not an expression, presumably we should reject, | ||||||||||
5652 | // but the standard fails to actually say so. | ||||||||||
5653 | else if (isa<InitListExpr>(Args[0])) | ||||||||||
5654 | SetFailed(FK_ParenthesizedListInitForReference); | ||||||||||
5655 | else | ||||||||||
5656 | TryReferenceInitialization(S, Entity, Kind, Args[0], *this); | ||||||||||
5657 | return; | ||||||||||
5658 | } | ||||||||||
5659 | |||||||||||
5660 | // - If the initializer is (), the object is value-initialized. | ||||||||||
5661 | if (Kind.getKind() == InitializationKind::IK_Value || | ||||||||||
5662 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { | ||||||||||
5663 | TryValueInitialization(S, Entity, Kind, *this); | ||||||||||
5664 | return; | ||||||||||
5665 | } | ||||||||||
5666 | |||||||||||
5667 | // Handle default initialization. | ||||||||||
5668 | if (Kind.getKind() == InitializationKind::IK_Default) { | ||||||||||
5669 | TryDefaultInitialization(S, Entity, Kind, *this); | ||||||||||
5670 | return; | ||||||||||
5671 | } | ||||||||||
5672 | |||||||||||
5673 | // - If the destination type is an array of characters, an array of | ||||||||||
5674 | // char16_t, an array of char32_t, or an array of wchar_t, and the | ||||||||||
5675 | // initializer is a string literal, see 8.5.2. | ||||||||||
5676 | // - Otherwise, if the destination type is an array, the program is | ||||||||||
5677 | // ill-formed. | ||||||||||
5678 | if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) { | ||||||||||
5679 | if (Initializer && isa<VariableArrayType>(DestAT)) { | ||||||||||
5680 | SetFailed(FK_VariableLengthArrayHasInitializer); | ||||||||||
5681 | return; | ||||||||||
5682 | } | ||||||||||
5683 | |||||||||||
5684 | if (Initializer) { | ||||||||||
5685 | switch (IsStringInit(Initializer, DestAT, Context)) { | ||||||||||
5686 | case SIF_None: | ||||||||||
5687 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this); | ||||||||||
5688 | return; | ||||||||||
5689 | case SIF_NarrowStringIntoWideChar: | ||||||||||
5690 | SetFailed(FK_NarrowStringIntoWideCharArray); | ||||||||||
5691 | return; | ||||||||||
5692 | case SIF_WideStringIntoChar: | ||||||||||
5693 | SetFailed(FK_WideStringIntoCharArray); | ||||||||||
5694 | return; | ||||||||||
5695 | case SIF_IncompatWideStringIntoWideChar: | ||||||||||
5696 | SetFailed(FK_IncompatWideStringIntoWideChar); | ||||||||||
5697 | return; | ||||||||||
5698 | case SIF_PlainStringIntoUTF8Char: | ||||||||||
5699 | SetFailed(FK_PlainStringIntoUTF8Char); | ||||||||||
5700 | return; | ||||||||||
5701 | case SIF_UTF8StringIntoPlainChar: | ||||||||||
5702 | SetFailed(FK_UTF8StringIntoPlainChar); | ||||||||||
5703 | return; | ||||||||||
5704 | case SIF_Other: | ||||||||||
5705 | break; | ||||||||||
5706 | } | ||||||||||
5707 | } | ||||||||||
5708 | |||||||||||
5709 | // Some kinds of initialization permit an array to be initialized from | ||||||||||
5710 | // another array of the same type, and perform elementwise initialization. | ||||||||||
5711 | if (Initializer && isa<ConstantArrayType>(DestAT) && | ||||||||||
5712 | S.Context.hasSameUnqualifiedType(Initializer->getType(), | ||||||||||
5713 | Entity.getType()) && | ||||||||||
5714 | canPerformArrayCopy(Entity)) { | ||||||||||
5715 | // If source is a prvalue, use it directly. | ||||||||||
5716 | if (Initializer->getValueKind() == VK_RValue) { | ||||||||||
5717 | AddArrayInitStep(DestType, /*IsGNUExtension*/false); | ||||||||||
5718 | return; | ||||||||||
5719 | } | ||||||||||
5720 | |||||||||||
5721 | // Emit element-at-a-time copy loop. | ||||||||||
5722 | InitializedEntity Element = | ||||||||||
5723 | InitializedEntity::InitializeElement(S.Context, 0, Entity); | ||||||||||
5724 | QualType InitEltT = | ||||||||||
5725 | Context.getAsArrayType(Initializer->getType())->getElementType(); | ||||||||||
5726 | OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT, | ||||||||||
5727 | Initializer->getValueKind(), | ||||||||||
5728 | Initializer->getObjectKind()); | ||||||||||
5729 | Expr *OVEAsExpr = &OVE; | ||||||||||
5730 | InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList, | ||||||||||
5731 | TreatUnavailableAsInvalid); | ||||||||||
5732 | if (!Failed()) | ||||||||||
5733 | AddArrayInitLoopStep(Entity.getType(), InitEltT); | ||||||||||
5734 | return; | ||||||||||
5735 | } | ||||||||||
5736 | |||||||||||
5737 | // Note: as an GNU C extension, we allow initialization of an | ||||||||||
5738 | // array from a compound literal that creates an array of the same | ||||||||||
5739 | // type, so long as the initializer has no side effects. | ||||||||||
5740 | if (!S.getLangOpts().CPlusPlus && Initializer && | ||||||||||
5741 | isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) && | ||||||||||
5742 | Initializer->getType()->isArrayType()) { | ||||||||||
5743 | const ArrayType *SourceAT | ||||||||||
5744 | = Context.getAsArrayType(Initializer->getType()); | ||||||||||
5745 | if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT)) | ||||||||||
5746 | SetFailed(FK_ArrayTypeMismatch); | ||||||||||
5747 | else if (Initializer->HasSideEffects(S.Context)) | ||||||||||
5748 | SetFailed(FK_NonConstantArrayInit); | ||||||||||
5749 | else { | ||||||||||
5750 | AddArrayInitStep(DestType, /*IsGNUExtension*/true); | ||||||||||
5751 | } | ||||||||||
5752 | } | ||||||||||
5753 | // Note: as a GNU C++ extension, we allow list-initialization of a | ||||||||||
5754 | // class member of array type from a parenthesized initializer list. | ||||||||||
5755 | else if (S.getLangOpts().CPlusPlus && | ||||||||||
5756 | Entity.getKind() == InitializedEntity::EK_Member && | ||||||||||
5757 | Initializer && isa<InitListExpr>(Initializer)) { | ||||||||||
5758 | TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer), | ||||||||||
5759 | *this, TreatUnavailableAsInvalid); | ||||||||||
5760 | AddParenthesizedArrayInitStep(DestType); | ||||||||||
5761 | } else if (DestAT->getElementType()->isCharType()) | ||||||||||
5762 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); | ||||||||||
5763 | else if (IsWideCharCompatible(DestAT->getElementType(), Context)) | ||||||||||
5764 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); | ||||||||||
5765 | else | ||||||||||
5766 | SetFailed(FK_ArrayNeedsInitList); | ||||||||||
5767 | |||||||||||
5768 | return; | ||||||||||
5769 | } | ||||||||||
5770 | |||||||||||
5771 | // Determine whether we should consider writeback conversions for | ||||||||||
5772 | // Objective-C ARC. | ||||||||||
5773 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && | ||||||||||
5774 | Entity.isParameterKind(); | ||||||||||
5775 | |||||||||||
5776 | if (TryOCLSamplerInitialization(S, *this, DestType, Initializer)) | ||||||||||
5777 | return; | ||||||||||
5778 | |||||||||||
5779 | // We're at the end of the line for C: it's either a write-back conversion | ||||||||||
5780 | // or it's a C assignment. There's no need to check anything else. | ||||||||||
5781 | if (!S.getLangOpts().CPlusPlus) { | ||||||||||
5782 | // If allowed, check whether this is an Objective-C writeback conversion. | ||||||||||
5783 | if (allowObjCWritebackConversion && | ||||||||||
5784 | tryObjCWritebackConversion(S, *this, Entity, Initializer)) { | ||||||||||
5785 | return; | ||||||||||
5786 | } | ||||||||||
5787 | |||||||||||
5788 | if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer)) | ||||||||||
5789 | return; | ||||||||||
5790 | |||||||||||
5791 | // Handle initialization in C | ||||||||||
5792 | AddCAssignmentStep(DestType); | ||||||||||
5793 | MaybeProduceObjCObject(S, *this, Entity); | ||||||||||
5794 | return; | ||||||||||
5795 | } | ||||||||||
5796 | |||||||||||
5797 | assert
("S.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5797, __PRETTY_FUNCTION__)); | ||||||||||
5798 | |||||||||||
5799 | // - If the destination type is a (possibly cv-qualified) class type: | ||||||||||
5800 | if (DestType->isRecordType()) { | ||||||||||
5801 | // - If the initialization is direct-initialization, or if it is | ||||||||||
5802 | // copy-initialization where the cv-unqualified version of the | ||||||||||
5803 | // source type is the same class as, or a derived class of, the | ||||||||||
5804 | // class of the destination, constructors are considered. [...] | ||||||||||
5805 | if (Kind.getKind() == InitializationKind::IK_Direct || | ||||||||||
5806 | (Kind.getKind() == InitializationKind::IK_Copy && | ||||||||||
5807 | (Context.hasSameUnqualifiedType(SourceType, DestType) || | ||||||||||
5808 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, DestType)))) | ||||||||||
5809 | TryConstructorInitialization(S, Entity, Kind, Args, | ||||||||||
5810 | DestType, DestType, *this); | ||||||||||
5811 | // - Otherwise (i.e., for the remaining copy-initialization cases), | ||||||||||
5812 | // user-defined conversion sequences that can convert from the source | ||||||||||
5813 | // type to the destination type or (when a conversion function is | ||||||||||
5814 | // used) to a derived class thereof are enumerated as described in | ||||||||||
5815 | // 13.3.1.4, and the best one is chosen through overload resolution | ||||||||||
5816 | // (13.3). | ||||||||||
5817 | else | ||||||||||
5818 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | ||||||||||
5819 | TopLevelOfInitList); | ||||||||||
5820 | return; | ||||||||||
5821 | } | ||||||||||
5822 | |||||||||||
5823 | 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-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5823, __PRETTY_FUNCTION__)); | ||||||||||
5824 | |||||||||||
5825 | // The remaining cases all need a source type. | ||||||||||
5826 | if (Args.size() > 1) { | ||||||||||
5827 | SetFailed(FK_TooManyInitsForScalar); | ||||||||||
5828 | return; | ||||||||||
5829 | } else if (isa<InitListExpr>(Args[0])) { | ||||||||||
5830 | SetFailed(FK_ParenthesizedListInitForScalar); | ||||||||||
5831 | return; | ||||||||||
5832 | } | ||||||||||
5833 | |||||||||||
5834 | // - Otherwise, if the source type is a (possibly cv-qualified) class | ||||||||||
5835 | // type, conversion functions are considered. | ||||||||||
5836 | if (!SourceType.isNull() && SourceType->isRecordType()) { | ||||||||||
5837 | // For a conversion to _Atomic(T) from either T or a class type derived | ||||||||||
5838 | // from T, initialize the T object then convert to _Atomic type. | ||||||||||
5839 | bool NeedAtomicConversion = false; | ||||||||||
5840 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { | ||||||||||
5841 | if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) || | ||||||||||
5842 | S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType, | ||||||||||
5843 | Atomic->getValueType())) { | ||||||||||
5844 | DestType = Atomic->getValueType(); | ||||||||||
5845 | NeedAtomicConversion = true; | ||||||||||
5846 | } | ||||||||||
5847 | } | ||||||||||
5848 | |||||||||||
5849 | TryUserDefinedConversion(S, DestType, Kind, Initializer, *this, | ||||||||||
5850 | TopLevelOfInitList); | ||||||||||
5851 | MaybeProduceObjCObject(S, *this, Entity); | ||||||||||
5852 | if (!Failed() && NeedAtomicConversion) | ||||||||||
5853 | AddAtomicConversionStep(Entity.getType()); | ||||||||||
5854 | return; | ||||||||||
5855 | } | ||||||||||
5856 | |||||||||||
5857 | // - Otherwise, the initial value of the object being initialized is the | ||||||||||
5858 | // (possibly converted) value of the initializer expression. Standard | ||||||||||
5859 | // conversions (Clause 4) will be used, if necessary, to convert the | ||||||||||
5860 | // initializer expression to the cv-unqualified version of the | ||||||||||
5861 | // destination type; no user-defined conversions are considered. | ||||||||||
5862 | |||||||||||
5863 | ImplicitConversionSequence ICS | ||||||||||
5864 | = S.TryImplicitConversion(Initializer, DestType, | ||||||||||
5865 | /*SuppressUserConversions*/true, | ||||||||||
5866 | /*AllowExplicitConversions*/ false, | ||||||||||
5867 | /*InOverloadResolution*/ false, | ||||||||||
5868 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), | ||||||||||
5869 | allowObjCWritebackConversion); | ||||||||||
5870 | |||||||||||
5871 | if (ICS.isStandard() && | ||||||||||
5872 | ICS.Standard.Second == ICK_Writeback_Conversion) { | ||||||||||
5873 | // Objective-C ARC writeback conversion. | ||||||||||
5874 | |||||||||||
5875 | // We should copy unless we're passing to an argument explicitly | ||||||||||
5876 | // marked 'out'. | ||||||||||
5877 | bool ShouldCopy = true; | ||||||||||
5878 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl())) | ||||||||||
5879 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); | ||||||||||
5880 | |||||||||||
5881 | // If there was an lvalue adjustment, add it as a separate conversion. | ||||||||||
5882 | if (ICS.Standard.First == ICK_Array_To_Pointer || | ||||||||||
5883 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { | ||||||||||
5884 | ImplicitConversionSequence LvalueICS; | ||||||||||
5885 | LvalueICS.setStandard(); | ||||||||||
5886 | LvalueICS.Standard.setAsIdentityConversion(); | ||||||||||
5887 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0)); | ||||||||||
5888 | LvalueICS.Standard.First = ICS.Standard.First; | ||||||||||
5889 | AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0)); | ||||||||||
5890 | } | ||||||||||
5891 | |||||||||||
5892 | AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy); | ||||||||||
5893 | } else if (ICS.isBad()) { | ||||||||||
5894 | DeclAccessPair dap; | ||||||||||
5895 | if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) { | ||||||||||
5896 | AddZeroInitializationStep(Entity.getType()); | ||||||||||
5897 | } else if (Initializer->getType() == Context.OverloadTy && | ||||||||||
| |||||||||||
5898 | !S.ResolveAddressOfOverloadedFunction(Initializer, DestType, | ||||||||||
5899 | false, dap)) | ||||||||||
5900 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); | ||||||||||
5901 | else if (Initializer->getType()->isFunctionType() && | ||||||||||
5902 | isExprAnUnaddressableFunction(S, Initializer)) | ||||||||||
5903 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); | ||||||||||
5904 | else | ||||||||||
5905 | SetFailed(InitializationSequence::FK_ConversionFailed); | ||||||||||
5906 | } else { | ||||||||||
5907 | AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList); | ||||||||||
5908 | |||||||||||
5909 | MaybeProduceObjCObject(S, *this, Entity); | ||||||||||
5910 | } | ||||||||||
5911 | } | ||||||||||
5912 | |||||||||||
5913 | InitializationSequence::~InitializationSequence() { | ||||||||||
5914 | for (auto &S : Steps) | ||||||||||
5915 | S.Destroy(); | ||||||||||
5916 | } | ||||||||||
5917 | |||||||||||
5918 | //===----------------------------------------------------------------------===// | ||||||||||
5919 | // Perform initialization | ||||||||||
5920 | //===----------------------------------------------------------------------===// | ||||||||||
5921 | static Sema::AssignmentAction | ||||||||||
5922 | getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) { | ||||||||||
5923 | switch(Entity.getKind()) { | ||||||||||
5924 | case InitializedEntity::EK_Variable: | ||||||||||
5925 | case InitializedEntity::EK_New: | ||||||||||
5926 | case InitializedEntity::EK_Exception: | ||||||||||
5927 | case InitializedEntity::EK_Base: | ||||||||||
5928 | case InitializedEntity::EK_Delegating: | ||||||||||
5929 | return Sema::AA_Initializing; | ||||||||||
5930 | |||||||||||
5931 | case InitializedEntity::EK_Parameter: | ||||||||||
5932 | if (Entity.getDecl() && | ||||||||||
5933 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | ||||||||||
5934 | return Sema::AA_Sending; | ||||||||||
5935 | |||||||||||
5936 | return Sema::AA_Passing; | ||||||||||
5937 | |||||||||||
5938 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||||||||
5939 | if (Entity.getDecl() && | ||||||||||
5940 | isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext())) | ||||||||||
5941 | return Sema::AA_Sending; | ||||||||||
5942 | |||||||||||
5943 | return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited; | ||||||||||
5944 | |||||||||||
5945 | case InitializedEntity::EK_Result: | ||||||||||
5946 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. | ||||||||||
5947 | return Sema::AA_Returning; | ||||||||||
5948 | |||||||||||
5949 | case InitializedEntity::EK_Temporary: | ||||||||||
5950 | case InitializedEntity::EK_RelatedResult: | ||||||||||
5951 | // FIXME: Can we tell apart casting vs. converting? | ||||||||||
5952 | return Sema::AA_Casting; | ||||||||||
5953 | |||||||||||
5954 | case InitializedEntity::EK_Member: | ||||||||||
5955 | case InitializedEntity::EK_Binding: | ||||||||||
5956 | case InitializedEntity::EK_ArrayElement: | ||||||||||
5957 | case InitializedEntity::EK_VectorElement: | ||||||||||
5958 | case InitializedEntity::EK_ComplexElement: | ||||||||||
5959 | case InitializedEntity::EK_BlockElement: | ||||||||||
5960 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||||||||
5961 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
5962 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
5963 | return Sema::AA_Initializing; | ||||||||||
5964 | } | ||||||||||
5965 | |||||||||||
5966 | llvm_unreachable("Invalid EntityKind!")::llvm::llvm_unreachable_internal("Invalid EntityKind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5966); | ||||||||||
5967 | } | ||||||||||
5968 | |||||||||||
5969 | /// Whether we should bind a created object as a temporary when | ||||||||||
5970 | /// initializing the given entity. | ||||||||||
5971 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { | ||||||||||
5972 | switch (Entity.getKind()) { | ||||||||||
5973 | case InitializedEntity::EK_ArrayElement: | ||||||||||
5974 | case InitializedEntity::EK_Member: | ||||||||||
5975 | case InitializedEntity::EK_Result: | ||||||||||
5976 | case InitializedEntity::EK_StmtExprResult: | ||||||||||
5977 | case InitializedEntity::EK_New: | ||||||||||
5978 | case InitializedEntity::EK_Variable: | ||||||||||
5979 | case InitializedEntity::EK_Base: | ||||||||||
5980 | case InitializedEntity::EK_Delegating: | ||||||||||
5981 | case InitializedEntity::EK_VectorElement: | ||||||||||
5982 | case InitializedEntity::EK_ComplexElement: | ||||||||||
5983 | case InitializedEntity::EK_Exception: | ||||||||||
5984 | case InitializedEntity::EK_BlockElement: | ||||||||||
5985 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||||||||
5986 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
5987 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
5988 | return false; | ||||||||||
5989 | |||||||||||
5990 | case InitializedEntity::EK_Parameter: | ||||||||||
5991 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||||||||
5992 | case InitializedEntity::EK_Temporary: | ||||||||||
5993 | case InitializedEntity::EK_RelatedResult: | ||||||||||
5994 | case InitializedEntity::EK_Binding: | ||||||||||
5995 | return true; | ||||||||||
5996 | } | ||||||||||
5997 | |||||||||||
5998 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 5998); | ||||||||||
5999 | } | ||||||||||
6000 | |||||||||||
6001 | /// Whether the given entity, when initialized with an object | ||||||||||
6002 | /// created for that initialization, requires destruction. | ||||||||||
6003 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { | ||||||||||
6004 | switch (Entity.getKind()) { | ||||||||||
6005 | case InitializedEntity::EK_Result: | ||||||||||
6006 | case InitializedEntity::EK_StmtExprResult: | ||||||||||
6007 | case InitializedEntity::EK_New: | ||||||||||
6008 | case InitializedEntity::EK_Base: | ||||||||||
6009 | case InitializedEntity::EK_Delegating: | ||||||||||
6010 | case InitializedEntity::EK_VectorElement: | ||||||||||
6011 | case InitializedEntity::EK_ComplexElement: | ||||||||||
6012 | case InitializedEntity::EK_BlockElement: | ||||||||||
6013 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||||||||
6014 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
6015 | return false; | ||||||||||
6016 | |||||||||||
6017 | case InitializedEntity::EK_Member: | ||||||||||
6018 | case InitializedEntity::EK_Binding: | ||||||||||
6019 | case InitializedEntity::EK_Variable: | ||||||||||
6020 | case InitializedEntity::EK_Parameter: | ||||||||||
6021 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||||||||
6022 | case InitializedEntity::EK_Temporary: | ||||||||||
6023 | case InitializedEntity::EK_ArrayElement: | ||||||||||
6024 | case InitializedEntity::EK_Exception: | ||||||||||
6025 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
6026 | case InitializedEntity::EK_RelatedResult: | ||||||||||
6027 | return true; | ||||||||||
6028 | } | ||||||||||
6029 | |||||||||||
6030 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 6030); | ||||||||||
6031 | } | ||||||||||
6032 | |||||||||||
6033 | /// Get the location at which initialization diagnostics should appear. | ||||||||||
6034 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, | ||||||||||
6035 | Expr *Initializer) { | ||||||||||
6036 | switch (Entity.getKind()) { | ||||||||||
6037 | case InitializedEntity::EK_Result: | ||||||||||
6038 | case InitializedEntity::EK_StmtExprResult: | ||||||||||
6039 | return Entity.getReturnLoc(); | ||||||||||
6040 | |||||||||||
6041 | case InitializedEntity::EK_Exception: | ||||||||||
6042 | return Entity.getThrowLoc(); | ||||||||||
6043 | |||||||||||
6044 | case InitializedEntity::EK_Variable: | ||||||||||
6045 | case InitializedEntity::EK_Binding: | ||||||||||
6046 | return Entity.getDecl()->getLocation(); | ||||||||||
6047 | |||||||||||
6048 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
6049 | return Entity.getCaptureLoc(); | ||||||||||
6050 | |||||||||||
6051 | case InitializedEntity::EK_ArrayElement: | ||||||||||
6052 | case InitializedEntity::EK_Member: | ||||||||||
6053 | case InitializedEntity::EK_Parameter: | ||||||||||
6054 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||||||||
6055 | case InitializedEntity::EK_Temporary: | ||||||||||
6056 | case InitializedEntity::EK_New: | ||||||||||
6057 | case InitializedEntity::EK_Base: | ||||||||||
6058 | case InitializedEntity::EK_Delegating: | ||||||||||
6059 | case InitializedEntity::EK_VectorElement: | ||||||||||
6060 | case InitializedEntity::EK_ComplexElement: | ||||||||||
6061 | case InitializedEntity::EK_BlockElement: | ||||||||||
6062 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||||||||
6063 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
6064 | case InitializedEntity::EK_RelatedResult: | ||||||||||
6065 | return Initializer->getBeginLoc(); | ||||||||||
6066 | } | ||||||||||
6067 | llvm_unreachable("missed an InitializedEntity kind?")::llvm::llvm_unreachable_internal("missed an InitializedEntity kind?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 6067); | ||||||||||
6068 | } | ||||||||||
6069 | |||||||||||
6070 | /// Make a (potentially elidable) temporary copy of the object | ||||||||||
6071 | /// provided by the given initializer by calling the appropriate copy | ||||||||||
6072 | /// constructor. | ||||||||||
6073 | /// | ||||||||||
6074 | /// \param S The Sema object used for type-checking. | ||||||||||
6075 | /// | ||||||||||
6076 | /// \param T The type of the temporary object, which must either be | ||||||||||
6077 | /// the type of the initializer expression or a superclass thereof. | ||||||||||
6078 | /// | ||||||||||
6079 | /// \param Entity The entity being initialized. | ||||||||||
6080 | /// | ||||||||||
6081 | /// \param CurInit The initializer expression. | ||||||||||
6082 | /// | ||||||||||
6083 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that | ||||||||||
6084 | /// is permitted in C++03 (but not C++0x) when binding a reference to | ||||||||||
6085 | /// an rvalue. | ||||||||||
6086 | /// | ||||||||||
6087 | /// \returns An expression that copies the initializer expression into | ||||||||||
6088 | /// a temporary object, or an error expression if a copy could not be | ||||||||||
6089 | /// created. | ||||||||||
6090 | static ExprResult CopyObject(Sema &S, | ||||||||||
6091 | QualType T, | ||||||||||
6092 | const InitializedEntity &Entity, | ||||||||||
6093 | ExprResult CurInit, | ||||||||||
6094 | bool IsExtraneousCopy) { | ||||||||||
6095 | if (CurInit.isInvalid()) | ||||||||||
6096 | return CurInit; | ||||||||||
6097 | // Determine which class type we're copying to. | ||||||||||
6098 | Expr *CurInitExpr = (Expr *)CurInit.get(); | ||||||||||
6099 | CXXRecordDecl *Class = nullptr; | ||||||||||
6100 | if (const RecordType *Record = T->getAs<RecordType>()) | ||||||||||
6101 | Class = cast<CXXRecordDecl>(Record->getDecl()); | ||||||||||
6102 | if (!Class) | ||||||||||
6103 | return CurInit; | ||||||||||
6104 | |||||||||||
6105 | SourceLocation Loc = getInitializationLoc(Entity, CurInit.get()); | ||||||||||
6106 | |||||||||||
6107 | // Make sure that the type we are copying is complete. | ||||||||||
6108 | if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete)) | ||||||||||
6109 | return CurInit; | ||||||||||
6110 | |||||||||||
6111 | // Perform overload resolution using the class's constructors. Per | ||||||||||
6112 | // C++11 [dcl.init]p16, second bullet for class types, this initialization | ||||||||||
6113 | // is direct-initialization. | ||||||||||
6114 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | ||||||||||
6115 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); | ||||||||||
6116 | |||||||||||
6117 | OverloadCandidateSet::iterator Best; | ||||||||||
6118 | switch (ResolveConstructorOverload( | ||||||||||
6119 | S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best, | ||||||||||
6120 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | ||||||||||
6121 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | ||||||||||
6122 | /*SecondStepOfCopyInit=*/true)) { | ||||||||||
6123 | case OR_Success: | ||||||||||
6124 | break; | ||||||||||
6125 | |||||||||||
6126 | case OR_No_Viable_Function: | ||||||||||
6127 | CandidateSet.NoteCandidates( | ||||||||||
6128 | PartialDiagnosticAt( | ||||||||||
6129 | Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext() | ||||||||||
6130 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable | ||||||||||
6131 | : diag::err_temp_copy_no_viable) | ||||||||||
6132 | << (int)Entity.getKind() << CurInitExpr->getType() | ||||||||||
6133 | << CurInitExpr->getSourceRange()), | ||||||||||
6134 | S, OCD_AllCandidates, CurInitExpr); | ||||||||||
6135 | if (!IsExtraneousCopy || S.isSFINAEContext()) | ||||||||||
6136 | return ExprError(); | ||||||||||
6137 | return CurInit; | ||||||||||
6138 | |||||||||||
6139 | case OR_Ambiguous: | ||||||||||
6140 | CandidateSet.NoteCandidates( | ||||||||||
6141 | PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous) | ||||||||||
6142 | << (int)Entity.getKind() | ||||||||||
6143 | << CurInitExpr->getType() | ||||||||||
6144 | << CurInitExpr->getSourceRange()), | ||||||||||
6145 | S, OCD_AmbiguousCandidates, CurInitExpr); | ||||||||||
6146 | return ExprError(); | ||||||||||
6147 | |||||||||||
6148 | case OR_Deleted: | ||||||||||
6149 | S.Diag(Loc, diag::err_temp_copy_deleted) | ||||||||||
6150 | << (int)Entity.getKind() << CurInitExpr->getType() | ||||||||||
6151 | << CurInitExpr->getSourceRange(); | ||||||||||
6152 | S.NoteDeletedFunction(Best->Function); | ||||||||||
6153 | return ExprError(); | ||||||||||
6154 | } | ||||||||||
6155 | |||||||||||
6156 | bool HadMultipleCandidates = CandidateSet.size() > 1; | ||||||||||
6157 | |||||||||||
6158 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); | ||||||||||
6159 | SmallVector<Expr*, 8> ConstructorArgs; | ||||||||||
6160 | CurInit.get(); // Ownership transferred into MultiExprArg, below. | ||||||||||
6161 | |||||||||||
6162 | S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity, | ||||||||||
6163 | IsExtraneousCopy); | ||||||||||
6164 | |||||||||||
6165 | if (IsExtraneousCopy) { | ||||||||||
6166 | // If this is a totally extraneous copy for C++03 reference | ||||||||||
6167 | // binding purposes, just return the original initialization | ||||||||||
6168 | // expression. We don't generate an (elided) copy operation here | ||||||||||
6169 | // because doing so would require us to pass down a flag to avoid | ||||||||||
6170 | // infinite recursion, where each step adds another extraneous, | ||||||||||
6171 | // elidable copy. | ||||||||||
6172 | |||||||||||
6173 | // Instantiate the default arguments of any extra parameters in | ||||||||||
6174 | // the selected copy constructor, as if we were going to create a | ||||||||||
6175 | // proper call to the copy constructor. | ||||||||||
6176 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { | ||||||||||
6177 | ParmVarDecl *Parm = Constructor->getParamDecl(I); | ||||||||||
6178 | if (S.RequireCompleteType(Loc, Parm->getType(), | ||||||||||
6179 | diag::err_call_incomplete_argument)) | ||||||||||
6180 | break; | ||||||||||
6181 | |||||||||||
6182 | // Build the default argument expression; we don't actually care | ||||||||||
6183 | // if this succeeds or not, because this routine will complain | ||||||||||
6184 | // if there was a problem. | ||||||||||
6185 | S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm); | ||||||||||
6186 | } | ||||||||||
6187 | |||||||||||
6188 | return CurInitExpr; | ||||||||||
6189 | } | ||||||||||
6190 | |||||||||||
6191 | // Determine the arguments required to actually perform the | ||||||||||
6192 | // constructor call (we might have derived-to-base conversions, or | ||||||||||
6193 | // the copy constructor may have default arguments). | ||||||||||
6194 | if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs)) | ||||||||||
6195 | return ExprError(); | ||||||||||
6196 | |||||||||||
6197 | // C++0x [class.copy]p32: | ||||||||||
6198 | // When certain criteria are met, an implementation is allowed to | ||||||||||
6199 | // omit the copy/move construction of a class object, even if the | ||||||||||
6200 | // copy/move constructor and/or destructor for the object have | ||||||||||
6201 | // side effects. [...] | ||||||||||
6202 | // - when a temporary class object that has not been bound to a | ||||||||||
6203 | // reference (12.2) would be copied/moved to a class object | ||||||||||
6204 | // with the same cv-unqualified type, the copy/move operation | ||||||||||
6205 | // can be omitted by constructing the temporary object | ||||||||||
6206 | // directly into the target of the omitted copy/move | ||||||||||
6207 | // | ||||||||||
6208 | // Note that the other three bullets are handled elsewhere. Copy | ||||||||||
6209 | // elision for return statements and throw expressions are handled as part | ||||||||||
6210 | // of constructor initialization, while copy elision for exception handlers | ||||||||||
6211 | // is handled by the run-time. | ||||||||||
6212 | // | ||||||||||
6213 | // FIXME: If the function parameter is not the same type as the temporary, we | ||||||||||
6214 | // should still be able to elide the copy, but we don't have a way to | ||||||||||
6215 | // represent in the AST how much should be elided in this case. | ||||||||||
6216 | bool Elidable = | ||||||||||
6217 | CurInitExpr->isTemporaryObject(S.Context, Class) && | ||||||||||
6218 | S.Context.hasSameUnqualifiedType( | ||||||||||
6219 | Best->Function->getParamDecl(0)->getType().getNonReferenceType(), | ||||||||||
6220 | CurInitExpr->getType()); | ||||||||||
6221 | |||||||||||
6222 | // Actually perform the constructor call. | ||||||||||
6223 | CurInit = S.BuildCXXConstructExpr(Loc, T, Best->FoundDecl, Constructor, | ||||||||||
6224 | Elidable, | ||||||||||
6225 | ConstructorArgs, | ||||||||||
6226 | HadMultipleCandidates, | ||||||||||
6227 | /*ListInit*/ false, | ||||||||||
6228 | /*StdInitListInit*/ false, | ||||||||||
6229 | /*ZeroInit*/ false, | ||||||||||
6230 | CXXConstructExpr::CK_Complete, | ||||||||||
6231 | SourceRange()); | ||||||||||
6232 | |||||||||||
6233 | // If we're supposed to bind temporaries, do so. | ||||||||||
6234 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) | ||||||||||
6235 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | ||||||||||
6236 | return CurInit; | ||||||||||
6237 | } | ||||||||||
6238 | |||||||||||
6239 | /// Check whether elidable copy construction for binding a reference to | ||||||||||
6240 | /// a temporary would have succeeded if we were building in C++98 mode, for | ||||||||||
6241 | /// -Wc++98-compat. | ||||||||||
6242 | static void CheckCXX98CompatAccessibleCopy(Sema &S, | ||||||||||
6243 | const InitializedEntity &Entity, | ||||||||||
6244 | Expr *CurInitExpr) { | ||||||||||
6245 | assert(S.getLangOpts().CPlusPlus11)((S.getLangOpts().CPlusPlus11) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 6245, __PRETTY_FUNCTION__)); | ||||||||||
6246 | |||||||||||
6247 | const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>(); | ||||||||||
6248 | if (!Record) | ||||||||||
6249 | return; | ||||||||||
6250 | |||||||||||
6251 | SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr); | ||||||||||
6252 | if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc)) | ||||||||||
6253 | return; | ||||||||||
6254 | |||||||||||
6255 | // Find constructors which would have been considered. | ||||||||||
6256 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | ||||||||||
6257 | DeclContext::lookup_result Ctors = | ||||||||||
6258 | S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl())); | ||||||||||
6259 | |||||||||||
6260 | // Perform overload resolution. | ||||||||||
6261 | OverloadCandidateSet::iterator Best; | ||||||||||
6262 | OverloadingResult OR = ResolveConstructorOverload( | ||||||||||
6263 | S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best, | ||||||||||
6264 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, | ||||||||||
6265 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, | ||||||||||
6266 | /*SecondStepOfCopyInit=*/true); | ||||||||||
6267 | |||||||||||
6268 | PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy) | ||||||||||
6269 | << OR << (int)Entity.getKind() << CurInitExpr->getType() | ||||||||||
6270 | << CurInitExpr->getSourceRange(); | ||||||||||
6271 | |||||||||||
6272 | switch (OR) { | ||||||||||
6273 | case OR_Success: | ||||||||||
6274 | S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function), | ||||||||||
6275 | Best->FoundDecl, Entity, Diag); | ||||||||||
6276 | // FIXME: Check default arguments as far as that's possible. | ||||||||||
6277 | break; | ||||||||||
6278 | |||||||||||
6279 | case OR_No_Viable_Function: | ||||||||||
6280 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | ||||||||||
6281 | OCD_AllCandidates, CurInitExpr); | ||||||||||
6282 | break; | ||||||||||
6283 | |||||||||||
6284 | case OR_Ambiguous: | ||||||||||
6285 | CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, | ||||||||||
6286 | OCD_AmbiguousCandidates, CurInitExpr); | ||||||||||
6287 | break; | ||||||||||
6288 | |||||||||||
6289 | case OR_Deleted: | ||||||||||
6290 | S.Diag(Loc, Diag); | ||||||||||
6291 | S.NoteDeletedFunction(Best->Function); | ||||||||||
6292 | break; | ||||||||||
6293 | } | ||||||||||
6294 | } | ||||||||||
6295 | |||||||||||
6296 | void InitializationSequence::PrintInitLocationNote(Sema &S, | ||||||||||
6297 | const InitializedEntity &Entity) { | ||||||||||
6298 | if (Entity.isParameterKind() && Entity.getDecl()) { | ||||||||||
6299 | if (Entity.getDecl()->getLocation().isInvalid()) | ||||||||||
6300 | return; | ||||||||||
6301 | |||||||||||
6302 | if (Entity.getDecl()->getDeclName()) | ||||||||||
6303 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here) | ||||||||||
6304 | << Entity.getDecl()->getDeclName(); | ||||||||||
6305 | else | ||||||||||
6306 | S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here); | ||||||||||
6307 | } | ||||||||||
6308 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && | ||||||||||
6309 | Entity.getMethodDecl()) | ||||||||||
6310 | S.Diag(Entity.getMethodDecl()->getLocation(), | ||||||||||
6311 | diag::note_method_return_type_change) | ||||||||||
6312 | << Entity.getMethodDecl()->getDeclName(); | ||||||||||
6313 | } | ||||||||||
6314 | |||||||||||
6315 | /// Returns true if the parameters describe a constructor initialization of | ||||||||||
6316 | /// an explicit temporary object, e.g. "Point(x, y)". | ||||||||||
6317 | static bool isExplicitTemporary(const InitializedEntity &Entity, | ||||||||||
6318 | const InitializationKind &Kind, | ||||||||||
6319 | unsigned NumArgs) { | ||||||||||
6320 | switch (Entity.getKind()) { | ||||||||||
6321 | case InitializedEntity::EK_Temporary: | ||||||||||
6322 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
6323 | case InitializedEntity::EK_RelatedResult: | ||||||||||
6324 | break; | ||||||||||
6325 | default: | ||||||||||
6326 | return false; | ||||||||||
6327 | } | ||||||||||
6328 | |||||||||||
6329 | switch (Kind.getKind()) { | ||||||||||
6330 | case InitializationKind::IK_DirectList: | ||||||||||
6331 | return true; | ||||||||||
6332 | // FIXME: Hack to work around cast weirdness. | ||||||||||
6333 | case InitializationKind::IK_Direct: | ||||||||||
6334 | case InitializationKind::IK_Value: | ||||||||||
6335 | return NumArgs != 1; | ||||||||||
6336 | default: | ||||||||||
6337 | return false; | ||||||||||
6338 | } | ||||||||||
6339 | } | ||||||||||
6340 | |||||||||||
6341 | static ExprResult | ||||||||||
6342 | PerformConstructorInitialization(Sema &S, | ||||||||||
6343 | const InitializedEntity &Entity, | ||||||||||
6344 | const InitializationKind &Kind, | ||||||||||
6345 | MultiExprArg Args, | ||||||||||
6346 | const InitializationSequence::Step& Step, | ||||||||||
6347 | bool &ConstructorInitRequiresZeroInit, | ||||||||||
6348 | bool IsListInitialization, | ||||||||||
6349 | bool IsStdInitListInitialization, | ||||||||||
6350 | SourceLocation LBraceLoc, | ||||||||||
6351 | SourceLocation RBraceLoc) { | ||||||||||
6352 | unsigned NumArgs = Args.size(); | ||||||||||
6353 | CXXConstructorDecl *Constructor | ||||||||||
6354 | = cast<CXXConstructorDecl>(Step.Function.Function); | ||||||||||
6355 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; | ||||||||||
6356 | |||||||||||
6357 | // Build a call to the selected constructor. | ||||||||||
6358 | SmallVector<Expr*, 8> ConstructorArgs; | ||||||||||
6359 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) | ||||||||||
6360 | ? Kind.getEqualLoc() | ||||||||||
6361 | : Kind.getLocation(); | ||||||||||
6362 | |||||||||||
6363 | if (Kind.getKind() == InitializationKind::IK_Default) { | ||||||||||
6364 | // Force even a trivial, implicit default constructor to be | ||||||||||
6365 | // semantically checked. We do this explicitly because we don't build | ||||||||||
6366 | // the definition for completely trivial constructors. | ||||||||||
6367 | assert(Constructor->getParent() && "No parent class for constructor.")((Constructor->getParent() && "No parent class for constructor." ) ? static_cast<void> (0) : __assert_fail ("Constructor->getParent() && \"No parent class for constructor.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 6367, __PRETTY_FUNCTION__)); | ||||||||||
6368 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && | ||||||||||
6369 | Constructor->isTrivial() && !Constructor->isUsed(false)) { | ||||||||||
6370 | S.runWithSufficientStackSpace(Loc, [&] { | ||||||||||
6371 | S.DefineImplicitDefaultConstructor(Loc, Constructor); | ||||||||||
6372 | }); | ||||||||||
6373 | } | ||||||||||
6374 | } | ||||||||||
6375 | |||||||||||
6376 | ExprResult CurInit((Expr *)nullptr); | ||||||||||
6377 | |||||||||||
6378 | // C++ [over.match.copy]p1: | ||||||||||
6379 | // - When initializing a temporary to be bound to the first parameter | ||||||||||
6380 | // of a constructor that takes a reference to possibly cv-qualified | ||||||||||
6381 | // T as its first argument, called with a single argument in the | ||||||||||
6382 | // context of direct-initialization, explicit conversion functions | ||||||||||
6383 | // are also considered. | ||||||||||
6384 | bool AllowExplicitConv = | ||||||||||
6385 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && | ||||||||||
6386 | hasCopyOrMoveCtorParam(S.Context, | ||||||||||
6387 | getConstructorInfo(Step.Function.FoundDecl)); | ||||||||||
6388 | |||||||||||
6389 | // Determine the arguments required to actually perform the constructor | ||||||||||
6390 | // call. | ||||||||||
6391 | if (S.CompleteConstructorCall(Constructor, Args, | ||||||||||
6392 | Loc, ConstructorArgs, | ||||||||||
6393 | AllowExplicitConv, | ||||||||||
6394 | IsListInitialization)) | ||||||||||
6395 | return ExprError(); | ||||||||||
6396 | |||||||||||
6397 | |||||||||||
6398 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { | ||||||||||
6399 | // An explicitly-constructed temporary, e.g., X(1, 2). | ||||||||||
6400 | if (S.DiagnoseUseOfDecl(Constructor, Loc)) | ||||||||||
6401 | return ExprError(); | ||||||||||
6402 | |||||||||||
6403 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | ||||||||||
6404 | if (!TSInfo) | ||||||||||
6405 | TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc); | ||||||||||
6406 | SourceRange ParenOrBraceRange = | ||||||||||
6407 | (Kind.getKind() == InitializationKind::IK_DirectList) | ||||||||||
6408 | ? SourceRange(LBraceLoc, RBraceLoc) | ||||||||||
6409 | : Kind.getParenOrBraceRange(); | ||||||||||
6410 | |||||||||||
6411 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( | ||||||||||
6412 | Step.Function.FoundDecl.getDecl())) { | ||||||||||
6413 | Constructor = S.findInheritingConstructor(Loc, Constructor, Shadow); | ||||||||||
6414 | if (S.DiagnoseUseOfDecl(Constructor, Loc)) | ||||||||||
6415 | return ExprError(); | ||||||||||
6416 | } | ||||||||||
6417 | S.MarkFunctionReferenced(Loc, Constructor); | ||||||||||
6418 | |||||||||||
6419 | CurInit = CXXTemporaryObjectExpr::Create( | ||||||||||
6420 | S.Context, Constructor, | ||||||||||
6421 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | ||||||||||
6422 | ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, | ||||||||||
6423 | IsListInitialization, IsStdInitListInitialization, | ||||||||||
6424 | ConstructorInitRequiresZeroInit); | ||||||||||
6425 | } else { | ||||||||||
6426 | CXXConstructExpr::ConstructionKind ConstructKind = | ||||||||||
6427 | CXXConstructExpr::CK_Complete; | ||||||||||
6428 | |||||||||||
6429 | if (Entity.getKind() == InitializedEntity::EK_Base) { | ||||||||||
6430 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() ? | ||||||||||
6431 | CXXConstructExpr::CK_VirtualBase : | ||||||||||
6432 | CXXConstructExpr::CK_NonVirtualBase; | ||||||||||
6433 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { | ||||||||||
6434 | ConstructKind = CXXConstructExpr::CK_Delegating; | ||||||||||
6435 | } | ||||||||||
6436 | |||||||||||
6437 | // Only get the parenthesis or brace range if it is a list initialization or | ||||||||||
6438 | // direct construction. | ||||||||||
6439 | SourceRange ParenOrBraceRange; | ||||||||||
6440 | if (IsListInitialization) | ||||||||||
6441 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); | ||||||||||
6442 | else if (Kind.getKind() == InitializationKind::IK_Direct) | ||||||||||
6443 | ParenOrBraceRange = Kind.getParenOrBraceRange(); | ||||||||||
6444 | |||||||||||
6445 | // If the entity allows NRVO, mark the construction as elidable | ||||||||||
6446 | // unconditionally. | ||||||||||
6447 | if (Entity.allowsNRVO()) | ||||||||||
6448 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | ||||||||||
6449 | Step.Function.FoundDecl, | ||||||||||
6450 | Constructor, /*Elidable=*/true, | ||||||||||
6451 | ConstructorArgs, | ||||||||||
6452 | HadMultipleCandidates, | ||||||||||
6453 | IsListInitialization, | ||||||||||
6454 | IsStdInitListInitialization, | ||||||||||
6455 | ConstructorInitRequiresZeroInit, | ||||||||||
6456 | ConstructKind, | ||||||||||
6457 | ParenOrBraceRange); | ||||||||||
6458 | else | ||||||||||
6459 | CurInit = S.BuildCXXConstructExpr(Loc, Step.Type, | ||||||||||
6460 | Step.Function.FoundDecl, | ||||||||||
6461 | Constructor, | ||||||||||
6462 | ConstructorArgs, | ||||||||||
6463 | HadMultipleCandidates, | ||||||||||
6464 | IsListInitialization, | ||||||||||
6465 | IsStdInitListInitialization, | ||||||||||
6466 | ConstructorInitRequiresZeroInit, | ||||||||||
6467 | ConstructKind, | ||||||||||
6468 | ParenOrBraceRange); | ||||||||||
6469 | } | ||||||||||
6470 | if (CurInit.isInvalid()) | ||||||||||
6471 | return ExprError(); | ||||||||||
6472 | |||||||||||
6473 | // Only check access if all of that succeeded. | ||||||||||
6474 | S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity); | ||||||||||
6475 | if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc)) | ||||||||||
6476 | return ExprError(); | ||||||||||
6477 | |||||||||||
6478 | if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType())) | ||||||||||
6479 | if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S)) | ||||||||||
6480 | return ExprError(); | ||||||||||
6481 | |||||||||||
6482 | if (shouldBindAsTemporary(Entity)) | ||||||||||
6483 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||||||||
6484 | |||||||||||
6485 | return CurInit; | ||||||||||
6486 | } | ||||||||||
6487 | |||||||||||
6488 | namespace { | ||||||||||
6489 | enum LifetimeKind { | ||||||||||
6490 | /// The lifetime of a temporary bound to this entity ends at the end of the | ||||||||||
6491 | /// full-expression, and that's (probably) fine. | ||||||||||
6492 | LK_FullExpression, | ||||||||||
6493 | |||||||||||
6494 | /// The lifetime of a temporary bound to this entity is extended to the | ||||||||||
6495 | /// lifeitme of the entity itself. | ||||||||||
6496 | LK_Extended, | ||||||||||
6497 | |||||||||||
6498 | /// The lifetime of a temporary bound to this entity probably ends too soon, | ||||||||||
6499 | /// because the entity is allocated in a new-expression. | ||||||||||
6500 | LK_New, | ||||||||||
6501 | |||||||||||
6502 | /// The lifetime of a temporary bound to this entity ends too soon, because | ||||||||||
6503 | /// the entity is a return object. | ||||||||||
6504 | LK_Return, | ||||||||||
6505 | |||||||||||
6506 | /// The lifetime of a temporary bound to this entity ends too soon, because | ||||||||||
6507 | /// the entity is the result of a statement expression. | ||||||||||
6508 | LK_StmtExprResult, | ||||||||||
6509 | |||||||||||
6510 | /// This is a mem-initializer: if it would extend a temporary (other than via | ||||||||||
6511 | /// a default member initializer), the program is ill-formed. | ||||||||||
6512 | LK_MemInitializer, | ||||||||||
6513 | }; | ||||||||||
6514 | using LifetimeResult = | ||||||||||
6515 | llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; | ||||||||||
6516 | } | ||||||||||
6517 | |||||||||||
6518 | /// Determine the declaration which an initialized entity ultimately refers to, | ||||||||||
6519 | /// for the purpose of lifetime-extending a temporary bound to a reference in | ||||||||||
6520 | /// the initialization of \p Entity. | ||||||||||
6521 | static LifetimeResult getEntityLifetime( | ||||||||||
6522 | const InitializedEntity *Entity, | ||||||||||
6523 | const InitializedEntity *InitField = nullptr) { | ||||||||||
6524 | // C++11 [class.temporary]p5: | ||||||||||
6525 | switch (Entity->getKind()) { | ||||||||||
6526 | case InitializedEntity::EK_Variable: | ||||||||||
6527 | // The temporary [...] persists for the lifetime of the reference | ||||||||||
6528 | return {Entity, LK_Extended}; | ||||||||||
6529 | |||||||||||
6530 | case InitializedEntity::EK_Member: | ||||||||||
6531 | // For subobjects, we look at the complete object. | ||||||||||
6532 | if (Entity->getParent()) | ||||||||||
6533 | return getEntityLifetime(Entity->getParent(), Entity); | ||||||||||
6534 | |||||||||||
6535 | // except: | ||||||||||
6536 | // C++17 [class.base.init]p8: | ||||||||||
6537 | // A temporary expression bound to a reference member in a | ||||||||||
6538 | // mem-initializer is ill-formed. | ||||||||||
6539 | // C++17 [class.base.init]p11: | ||||||||||
6540 | // A temporary expression bound to a reference member from a | ||||||||||
6541 | // default member initializer is ill-formed. | ||||||||||
6542 | // | ||||||||||
6543 | // The context of p11 and its example suggest that it's only the use of a | ||||||||||
6544 | // default member initializer from a constructor that makes the program | ||||||||||
6545 | // ill-formed, not its mere existence, and that it can even be used by | ||||||||||
6546 | // aggregate initialization. | ||||||||||
6547 | return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended | ||||||||||
6548 | : LK_MemInitializer}; | ||||||||||
6549 | |||||||||||
6550 | case InitializedEntity::EK_Binding: | ||||||||||
6551 | // Per [dcl.decomp]p3, the binding is treated as a variable of reference | ||||||||||
6552 | // type. | ||||||||||
6553 | return {Entity, LK_Extended}; | ||||||||||
6554 | |||||||||||
6555 | case InitializedEntity::EK_Parameter: | ||||||||||
6556 | case InitializedEntity::EK_Parameter_CF_Audited: | ||||||||||
6557 | // -- A temporary bound to a reference parameter in a function call | ||||||||||
6558 | // persists until the completion of the full-expression containing | ||||||||||
6559 | // the call. | ||||||||||
6560 | return {nullptr, LK_FullExpression}; | ||||||||||
6561 | |||||||||||
6562 | case InitializedEntity::EK_Result: | ||||||||||
6563 | // -- The lifetime of a temporary bound to the returned value in a | ||||||||||
6564 | // function return statement is not extended; the temporary is | ||||||||||
6565 | // destroyed at the end of the full-expression in the return statement. | ||||||||||
6566 | return {nullptr, LK_Return}; | ||||||||||
6567 | |||||||||||
6568 | case InitializedEntity::EK_StmtExprResult: | ||||||||||
6569 | // FIXME: Should we lifetime-extend through the result of a statement | ||||||||||
6570 | // expression? | ||||||||||
6571 | return {nullptr, LK_StmtExprResult}; | ||||||||||
6572 | |||||||||||
6573 | case InitializedEntity::EK_New: | ||||||||||
6574 | // -- A temporary bound to a reference in a new-initializer persists | ||||||||||
6575 | // until the completion of the full-expression containing the | ||||||||||
6576 | // new-initializer. | ||||||||||
6577 | return {nullptr, LK_New}; | ||||||||||
6578 | |||||||||||
6579 | case InitializedEntity::EK_Temporary: | ||||||||||
6580 | case InitializedEntity::EK_CompoundLiteralInit: | ||||||||||
6581 | case InitializedEntity::EK_RelatedResult: | ||||||||||
6582 | // We don't yet know the storage duration of the surrounding temporary. | ||||||||||
6583 | // Assume it's got full-expression duration for now, it will patch up our | ||||||||||
6584 | // storage duration if that's not correct. | ||||||||||
6585 | return {nullptr, LK_FullExpression}; | ||||||||||
6586 | |||||||||||
6587 | case InitializedEntity::EK_ArrayElement: | ||||||||||
6588 | // For subobjects, we look at the complete object. | ||||||||||
6589 | return getEntityLifetime(Entity->getParent(), InitField); | ||||||||||
6590 | |||||||||||
6591 | case InitializedEntity::EK_Base: | ||||||||||
6592 | // For subobjects, we look at the complete object. | ||||||||||
6593 | if (Entity->getParent()) | ||||||||||
6594 | return getEntityLifetime(Entity->getParent(), InitField); | ||||||||||
6595 | return {InitField, LK_MemInitializer}; | ||||||||||
6596 | |||||||||||
6597 | case InitializedEntity::EK_Delegating: | ||||||||||
6598 | // We can reach this case for aggregate initialization in a constructor: | ||||||||||
6599 | // struct A { int &&r; }; | ||||||||||
6600 | // struct B : A { B() : A{0} {} }; | ||||||||||
6601 | // In this case, use the outermost field decl as the context. | ||||||||||
6602 | return {InitField, LK_MemInitializer}; | ||||||||||
6603 | |||||||||||
6604 | case InitializedEntity::EK_BlockElement: | ||||||||||
6605 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: | ||||||||||
6606 | case InitializedEntity::EK_LambdaCapture: | ||||||||||
6607 | case InitializedEntity::EK_VectorElement: | ||||||||||
6608 | case InitializedEntity::EK_ComplexElement: | ||||||||||
6609 | return {nullptr, LK_FullExpression}; | ||||||||||
6610 | |||||||||||
6611 | case InitializedEntity::EK_Exception: | ||||||||||
6612 | // FIXME: Can we diagnose lifetime problems with exceptions? | ||||||||||
6613 | return {nullptr, LK_FullExpression}; | ||||||||||
6614 | } | ||||||||||
6615 | llvm_unreachable("unknown entity kind")::llvm::llvm_unreachable_internal("unknown entity kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 6615); | ||||||||||
6616 | } | ||||||||||
6617 | |||||||||||
6618 | namespace { | ||||||||||
6619 | enum ReferenceKind { | ||||||||||
6620 | /// Lifetime would be extended by a reference binding to a temporary. | ||||||||||
6621 | RK_ReferenceBinding, | ||||||||||
6622 | /// Lifetime would be extended by a std::initializer_list object binding to | ||||||||||
6623 | /// its backing array. | ||||||||||
6624 | RK_StdInitializerList, | ||||||||||
6625 | }; | ||||||||||
6626 | |||||||||||
6627 | /// A temporary or local variable. This will be one of: | ||||||||||
6628 | /// * A MaterializeTemporaryExpr. | ||||||||||
6629 | /// * A DeclRefExpr whose declaration is a local. | ||||||||||
6630 | /// * An AddrLabelExpr. | ||||||||||
6631 | /// * A BlockExpr for a block with captures. | ||||||||||
6632 | using Local = Expr*; | ||||||||||
6633 | |||||||||||
6634 | /// Expressions we stepped over when looking for the local state. Any steps | ||||||||||
6635 | /// that would inhibit lifetime extension or take us out of subexpressions of | ||||||||||
6636 | /// the initializer are included. | ||||||||||
6637 | struct IndirectLocalPathEntry { | ||||||||||
6638 | enum EntryKind { | ||||||||||
6639 | DefaultInit, | ||||||||||
6640 | AddressOf, | ||||||||||
6641 | VarInit, | ||||||||||
6642 | LValToRVal, | ||||||||||
6643 | LifetimeBoundCall, | ||||||||||
6644 | GslReferenceInit, | ||||||||||
6645 | GslPointerInit | ||||||||||
6646 | } Kind; | ||||||||||
6647 | Expr *E; | ||||||||||
6648 | const Decl *D = nullptr; | ||||||||||
6649 | IndirectLocalPathEntry() {} | ||||||||||
6650 | IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} | ||||||||||
6651 | IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) | ||||||||||
6652 | : Kind(K), E(E), D(D) {} | ||||||||||
6653 | }; | ||||||||||
6654 | |||||||||||
6655 | using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; | ||||||||||
6656 | |||||||||||
6657 | struct RevertToOldSizeRAII { | ||||||||||
6658 | IndirectLocalPath &Path; | ||||||||||
6659 | unsigned OldSize = Path.size(); | ||||||||||
6660 | RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} | ||||||||||
6661 | ~RevertToOldSizeRAII() { Path.resize(OldSize); } | ||||||||||
6662 | }; | ||||||||||
6663 | |||||||||||
6664 | using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, | ||||||||||
6665 | ReferenceKind RK)>; | ||||||||||
6666 | } | ||||||||||
6667 | |||||||||||
6668 | static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) { | ||||||||||
6669 | for (auto E : Path) | ||||||||||
6670 | if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) | ||||||||||
6671 | return true; | ||||||||||
6672 | return false; | ||||||||||
6673 | } | ||||||||||
6674 | |||||||||||
6675 | static bool pathContainsInit(IndirectLocalPath &Path) { | ||||||||||
6676 | return llvm::any_of(Path, [=](IndirectLocalPathEntry E) { | ||||||||||
6677 | return E.Kind == IndirectLocalPathEntry::DefaultInit || | ||||||||||
6678 | E.Kind == IndirectLocalPathEntry::VarInit; | ||||||||||
6679 | }); | ||||||||||
6680 | } | ||||||||||
6681 | |||||||||||
6682 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | ||||||||||
6683 | Expr *Init, LocalVisitor Visit, | ||||||||||
6684 | bool RevisitSubinits, | ||||||||||
6685 | bool EnableLifetimeWarnings); | ||||||||||
6686 | |||||||||||
6687 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | ||||||||||
6688 | Expr *Init, ReferenceKind RK, | ||||||||||
6689 | LocalVisitor Visit, | ||||||||||
6690 | bool EnableLifetimeWarnings); | ||||||||||
6691 | |||||||||||
6692 | template <typename T> static bool isRecordWithAttr(QualType Type) { | ||||||||||
6693 | if (auto *RD = Type->getAsCXXRecordDecl()) | ||||||||||
6694 | return RD->hasAttr<T>(); | ||||||||||
6695 | return false; | ||||||||||
6696 | } | ||||||||||
6697 | |||||||||||
6698 | // Decl::isInStdNamespace will return false for iterators in some STL | ||||||||||
6699 | // implementations due to them being defined in a namespace outside of the std | ||||||||||
6700 | // namespace. | ||||||||||
6701 | static bool isInStlNamespace(const Decl *D) { | ||||||||||
6702 | const DeclContext *DC = D->getDeclContext(); | ||||||||||
6703 | if (!DC) | ||||||||||
6704 | return false; | ||||||||||
6705 | if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) | ||||||||||
6706 | if (const IdentifierInfo *II = ND->getIdentifier()) { | ||||||||||
6707 | StringRef Name = II->getName(); | ||||||||||
6708 | if (Name.size() >= 2 && Name.front() == '_' && | ||||||||||
6709 | (Name[1] == '_' || isUppercase(Name[1]))) | ||||||||||
6710 | return true; | ||||||||||
6711 | } | ||||||||||
6712 | |||||||||||
6713 | return DC->isStdNamespace(); | ||||||||||
6714 | } | ||||||||||
6715 | |||||||||||
6716 | static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) { | ||||||||||
6717 | if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee)) | ||||||||||
6718 | if (isRecordWithAttr<PointerAttr>(Conv->getConversionType())) | ||||||||||
6719 | return true; | ||||||||||
6720 | if (!isInStlNamespace(Callee->getParent())) | ||||||||||
6721 | return false; | ||||||||||
6722 | if (!isRecordWithAttr<PointerAttr>(Callee->getThisObjectType()) && | ||||||||||
6723 | !isRecordWithAttr<OwnerAttr>(Callee->getThisObjectType())) | ||||||||||
6724 | return false; | ||||||||||
6725 | if (Callee->getReturnType()->isPointerType() || | ||||||||||
6726 | isRecordWithAttr<PointerAttr>(Callee->getReturnType())) { | ||||||||||
6727 | if (!Callee->getIdentifier()) | ||||||||||
6728 | return false; | ||||||||||
6729 | return llvm::StringSwitch<bool>(Callee->getName()) | ||||||||||
6730 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | ||||||||||
6731 | .Cases("end", "rend", "cend", "crend", true) | ||||||||||
6732 | .Cases("c_str", "data", "get", true) | ||||||||||
6733 | // Map and set types. | ||||||||||
6734 | .Cases("find", "equal_range", "lower_bound", "upper_bound", true) | ||||||||||
6735 | .Default(false); | ||||||||||
6736 | } else if (Callee->getReturnType()->isReferenceType()) { | ||||||||||
6737 | if (!Callee->getIdentifier()) { | ||||||||||
6738 | auto OO = Callee->getOverloadedOperator(); | ||||||||||
6739 | return OO == OverloadedOperatorKind::OO_Subscript || | ||||||||||
6740 | OO == OverloadedOperatorKind::OO_Star; | ||||||||||
6741 | } | ||||||||||
6742 | return llvm::StringSwitch<bool>(Callee->getName()) | ||||||||||
6743 | .Cases("front", "back", "at", "top", "value", true) | ||||||||||
6744 | .Default(false); | ||||||||||
6745 | } | ||||||||||
6746 | return false; | ||||||||||
6747 | } | ||||||||||
6748 | |||||||||||
6749 | static bool shouldTrackFirstArgument(const FunctionDecl *FD) { | ||||||||||
6750 | if (!FD->getIdentifier() || FD->getNumParams() != 1) | ||||||||||
6751 | return false; | ||||||||||
6752 | const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl(); | ||||||||||
6753 | if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace()) | ||||||||||
6754 | return false; | ||||||||||
6755 | if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) && | ||||||||||
6756 | !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0))) | ||||||||||
6757 | return false; | ||||||||||
6758 | if (FD->getReturnType()->isPointerType() || | ||||||||||
6759 | isRecordWithAttr<PointerAttr>(FD->getReturnType())) { | ||||||||||
6760 | return llvm::StringSwitch<bool>(FD->getName()) | ||||||||||
6761 | .Cases("begin", "rbegin", "cbegin", "crbegin", true) | ||||||||||
6762 | .Cases("end", "rend", "cend", "crend", true) | ||||||||||
6763 | .Case("data", true) | ||||||||||
6764 | .Default(false); | ||||||||||
6765 | } else if (FD->getReturnType()->isReferenceType()) { | ||||||||||
6766 | return llvm::StringSwitch<bool>(FD->getName()) | ||||||||||
6767 | .Cases("get", "any_cast", true) | ||||||||||
6768 | .Default(false); | ||||||||||
6769 | } | ||||||||||
6770 | return false; | ||||||||||
6771 | } | ||||||||||
6772 | |||||||||||
6773 | static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call, | ||||||||||
6774 | LocalVisitor Visit) { | ||||||||||
6775 | auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) { | ||||||||||
6776 | // We are not interested in the temporary base objects of gsl Pointers: | ||||||||||
6777 | // Temp().ptr; // Here ptr might not dangle. | ||||||||||
6778 | if (isa<MemberExpr>(Arg->IgnoreImpCasts())) | ||||||||||
6779 | return; | ||||||||||
6780 | // Once we initialized a value with a reference, it can no longer dangle. | ||||||||||
6781 | if (!Value) { | ||||||||||
6782 | for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { | ||||||||||
6783 | if (It->Kind == IndirectLocalPathEntry::GslReferenceInit) | ||||||||||
6784 | continue; | ||||||||||
6785 | if (It->Kind == IndirectLocalPathEntry::GslPointerInit) | ||||||||||
6786 | return; | ||||||||||
6787 | break; | ||||||||||
6788 | } | ||||||||||
6789 | } | ||||||||||
6790 | Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit | ||||||||||
6791 | : IndirectLocalPathEntry::GslReferenceInit, | ||||||||||
6792 | Arg, D}); | ||||||||||
6793 | if (Arg->isGLValue()) | ||||||||||
6794 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | ||||||||||
6795 | Visit, | ||||||||||
6796 | /*EnableLifetimeWarnings=*/true); | ||||||||||
6797 | else | ||||||||||
6798 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | ||||||||||
6799 | /*EnableLifetimeWarnings=*/true); | ||||||||||
6800 | Path.pop_back(); | ||||||||||
6801 | }; | ||||||||||
6802 | |||||||||||
6803 | if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | ||||||||||
6804 | const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee()); | ||||||||||
6805 | if (MD && shouldTrackImplicitObjectArg(MD)) | ||||||||||
6806 | VisitPointerArg(MD, MCE->getImplicitObjectArgument(), | ||||||||||
6807 | !MD->getReturnType()->isReferenceType()); | ||||||||||
6808 | return; | ||||||||||
6809 | } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) { | ||||||||||
6810 | FunctionDecl *Callee = OCE->getDirectCallee(); | ||||||||||
6811 | if (Callee && Callee->isCXXInstanceMember() && | ||||||||||
6812 | shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee))) | ||||||||||
6813 | VisitPointerArg(Callee, OCE->getArg(0), | ||||||||||
6814 | !Callee->getReturnType()->isReferenceType()); | ||||||||||
6815 | return; | ||||||||||
6816 | } else if (auto *CE = dyn_cast<CallExpr>(Call)) { | ||||||||||
6817 | FunctionDecl *Callee = CE->getDirectCallee(); | ||||||||||
6818 | if (Callee && shouldTrackFirstArgument(Callee)) | ||||||||||
6819 | VisitPointerArg(Callee, CE->getArg(0), | ||||||||||
6820 | !Callee->getReturnType()->isReferenceType()); | ||||||||||
6821 | return; | ||||||||||
6822 | } | ||||||||||
6823 | |||||||||||
6824 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) { | ||||||||||
6825 | const auto *Ctor = CCE->getConstructor(); | ||||||||||
6826 | const CXXRecordDecl *RD = Ctor->getParent(); | ||||||||||
6827 | if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>()) | ||||||||||
6828 | VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true); | ||||||||||
6829 | } | ||||||||||
6830 | } | ||||||||||
6831 | |||||||||||
6832 | static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) { | ||||||||||
6833 | const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); | ||||||||||
6834 | if (!TSI) | ||||||||||
6835 | return false; | ||||||||||
6836 | // Don't declare this variable in the second operand of the for-statement; | ||||||||||
6837 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||||||||
6838 | // third operand. See gcc.gnu.org/PR86769. | ||||||||||
6839 | AttributedTypeLoc ATL; | ||||||||||
6840 | for (TypeLoc TL = TSI->getTypeLoc(); | ||||||||||
6841 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||||||||
6842 | TL = ATL.getModifiedLoc()) { | ||||||||||
6843 | if (ATL.getAttrAs<LifetimeBoundAttr>()) | ||||||||||
6844 | return true; | ||||||||||
6845 | } | ||||||||||
6846 | return false; | ||||||||||
6847 | } | ||||||||||
6848 | |||||||||||
6849 | static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call, | ||||||||||
6850 | LocalVisitor Visit) { | ||||||||||
6851 | const FunctionDecl *Callee; | ||||||||||
6852 | ArrayRef<Expr*> Args; | ||||||||||
6853 | |||||||||||
6854 | if (auto *CE = dyn_cast<CallExpr>(Call)) { | ||||||||||
6855 | Callee = CE->getDirectCallee(); | ||||||||||
6856 | Args = llvm::makeArrayRef(CE->getArgs(), CE->getNumArgs()); | ||||||||||
6857 | } else { | ||||||||||
6858 | auto *CCE = cast<CXXConstructExpr>(Call); | ||||||||||
6859 | Callee = CCE->getConstructor(); | ||||||||||
6860 | Args = llvm::makeArrayRef(CCE->getArgs(), CCE->getNumArgs()); | ||||||||||
6861 | } | ||||||||||
6862 | if (!Callee) | ||||||||||
6863 | return; | ||||||||||
6864 | |||||||||||
6865 | Expr *ObjectArg = nullptr; | ||||||||||
6866 | if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) { | ||||||||||
6867 | ObjectArg = Args[0]; | ||||||||||
6868 | Args = Args.slice(1); | ||||||||||
6869 | } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) { | ||||||||||
6870 | ObjectArg = MCE->getImplicitObjectArgument(); | ||||||||||
6871 | } | ||||||||||
6872 | |||||||||||
6873 | auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { | ||||||||||
6874 | Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); | ||||||||||
6875 | if (Arg->isGLValue()) | ||||||||||
6876 | visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding, | ||||||||||
6877 | Visit, | ||||||||||
6878 | /*EnableLifetimeWarnings=*/false); | ||||||||||
6879 | else | ||||||||||
6880 | visitLocalsRetainedByInitializer(Path, Arg, Visit, true, | ||||||||||
6881 | /*EnableLifetimeWarnings=*/false); | ||||||||||
6882 | Path.pop_back(); | ||||||||||
6883 | }; | ||||||||||
6884 | |||||||||||
6885 | if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee)) | ||||||||||
6886 | VisitLifetimeBoundArg(Callee, ObjectArg); | ||||||||||
6887 | |||||||||||
6888 | for (unsigned I = 0, | ||||||||||
6889 | N = std::min<unsigned>(Callee->getNumParams(), Args.size()); | ||||||||||
6890 | I != N; ++I) { | ||||||||||
6891 | if (Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>()) | ||||||||||
6892 | VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]); | ||||||||||
6893 | } | ||||||||||
6894 | } | ||||||||||
6895 | |||||||||||
6896 | /// Visit the locals that would be reachable through a reference bound to the | ||||||||||
6897 | /// glvalue expression \c Init. | ||||||||||
6898 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, | ||||||||||
6899 | Expr *Init, ReferenceKind RK, | ||||||||||
6900 | LocalVisitor Visit, | ||||||||||
6901 | bool EnableLifetimeWarnings) { | ||||||||||
6902 | RevertToOldSizeRAII RAII(Path); | ||||||||||
6903 | |||||||||||
6904 | // Walk past any constructs which we can lifetime-extend across. | ||||||||||
6905 | Expr *Old; | ||||||||||
6906 | do { | ||||||||||
6907 | Old = Init; | ||||||||||
6908 | |||||||||||
6909 | if (auto *FE = dyn_cast<FullExpr>(Init)) | ||||||||||
6910 | Init = FE->getSubExpr(); | ||||||||||
6911 | |||||||||||
6912 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | ||||||||||
6913 | // If this is just redundant braces around an initializer, step over it. | ||||||||||
6914 | if (ILE->isTransparent()) | ||||||||||
6915 | Init = ILE->getInit(0); | ||||||||||
6916 | } | ||||||||||
6917 | |||||||||||
6918 | // Step over any subobject adjustments; we may have a materialized | ||||||||||
6919 | // temporary inside them. | ||||||||||
6920 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | ||||||||||
6921 | |||||||||||
6922 | // Per current approach for DR1376, look through casts to reference type | ||||||||||
6923 | // when performing lifetime extension. | ||||||||||
6924 | if (CastExpr *CE = dyn_cast<CastExpr>(Init)) | ||||||||||
6925 | if (CE->getSubExpr()->isGLValue()) | ||||||||||
6926 | Init = CE->getSubExpr(); | ||||||||||
6927 | |||||||||||
6928 | // Per the current approach for DR1299, look through array element access | ||||||||||
6929 | // on array glvalues when performing lifetime extension. | ||||||||||
6930 | if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) { | ||||||||||
6931 | Init = ASE->getBase(); | ||||||||||
6932 | auto *ICE = dyn_cast<ImplicitCastExpr>(Init); | ||||||||||
6933 | if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) | ||||||||||
6934 | Init = ICE->getSubExpr(); | ||||||||||
6935 | else | ||||||||||
6936 | // We can't lifetime extend through this but we might still find some | ||||||||||
6937 | // retained temporaries. | ||||||||||
6938 | return visitLocalsRetainedByInitializer(Path, Init, Visit, true, | ||||||||||
6939 | EnableLifetimeWarnings); | ||||||||||
6940 | } | ||||||||||
6941 | |||||||||||
6942 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | ||||||||||
6943 | // constructor inherits one as an implicit mem-initializer. | ||||||||||
6944 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | ||||||||||
6945 | Path.push_back( | ||||||||||
6946 | {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | ||||||||||
6947 | Init = DIE->getExpr(); | ||||||||||
6948 | } | ||||||||||
6949 | } while (Init != Old); | ||||||||||
6950 | |||||||||||
6951 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) { | ||||||||||
6952 | if (Visit(Path, Local(MTE), RK)) | ||||||||||
6953 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true, | ||||||||||
6954 | EnableLifetimeWarnings); | ||||||||||
6955 | } | ||||||||||
6956 | |||||||||||
6957 | if (isa<CallExpr>(Init)) { | ||||||||||
6958 | if (EnableLifetimeWarnings) | ||||||||||
6959 | handleGslAnnotatedTypes(Path, Init, Visit); | ||||||||||
6960 | return visitLifetimeBoundArguments(Path, Init, Visit); | ||||||||||
6961 | } | ||||||||||
6962 | |||||||||||
6963 | switch (Init->getStmtClass()) { | ||||||||||
6964 | case Stmt::DeclRefExprClass: { | ||||||||||
6965 | // If we find the name of a local non-reference parameter, we could have a | ||||||||||
6966 | // lifetime problem. | ||||||||||
6967 | auto *DRE = cast<DeclRefExpr>(Init); | ||||||||||
6968 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | ||||||||||
6969 | if (VD && VD->hasLocalStorage() && | ||||||||||
6970 | !DRE->refersToEnclosingVariableOrCapture()) { | ||||||||||
6971 | if (!VD->getType()->isReferenceType()) { | ||||||||||
6972 | Visit(Path, Local(DRE), RK); | ||||||||||
6973 | } else if (isa<ParmVarDecl>(DRE->getDecl())) { | ||||||||||
6974 | // The lifetime of a reference parameter is unknown; assume it's OK | ||||||||||
6975 | // for now. | ||||||||||
6976 | break; | ||||||||||
6977 | } else if (VD->getInit() && !isVarOnPath(Path, VD)) { | ||||||||||
6978 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | ||||||||||
6979 | visitLocalsRetainedByReferenceBinding(Path, VD->getInit(), | ||||||||||
6980 | RK_ReferenceBinding, Visit, | ||||||||||
6981 | EnableLifetimeWarnings); | ||||||||||
6982 | } | ||||||||||
6983 | } | ||||||||||
6984 | break; | ||||||||||
6985 | } | ||||||||||
6986 | |||||||||||
6987 | case Stmt::UnaryOperatorClass: { | ||||||||||
6988 | // The only unary operator that make sense to handle here | ||||||||||
6989 | // is Deref. All others don't resolve to a "name." This includes | ||||||||||
6990 | // handling all sorts of rvalues passed to a unary operator. | ||||||||||
6991 | const UnaryOperator *U = cast<UnaryOperator>(Init); | ||||||||||
6992 | if (U->getOpcode() == UO_Deref) | ||||||||||
6993 | visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true, | ||||||||||
6994 | EnableLifetimeWarnings); | ||||||||||
6995 | break; | ||||||||||
6996 | } | ||||||||||
6997 | |||||||||||
6998 | case Stmt::OMPArraySectionExprClass: { | ||||||||||
6999 | visitLocalsRetainedByInitializer(Path, | ||||||||||
7000 | cast<OMPArraySectionExpr>(Init)->getBase(), | ||||||||||
7001 | Visit, true, EnableLifetimeWarnings); | ||||||||||
7002 | break; | ||||||||||
7003 | } | ||||||||||
7004 | |||||||||||
7005 | case Stmt::ConditionalOperatorClass: | ||||||||||
7006 | case Stmt::BinaryConditionalOperatorClass: { | ||||||||||
7007 | auto *C = cast<AbstractConditionalOperator>(Init); | ||||||||||
7008 | if (!C->getTrueExpr()->getType()->isVoidType()) | ||||||||||
7009 | visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit, | ||||||||||
7010 | EnableLifetimeWarnings); | ||||||||||
7011 | if (!C->getFalseExpr()->getType()->isVoidType()) | ||||||||||
7012 | visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit, | ||||||||||
7013 | EnableLifetimeWarnings); | ||||||||||
7014 | break; | ||||||||||
7015 | } | ||||||||||
7016 | |||||||||||
7017 | // FIXME: Visit the left-hand side of an -> or ->*. | ||||||||||
7018 | |||||||||||
7019 | default: | ||||||||||
7020 | break; | ||||||||||
7021 | } | ||||||||||
7022 | } | ||||||||||
7023 | |||||||||||
7024 | /// Visit the locals that would be reachable through an object initialized by | ||||||||||
7025 | /// the prvalue expression \c Init. | ||||||||||
7026 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, | ||||||||||
7027 | Expr *Init, LocalVisitor Visit, | ||||||||||
7028 | bool RevisitSubinits, | ||||||||||
7029 | bool EnableLifetimeWarnings) { | ||||||||||
7030 | RevertToOldSizeRAII RAII(Path); | ||||||||||
7031 | |||||||||||
7032 | Expr *Old; | ||||||||||
7033 | do { | ||||||||||
7034 | Old = Init; | ||||||||||
7035 | |||||||||||
7036 | // Step into CXXDefaultInitExprs so we can diagnose cases where a | ||||||||||
7037 | // constructor inherits one as an implicit mem-initializer. | ||||||||||
7038 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) { | ||||||||||
7039 | Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); | ||||||||||
7040 | Init = DIE->getExpr(); | ||||||||||
7041 | } | ||||||||||
7042 | |||||||||||
7043 | if (auto *FE = dyn_cast<FullExpr>(Init)) | ||||||||||
7044 | Init = FE->getSubExpr(); | ||||||||||
7045 | |||||||||||
7046 | // Dig out the expression which constructs the extended temporary. | ||||||||||
7047 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); | ||||||||||
7048 | |||||||||||
7049 | if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) | ||||||||||
7050 | Init = BTE->getSubExpr(); | ||||||||||
7051 | |||||||||||
7052 | Init = Init->IgnoreParens(); | ||||||||||
7053 | |||||||||||
7054 | // Step over value-preserving rvalue casts. | ||||||||||
7055 | if (auto *CE = dyn_cast<CastExpr>(Init)) { | ||||||||||
7056 | switch (CE->getCastKind()) { | ||||||||||
7057 | case CK_LValueToRValue: | ||||||||||
7058 | // If we can match the lvalue to a const object, we can look at its | ||||||||||
7059 | // initializer. | ||||||||||
7060 | Path.push_back({IndirectLocalPathEntry::LValToRVal, CE}); | ||||||||||
7061 | return visitLocalsRetainedByReferenceBinding( | ||||||||||
7062 | Path, Init, RK_ReferenceBinding, | ||||||||||
7063 | [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { | ||||||||||
7064 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | ||||||||||
7065 | auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); | ||||||||||
7066 | if (VD && VD->getType().isConstQualified() && VD->getInit() && | ||||||||||
7067 | !isVarOnPath(Path, VD)) { | ||||||||||
7068 | Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD}); | ||||||||||
7069 | visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true, | ||||||||||
7070 | EnableLifetimeWarnings); | ||||||||||
7071 | } | ||||||||||
7072 | } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) { | ||||||||||
7073 | if (MTE->getType().isConstQualified()) | ||||||||||
7074 | visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, | ||||||||||
7075 | true, EnableLifetimeWarnings); | ||||||||||
7076 | } | ||||||||||
7077 | return false; | ||||||||||
7078 | }, EnableLifetimeWarnings); | ||||||||||
7079 | |||||||||||
7080 | // We assume that objects can be retained by pointers cast to integers, | ||||||||||
7081 | // but not if the integer is cast to floating-point type or to _Complex. | ||||||||||
7082 | // We assume that casts to 'bool' do not preserve enough information to | ||||||||||
7083 | // retain a local object. | ||||||||||
7084 | case CK_NoOp: | ||||||||||
7085 | case CK_BitCast: | ||||||||||
7086 | case CK_BaseToDerived: | ||||||||||
7087 | case CK_DerivedToBase: | ||||||||||
7088 | case CK_UncheckedDerivedToBase: | ||||||||||
7089 | case CK_Dynamic: | ||||||||||
7090 | case CK_ToUnion: | ||||||||||
7091 | case CK_UserDefinedConversion: | ||||||||||
7092 | case CK_ConstructorConversion: | ||||||||||
7093 | case CK_IntegralToPointer: | ||||||||||
7094 | case CK_PointerToIntegral: | ||||||||||
7095 | case CK_VectorSplat: | ||||||||||
7096 | case CK_IntegralCast: | ||||||||||
7097 | case CK_CPointerToObjCPointerCast: | ||||||||||
7098 | case CK_BlockPointerToObjCPointerCast: | ||||||||||
7099 | case CK_AnyPointerToBlockPointerCast: | ||||||||||
7100 | case CK_AddressSpaceConversion: | ||||||||||
7101 | break; | ||||||||||
7102 | |||||||||||
7103 | case CK_ArrayToPointerDecay: | ||||||||||
7104 | // Model array-to-pointer decay as taking the address of the array | ||||||||||
7105 | // lvalue. | ||||||||||
7106 | Path.push_back({IndirectLocalPathEntry::AddressOf, CE}); | ||||||||||
7107 | return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(), | ||||||||||
7108 | RK_ReferenceBinding, Visit, | ||||||||||
7109 | EnableLifetimeWarnings); | ||||||||||
7110 | |||||||||||
7111 | default: | ||||||||||
7112 | return; | ||||||||||
7113 | } | ||||||||||
7114 | |||||||||||
7115 | Init = CE->getSubExpr(); | ||||||||||
7116 | } | ||||||||||
7117 | } while (Old != Init); | ||||||||||
7118 | |||||||||||
7119 | // C++17 [dcl.init.list]p6: | ||||||||||
7120 | // initializing an initializer_list object from the array extends the | ||||||||||
7121 | // lifetime of the array exactly like binding a reference to a temporary. | ||||||||||
7122 | if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init)) | ||||||||||
7123 | return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(), | ||||||||||
7124 | RK_StdInitializerList, Visit, | ||||||||||
7125 | EnableLifetimeWarnings); | ||||||||||
7126 | |||||||||||
7127 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { | ||||||||||
7128 | // We already visited the elements of this initializer list while | ||||||||||
7129 | // performing the initialization. Don't visit them again unless we've | ||||||||||
7130 | // changed the lifetime of the initialized entity. | ||||||||||
7131 | if (!RevisitSubinits) | ||||||||||
7132 | return; | ||||||||||
7133 | |||||||||||
7134 | if (ILE->isTransparent()) | ||||||||||
7135 | return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit, | ||||||||||
7136 | RevisitSubinits, | ||||||||||
7137 | EnableLifetimeWarnings); | ||||||||||
7138 | |||||||||||
7139 | if (ILE->getType()->isArrayType()) { | ||||||||||
7140 | for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) | ||||||||||
7141 | visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit, | ||||||||||
7142 | RevisitSubinits, | ||||||||||
7143 | EnableLifetimeWarnings); | ||||||||||
7144 | return; | ||||||||||
7145 | } | ||||||||||
7146 | |||||||||||
7147 | if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { | ||||||||||
7148 | assert(RD->isAggregate() && "aggregate init on non-aggregate")((RD->isAggregate() && "aggregate init on non-aggregate" ) ? static_cast<void> (0) : __assert_fail ("RD->isAggregate() && \"aggregate init on non-aggregate\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 7148, __PRETTY_FUNCTION__)); | ||||||||||
7149 | |||||||||||
7150 | // If we lifetime-extend a braced initializer which is initializing an | ||||||||||
7151 | // aggregate, and that aggregate contains reference members which are | ||||||||||
7152 | // bound to temporaries, those temporaries are also lifetime-extended. | ||||||||||
7153 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() && | ||||||||||
7154 | ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) | ||||||||||
7155 | visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0), | ||||||||||
7156 | RK_ReferenceBinding, Visit, | ||||||||||
7157 | EnableLifetimeWarnings); | ||||||||||
7158 | else { | ||||||||||
7159 | unsigned Index = 0; | ||||||||||
7160 | for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) | ||||||||||
7161 | visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit, | ||||||||||
7162 | RevisitSubinits, | ||||||||||
7163 | EnableLifetimeWarnings); | ||||||||||
7164 | for (const auto *I : RD->fields()) { | ||||||||||
7165 | if (Index >= ILE->getNumInits()) | ||||||||||
7166 | break; | ||||||||||
7167 | if (I->isUnnamedBitfield()) | ||||||||||
7168 | continue; | ||||||||||
7169 | Expr *SubInit = ILE->getInit(Index); | ||||||||||
7170 | if (I->getType()->isReferenceType()) | ||||||||||
7171 | visitLocalsRetainedByReferenceBinding(Path, SubInit, | ||||||||||
7172 | RK_ReferenceBinding, Visit, | ||||||||||
7173 | EnableLifetimeWarnings); | ||||||||||
7174 | else | ||||||||||
7175 | // This might be either aggregate-initialization of a member or | ||||||||||
7176 | // initialization of a std::initializer_list object. Regardless, | ||||||||||
7177 | // we should recursively lifetime-extend that initializer. | ||||||||||
7178 | visitLocalsRetainedByInitializer(Path, SubInit, Visit, | ||||||||||
7179 | RevisitSubinits, | ||||||||||
7180 | EnableLifetimeWarnings); | ||||||||||
7181 | ++Index; | ||||||||||
7182 | } | ||||||||||
7183 | } | ||||||||||
7184 | } | ||||||||||
7185 | return; | ||||||||||
7186 | } | ||||||||||
7187 | |||||||||||
7188 | // The lifetime of an init-capture is that of the closure object constructed | ||||||||||
7189 | // by a lambda-expression. | ||||||||||
7190 | if (auto *LE = dyn_cast<LambdaExpr>(Init)) { | ||||||||||
7191 | for (Expr *E : LE->capture_inits()) { | ||||||||||
7192 | if (!E) | ||||||||||
7193 | continue; | ||||||||||
7194 | if (E->isGLValue()) | ||||||||||
7195 | visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding, | ||||||||||
7196 | Visit, EnableLifetimeWarnings); | ||||||||||
7197 | else | ||||||||||
7198 | visitLocalsRetainedByInitializer(Path, E, Visit, true, | ||||||||||
7199 | EnableLifetimeWarnings); | ||||||||||
7200 | } | ||||||||||
7201 | } | ||||||||||
7202 | |||||||||||
7203 | if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) { | ||||||||||
7204 | if (EnableLifetimeWarnings) | ||||||||||
7205 | handleGslAnnotatedTypes(Path, Init, Visit); | ||||||||||
7206 | return visitLifetimeBoundArguments(Path, Init, Visit); | ||||||||||
7207 | } | ||||||||||
7208 | |||||||||||
7209 | switch (Init->getStmtClass()) { | ||||||||||
7210 | case Stmt::UnaryOperatorClass: { | ||||||||||
7211 | auto *UO = cast<UnaryOperator>(Init); | ||||||||||
7212 | // If the initializer is the address of a local, we could have a lifetime | ||||||||||
7213 | // problem. | ||||||||||
7214 | if (UO->getOpcode() == UO_AddrOf) { | ||||||||||
7215 | // If this is &rvalue, then it's ill-formed and we have already diagnosed | ||||||||||
7216 | // it. Don't produce a redundant warning about the lifetime of the | ||||||||||
7217 | // temporary. | ||||||||||
7218 | if (isa<MaterializeTemporaryExpr>(UO->getSubExpr())) | ||||||||||
7219 | return; | ||||||||||
7220 | |||||||||||
7221 | Path.push_back({IndirectLocalPathEntry::AddressOf, UO}); | ||||||||||
7222 | visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(), | ||||||||||
7223 | RK_ReferenceBinding, Visit, | ||||||||||
7224 | EnableLifetimeWarnings); | ||||||||||
7225 | } | ||||||||||
7226 | break; | ||||||||||
7227 | } | ||||||||||
7228 | |||||||||||
7229 | case Stmt::BinaryOperatorClass: { | ||||||||||
7230 | // Handle pointer arithmetic. | ||||||||||
7231 | auto *BO = cast<BinaryOperator>(Init); | ||||||||||
7232 | BinaryOperatorKind BOK = BO->getOpcode(); | ||||||||||
7233 | if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) | ||||||||||
7234 | break; | ||||||||||
7235 | |||||||||||
7236 | if (BO->getLHS()->getType()->isPointerType()) | ||||||||||
7237 | visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true, | ||||||||||
7238 | EnableLifetimeWarnings); | ||||||||||
7239 | else if (BO->getRHS()->getType()->isPointerType()) | ||||||||||
7240 | visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true, | ||||||||||
7241 | EnableLifetimeWarnings); | ||||||||||
7242 | break; | ||||||||||
7243 | } | ||||||||||
7244 | |||||||||||
7245 | case Stmt::ConditionalOperatorClass: | ||||||||||
7246 | case Stmt::BinaryConditionalOperatorClass: { | ||||||||||
7247 | auto *C = cast<AbstractConditionalOperator>(Init); | ||||||||||
7248 | // In C++, we can have a throw-expression operand, which has 'void' type | ||||||||||
7249 | // and isn't interesting from a lifetime perspective. | ||||||||||
7250 | if (!C->getTrueExpr()->getType()->isVoidType()) | ||||||||||
7251 | visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true, | ||||||||||
7252 | EnableLifetimeWarnings); | ||||||||||
7253 | if (!C->getFalseExpr()->getType()->isVoidType()) | ||||||||||
7254 | visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true, | ||||||||||
7255 | EnableLifetimeWarnings); | ||||||||||
7256 | break; | ||||||||||
7257 | } | ||||||||||
7258 | |||||||||||
7259 | case Stmt::BlockExprClass: | ||||||||||
7260 | if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) { | ||||||||||
7261 | // This is a local block, whose lifetime is that of the function. | ||||||||||
7262 | Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding); | ||||||||||
7263 | } | ||||||||||
7264 | break; | ||||||||||
7265 | |||||||||||
7266 | case Stmt::AddrLabelExprClass: | ||||||||||
7267 | // We want to warn if the address of a label would escape the function. | ||||||||||
7268 | Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding); | ||||||||||
7269 | break; | ||||||||||
7270 | |||||||||||
7271 | default: | ||||||||||
7272 | break; | ||||||||||
7273 | } | ||||||||||
7274 | } | ||||||||||
7275 | |||||||||||
7276 | /// Determine whether this is an indirect path to a temporary that we are | ||||||||||
7277 | /// supposed to lifetime-extend along (but don't). | ||||||||||
7278 | static bool shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { | ||||||||||
7279 | for (auto Elem : Path) { | ||||||||||
7280 | if (Elem.Kind != IndirectLocalPathEntry::DefaultInit) | ||||||||||
7281 | return false; | ||||||||||
7282 | } | ||||||||||
7283 | return true; | ||||||||||
7284 | } | ||||||||||
7285 | |||||||||||
7286 | /// Find the range for the first interesting entry in the path at or after I. | ||||||||||
7287 | static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, | ||||||||||
7288 | Expr *E) { | ||||||||||
7289 | for (unsigned N = Path.size(); I != N; ++I) { | ||||||||||
7290 | switch (Path[I].Kind) { | ||||||||||
7291 | case IndirectLocalPathEntry::AddressOf: | ||||||||||
7292 | case IndirectLocalPathEntry::LValToRVal: | ||||||||||
7293 | case IndirectLocalPathEntry::LifetimeBoundCall: | ||||||||||
7294 | case IndirectLocalPathEntry::GslReferenceInit: | ||||||||||
7295 | case IndirectLocalPathEntry::GslPointerInit: | ||||||||||
7296 | // These exist primarily to mark the path as not permitting or | ||||||||||
7297 | // supporting lifetime extension. | ||||||||||
7298 | break; | ||||||||||
7299 | |||||||||||
7300 | case IndirectLocalPathEntry::VarInit: | ||||||||||
7301 | if (cast<VarDecl>(Path[I].D)->isImplicit()) | ||||||||||
7302 | return SourceRange(); | ||||||||||
7303 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
7304 | case IndirectLocalPathEntry::DefaultInit: | ||||||||||
7305 | return Path[I].E->getSourceRange(); | ||||||||||
7306 | } | ||||||||||
7307 | } | ||||||||||
7308 | return E->getSourceRange(); | ||||||||||
7309 | } | ||||||||||
7310 | |||||||||||
7311 | static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) { | ||||||||||
7312 | for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) { | ||||||||||
7313 | if (It->Kind == IndirectLocalPathEntry::VarInit) | ||||||||||
7314 | continue; | ||||||||||
7315 | if (It->Kind == IndirectLocalPathEntry::AddressOf) | ||||||||||
7316 | continue; | ||||||||||
7317 | return It->Kind == IndirectLocalPathEntry::GslPointerInit || | ||||||||||
7318 | It->Kind == IndirectLocalPathEntry::GslReferenceInit; | ||||||||||
7319 | } | ||||||||||
7320 | return false; | ||||||||||
7321 | } | ||||||||||
7322 | |||||||||||
7323 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, | ||||||||||
7324 | Expr *Init) { | ||||||||||
7325 | LifetimeResult LR = getEntityLifetime(&Entity); | ||||||||||
7326 | LifetimeKind LK = LR.getInt(); | ||||||||||
7327 | const InitializedEntity *ExtendingEntity = LR.getPointer(); | ||||||||||
7328 | |||||||||||
7329 | // If this entity doesn't have an interesting lifetime, don't bother looking | ||||||||||
7330 | // for temporaries within its initializer. | ||||||||||
7331 | if (LK == LK_FullExpression) | ||||||||||
7332 | return; | ||||||||||
7333 | |||||||||||
7334 | auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L, | ||||||||||
7335 | ReferenceKind RK) -> bool { | ||||||||||
7336 | SourceRange DiagRange = nextPathEntryRange(Path, 0, L); | ||||||||||
7337 | SourceLocation DiagLoc = DiagRange.getBegin(); | ||||||||||
7338 | |||||||||||
7339 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L); | ||||||||||
7340 | |||||||||||
7341 | bool IsGslPtrInitWithGslTempOwner = false; | ||||||||||
7342 | bool IsLocalGslOwner = false; | ||||||||||
7343 | if (pathOnlyInitializesGslPointer(Path)) { | ||||||||||
7344 | if (isa<DeclRefExpr>(L)) { | ||||||||||
7345 | // We do not want to follow the references when returning a pointer originating | ||||||||||
7346 | // from a local owner to avoid the following false positive: | ||||||||||
7347 | // int &p = *localUniquePtr; | ||||||||||
7348 | // someContainer.add(std::move(localUniquePtr)); | ||||||||||
7349 | // return p; | ||||||||||
7350 | IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType()); | ||||||||||
7351 | if (pathContainsInit(Path) || !IsLocalGslOwner) | ||||||||||
7352 | return false; | ||||||||||
7353 | } else { | ||||||||||
7354 | IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() && | ||||||||||
7355 | isRecordWithAttr<OwnerAttr>(MTE->getType()); | ||||||||||
7356 | // Skipping a chain of initializing gsl::Pointer annotated objects. | ||||||||||
7357 | // We are looking only for the final source to find out if it was | ||||||||||
7358 | // a local or temporary owner or the address of a local variable/param. | ||||||||||
7359 | if (!IsGslPtrInitWithGslTempOwner) | ||||||||||
7360 | return true; | ||||||||||
7361 | } | ||||||||||
7362 | } | ||||||||||
7363 | |||||||||||
7364 | switch (LK) { | ||||||||||
7365 | case LK_FullExpression: | ||||||||||
7366 | llvm_unreachable("already handled this")::llvm::llvm_unreachable_internal("already handled this", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 7366); | ||||||||||
7367 | |||||||||||
7368 | case LK_Extended: { | ||||||||||
7369 | if (!MTE) { | ||||||||||
7370 | // The initialized entity has lifetime beyond the full-expression, | ||||||||||
7371 | // and the local entity does too, so don't warn. | ||||||||||
7372 | // | ||||||||||
7373 | // FIXME: We should consider warning if a static / thread storage | ||||||||||
7374 | // duration variable retains an automatic storage duration local. | ||||||||||
7375 | return false; | ||||||||||
7376 | } | ||||||||||
7377 | |||||||||||
7378 | if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) { | ||||||||||
7379 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | ||||||||||
7380 | return false; | ||||||||||
7381 | } | ||||||||||
7382 | |||||||||||
7383 | // Lifetime-extend the temporary. | ||||||||||
7384 | if (Path.empty()) { | ||||||||||
7385 | // Update the storage duration of the materialized temporary. | ||||||||||
7386 | // FIXME: Rebuild the expression instead of mutating it. | ||||||||||
7387 | MTE->setExtendingDecl(ExtendingEntity->getDecl(), | ||||||||||
7388 | ExtendingEntity->allocateManglingNumber()); | ||||||||||
7389 | // Also visit the temporaries lifetime-extended by this initializer. | ||||||||||
7390 | return true; | ||||||||||
7391 | } | ||||||||||
7392 | |||||||||||
7393 | if (shouldLifetimeExtendThroughPath(Path)) { | ||||||||||
7394 | // We're supposed to lifetime-extend the temporary along this path (per | ||||||||||
7395 | // the resolution of DR1815), but we don't support that yet. | ||||||||||
7396 | // | ||||||||||
7397 | // FIXME: Properly handle this situation. Perhaps the easiest approach | ||||||||||
7398 | // would be to clone the initializer expression on each use that would | ||||||||||
7399 | // lifetime extend its temporaries. | ||||||||||
7400 | Diag(DiagLoc, diag::warn_unsupported_lifetime_extension) | ||||||||||
7401 | << RK << DiagRange; | ||||||||||
7402 | } else { | ||||||||||
7403 | // If the path goes through the initialization of a variable or field, | ||||||||||
7404 | // it can't possibly reach a temporary created in this full-expression. | ||||||||||
7405 | // We will have already diagnosed any problems with the initializer. | ||||||||||
7406 | if (pathContainsInit(Path)) | ||||||||||
7407 | return false; | ||||||||||
7408 | |||||||||||
7409 | Diag(DiagLoc, diag::warn_dangling_variable) | ||||||||||
7410 | << RK << !Entity.getParent() | ||||||||||
7411 | << ExtendingEntity->getDecl()->isImplicit() | ||||||||||
7412 | << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; | ||||||||||
7413 | } | ||||||||||
7414 | break; | ||||||||||
7415 | } | ||||||||||
7416 | |||||||||||
7417 | case LK_MemInitializer: { | ||||||||||
7418 | if (isa<MaterializeTemporaryExpr>(L)) { | ||||||||||
7419 | // Under C++ DR1696, if a mem-initializer (or a default member | ||||||||||
7420 | // initializer used by the absence of one) would lifetime-extend a | ||||||||||
7421 | // temporary, the program is ill-formed. | ||||||||||
7422 | if (auto *ExtendingDecl = | ||||||||||
7423 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | ||||||||||
7424 | if (IsGslPtrInitWithGslTempOwner) { | ||||||||||
7425 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member) | ||||||||||
7426 | << ExtendingDecl << DiagRange; | ||||||||||
7427 | Diag(ExtendingDecl->getLocation(), | ||||||||||
7428 | diag::note_ref_or_ptr_member_declared_here) | ||||||||||
7429 | << true; | ||||||||||
7430 | return false; | ||||||||||
7431 | } | ||||||||||
7432 | bool IsSubobjectMember = ExtendingEntity != &Entity; | ||||||||||
7433 | Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) | ||||||||||
7434 | ? diag::err_dangling_member | ||||||||||
7435 | : diag::warn_dangling_member) | ||||||||||
7436 | << ExtendingDecl << IsSubobjectMember << RK << DiagRange; | ||||||||||
7437 | // Don't bother adding a note pointing to the field if we're inside | ||||||||||
7438 | // its default member initializer; our primary diagnostic points to | ||||||||||
7439 | // the same place in that case. | ||||||||||
7440 | if (Path.empty() || | ||||||||||
7441 | Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { | ||||||||||
7442 | Diag(ExtendingDecl->getLocation(), | ||||||||||
7443 | diag::note_lifetime_extending_member_declared_here) | ||||||||||
7444 | << RK << IsSubobjectMember; | ||||||||||
7445 | } | ||||||||||
7446 | } else { | ||||||||||
7447 | // We have a mem-initializer but no particular field within it; this | ||||||||||
7448 | // is either a base class or a delegating initializer directly | ||||||||||
7449 | // initializing the base-class from something that doesn't live long | ||||||||||
7450 | // enough. | ||||||||||
7451 | // | ||||||||||
7452 | // FIXME: Warn on this. | ||||||||||
7453 | return false; | ||||||||||
7454 | } | ||||||||||
7455 | } else { | ||||||||||
7456 | // Paths via a default initializer can only occur during error recovery | ||||||||||
7457 | // (there's no other way that a default initializer can refer to a | ||||||||||
7458 | // local). Don't produce a bogus warning on those cases. | ||||||||||
7459 | if (pathContainsInit(Path)) | ||||||||||
7460 | return false; | ||||||||||
7461 | |||||||||||
7462 | // Suppress false positives for code like the one below: | ||||||||||
7463 | // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {} | ||||||||||
7464 | if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path)) | ||||||||||
7465 | return false; | ||||||||||
7466 | |||||||||||
7467 | auto *DRE = dyn_cast<DeclRefExpr>(L); | ||||||||||
7468 | auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr; | ||||||||||
7469 | if (!VD) { | ||||||||||
7470 | // A member was initialized to a local block. | ||||||||||
7471 | // FIXME: Warn on this. | ||||||||||
7472 | return false; | ||||||||||
7473 | } | ||||||||||
7474 | |||||||||||
7475 | if (auto *Member = | ||||||||||
7476 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { | ||||||||||
7477 | bool IsPointer = !Member->getType()->isReferenceType(); | ||||||||||
7478 | Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr | ||||||||||
7479 | : diag::warn_bind_ref_member_to_parameter) | ||||||||||
7480 | << Member << VD << isa<ParmVarDecl>(VD) << DiagRange; | ||||||||||
7481 | Diag(Member->getLocation(), | ||||||||||
7482 | diag::note_ref_or_ptr_member_declared_here) | ||||||||||
7483 | << (unsigned)IsPointer; | ||||||||||
7484 | } | ||||||||||
7485 | } | ||||||||||
7486 | break; | ||||||||||
7487 | } | ||||||||||
7488 | |||||||||||
7489 | case LK_New: | ||||||||||
7490 | if (isa<MaterializeTemporaryExpr>(L)) { | ||||||||||
7491 | if (IsGslPtrInitWithGslTempOwner) | ||||||||||
7492 | Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange; | ||||||||||
7493 | else | ||||||||||
7494 | Diag(DiagLoc, RK == RK_ReferenceBinding | ||||||||||
7495 | ? diag::warn_new_dangling_reference | ||||||||||
7496 | : diag::warn_new_dangling_initializer_list) | ||||||||||
7497 | << !Entity.getParent() << DiagRange; | ||||||||||
7498 | } else { | ||||||||||
7499 | // We can't determine if the allocation outlives the local declaration. | ||||||||||
7500 | return false; | ||||||||||
7501 | } | ||||||||||
7502 | break; | ||||||||||
7503 | |||||||||||
7504 | case LK_Return: | ||||||||||
7505 | case LK_StmtExprResult: | ||||||||||
7506 | if (auto *DRE = dyn_cast<DeclRefExpr>(L)) { | ||||||||||
7507 | // We can't determine if the local variable outlives the statement | ||||||||||
7508 | // expression. | ||||||||||
7509 | if (LK == LK_StmtExprResult) | ||||||||||
7510 | return false; | ||||||||||
7511 | Diag(DiagLoc, diag::warn_ret_stack_addr_ref) | ||||||||||
7512 | << Entity.getType()->isReferenceType() << DRE->getDecl() | ||||||||||
7513 | << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange; | ||||||||||
7514 | } else if (isa<BlockExpr>(L)) { | ||||||||||
7515 | Diag(DiagLoc, diag::err_ret_local_block) << DiagRange; | ||||||||||
7516 | } else if (isa<AddrLabelExpr>(L)) { | ||||||||||
7517 | // Don't warn when returning a label from a statement expression. | ||||||||||
7518 | // Leaving the scope doesn't end its lifetime. | ||||||||||
7519 | if (LK == LK_StmtExprResult) | ||||||||||
7520 | return false; | ||||||||||
7521 | Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange; | ||||||||||
7522 | } else { | ||||||||||
7523 | Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref) | ||||||||||
7524 | << Entity.getType()->isReferenceType() << DiagRange; | ||||||||||
7525 | } | ||||||||||
7526 | break; | ||||||||||
7527 | } | ||||||||||
7528 | |||||||||||
7529 | for (unsigned I = 0; I != Path.size(); ++I) { | ||||||||||
7530 | auto Elem = Path[I]; | ||||||||||
7531 | |||||||||||
7532 | switch (Elem.Kind) { | ||||||||||
7533 | case IndirectLocalPathEntry::AddressOf: | ||||||||||
7534 | case IndirectLocalPathEntry::LValToRVal: | ||||||||||
7535 | // These exist primarily to mark the path as not permitting or | ||||||||||
7536 | // supporting lifetime extension. | ||||||||||
7537 | break; | ||||||||||
7538 | |||||||||||
7539 | case IndirectLocalPathEntry::LifetimeBoundCall: | ||||||||||
7540 | case IndirectLocalPathEntry::GslPointerInit: | ||||||||||
7541 | case IndirectLocalPathEntry::GslReferenceInit: | ||||||||||
7542 | // FIXME: Consider adding a note for these. | ||||||||||
7543 | break; | ||||||||||
7544 | |||||||||||
7545 | case IndirectLocalPathEntry::DefaultInit: { | ||||||||||
7546 | auto *FD = cast<FieldDecl>(Elem.D); | ||||||||||
7547 | Diag(FD->getLocation(), diag::note_init_with_default_member_initalizer) | ||||||||||
7548 | << FD << nextPathEntryRange(Path, I + 1, L); | ||||||||||
7549 | break; | ||||||||||
7550 | } | ||||||||||
7551 | |||||||||||
7552 | case IndirectLocalPathEntry::VarInit: | ||||||||||
7553 | const VarDecl *VD = cast<VarDecl>(Elem.D); | ||||||||||
7554 | Diag(VD->getLocation(), diag::note_local_var_initializer) | ||||||||||
7555 | << VD->getType()->isReferenceType() | ||||||||||
7556 | << VD->isImplicit() << VD->getDeclName() | ||||||||||
7557 | << nextPathEntryRange(Path, I + 1, L); | ||||||||||
7558 | break; | ||||||||||
7559 | } | ||||||||||
7560 | } | ||||||||||
7561 | |||||||||||
7562 | // We didn't lifetime-extend, so don't go any further; we don't need more | ||||||||||
7563 | // warnings or errors on inner temporaries within this one's initializer. | ||||||||||
7564 | return false; | ||||||||||
7565 | }; | ||||||||||
7566 | |||||||||||
7567 | bool EnableLifetimeWarnings = !getDiagnostics().isIgnored( | ||||||||||
7568 | diag::warn_dangling_lifetime_pointer, SourceLocation()); | ||||||||||
7569 | llvm::SmallVector<IndirectLocalPathEntry, 8> Path; | ||||||||||
7570 | if (Init->isGLValue()) | ||||||||||
7571 | visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding, | ||||||||||
7572 | TemporaryVisitor, | ||||||||||
7573 | EnableLifetimeWarnings); | ||||||||||
7574 | else | ||||||||||
7575 | visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false, | ||||||||||
7576 | EnableLifetimeWarnings); | ||||||||||
7577 | } | ||||||||||
7578 | |||||||||||
7579 | static void DiagnoseNarrowingInInitList(Sema &S, | ||||||||||
7580 | const ImplicitConversionSequence &ICS, | ||||||||||
7581 | QualType PreNarrowingType, | ||||||||||
7582 | QualType EntityType, | ||||||||||
7583 | const Expr *PostInit); | ||||||||||
7584 | |||||||||||
7585 | /// Provide warnings when std::move is used on construction. | ||||||||||
7586 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, | ||||||||||
7587 | bool IsReturnStmt) { | ||||||||||
7588 | if (!InitExpr) | ||||||||||
7589 | return; | ||||||||||
7590 | |||||||||||
7591 | if (S.inTemplateInstantiation()) | ||||||||||
7592 | return; | ||||||||||
7593 | |||||||||||
7594 | QualType DestType = InitExpr->getType(); | ||||||||||
7595 | if (!DestType->isRecordType()) | ||||||||||
7596 | return; | ||||||||||
7597 | |||||||||||
7598 | unsigned DiagID = 0; | ||||||||||
7599 | if (IsReturnStmt) { | ||||||||||
7600 | const CXXConstructExpr *CCE = | ||||||||||
7601 | dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens()); | ||||||||||
7602 | if (!CCE || CCE->getNumArgs() != 1) | ||||||||||
7603 | return; | ||||||||||
7604 | |||||||||||
7605 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) | ||||||||||
7606 | return; | ||||||||||
7607 | |||||||||||
7608 | InitExpr = CCE->getArg(0)->IgnoreImpCasts(); | ||||||||||
7609 | } | ||||||||||
7610 | |||||||||||
7611 | // Find the std::move call and get the argument. | ||||||||||
7612 | const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens()); | ||||||||||
7613 | if (!CE || !CE->isCallToStdMove()) | ||||||||||
7614 | return; | ||||||||||
7615 | |||||||||||
7616 | const Expr *Arg = CE->getArg(0)->IgnoreImplicit(); | ||||||||||
7617 | |||||||||||
7618 | if (IsReturnStmt) { | ||||||||||
7619 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts()); | ||||||||||
7620 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) | ||||||||||
7621 | return; | ||||||||||
7622 | |||||||||||
7623 | const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); | ||||||||||
7624 | if (!VD || !VD->hasLocalStorage()) | ||||||||||
7625 | return; | ||||||||||
7626 | |||||||||||
7627 | // __block variables are not moved implicitly. | ||||||||||
7628 | if (VD->hasAttr<BlocksAttr>()) | ||||||||||
7629 | return; | ||||||||||
7630 | |||||||||||
7631 | QualType SourceType = VD->getType(); | ||||||||||
7632 | if (!SourceType->isRecordType()) | ||||||||||
7633 | return; | ||||||||||
7634 | |||||||||||
7635 | if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) { | ||||||||||
7636 | return; | ||||||||||
7637 | } | ||||||||||
7638 | |||||||||||
7639 | // If we're returning a function parameter, copy elision | ||||||||||
7640 | // is not possible. | ||||||||||
7641 | if (isa<ParmVarDecl>(VD)) | ||||||||||
7642 | DiagID = diag::warn_redundant_move_on_return; | ||||||||||
7643 | else | ||||||||||
7644 | DiagID = diag::warn_pessimizing_move_on_return; | ||||||||||
7645 | } else { | ||||||||||
7646 | DiagID = diag::warn_pessimizing_move_on_initialization; | ||||||||||
7647 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); | ||||||||||
7648 | if (!ArgStripped->isRValue() || !ArgStripped->getType()->isRecordType()) | ||||||||||
7649 | return; | ||||||||||
7650 | } | ||||||||||
7651 | |||||||||||
7652 | S.Diag(CE->getBeginLoc(), DiagID); | ||||||||||
7653 | |||||||||||
7654 | // Get all the locations for a fix-it. Don't emit the fix-it if any location | ||||||||||
7655 | // is within a macro. | ||||||||||
7656 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); | ||||||||||
7657 | if (CallBegin.isMacroID()) | ||||||||||
7658 | return; | ||||||||||
7659 | SourceLocation RParen = CE->getRParenLoc(); | ||||||||||
7660 | if (RParen.isMacroID()) | ||||||||||
7661 | return; | ||||||||||
7662 | SourceLocation LParen; | ||||||||||
7663 | SourceLocation ArgLoc = Arg->getBeginLoc(); | ||||||||||
7664 | |||||||||||
7665 | // Special testing for the argument location. Since the fix-it needs the | ||||||||||
7666 | // location right before the argument, the argument location can be in a | ||||||||||
7667 | // macro only if it is at the beginning of the macro. | ||||||||||
7668 | while (ArgLoc.isMacroID() && | ||||||||||
7669 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) { | ||||||||||
7670 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin(); | ||||||||||
7671 | } | ||||||||||
7672 | |||||||||||
7673 | if (LParen.isMacroID()) | ||||||||||
7674 | return; | ||||||||||
7675 | |||||||||||
7676 | LParen = ArgLoc.getLocWithOffset(-1); | ||||||||||
7677 | |||||||||||
7678 | S.Diag(CE->getBeginLoc(), diag::note_remove_move) | ||||||||||
7679 | << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen)) | ||||||||||
7680 | << FixItHint::CreateRemoval(SourceRange(RParen, RParen)); | ||||||||||
7681 | } | ||||||||||
7682 | |||||||||||
7683 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { | ||||||||||
7684 | // Check to see if we are dereferencing a null pointer. If so, this is | ||||||||||
7685 | // undefined behavior, so warn about it. This only handles the pattern | ||||||||||
7686 | // "*null", which is a very syntactic check. | ||||||||||
7687 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) | ||||||||||
7688 | if (UO->getOpcode() == UO_Deref && | ||||||||||
7689 | UO->getSubExpr()->IgnoreParenCasts()-> | ||||||||||
7690 | isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) { | ||||||||||
7691 | S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, | ||||||||||
7692 | S.PDiag(diag::warn_binding_null_to_reference) | ||||||||||
7693 | << UO->getSubExpr()->getSourceRange()); | ||||||||||
7694 | } | ||||||||||
7695 | } | ||||||||||
7696 | |||||||||||
7697 | MaterializeTemporaryExpr * | ||||||||||
7698 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, | ||||||||||
7699 | bool BoundToLvalueReference) { | ||||||||||
7700 | auto MTE = new (Context) | ||||||||||
7701 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); | ||||||||||
7702 | |||||||||||
7703 | // Order an ExprWithCleanups for lifetime marks. | ||||||||||
7704 | // | ||||||||||
7705 | // TODO: It'll be good to have a single place to check the access of the | ||||||||||
7706 | // destructor and generate ExprWithCleanups for various uses. Currently these | ||||||||||
7707 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, | ||||||||||
7708 | // but there may be a chance to merge them. | ||||||||||
7709 | Cleanup.setExprNeedsCleanups(false); | ||||||||||
7710 | return MTE; | ||||||||||
7711 | } | ||||||||||
7712 | |||||||||||
7713 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { | ||||||||||
7714 | // In C++98, we don't want to implicitly create an xvalue. | ||||||||||
7715 | // FIXME: This means that AST consumers need to deal with "prvalues" that | ||||||||||
7716 | // denote materialized temporaries. Maybe we should add another ValueKind | ||||||||||
7717 | // for "xvalue pretending to be a prvalue" for C++98 support. | ||||||||||
7718 | if (!E->isRValue() || !getLangOpts().CPlusPlus11) | ||||||||||
7719 | return E; | ||||||||||
7720 | |||||||||||
7721 | // C++1z [conv.rval]/1: T shall be a complete type. | ||||||||||
7722 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? | ||||||||||
7723 | // If so, we should check for a non-abstract class type here too. | ||||||||||
7724 | QualType T = E->getType(); | ||||||||||
7725 | if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type)) | ||||||||||
7726 | return ExprError(); | ||||||||||
7727 | |||||||||||
7728 | return CreateMaterializeTemporaryExpr(E->getType(), E, false); | ||||||||||
7729 | } | ||||||||||
7730 | |||||||||||
7731 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, | ||||||||||
7732 | ExprValueKind VK, | ||||||||||
7733 | CheckedConversionKind CCK) { | ||||||||||
7734 | |||||||||||
7735 | CastKind CK = CK_NoOp; | ||||||||||
7736 | |||||||||||
7737 | if (VK == VK_RValue) { | ||||||||||
7738 | auto PointeeTy = Ty->getPointeeType(); | ||||||||||
7739 | auto ExprPointeeTy = E->getType()->getPointeeType(); | ||||||||||
7740 | if (!PointeeTy.isNull() && | ||||||||||
7741 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) | ||||||||||
7742 | CK = CK_AddressSpaceConversion; | ||||||||||
7743 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { | ||||||||||
7744 | CK = CK_AddressSpaceConversion; | ||||||||||
7745 | } | ||||||||||
7746 | |||||||||||
7747 | return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK); | ||||||||||
7748 | } | ||||||||||
7749 | |||||||||||
7750 | ExprResult InitializationSequence::Perform(Sema &S, | ||||||||||
7751 | const InitializedEntity &Entity, | ||||||||||
7752 | const InitializationKind &Kind, | ||||||||||
7753 | MultiExprArg Args, | ||||||||||
7754 | QualType *ResultType) { | ||||||||||
7755 | if (Failed()) { | ||||||||||
7756 | Diagnose(S, Entity, Kind, Args); | ||||||||||
7757 | return ExprError(); | ||||||||||
7758 | } | ||||||||||
7759 | if (!ZeroInitializationFixit.empty()) { | ||||||||||
7760 | unsigned DiagID = diag::err_default_init_const; | ||||||||||
7761 | if (Decl *D = Entity.getDecl()) | ||||||||||
7762 | if (S.getLangOpts().MSVCCompat && D->hasAttr<SelectAnyAttr>()) | ||||||||||
7763 | DiagID = diag::ext_default_init_const; | ||||||||||
7764 | |||||||||||
7765 | // The initialization would have succeeded with this fixit. Since the fixit | ||||||||||
7766 | // is on the error, we need to build a valid AST in this case, so this isn't | ||||||||||
7767 | // handled in the Failed() branch above. | ||||||||||
7768 | QualType DestType = Entity.getType(); | ||||||||||
7769 | S.Diag(Kind.getLocation(), DiagID) | ||||||||||
7770 | << DestType << (bool)DestType->getAs<RecordType>() | ||||||||||
7771 | << FixItHint::CreateInsertion(ZeroInitializationFixitLoc, | ||||||||||
7772 | ZeroInitializationFixit); | ||||||||||
7773 | } | ||||||||||
7774 | |||||||||||
7775 | if (getKind() == DependentSequence) { | ||||||||||
7776 | // If the declaration is a non-dependent, incomplete array type | ||||||||||
7777 | // that has an initializer, then its type will be completed once | ||||||||||
7778 | // the initializer is instantiated. | ||||||||||
7779 | if (ResultType && !Entity.getType()->isDependentType() && | ||||||||||
7780 | Args.size() == 1) { | ||||||||||
7781 | QualType DeclType = Entity.getType(); | ||||||||||
7782 | if (const IncompleteArrayType *ArrayT | ||||||||||
7783 | = S.Context.getAsIncompleteArrayType(DeclType)) { | ||||||||||
7784 | // FIXME: We don't currently have the ability to accurately | ||||||||||
7785 | // compute the length of an initializer list without | ||||||||||
7786 | // performing full type-checking of the initializer list | ||||||||||
7787 | // (since we have to determine where braces are implicitly | ||||||||||
7788 | // introduced and such). So, we fall back to making the array | ||||||||||
7789 | // type a dependently-sized array type with no specified | ||||||||||
7790 | // bound. | ||||||||||
7791 | if (isa<InitListExpr>((Expr *)Args[0])) { | ||||||||||
7792 | SourceRange Brackets; | ||||||||||
7793 | |||||||||||
7794 | // Scavange the location of the brackets from the entity, if we can. | ||||||||||
7795 | if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) { | ||||||||||
7796 | if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) { | ||||||||||
7797 | TypeLoc TL = TInfo->getTypeLoc(); | ||||||||||
7798 | if (IncompleteArrayTypeLoc ArrayLoc = | ||||||||||
7799 | TL.getAs<IncompleteArrayTypeLoc>()) | ||||||||||
7800 | Brackets = ArrayLoc.getBracketsRange(); | ||||||||||
7801 | } | ||||||||||
7802 | } | ||||||||||
7803 | |||||||||||
7804 | *ResultType | ||||||||||
7805 | = S.Context.getDependentSizedArrayType(ArrayT->getElementType(), | ||||||||||
7806 | /*NumElts=*/nullptr, | ||||||||||
7807 | ArrayT->getSizeModifier(), | ||||||||||
7808 | ArrayT->getIndexTypeCVRQualifiers(), | ||||||||||
7809 | Brackets); | ||||||||||
7810 | } | ||||||||||
7811 | |||||||||||
7812 | } | ||||||||||
7813 | } | ||||||||||
7814 | if (Kind.getKind() == InitializationKind::IK_Direct && | ||||||||||
7815 | !Kind.isExplicitCast()) { | ||||||||||
7816 | // Rebuild the ParenListExpr. | ||||||||||
7817 | SourceRange ParenRange = Kind.getParenOrBraceRange(); | ||||||||||
7818 | return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(), | ||||||||||
7819 | Args); | ||||||||||
7820 | } | ||||||||||
7821 | assert(Kind.getKind() == InitializationKind::IK_Copy ||((Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast () || Kind.getKind() == InitializationKind::IK_DirectList) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 7823, __PRETTY_FUNCTION__)) | ||||||||||
7822 | Kind.isExplicitCast() ||((Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast () || Kind.getKind() == InitializationKind::IK_DirectList) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 7823, __PRETTY_FUNCTION__)) | ||||||||||
7823 | Kind.getKind() == InitializationKind::IK_DirectList)((Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast () || Kind.getKind() == InitializationKind::IK_DirectList) ? static_cast <void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast() || Kind.getKind() == InitializationKind::IK_DirectList" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 7823, __PRETTY_FUNCTION__)); | ||||||||||
7824 | return ExprResult(Args[0]); | ||||||||||
7825 | } | ||||||||||
7826 | |||||||||||
7827 | // No steps means no initialization. | ||||||||||
7828 | if (Steps.empty()) | ||||||||||
7829 | return ExprResult((Expr *)nullptr); | ||||||||||
7830 | |||||||||||
7831 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && | ||||||||||
7832 | Args.size() == 1 && isa<InitListExpr>(Args[0]) && | ||||||||||
7833 | !Entity.isParameterKind()) { | ||||||||||
7834 | // Produce a C++98 compatibility warning if we are initializing a reference | ||||||||||
7835 | // from an initializer list. For parameters, we produce a better warning | ||||||||||
7836 | // elsewhere. | ||||||||||
7837 | Expr *Init = Args[0]; | ||||||||||
7838 | S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init) | ||||||||||
7839 | << Init->getSourceRange(); | ||||||||||
7840 | } | ||||||||||
7841 | |||||||||||
7842 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope | ||||||||||
7843 | QualType ETy = Entity.getType(); | ||||||||||
7844 | bool HasGlobalAS = ETy.hasAddressSpace() && | ||||||||||
7845 | ETy.getAddressSpace() == LangAS::opencl_global; | ||||||||||
7846 | |||||||||||
7847 | if (S.getLangOpts().OpenCLVersion >= 200 && | ||||||||||
7848 | ETy->isAtomicType() && !HasGlobalAS && | ||||||||||
7849 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { | ||||||||||
7850 | S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init) | ||||||||||
7851 | << 1 | ||||||||||
7852 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); | ||||||||||
7853 | return ExprError(); | ||||||||||
7854 | } | ||||||||||
7855 | |||||||||||
7856 | QualType DestType = Entity.getType().getNonReferenceType(); | ||||||||||
7857 | // FIXME: Ugly hack around the fact that Entity.getType() is not | ||||||||||
7858 | // the same as Entity.getDecl()->getType() in cases involving type merging, | ||||||||||
7859 | // and we want latter when it makes sense. | ||||||||||
7860 | if (ResultType) | ||||||||||
7861 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : | ||||||||||
7862 | Entity.getType(); | ||||||||||
7863 | |||||||||||
7864 | ExprResult CurInit((Expr *)nullptr); | ||||||||||
7865 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; | ||||||||||
7866 | |||||||||||
7867 | // For initialization steps that start with a single initializer, | ||||||||||
7868 | // grab the only argument out the Args and place it into the "current" | ||||||||||
7869 | // initializer. | ||||||||||
7870 | switch (Steps.front().Kind) { | ||||||||||
7871 | case SK_ResolveAddressOfOverloadedFunction: | ||||||||||
7872 | case SK_CastDerivedToBaseRValue: | ||||||||||
7873 | case SK_CastDerivedToBaseXValue: | ||||||||||
7874 | case SK_CastDerivedToBaseLValue: | ||||||||||
7875 | case SK_BindReference: | ||||||||||
7876 | case SK_BindReferenceToTemporary: | ||||||||||
7877 | case SK_FinalCopy: | ||||||||||
7878 | case SK_ExtraneousCopyToTemporary: | ||||||||||
7879 | case SK_UserConversion: | ||||||||||
7880 | case SK_QualificationConversionLValue: | ||||||||||
7881 | case SK_QualificationConversionXValue: | ||||||||||
7882 | case SK_QualificationConversionRValue: | ||||||||||
7883 | case SK_AtomicConversion: | ||||||||||
7884 | case SK_ConversionSequence: | ||||||||||
7885 | case SK_ConversionSequenceNoNarrowing: | ||||||||||
7886 | case SK_ListInitialization: | ||||||||||
7887 | case SK_UnwrapInitList: | ||||||||||
7888 | case SK_RewrapInitList: | ||||||||||
7889 | case SK_CAssignment: | ||||||||||
7890 | case SK_StringInit: | ||||||||||
7891 | case SK_ObjCObjectConversion: | ||||||||||
7892 | case SK_ArrayLoopIndex: | ||||||||||
7893 | case SK_ArrayLoopInit: | ||||||||||
7894 | case SK_ArrayInit: | ||||||||||
7895 | case SK_GNUArrayInit: | ||||||||||
7896 | case SK_ParenthesizedArrayInit: | ||||||||||
7897 | case SK_PassByIndirectCopyRestore: | ||||||||||
7898 | case SK_PassByIndirectRestore: | ||||||||||
7899 | case SK_ProduceObjCObject: | ||||||||||
7900 | case SK_StdInitializerList: | ||||||||||
7901 | case SK_OCLSamplerInit: | ||||||||||
7902 | case SK_OCLZeroOpaqueType: { | ||||||||||
7903 | assert(Args.size() == 1)((Args.size() == 1) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 7903, __PRETTY_FUNCTION__)); | ||||||||||
7904 | CurInit = Args[0]; | ||||||||||
7905 | if (!CurInit.get()) return ExprError(); | ||||||||||
7906 | break; | ||||||||||
7907 | } | ||||||||||
7908 | |||||||||||
7909 | case SK_ConstructorInitialization: | ||||||||||
7910 | case SK_ConstructorInitializationFromList: | ||||||||||
7911 | case SK_StdInitializerListConstructorCall: | ||||||||||
7912 | case SK_ZeroInitialization: | ||||||||||
7913 | break; | ||||||||||
7914 | } | ||||||||||
7915 | |||||||||||
7916 | // Promote from an unevaluated context to an unevaluated list context in | ||||||||||
7917 | // C++11 list-initialization; we need to instantiate entities usable in | ||||||||||
7918 | // constant expressions here in order to perform narrowing checks =( | ||||||||||
7919 | EnterExpressionEvaluationContext Evaluated( | ||||||||||
7920 | S, EnterExpressionEvaluationContext::InitList, | ||||||||||
7921 | CurInit.get() && isa<InitListExpr>(CurInit.get())); | ||||||||||
7922 | |||||||||||
7923 | // C++ [class.abstract]p2: | ||||||||||
7924 | // no objects of an abstract class can be created except as subobjects | ||||||||||
7925 | // of a class derived from it | ||||||||||
7926 | auto checkAbstractType = [&](QualType T) -> bool { | ||||||||||
7927 | if (Entity.getKind() == InitializedEntity::EK_Base || | ||||||||||
7928 | Entity.getKind() == InitializedEntity::EK_Delegating) | ||||||||||
7929 | return false; | ||||||||||
7930 | return S.RequireNonAbstractType(Kind.getLocation(), T, | ||||||||||
7931 | diag::err_allocation_of_abstract_type); | ||||||||||
7932 | }; | ||||||||||
7933 | |||||||||||
7934 | // Walk through the computed steps for the initialization sequence, | ||||||||||
7935 | // performing the specified conversions along the way. | ||||||||||
7936 | bool ConstructorInitRequiresZeroInit = false; | ||||||||||
7937 | for (step_iterator Step = step_begin(), StepEnd = step_end(); | ||||||||||
7938 | Step != StepEnd; ++Step) { | ||||||||||
7939 | if (CurInit.isInvalid()) | ||||||||||
7940 | return ExprError(); | ||||||||||
7941 | |||||||||||
7942 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); | ||||||||||
7943 | |||||||||||
7944 | switch (Step->Kind) { | ||||||||||
7945 | case SK_ResolveAddressOfOverloadedFunction: | ||||||||||
7946 | // Overload resolution determined which function invoke; update the | ||||||||||
7947 | // initializer to reflect that choice. | ||||||||||
7948 | S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl); | ||||||||||
7949 | if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation())) | ||||||||||
7950 | return ExprError(); | ||||||||||
7951 | CurInit = S.FixOverloadedFunctionReference(CurInit, | ||||||||||
7952 | Step->Function.FoundDecl, | ||||||||||
7953 | Step->Function.Function); | ||||||||||
7954 | break; | ||||||||||
7955 | |||||||||||
7956 | case SK_CastDerivedToBaseRValue: | ||||||||||
7957 | case SK_CastDerivedToBaseXValue: | ||||||||||
7958 | case SK_CastDerivedToBaseLValue: { | ||||||||||
7959 | // We have a derived-to-base cast that produces either an rvalue or an | ||||||||||
7960 | // lvalue. Perform that cast. | ||||||||||
7961 | |||||||||||
7962 | CXXCastPath BasePath; | ||||||||||
7963 | |||||||||||
7964 | // Casts to inaccessible base classes are allowed with C-style casts. | ||||||||||
7965 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); | ||||||||||
7966 | if (S.CheckDerivedToBaseConversion( | ||||||||||
7967 | SourceType, Step->Type, CurInit.get()->getBeginLoc(), | ||||||||||
7968 | CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess)) | ||||||||||
7969 | return ExprError(); | ||||||||||
7970 | |||||||||||
7971 | ExprValueKind VK = | ||||||||||
7972 | Step->Kind == SK_CastDerivedToBaseLValue ? | ||||||||||
7973 | VK_LValue : | ||||||||||
7974 | (Step->Kind == SK_CastDerivedToBaseXValue ? | ||||||||||
7975 | VK_XValue : | ||||||||||
7976 | VK_RValue); | ||||||||||
7977 | CurInit = | ||||||||||
7978 | ImplicitCastExpr::Create(S.Context, Step->Type, CK_DerivedToBase, | ||||||||||
7979 | CurInit.get(), &BasePath, VK); | ||||||||||
7980 | break; | ||||||||||
7981 | } | ||||||||||
7982 | |||||||||||
7983 | case SK_BindReference: | ||||||||||
7984 | // Reference binding does not have any corresponding ASTs. | ||||||||||
7985 | |||||||||||
7986 | // Check exception specifications | ||||||||||
7987 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | ||||||||||
7988 | return ExprError(); | ||||||||||
7989 | |||||||||||
7990 | // We don't check for e.g. function pointers here, since address | ||||||||||
7991 | // availability checks should only occur when the function first decays | ||||||||||
7992 | // into a pointer or reference. | ||||||||||
7993 | if (CurInit.get()->getType()->isFunctionProtoType()) { | ||||||||||
7994 | if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) { | ||||||||||
7995 | if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { | ||||||||||
7996 | if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||||||||
7997 | DRE->getBeginLoc())) | ||||||||||
7998 | return ExprError(); | ||||||||||
7999 | } | ||||||||||
8000 | } | ||||||||||
8001 | } | ||||||||||
8002 | |||||||||||
8003 | CheckForNullPointerDereference(S, CurInit.get()); | ||||||||||
8004 | break; | ||||||||||
8005 | |||||||||||
8006 | case SK_BindReferenceToTemporary: { | ||||||||||
8007 | // Make sure the "temporary" is actually an rvalue. | ||||||||||
8008 | assert(CurInit.get()->isRValue() && "not a temporary")((CurInit.get()->isRValue() && "not a temporary") ? static_cast<void> (0) : __assert_fail ("CurInit.get()->isRValue() && \"not a temporary\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8008, __PRETTY_FUNCTION__)); | ||||||||||
8009 | |||||||||||
8010 | // Check exception specifications | ||||||||||
8011 | if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType)) | ||||||||||
8012 | return ExprError(); | ||||||||||
8013 | |||||||||||
8014 | // Materialize the temporary into memory. | ||||||||||
8015 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | ||||||||||
8016 | Step->Type, CurInit.get(), Entity.getType()->isLValueReferenceType()); | ||||||||||
8017 | CurInit = MTE; | ||||||||||
8018 | |||||||||||
8019 | // If we're extending this temporary to automatic storage duration -- we | ||||||||||
8020 | // need to register its cleanup during the full-expression's cleanups. | ||||||||||
8021 | if (MTE->getStorageDuration() == SD_Automatic && | ||||||||||
8022 | MTE->getType().isDestructedType()) | ||||||||||
8023 | S.Cleanup.setExprNeedsCleanups(true); | ||||||||||
8024 | break; | ||||||||||
8025 | } | ||||||||||
8026 | |||||||||||
8027 | case SK_FinalCopy: | ||||||||||
8028 | if (checkAbstractType(Step->Type)) | ||||||||||
8029 | return ExprError(); | ||||||||||
8030 | |||||||||||
8031 | // If the overall initialization is initializing a temporary, we already | ||||||||||
8032 | // bound our argument if it was necessary to do so. If not (if we're | ||||||||||
8033 | // ultimately initializing a non-temporary), our argument needs to be | ||||||||||
8034 | // bound since it's initializing a function parameter. | ||||||||||
8035 | // FIXME: This is a mess. Rationalize temporary destruction. | ||||||||||
8036 | if (!shouldBindAsTemporary(Entity)) | ||||||||||
8037 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||||||||
8038 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | ||||||||||
8039 | /*IsExtraneousCopy=*/false); | ||||||||||
8040 | break; | ||||||||||
8041 | |||||||||||
8042 | case SK_ExtraneousCopyToTemporary: | ||||||||||
8043 | CurInit = CopyObject(S, Step->Type, Entity, CurInit, | ||||||||||
8044 | /*IsExtraneousCopy=*/true); | ||||||||||
8045 | break; | ||||||||||
8046 | |||||||||||
8047 | case SK_UserConversion: { | ||||||||||
8048 | // We have a user-defined conversion that invokes either a constructor | ||||||||||
8049 | // or a conversion function. | ||||||||||
8050 | CastKind CastKind; | ||||||||||
8051 | FunctionDecl *Fn = Step->Function.Function; | ||||||||||
8052 | DeclAccessPair FoundFn = Step->Function.FoundDecl; | ||||||||||
8053 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; | ||||||||||
8054 | bool CreatedObject = false; | ||||||||||
8055 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) { | ||||||||||
8056 | // Build a call to the selected constructor. | ||||||||||
8057 | SmallVector<Expr*, 8> ConstructorArgs; | ||||||||||
8058 | SourceLocation Loc = CurInit.get()->getBeginLoc(); | ||||||||||
8059 | |||||||||||
8060 | // Determine the arguments required to actually perform the constructor | ||||||||||
8061 | // call. | ||||||||||
8062 | Expr *Arg = CurInit.get(); | ||||||||||
8063 | if (S.CompleteConstructorCall(Constructor, | ||||||||||
8064 | MultiExprArg(&Arg, 1), | ||||||||||
8065 | Loc, ConstructorArgs)) | ||||||||||
8066 | return ExprError(); | ||||||||||
8067 | |||||||||||
8068 | // Build an expression that constructs a temporary. | ||||||||||
8069 | CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, | ||||||||||
8070 | FoundFn, Constructor, | ||||||||||
8071 | ConstructorArgs, | ||||||||||
8072 | HadMultipleCandidates, | ||||||||||
8073 | /*ListInit*/ false, | ||||||||||
8074 | /*StdInitListInit*/ false, | ||||||||||
8075 | /*ZeroInit*/ false, | ||||||||||
8076 | CXXConstructExpr::CK_Complete, | ||||||||||
8077 | SourceRange()); | ||||||||||
8078 | if (CurInit.isInvalid()) | ||||||||||
8079 | return ExprError(); | ||||||||||
8080 | |||||||||||
8081 | S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn, | ||||||||||
8082 | Entity); | ||||||||||
8083 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | ||||||||||
8084 | return ExprError(); | ||||||||||
8085 | |||||||||||
8086 | CastKind = CK_ConstructorConversion; | ||||||||||
8087 | CreatedObject = true; | ||||||||||
8088 | } else { | ||||||||||
8089 | // Build a call to the conversion function. | ||||||||||
8090 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn); | ||||||||||
8091 | S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr, | ||||||||||
8092 | FoundFn); | ||||||||||
8093 | if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation())) | ||||||||||
8094 | return ExprError(); | ||||||||||
8095 | |||||||||||
8096 | CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion, | ||||||||||
8097 | HadMultipleCandidates); | ||||||||||
8098 | if (CurInit.isInvalid()) | ||||||||||
8099 | return ExprError(); | ||||||||||
8100 | |||||||||||
8101 | CastKind = CK_UserDefinedConversion; | ||||||||||
8102 | CreatedObject = Conversion->getReturnType()->isRecordType(); | ||||||||||
8103 | } | ||||||||||
8104 | |||||||||||
8105 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) | ||||||||||
8106 | return ExprError(); | ||||||||||
8107 | |||||||||||
8108 | CurInit = ImplicitCastExpr::Create(S.Context, CurInit.get()->getType(), | ||||||||||
8109 | CastKind, CurInit.get(), nullptr, | ||||||||||
8110 | CurInit.get()->getValueKind()); | ||||||||||
8111 | |||||||||||
8112 | if (shouldBindAsTemporary(Entity)) | ||||||||||
8113 | // The overall entity is temporary, so this expression should be | ||||||||||
8114 | // destroyed at the end of its full-expression. | ||||||||||
8115 | CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>()); | ||||||||||
8116 | else if (CreatedObject && shouldDestroyEntity(Entity)) { | ||||||||||
8117 | // The object outlasts the full-expression, but we need to prepare for | ||||||||||
8118 | // a destructor being run on it. | ||||||||||
8119 | // FIXME: It makes no sense to do this here. This should happen | ||||||||||
8120 | // regardless of how we initialized the entity. | ||||||||||
8121 | QualType T = CurInit.get()->getType(); | ||||||||||
8122 | if (const RecordType *Record = T->getAs<RecordType>()) { | ||||||||||
8123 | CXXDestructorDecl *Destructor | ||||||||||
8124 | = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl())); | ||||||||||
8125 | S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor, | ||||||||||
8126 | S.PDiag(diag::err_access_dtor_temp) << T); | ||||||||||
8127 | S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor); | ||||||||||
8128 | if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc())) | ||||||||||
8129 | return ExprError(); | ||||||||||
8130 | } | ||||||||||
8131 | } | ||||||||||
8132 | break; | ||||||||||
8133 | } | ||||||||||
8134 | |||||||||||
8135 | case SK_QualificationConversionLValue: | ||||||||||
8136 | case SK_QualificationConversionXValue: | ||||||||||
8137 | case SK_QualificationConversionRValue: { | ||||||||||
8138 | // Perform a qualification conversion; these can never go wrong. | ||||||||||
8139 | ExprValueKind VK = | ||||||||||
8140 | Step->Kind == SK_QualificationConversionLValue | ||||||||||
8141 | ? VK_LValue | ||||||||||
8142 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue | ||||||||||
8143 | : VK_RValue); | ||||||||||
8144 | CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK); | ||||||||||
8145 | break; | ||||||||||
8146 | } | ||||||||||
8147 | |||||||||||
8148 | case SK_AtomicConversion: { | ||||||||||
8149 | assert(CurInit.get()->isRValue() && "cannot convert glvalue to atomic")((CurInit.get()->isRValue() && "cannot convert glvalue to atomic" ) ? static_cast<void> (0) : __assert_fail ("CurInit.get()->isRValue() && \"cannot convert glvalue to atomic\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8149, __PRETTY_FUNCTION__)); | ||||||||||
8150 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | ||||||||||
8151 | CK_NonAtomicToAtomic, VK_RValue); | ||||||||||
8152 | break; | ||||||||||
8153 | } | ||||||||||
8154 | |||||||||||
8155 | case SK_ConversionSequence: | ||||||||||
8156 | case SK_ConversionSequenceNoNarrowing: { | ||||||||||
8157 | if (const auto *FromPtrType = | ||||||||||
8158 | CurInit.get()->getType()->getAs<PointerType>()) { | ||||||||||
8159 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { | ||||||||||
8160 | if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) && | ||||||||||
8161 | !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||||||||
8162 | S.Diag(CurInit.get()->getExprLoc(), | ||||||||||
8163 | diag::warn_noderef_to_dereferenceable_pointer) | ||||||||||
8164 | << CurInit.get()->getSourceRange(); | ||||||||||
8165 | } | ||||||||||
8166 | } | ||||||||||
8167 | } | ||||||||||
8168 | |||||||||||
8169 | Sema::CheckedConversionKind CCK | ||||||||||
8170 | = Kind.isCStyleCast()? Sema::CCK_CStyleCast | ||||||||||
8171 | : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast | ||||||||||
8172 | : Kind.isExplicitCast()? Sema::CCK_OtherCast | ||||||||||
8173 | : Sema::CCK_ImplicitConversion; | ||||||||||
8174 | ExprResult CurInitExprRes = | ||||||||||
8175 | S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS, | ||||||||||
8176 | getAssignmentAction(Entity), CCK); | ||||||||||
8177 | if (CurInitExprRes.isInvalid()) | ||||||||||
8178 | return ExprError(); | ||||||||||
8179 | |||||||||||
8180 | S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get()); | ||||||||||
8181 | |||||||||||
8182 | CurInit = CurInitExprRes; | ||||||||||
8183 | |||||||||||
8184 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && | ||||||||||
8185 | S.getLangOpts().CPlusPlus) | ||||||||||
8186 | DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(), | ||||||||||
8187 | CurInit.get()); | ||||||||||
8188 | |||||||||||
8189 | break; | ||||||||||
8190 | } | ||||||||||
8191 | |||||||||||
8192 | case SK_ListInitialization: { | ||||||||||
8193 | if (checkAbstractType(Step->Type)) | ||||||||||
8194 | return ExprError(); | ||||||||||
8195 | |||||||||||
8196 | InitListExpr *InitList = cast<InitListExpr>(CurInit.get()); | ||||||||||
8197 | // If we're not initializing the top-level entity, we need to create an | ||||||||||
8198 | // InitializeTemporary entity for our target type. | ||||||||||
8199 | QualType Ty = Step->Type; | ||||||||||
8200 | bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty); | ||||||||||
8201 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty); | ||||||||||
8202 | InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity; | ||||||||||
8203 | InitListChecker PerformInitList(S, InitEntity, | ||||||||||
8204 | InitList, Ty, /*VerifyOnly=*/false, | ||||||||||
8205 | /*TreatUnavailableAsInvalid=*/false); | ||||||||||
8206 | if (PerformInitList.HadError()) | ||||||||||
8207 | return ExprError(); | ||||||||||
8208 | |||||||||||
8209 | // Hack: We must update *ResultType if available in order to set the | ||||||||||
8210 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. | ||||||||||
8211 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. | ||||||||||
8212 | if (ResultType && | ||||||||||
8213 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { | ||||||||||
8214 | if ((*ResultType)->isRValueReferenceType()) | ||||||||||
8215 | Ty = S.Context.getRValueReferenceType(Ty); | ||||||||||
8216 | else if ((*ResultType)->isLValueReferenceType()) | ||||||||||
8217 | Ty = S.Context.getLValueReferenceType(Ty, | ||||||||||
8218 | (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); | ||||||||||
8219 | *ResultType = Ty; | ||||||||||
8220 | } | ||||||||||
8221 | |||||||||||
8222 | InitListExpr *StructuredInitList = | ||||||||||
8223 | PerformInitList.getFullyStructuredList(); | ||||||||||
8224 | CurInit.get(); | ||||||||||
8225 | CurInit = shouldBindAsTemporary(InitEntity) | ||||||||||
8226 | ? S.MaybeBindToTemporary(StructuredInitList) | ||||||||||
8227 | : StructuredInitList; | ||||||||||
8228 | break; | ||||||||||
8229 | } | ||||||||||
8230 | |||||||||||
8231 | case SK_ConstructorInitializationFromList: { | ||||||||||
8232 | if (checkAbstractType(Step->Type)) | ||||||||||
8233 | return ExprError(); | ||||||||||
8234 | |||||||||||
8235 | // When an initializer list is passed for a parameter of type "reference | ||||||||||
8236 | // to object", we don't get an EK_Temporary entity, but instead an | ||||||||||
8237 | // EK_Parameter entity with reference type. | ||||||||||
8238 | // FIXME: This is a hack. What we really should do is create a user | ||||||||||
8239 | // conversion step for this case, but this makes it considerably more | ||||||||||
8240 | // complicated. For now, this will do. | ||||||||||
8241 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | ||||||||||
8242 | Entity.getType().getNonReferenceType()); | ||||||||||
8243 | bool UseTemporary = Entity.getType()->isReferenceType(); | ||||||||||
8244 | assert(Args.size() == 1 && "expected a single argument for list init")((Args.size() == 1 && "expected a single argument for list init" ) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1 && \"expected a single argument for list init\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8244, __PRETTY_FUNCTION__)); | ||||||||||
8245 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||||||||
8246 | S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init) | ||||||||||
8247 | << InitList->getSourceRange(); | ||||||||||
8248 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); | ||||||||||
8249 | CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity : | ||||||||||
8250 | Entity, | ||||||||||
8251 | Kind, Arg, *Step, | ||||||||||
8252 | ConstructorInitRequiresZeroInit, | ||||||||||
8253 | /*IsListInitialization*/true, | ||||||||||
8254 | /*IsStdInitListInit*/false, | ||||||||||
8255 | InitList->getLBraceLoc(), | ||||||||||
8256 | InitList->getRBraceLoc()); | ||||||||||
8257 | break; | ||||||||||
8258 | } | ||||||||||
8259 | |||||||||||
8260 | case SK_UnwrapInitList: | ||||||||||
8261 | CurInit = cast<InitListExpr>(CurInit.get())->getInit(0); | ||||||||||
8262 | break; | ||||||||||
8263 | |||||||||||
8264 | case SK_RewrapInitList: { | ||||||||||
8265 | Expr *E = CurInit.get(); | ||||||||||
8266 | InitListExpr *Syntactic = Step->WrappingSyntacticList; | ||||||||||
8267 | InitListExpr *ILE = new (S.Context) InitListExpr(S.Context, | ||||||||||
8268 | Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc()); | ||||||||||
8269 | ILE->setSyntacticForm(Syntactic); | ||||||||||
8270 | ILE->setType(E->getType()); | ||||||||||
8271 | ILE->setValueKind(E->getValueKind()); | ||||||||||
8272 | CurInit = ILE; | ||||||||||
8273 | break; | ||||||||||
8274 | } | ||||||||||
8275 | |||||||||||
8276 | case SK_ConstructorInitialization: | ||||||||||
8277 | case SK_StdInitializerListConstructorCall: { | ||||||||||
8278 | if (checkAbstractType(Step->Type)) | ||||||||||
8279 | return ExprError(); | ||||||||||
8280 | |||||||||||
8281 | // When an initializer list is passed for a parameter of type "reference | ||||||||||
8282 | // to object", we don't get an EK_Temporary entity, but instead an | ||||||||||
8283 | // EK_Parameter entity with reference type. | ||||||||||
8284 | // FIXME: This is a hack. What we really should do is create a user | ||||||||||
8285 | // conversion step for this case, but this makes it considerably more | ||||||||||
8286 | // complicated. For now, this will do. | ||||||||||
8287 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( | ||||||||||
8288 | Entity.getType().getNonReferenceType()); | ||||||||||
8289 | bool UseTemporary = Entity.getType()->isReferenceType(); | ||||||||||
8290 | bool IsStdInitListInit = | ||||||||||
8291 | Step->Kind == SK_StdInitializerListConstructorCall; | ||||||||||
8292 | Expr *Source = CurInit.get(); | ||||||||||
8293 | SourceRange Range = Kind.hasParenOrBraceRange() | ||||||||||
8294 | ? Kind.getParenOrBraceRange() | ||||||||||
8295 | : SourceRange(); | ||||||||||
8296 | CurInit = PerformConstructorInitialization( | ||||||||||
8297 | S, UseTemporary ? TempEntity : Entity, Kind, | ||||||||||
8298 | Source ? MultiExprArg(Source) : Args, *Step, | ||||||||||
8299 | ConstructorInitRequiresZeroInit, | ||||||||||
8300 | /*IsListInitialization*/ IsStdInitListInit, | ||||||||||
8301 | /*IsStdInitListInitialization*/ IsStdInitListInit, | ||||||||||
8302 | /*LBraceLoc*/ Range.getBegin(), | ||||||||||
8303 | /*RBraceLoc*/ Range.getEnd()); | ||||||||||
8304 | break; | ||||||||||
8305 | } | ||||||||||
8306 | |||||||||||
8307 | case SK_ZeroInitialization: { | ||||||||||
8308 | step_iterator NextStep = Step; | ||||||||||
8309 | ++NextStep; | ||||||||||
8310 | if (NextStep != StepEnd && | ||||||||||
8311 | (NextStep->Kind == SK_ConstructorInitialization || | ||||||||||
8312 | NextStep->Kind == SK_ConstructorInitializationFromList)) { | ||||||||||
8313 | // The need for zero-initialization is recorded directly into | ||||||||||
8314 | // the call to the object's constructor within the next step. | ||||||||||
8315 | ConstructorInitRequiresZeroInit = true; | ||||||||||
8316 | } else if (Kind.getKind() == InitializationKind::IK_Value && | ||||||||||
8317 | S.getLangOpts().CPlusPlus && | ||||||||||
8318 | !Kind.isImplicitValueInit()) { | ||||||||||
8319 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); | ||||||||||
8320 | if (!TSInfo) | ||||||||||
8321 | TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type, | ||||||||||
8322 | Kind.getRange().getBegin()); | ||||||||||
8323 | |||||||||||
8324 | CurInit = new (S.Context) CXXScalarValueInitExpr( | ||||||||||
8325 | Entity.getType().getNonLValueExprType(S.Context), TSInfo, | ||||||||||
8326 | Kind.getRange().getEnd()); | ||||||||||
8327 | } else { | ||||||||||
8328 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); | ||||||||||
8329 | } | ||||||||||
8330 | break; | ||||||||||
8331 | } | ||||||||||
8332 | |||||||||||
8333 | case SK_CAssignment: { | ||||||||||
8334 | QualType SourceType = CurInit.get()->getType(); | ||||||||||
8335 | |||||||||||
8336 | // Save off the initial CurInit in case we need to emit a diagnostic | ||||||||||
8337 | ExprResult InitialCurInit = CurInit; | ||||||||||
8338 | ExprResult Result = CurInit; | ||||||||||
8339 | Sema::AssignConvertType ConvTy = | ||||||||||
8340 | S.CheckSingleAssignmentConstraints(Step->Type, Result, true, | ||||||||||
8341 | Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); | ||||||||||
8342 | if (Result.isInvalid()) | ||||||||||
8343 | return ExprError(); | ||||||||||
8344 | CurInit = Result; | ||||||||||
8345 | |||||||||||
8346 | // If this is a call, allow conversion to a transparent union. | ||||||||||
8347 | ExprResult CurInitExprRes = CurInit; | ||||||||||
8348 | if (ConvTy != Sema::Compatible && | ||||||||||
8349 | Entity.isParameterKind() && | ||||||||||
8350 | S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes) | ||||||||||
8351 | == Sema::Compatible) | ||||||||||
8352 | ConvTy = Sema::Compatible; | ||||||||||
8353 | if (CurInitExprRes.isInvalid()) | ||||||||||
8354 | return ExprError(); | ||||||||||
8355 | CurInit = CurInitExprRes; | ||||||||||
8356 | |||||||||||
8357 | bool Complained; | ||||||||||
8358 | if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(), | ||||||||||
8359 | Step->Type, SourceType, | ||||||||||
8360 | InitialCurInit.get(), | ||||||||||
8361 | getAssignmentAction(Entity, true), | ||||||||||
8362 | &Complained)) { | ||||||||||
8363 | PrintInitLocationNote(S, Entity); | ||||||||||
8364 | return ExprError(); | ||||||||||
8365 | } else if (Complained) | ||||||||||
8366 | PrintInitLocationNote(S, Entity); | ||||||||||
8367 | break; | ||||||||||
8368 | } | ||||||||||
8369 | |||||||||||
8370 | case SK_StringInit: { | ||||||||||
8371 | QualType Ty = Step->Type; | ||||||||||
8372 | CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty, | ||||||||||
8373 | S.Context.getAsArrayType(Ty), S); | ||||||||||
8374 | break; | ||||||||||
8375 | } | ||||||||||
8376 | |||||||||||
8377 | case SK_ObjCObjectConversion: | ||||||||||
8378 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | ||||||||||
8379 | CK_ObjCObjectLValueCast, | ||||||||||
8380 | CurInit.get()->getValueKind()); | ||||||||||
8381 | break; | ||||||||||
8382 | |||||||||||
8383 | case SK_ArrayLoopIndex: { | ||||||||||
8384 | Expr *Cur = CurInit.get(); | ||||||||||
8385 | Expr *BaseExpr = new (S.Context) | ||||||||||
8386 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), | ||||||||||
8387 | Cur->getValueKind(), Cur->getObjectKind(), Cur); | ||||||||||
8388 | Expr *IndexExpr = | ||||||||||
8389 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); | ||||||||||
8390 | CurInit = S.CreateBuiltinArraySubscriptExpr( | ||||||||||
8391 | BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation()); | ||||||||||
8392 | ArrayLoopCommonExprs.push_back(BaseExpr); | ||||||||||
8393 | break; | ||||||||||
8394 | } | ||||||||||
8395 | |||||||||||
8396 | case SK_ArrayLoopInit: { | ||||||||||
8397 | assert(!ArrayLoopCommonExprs.empty() &&((!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ) ? static_cast<void> (0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8398, __PRETTY_FUNCTION__)) | ||||||||||
8398 | "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit")((!ArrayLoopCommonExprs.empty() && "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ) ? static_cast<void> (0) : __assert_fail ("!ArrayLoopCommonExprs.empty() && \"mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8398, __PRETTY_FUNCTION__)); | ||||||||||
8399 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); | ||||||||||
8400 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, | ||||||||||
8401 | CurInit.get()); | ||||||||||
8402 | break; | ||||||||||
8403 | } | ||||||||||
8404 | |||||||||||
8405 | case SK_GNUArrayInit: | ||||||||||
8406 | // Okay: we checked everything before creating this step. Note that | ||||||||||
8407 | // this is a GNU extension. | ||||||||||
8408 | S.Diag(Kind.getLocation(), diag::ext_array_init_copy) | ||||||||||
8409 | << Step->Type << CurInit.get()->getType() | ||||||||||
8410 | << CurInit.get()->getSourceRange(); | ||||||||||
8411 | updateGNUCompoundLiteralRValue(CurInit.get()); | ||||||||||
8412 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
8413 | case SK_ArrayInit: | ||||||||||
8414 | // If the destination type is an incomplete array type, update the | ||||||||||
8415 | // type accordingly. | ||||||||||
8416 | if (ResultType) { | ||||||||||
8417 | if (const IncompleteArrayType *IncompleteDest | ||||||||||
8418 | = S.Context.getAsIncompleteArrayType(Step->Type)) { | ||||||||||
8419 | if (const ConstantArrayType *ConstantSource | ||||||||||
8420 | = S.Context.getAsConstantArrayType(CurInit.get()->getType())) { | ||||||||||
8421 | *ResultType = S.Context.getConstantArrayType( | ||||||||||
8422 | IncompleteDest->getElementType(), | ||||||||||
8423 | ConstantSource->getSize(), | ||||||||||
8424 | ConstantSource->getSizeExpr(), | ||||||||||
8425 | ArrayType::Normal, 0); | ||||||||||
8426 | } | ||||||||||
8427 | } | ||||||||||
8428 | } | ||||||||||
8429 | break; | ||||||||||
8430 | |||||||||||
8431 | case SK_ParenthesizedArrayInit: | ||||||||||
8432 | // Okay: we checked everything before creating this step. Note that | ||||||||||
8433 | // this is a GNU extension. | ||||||||||
8434 | S.Diag(Kind.getLocation(), diag::ext_array_init_parens) | ||||||||||
8435 | << CurInit.get()->getSourceRange(); | ||||||||||
8436 | break; | ||||||||||
8437 | |||||||||||
8438 | case SK_PassByIndirectCopyRestore: | ||||||||||
8439 | case SK_PassByIndirectRestore: | ||||||||||
8440 | checkIndirectCopyRestoreSource(S, CurInit.get()); | ||||||||||
8441 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( | ||||||||||
8442 | CurInit.get(), Step->Type, | ||||||||||
8443 | Step->Kind == SK_PassByIndirectCopyRestore); | ||||||||||
8444 | break; | ||||||||||
8445 | |||||||||||
8446 | case SK_ProduceObjCObject: | ||||||||||
8447 | CurInit = | ||||||||||
8448 | ImplicitCastExpr::Create(S.Context, Step->Type, CK_ARCProduceObject, | ||||||||||
8449 | CurInit.get(), nullptr, VK_RValue); | ||||||||||
8450 | break; | ||||||||||
8451 | |||||||||||
8452 | case SK_StdInitializerList: { | ||||||||||
8453 | S.Diag(CurInit.get()->getExprLoc(), | ||||||||||
8454 | diag::warn_cxx98_compat_initializer_list_init) | ||||||||||
8455 | << CurInit.get()->getSourceRange(); | ||||||||||
8456 | |||||||||||
8457 | // Materialize the temporary into memory. | ||||||||||
8458 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( | ||||||||||
8459 | CurInit.get()->getType(), CurInit.get(), | ||||||||||
8460 | /*BoundToLvalueReference=*/false); | ||||||||||
8461 | |||||||||||
8462 | // Wrap it in a construction of a std::initializer_list<T>. | ||||||||||
8463 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); | ||||||||||
8464 | |||||||||||
8465 | // Bind the result, in case the library has given initializer_list a | ||||||||||
8466 | // non-trivial destructor. | ||||||||||
8467 | if (shouldBindAsTemporary(Entity)) | ||||||||||
8468 | CurInit = S.MaybeBindToTemporary(CurInit.get()); | ||||||||||
8469 | break; | ||||||||||
8470 | } | ||||||||||
8471 | |||||||||||
8472 | case SK_OCLSamplerInit: { | ||||||||||
8473 | // Sampler initialization have 5 cases: | ||||||||||
8474 | // 1. function argument passing | ||||||||||
8475 | // 1a. argument is a file-scope variable | ||||||||||
8476 | // 1b. argument is a function-scope variable | ||||||||||
8477 | // 1c. argument is one of caller function's parameters | ||||||||||
8478 | // 2. variable initialization | ||||||||||
8479 | // 2a. initializing a file-scope variable | ||||||||||
8480 | // 2b. initializing a function-scope variable | ||||||||||
8481 | // | ||||||||||
8482 | // For file-scope variables, since they cannot be initialized by function | ||||||||||
8483 | // call of __translate_sampler_initializer in LLVM IR, their references | ||||||||||
8484 | // need to be replaced by a cast from their literal initializers to | ||||||||||
8485 | // sampler type. Since sampler variables can only be used in function | ||||||||||
8486 | // calls as arguments, we only need to replace them when handling the | ||||||||||
8487 | // argument passing. | ||||||||||
8488 | assert(Step->Type->isSamplerT() &&((Step->Type->isSamplerT() && "Sampler initialization on non-sampler type." ) ? static_cast<void> (0) : __assert_fail ("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8489, __PRETTY_FUNCTION__)) | ||||||||||
8489 | "Sampler initialization on non-sampler type.")((Step->Type->isSamplerT() && "Sampler initialization on non-sampler type." ) ? static_cast<void> (0) : __assert_fail ("Step->Type->isSamplerT() && \"Sampler initialization on non-sampler type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8489, __PRETTY_FUNCTION__)); | ||||||||||
8490 | Expr *Init = CurInit.get()->IgnoreParens(); | ||||||||||
8491 | QualType SourceType = Init->getType(); | ||||||||||
8492 | // Case 1 | ||||||||||
8493 | if (Entity.isParameterKind()) { | ||||||||||
8494 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { | ||||||||||
8495 | S.Diag(Kind.getLocation(), diag::err_sampler_argument_required) | ||||||||||
8496 | << SourceType; | ||||||||||
8497 | break; | ||||||||||
8498 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) { | ||||||||||
8499 | auto Var = cast<VarDecl>(DRE->getDecl()); | ||||||||||
8500 | // Case 1b and 1c | ||||||||||
8501 | // No cast from integer to sampler is needed. | ||||||||||
8502 | if (!Var->hasGlobalStorage()) { | ||||||||||
8503 | CurInit = ImplicitCastExpr::Create(S.Context, Step->Type, | ||||||||||
8504 | CK_LValueToRValue, Init, | ||||||||||
8505 | /*BasePath=*/nullptr, VK_RValue); | ||||||||||
8506 | break; | ||||||||||
8507 | } | ||||||||||
8508 | // Case 1a | ||||||||||
8509 | // For function call with a file-scope sampler variable as argument, | ||||||||||
8510 | // get the integer literal. | ||||||||||
8511 | // Do not diagnose if the file-scope variable does not have initializer | ||||||||||
8512 | // since this has already been diagnosed when parsing the variable | ||||||||||
8513 | // declaration. | ||||||||||
8514 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit())) | ||||||||||
8515 | break; | ||||||||||
8516 | Init = cast<ImplicitCastExpr>(const_cast<Expr*>( | ||||||||||
8517 | Var->getInit()))->getSubExpr(); | ||||||||||
8518 | SourceType = Init->getType(); | ||||||||||
8519 | } | ||||||||||
8520 | } else { | ||||||||||
8521 | // Case 2 | ||||||||||
8522 | // Check initializer is 32 bit integer constant. | ||||||||||
8523 | // If the initializer is taken from global variable, do not diagnose since | ||||||||||
8524 | // this has already been done when parsing the variable declaration. | ||||||||||
8525 | if (!Init->isConstantInitializer(S.Context, false)) | ||||||||||
8526 | break; | ||||||||||
8527 | |||||||||||
8528 | if (!SourceType->isIntegerType() || | ||||||||||
8529 | 32 != S.Context.getIntWidth(SourceType)) { | ||||||||||
8530 | S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer) | ||||||||||
8531 | << SourceType; | ||||||||||
8532 | break; | ||||||||||
8533 | } | ||||||||||
8534 | |||||||||||
8535 | Expr::EvalResult EVResult; | ||||||||||
8536 | Init->EvaluateAsInt(EVResult, S.Context); | ||||||||||
8537 | llvm::APSInt Result = EVResult.Val.getInt(); | ||||||||||
8538 | const uint64_t SamplerValue = Result.getLimitedValue(); | ||||||||||
8539 | // 32-bit value of sampler's initializer is interpreted as | ||||||||||
8540 | // bit-field with the following structure: | ||||||||||
8541 | // |unspecified|Filter|Addressing Mode| Normalized Coords| | ||||||||||
8542 | // |31 6|5 4|3 1| 0| | ||||||||||
8543 | // This structure corresponds to enum values of sampler properties | ||||||||||
8544 | // defined in SPIR spec v1.2 and also opencl-c.h | ||||||||||
8545 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; | ||||||||||
8546 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; | ||||||||||
8547 | if (FilterMode != 1 && FilterMode != 2 && | ||||||||||
8548 | !S.getOpenCLOptions().isEnabled( | ||||||||||
8549 | "cl_intel_device_side_avc_motion_estimation")) | ||||||||||
8550 | S.Diag(Kind.getLocation(), | ||||||||||
8551 | diag::warn_sampler_initializer_invalid_bits) | ||||||||||
8552 | << "Filter Mode"; | ||||||||||
8553 | if (AddressingMode > 4) | ||||||||||
8554 | S.Diag(Kind.getLocation(), | ||||||||||
8555 | diag::warn_sampler_initializer_invalid_bits) | ||||||||||
8556 | << "Addressing Mode"; | ||||||||||
8557 | } | ||||||||||
8558 | |||||||||||
8559 | // Cases 1a, 2a and 2b | ||||||||||
8560 | // Insert cast from integer to sampler. | ||||||||||
8561 | CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy, | ||||||||||
8562 | CK_IntToOCLSampler); | ||||||||||
8563 | break; | ||||||||||
8564 | } | ||||||||||
8565 | case SK_OCLZeroOpaqueType: { | ||||||||||
8566 | assert((Step->Type->isEventT() || Step->Type->isQueueT() ||(((Step->Type->isEventT() || Step->Type->isQueueT () || Step->Type->isOCLIntelSubgroupAVCType()) && "Wrong type for initialization of OpenCL opaque type.") ? static_cast <void> (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8568, __PRETTY_FUNCTION__)) | ||||||||||
8567 | Step->Type->isOCLIntelSubgroupAVCType()) &&(((Step->Type->isEventT() || Step->Type->isQueueT () || Step->Type->isOCLIntelSubgroupAVCType()) && "Wrong type for initialization of OpenCL opaque type.") ? static_cast <void> (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8568, __PRETTY_FUNCTION__)) | ||||||||||
8568 | "Wrong type for initialization of OpenCL opaque type.")(((Step->Type->isEventT() || Step->Type->isQueueT () || Step->Type->isOCLIntelSubgroupAVCType()) && "Wrong type for initialization of OpenCL opaque type.") ? static_cast <void> (0) : __assert_fail ("(Step->Type->isEventT() || Step->Type->isQueueT() || Step->Type->isOCLIntelSubgroupAVCType()) && \"Wrong type for initialization of OpenCL opaque type.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8568, __PRETTY_FUNCTION__)); | ||||||||||
8569 | |||||||||||
8570 | CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, | ||||||||||
8571 | CK_ZeroToOCLOpaqueType, | ||||||||||
8572 | CurInit.get()->getValueKind()); | ||||||||||
8573 | break; | ||||||||||
8574 | } | ||||||||||
8575 | } | ||||||||||
8576 | } | ||||||||||
8577 | |||||||||||
8578 | // Check whether the initializer has a shorter lifetime than the initialized | ||||||||||
8579 | // entity, and if not, either lifetime-extend or warn as appropriate. | ||||||||||
8580 | if (auto *Init = CurInit.get()) | ||||||||||
8581 | S.checkInitializerLifetime(Entity, Init); | ||||||||||
8582 | |||||||||||
8583 | // Diagnose non-fatal problems with the completed initialization. | ||||||||||
8584 | if (Entity.getKind() == InitializedEntity::EK_Member && | ||||||||||
8585 | cast<FieldDecl>(Entity.getDecl())->isBitField()) | ||||||||||
8586 | S.CheckBitFieldInitialization(Kind.getLocation(), | ||||||||||
8587 | cast<FieldDecl>(Entity.getDecl()), | ||||||||||
8588 | CurInit.get()); | ||||||||||
8589 | |||||||||||
8590 | // Check for std::move on construction. | ||||||||||
8591 | if (const Expr *E = CurInit.get()) { | ||||||||||
8592 | CheckMoveOnConstruction(S, E, | ||||||||||
8593 | Entity.getKind() == InitializedEntity::EK_Result); | ||||||||||
8594 | } | ||||||||||
8595 | |||||||||||
8596 | return CurInit; | ||||||||||
8597 | } | ||||||||||
8598 | |||||||||||
8599 | /// Somewhere within T there is an uninitialized reference subobject. | ||||||||||
8600 | /// Dig it out and diagnose it. | ||||||||||
8601 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, | ||||||||||
8602 | QualType T) { | ||||||||||
8603 | if (T->isReferenceType()) { | ||||||||||
8604 | S.Diag(Loc, diag::err_reference_without_init) | ||||||||||
8605 | << T.getNonReferenceType(); | ||||||||||
8606 | return true; | ||||||||||
8607 | } | ||||||||||
8608 | |||||||||||
8609 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||||||||
8610 | if (!RD || !RD->hasUninitializedReferenceMember()) | ||||||||||
8611 | return false; | ||||||||||
8612 | |||||||||||
8613 | for (const auto *FI : RD->fields()) { | ||||||||||
8614 | if (FI->isUnnamedBitfield()) | ||||||||||
8615 | continue; | ||||||||||
8616 | |||||||||||
8617 | if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) { | ||||||||||
8618 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | ||||||||||
8619 | return true; | ||||||||||
8620 | } | ||||||||||
8621 | } | ||||||||||
8622 | |||||||||||
8623 | for (const auto &BI : RD->bases()) { | ||||||||||
8624 | if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) { | ||||||||||
8625 | S.Diag(Loc, diag::note_value_initialization_here) << RD; | ||||||||||
8626 | return true; | ||||||||||
8627 | } | ||||||||||
8628 | } | ||||||||||
8629 | |||||||||||
8630 | return false; | ||||||||||
8631 | } | ||||||||||
8632 | |||||||||||
8633 | |||||||||||
8634 | //===----------------------------------------------------------------------===// | ||||||||||
8635 | // Diagnose initialization failures | ||||||||||
8636 | //===----------------------------------------------------------------------===// | ||||||||||
8637 | |||||||||||
8638 | /// Emit notes associated with an initialization that failed due to a | ||||||||||
8639 | /// "simple" conversion failure. | ||||||||||
8640 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, | ||||||||||
8641 | Expr *op) { | ||||||||||
8642 | QualType destType = entity.getType(); | ||||||||||
8643 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && | ||||||||||
8644 | op->getType()->isObjCObjectPointerType()) { | ||||||||||
8645 | |||||||||||
8646 | // Emit a possible note about the conversion failing because the | ||||||||||
8647 | // operand is a message send with a related result type. | ||||||||||
8648 | S.EmitRelatedResultTypeNote(op); | ||||||||||
8649 | |||||||||||
8650 | // Emit a possible note about a return failing because we're | ||||||||||
8651 | // expecting a related result type. | ||||||||||
8652 | if (entity.getKind() == InitializedEntity::EK_Result) | ||||||||||
8653 | S.EmitRelatedResultTypeNoteForReturn(destType); | ||||||||||
8654 | } | ||||||||||
8655 | } | ||||||||||
8656 | |||||||||||
8657 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, | ||||||||||
8658 | InitListExpr *InitList) { | ||||||||||
8659 | QualType DestType = Entity.getType(); | ||||||||||
8660 | |||||||||||
8661 | QualType E; | ||||||||||
8662 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) { | ||||||||||
8663 | QualType ArrayType = S.Context.getConstantArrayType( | ||||||||||
8664 | E.withConst(), | ||||||||||
8665 | llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()), | ||||||||||
8666 | InitList->getNumInits()), | ||||||||||
8667 | nullptr, clang::ArrayType::Normal, 0); | ||||||||||
8668 | InitializedEntity HiddenArray = | ||||||||||
8669 | InitializedEntity::InitializeTemporary(ArrayType); | ||||||||||
8670 | return diagnoseListInit(S, HiddenArray, InitList); | ||||||||||
8671 | } | ||||||||||
8672 | |||||||||||
8673 | if (DestType->isReferenceType()) { | ||||||||||
8674 | // A list-initialization failure for a reference means that we tried to | ||||||||||
8675 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the | ||||||||||
8676 | // inner initialization failed. | ||||||||||
8677 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); | ||||||||||
8678 | diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList); | ||||||||||
8679 | SourceLocation Loc = InitList->getBeginLoc(); | ||||||||||
8680 | if (auto *D = Entity.getDecl()) | ||||||||||
8681 | Loc = D->getLocation(); | ||||||||||
8682 | S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T; | ||||||||||
8683 | return; | ||||||||||
8684 | } | ||||||||||
8685 | |||||||||||
8686 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, | ||||||||||
8687 | /*VerifyOnly=*/false, | ||||||||||
8688 | /*TreatUnavailableAsInvalid=*/false); | ||||||||||
8689 | assert(DiagnoseInitList.HadError() &&((DiagnoseInitList.HadError() && "Inconsistent init list check result." ) ? static_cast<void> (0) : __assert_fail ("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8690, __PRETTY_FUNCTION__)) | ||||||||||
8690 | "Inconsistent init list check result.")((DiagnoseInitList.HadError() && "Inconsistent init list check result." ) ? static_cast<void> (0) : __assert_fail ("DiagnoseInitList.HadError() && \"Inconsistent init list check result.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8690, __PRETTY_FUNCTION__)); | ||||||||||
8691 | } | ||||||||||
8692 | |||||||||||
8693 | bool InitializationSequence::Diagnose(Sema &S, | ||||||||||
8694 | const InitializedEntity &Entity, | ||||||||||
8695 | const InitializationKind &Kind, | ||||||||||
8696 | ArrayRef<Expr *> Args) { | ||||||||||
8697 | if (!Failed()) | ||||||||||
8698 | return false; | ||||||||||
8699 | |||||||||||
8700 | // When we want to diagnose only one element of a braced-init-list, | ||||||||||
8701 | // we need to factor it out. | ||||||||||
8702 | Expr *OnlyArg; | ||||||||||
8703 | if (Args.size() == 1) { | ||||||||||
8704 | auto *List = dyn_cast<InitListExpr>(Args[0]); | ||||||||||
8705 | if (List && List->getNumInits() == 1) | ||||||||||
8706 | OnlyArg = List->getInit(0); | ||||||||||
8707 | else | ||||||||||
8708 | OnlyArg = Args[0]; | ||||||||||
8709 | } | ||||||||||
8710 | else | ||||||||||
8711 | OnlyArg = nullptr; | ||||||||||
8712 | |||||||||||
8713 | QualType DestType = Entity.getType(); | ||||||||||
8714 | switch (Failure) { | ||||||||||
8715 | case FK_TooManyInitsForReference: | ||||||||||
8716 | // FIXME: Customize for the initialized entity? | ||||||||||
8717 | if (Args.empty()) { | ||||||||||
8718 | // Dig out the reference subobject which is uninitialized and diagnose it. | ||||||||||
8719 | // If this is value-initialization, this could be nested some way within | ||||||||||
8720 | // the target type. | ||||||||||
8721 | assert(Kind.getKind() == InitializationKind::IK_Value ||((Kind.getKind() == InitializationKind::IK_Value || DestType-> isReferenceType()) ? static_cast<void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8722, __PRETTY_FUNCTION__)) | ||||||||||
8722 | DestType->isReferenceType())((Kind.getKind() == InitializationKind::IK_Value || DestType-> isReferenceType()) ? static_cast<void> (0) : __assert_fail ("Kind.getKind() == InitializationKind::IK_Value || DestType->isReferenceType()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8722, __PRETTY_FUNCTION__)); | ||||||||||
8723 | bool Diagnosed = | ||||||||||
8724 | DiagnoseUninitializedReference(S, Kind.getLocation(), DestType); | ||||||||||
8725 | assert(Diagnosed && "couldn't find uninitialized reference to diagnose")((Diagnosed && "couldn't find uninitialized reference to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Diagnosed && \"couldn't find uninitialized reference to diagnose\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8725, __PRETTY_FUNCTION__)); | ||||||||||
8726 | (void)Diagnosed; | ||||||||||
8727 | } else // FIXME: diagnostic below could be better! | ||||||||||
8728 | S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits) | ||||||||||
8729 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | ||||||||||
8730 | break; | ||||||||||
8731 | case FK_ParenthesizedListInitForReference: | ||||||||||
8732 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | ||||||||||
8733 | << 1 << Entity.getType() << Args[0]->getSourceRange(); | ||||||||||
8734 | break; | ||||||||||
8735 | |||||||||||
8736 | case FK_ArrayNeedsInitList: | ||||||||||
8737 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0; | ||||||||||
8738 | break; | ||||||||||
8739 | case FK_ArrayNeedsInitListOrStringLiteral: | ||||||||||
8740 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1; | ||||||||||
8741 | break; | ||||||||||
8742 | case FK_ArrayNeedsInitListOrWideStringLiteral: | ||||||||||
8743 | S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2; | ||||||||||
8744 | break; | ||||||||||
8745 | case FK_NarrowStringIntoWideCharArray: | ||||||||||
8746 | S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar); | ||||||||||
8747 | break; | ||||||||||
8748 | case FK_WideStringIntoCharArray: | ||||||||||
8749 | S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char); | ||||||||||
8750 | break; | ||||||||||
8751 | case FK_IncompatWideStringIntoWideChar: | ||||||||||
8752 | S.Diag(Kind.getLocation(), | ||||||||||
8753 | diag::err_array_init_incompat_wide_string_into_wchar); | ||||||||||
8754 | break; | ||||||||||
8755 | case FK_PlainStringIntoUTF8Char: | ||||||||||
8756 | S.Diag(Kind.getLocation(), | ||||||||||
8757 | diag::err_array_init_plain_string_into_char8_t); | ||||||||||
8758 | S.Diag(Args.front()->getBeginLoc(), | ||||||||||
8759 | diag::note_array_init_plain_string_into_char8_t) | ||||||||||
8760 | << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8"); | ||||||||||
8761 | break; | ||||||||||
8762 | case FK_UTF8StringIntoPlainChar: | ||||||||||
8763 | S.Diag(Kind.getLocation(), | ||||||||||
8764 | diag::err_array_init_utf8_string_into_char) | ||||||||||
8765 | << S.getLangOpts().CPlusPlus2a; | ||||||||||
8766 | break; | ||||||||||
8767 | case FK_ArrayTypeMismatch: | ||||||||||
8768 | case FK_NonConstantArrayInit: | ||||||||||
8769 | S.Diag(Kind.getLocation(), | ||||||||||
8770 | (Failure == FK_ArrayTypeMismatch | ||||||||||
8771 | ? diag::err_array_init_different_type | ||||||||||
8772 | : diag::err_array_init_non_constant_array)) | ||||||||||
8773 | << DestType.getNonReferenceType() | ||||||||||
8774 | << OnlyArg->getType() | ||||||||||
8775 | << Args[0]->getSourceRange(); | ||||||||||
8776 | break; | ||||||||||
8777 | |||||||||||
8778 | case FK_VariableLengthArrayHasInitializer: | ||||||||||
8779 | S.Diag(Kind.getLocation(), diag::err_variable_object_no_init) | ||||||||||
8780 | << Args[0]->getSourceRange(); | ||||||||||
8781 | break; | ||||||||||
8782 | |||||||||||
8783 | case FK_AddressOfOverloadFailed: { | ||||||||||
8784 | DeclAccessPair Found; | ||||||||||
8785 | S.ResolveAddressOfOverloadedFunction(OnlyArg, | ||||||||||
8786 | DestType.getNonReferenceType(), | ||||||||||
8787 | true, | ||||||||||
8788 | Found); | ||||||||||
8789 | break; | ||||||||||
8790 | } | ||||||||||
8791 | |||||||||||
8792 | case FK_AddressOfUnaddressableFunction: { | ||||||||||
8793 | auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl()); | ||||||||||
8794 | S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, | ||||||||||
8795 | OnlyArg->getBeginLoc()); | ||||||||||
8796 | break; | ||||||||||
8797 | } | ||||||||||
8798 | |||||||||||
8799 | case FK_ReferenceInitOverloadFailed: | ||||||||||
8800 | case FK_UserConversionOverloadFailed: | ||||||||||
8801 | switch (FailedOverloadResult) { | ||||||||||
8802 | case OR_Ambiguous: | ||||||||||
8803 | |||||||||||
8804 | FailedCandidateSet.NoteCandidates( | ||||||||||
8805 | PartialDiagnosticAt( | ||||||||||
8806 | Kind.getLocation(), | ||||||||||
8807 | Failure == FK_UserConversionOverloadFailed | ||||||||||
8808 | ? (S.PDiag(diag::err_typecheck_ambiguous_condition) | ||||||||||
8809 | << OnlyArg->getType() << DestType | ||||||||||
8810 | << Args[0]->getSourceRange()) | ||||||||||
8811 | : (S.PDiag(diag::err_ref_init_ambiguous) | ||||||||||
8812 | << DestType << OnlyArg->getType() | ||||||||||
8813 | << Args[0]->getSourceRange())), | ||||||||||
8814 | S, OCD_AmbiguousCandidates, Args); | ||||||||||
8815 | break; | ||||||||||
8816 | |||||||||||
8817 | case OR_No_Viable_Function: { | ||||||||||
8818 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args); | ||||||||||
8819 | if (!S.RequireCompleteType(Kind.getLocation(), | ||||||||||
8820 | DestType.getNonReferenceType(), | ||||||||||
8821 | diag::err_typecheck_nonviable_condition_incomplete, | ||||||||||
8822 | OnlyArg->getType(), Args[0]->getSourceRange())) | ||||||||||
8823 | S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition) | ||||||||||
8824 | << (Entity.getKind() == InitializedEntity::EK_Result) | ||||||||||
8825 | << OnlyArg->getType() << Args[0]->getSourceRange() | ||||||||||
8826 | << DestType.getNonReferenceType(); | ||||||||||
8827 | |||||||||||
8828 | FailedCandidateSet.NoteCandidates(S, Args, Cands); | ||||||||||
8829 | break; | ||||||||||
8830 | } | ||||||||||
8831 | case OR_Deleted: { | ||||||||||
8832 | S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function) | ||||||||||
8833 | << OnlyArg->getType() << DestType.getNonReferenceType() | ||||||||||
8834 | << Args[0]->getSourceRange(); | ||||||||||
8835 | OverloadCandidateSet::iterator Best; | ||||||||||
8836 | OverloadingResult Ovl | ||||||||||
8837 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | ||||||||||
8838 | if (Ovl == OR_Deleted) { | ||||||||||
8839 | S.NoteDeletedFunction(Best->Function); | ||||||||||
8840 | } else { | ||||||||||
8841 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8841); | ||||||||||
8842 | } | ||||||||||
8843 | break; | ||||||||||
8844 | } | ||||||||||
8845 | |||||||||||
8846 | case OR_Success: | ||||||||||
8847 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8847); | ||||||||||
8848 | } | ||||||||||
8849 | break; | ||||||||||
8850 | |||||||||||
8851 | case FK_NonConstLValueReferenceBindingToTemporary: | ||||||||||
8852 | if (isa<InitListExpr>(Args[0])) { | ||||||||||
8853 | S.Diag(Kind.getLocation(), | ||||||||||
8854 | diag::err_lvalue_reference_bind_to_initlist) | ||||||||||
8855 | << DestType.getNonReferenceType().isVolatileQualified() | ||||||||||
8856 | << DestType.getNonReferenceType() | ||||||||||
8857 | << Args[0]->getSourceRange(); | ||||||||||
8858 | break; | ||||||||||
8859 | } | ||||||||||
8860 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
8861 | |||||||||||
8862 | case FK_NonConstLValueReferenceBindingToUnrelated: | ||||||||||
8863 | S.Diag(Kind.getLocation(), | ||||||||||
8864 | Failure == FK_NonConstLValueReferenceBindingToTemporary | ||||||||||
8865 | ? diag::err_lvalue_reference_bind_to_temporary | ||||||||||
8866 | : diag::err_lvalue_reference_bind_to_unrelated) | ||||||||||
8867 | << DestType.getNonReferenceType().isVolatileQualified() | ||||||||||
8868 | << DestType.getNonReferenceType() | ||||||||||
8869 | << OnlyArg->getType() | ||||||||||
8870 | << Args[0]->getSourceRange(); | ||||||||||
8871 | break; | ||||||||||
8872 | |||||||||||
8873 | case FK_NonConstLValueReferenceBindingToBitfield: { | ||||||||||
8874 | // We don't necessarily have an unambiguous source bit-field. | ||||||||||
8875 | FieldDecl *BitField = Args[0]->getSourceBitField(); | ||||||||||
8876 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield) | ||||||||||
8877 | << DestType.isVolatileQualified() | ||||||||||
8878 | << (BitField ? BitField->getDeclName() : DeclarationName()) | ||||||||||
8879 | << (BitField != nullptr) | ||||||||||
8880 | << Args[0]->getSourceRange(); | ||||||||||
8881 | if (BitField) | ||||||||||
8882 | S.Diag(BitField->getLocation(), diag::note_bitfield_decl); | ||||||||||
8883 | break; | ||||||||||
8884 | } | ||||||||||
8885 | |||||||||||
8886 | case FK_NonConstLValueReferenceBindingToVectorElement: | ||||||||||
8887 | S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element) | ||||||||||
8888 | << DestType.isVolatileQualified() | ||||||||||
8889 | << Args[0]->getSourceRange(); | ||||||||||
8890 | break; | ||||||||||
8891 | |||||||||||
8892 | case FK_RValueReferenceBindingToLValue: | ||||||||||
8893 | S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref) | ||||||||||
8894 | << DestType.getNonReferenceType() << OnlyArg->getType() | ||||||||||
8895 | << Args[0]->getSourceRange(); | ||||||||||
8896 | break; | ||||||||||
8897 | |||||||||||
8898 | case FK_ReferenceAddrspaceMismatchTemporary: | ||||||||||
8899 | S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace) | ||||||||||
8900 | << DestType << Args[0]->getSourceRange(); | ||||||||||
8901 | break; | ||||||||||
8902 | |||||||||||
8903 | case FK_ReferenceInitDropsQualifiers: { | ||||||||||
8904 | QualType SourceType = OnlyArg->getType(); | ||||||||||
8905 | QualType NonRefType = DestType.getNonReferenceType(); | ||||||||||
8906 | Qualifiers DroppedQualifiers = | ||||||||||
8907 | SourceType.getQualifiers() - NonRefType.getQualifiers(); | ||||||||||
8908 | |||||||||||
8909 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( | ||||||||||
8910 | SourceType.getQualifiers())) | ||||||||||
8911 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | ||||||||||
8912 | << NonRefType << SourceType << 1 /*addr space*/ | ||||||||||
8913 | << Args[0]->getSourceRange(); | ||||||||||
8914 | else if (DroppedQualifiers.hasQualifiers()) | ||||||||||
8915 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | ||||||||||
8916 | << NonRefType << SourceType << 0 /*cv quals*/ | ||||||||||
8917 | << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers()) | ||||||||||
8918 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); | ||||||||||
8919 | else | ||||||||||
8920 | // FIXME: Consider decomposing the type and explaining which qualifiers | ||||||||||
8921 | // were dropped where, or on which level a 'const' is missing, etc. | ||||||||||
8922 | S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals) | ||||||||||
8923 | << NonRefType << SourceType << 2 /*incompatible quals*/ | ||||||||||
8924 | << Args[0]->getSourceRange(); | ||||||||||
8925 | break; | ||||||||||
8926 | } | ||||||||||
8927 | |||||||||||
8928 | case FK_ReferenceInitFailed: | ||||||||||
8929 | S.Diag(Kind.getLocation(), diag::err_reference_bind_failed) | ||||||||||
8930 | << DestType.getNonReferenceType() | ||||||||||
8931 | << DestType.getNonReferenceType()->isIncompleteType() | ||||||||||
8932 | << OnlyArg->isLValue() | ||||||||||
8933 | << OnlyArg->getType() | ||||||||||
8934 | << Args[0]->getSourceRange(); | ||||||||||
8935 | emitBadConversionNotes(S, Entity, Args[0]); | ||||||||||
8936 | break; | ||||||||||
8937 | |||||||||||
8938 | case FK_ConversionFailed: { | ||||||||||
8939 | QualType FromType = OnlyArg->getType(); | ||||||||||
8940 | PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed) | ||||||||||
8941 | << (int)Entity.getKind() | ||||||||||
8942 | << DestType | ||||||||||
8943 | << OnlyArg->isLValue() | ||||||||||
8944 | << FromType | ||||||||||
8945 | << Args[0]->getSourceRange(); | ||||||||||
8946 | S.HandleFunctionTypeMismatch(PDiag, FromType, DestType); | ||||||||||
8947 | S.Diag(Kind.getLocation(), PDiag); | ||||||||||
8948 | emitBadConversionNotes(S, Entity, Args[0]); | ||||||||||
8949 | break; | ||||||||||
8950 | } | ||||||||||
8951 | |||||||||||
8952 | case FK_ConversionFromPropertyFailed: | ||||||||||
8953 | // No-op. This error has already been reported. | ||||||||||
8954 | break; | ||||||||||
8955 | |||||||||||
8956 | case FK_TooManyInitsForScalar: { | ||||||||||
8957 | SourceRange R; | ||||||||||
8958 | |||||||||||
8959 | auto *InitList = dyn_cast<InitListExpr>(Args[0]); | ||||||||||
8960 | if (InitList && InitList->getNumInits() >= 1) { | ||||||||||
8961 | R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc()); | ||||||||||
8962 | } else { | ||||||||||
8963 | assert(Args.size() > 1 && "Expected multiple initializers!")((Args.size() > 1 && "Expected multiple initializers!" ) ? static_cast<void> (0) : __assert_fail ("Args.size() > 1 && \"Expected multiple initializers!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 8963, __PRETTY_FUNCTION__)); | ||||||||||
8964 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); | ||||||||||
8965 | } | ||||||||||
8966 | |||||||||||
8967 | R.setBegin(S.getLocForEndOfToken(R.getBegin())); | ||||||||||
8968 | if (Kind.isCStyleOrFunctionalCast()) | ||||||||||
8969 | S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg) | ||||||||||
8970 | << R; | ||||||||||
8971 | else | ||||||||||
8972 | S.Diag(Kind.getLocation(), diag::err_excess_initializers) | ||||||||||
8973 | << /*scalar=*/2 << R; | ||||||||||
8974 | break; | ||||||||||
8975 | } | ||||||||||
8976 | |||||||||||
8977 | case FK_ParenthesizedListInitForScalar: | ||||||||||
8978 | S.Diag(Kind.getLocation(), diag::err_list_init_in_parens) | ||||||||||
8979 | << 0 << Entity.getType() << Args[0]->getSourceRange(); | ||||||||||
8980 | break; | ||||||||||
8981 | |||||||||||
8982 | case FK_ReferenceBindingToInitList: | ||||||||||
8983 | S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list) | ||||||||||
8984 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); | ||||||||||
8985 | break; | ||||||||||
8986 | |||||||||||
8987 | case FK_InitListBadDestinationType: | ||||||||||
8988 | S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type) | ||||||||||
8989 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); | ||||||||||
8990 | break; | ||||||||||
8991 | |||||||||||
8992 | case FK_ListConstructorOverloadFailed: | ||||||||||
8993 | case FK_ConstructorOverloadFailed: { | ||||||||||
8994 | SourceRange ArgsRange; | ||||||||||
8995 | if (Args.size()) | ||||||||||
8996 | ArgsRange = | ||||||||||
8997 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); | ||||||||||
8998 | |||||||||||
8999 | if (Failure == FK_ListConstructorOverloadFailed) { | ||||||||||
9000 | assert(Args.size() == 1 &&((Args.size() == 1 && "List construction from other than 1 argument." ) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9001, __PRETTY_FUNCTION__)) | ||||||||||
9001 | "List construction from other than 1 argument.")((Args.size() == 1 && "List construction from other than 1 argument." ) ? static_cast<void> (0) : __assert_fail ("Args.size() == 1 && \"List construction from other than 1 argument.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9001, __PRETTY_FUNCTION__)); | ||||||||||
9002 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||||||||
9003 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | ||||||||||
9004 | } | ||||||||||
9005 | |||||||||||
9006 | // FIXME: Using "DestType" for the entity we're printing is probably | ||||||||||
9007 | // bad. | ||||||||||
9008 | switch (FailedOverloadResult) { | ||||||||||
9009 | case OR_Ambiguous: | ||||||||||
9010 | FailedCandidateSet.NoteCandidates( | ||||||||||
9011 | PartialDiagnosticAt(Kind.getLocation(), | ||||||||||
9012 | S.PDiag(diag::err_ovl_ambiguous_init) | ||||||||||
9013 | << DestType << ArgsRange), | ||||||||||
9014 | S, OCD_AmbiguousCandidates, Args); | ||||||||||
9015 | break; | ||||||||||
9016 | |||||||||||
9017 | case OR_No_Viable_Function: | ||||||||||
9018 | if (Kind.getKind() == InitializationKind::IK_Default && | ||||||||||
9019 | (Entity.getKind() == InitializedEntity::EK_Base || | ||||||||||
9020 | Entity.getKind() == InitializedEntity::EK_Member) && | ||||||||||
9021 | isa<CXXConstructorDecl>(S.CurContext)) { | ||||||||||
9022 | // This is implicit default initialization of a member or | ||||||||||
9023 | // base within a constructor. If no viable function was | ||||||||||
9024 | // found, notify the user that they need to explicitly | ||||||||||
9025 | // initialize this base/member. | ||||||||||
9026 | CXXConstructorDecl *Constructor | ||||||||||
9027 | = cast<CXXConstructorDecl>(S.CurContext); | ||||||||||
9028 | const CXXRecordDecl *InheritedFrom = nullptr; | ||||||||||
9029 | if (auto Inherited = Constructor->getInheritedConstructor()) | ||||||||||
9030 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); | ||||||||||
9031 | if (Entity.getKind() == InitializedEntity::EK_Base) { | ||||||||||
9032 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | ||||||||||
9033 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | ||||||||||
9034 | << S.Context.getTypeDeclType(Constructor->getParent()) | ||||||||||
9035 | << /*base=*/0 | ||||||||||
9036 | << Entity.getType() | ||||||||||
9037 | << InheritedFrom; | ||||||||||
9038 | |||||||||||
9039 | RecordDecl *BaseDecl | ||||||||||
9040 | = Entity.getBaseSpecifier()->getType()->castAs<RecordType>() | ||||||||||
9041 | ->getDecl(); | ||||||||||
9042 | S.Diag(BaseDecl->getLocation(), diag::note_previous_decl) | ||||||||||
9043 | << S.Context.getTagDeclType(BaseDecl); | ||||||||||
9044 | } else { | ||||||||||
9045 | S.Diag(Kind.getLocation(), diag::err_missing_default_ctor) | ||||||||||
9046 | << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0) | ||||||||||
9047 | << S.Context.getTypeDeclType(Constructor->getParent()) | ||||||||||
9048 | << /*member=*/1 | ||||||||||
9049 | << Entity.getName() | ||||||||||
9050 | << InheritedFrom; | ||||||||||
9051 | S.Diag(Entity.getDecl()->getLocation(), | ||||||||||
9052 | diag::note_member_declared_at); | ||||||||||
9053 | |||||||||||
9054 | if (const RecordType *Record | ||||||||||
9055 | = Entity.getType()->getAs<RecordType>()) | ||||||||||
9056 | S.Diag(Record->getDecl()->getLocation(), | ||||||||||
9057 | diag::note_previous_decl) | ||||||||||
9058 | << S.Context.getTagDeclType(Record->getDecl()); | ||||||||||
9059 | } | ||||||||||
9060 | break; | ||||||||||
9061 | } | ||||||||||
9062 | |||||||||||
9063 | FailedCandidateSet.NoteCandidates( | ||||||||||
9064 | PartialDiagnosticAt( | ||||||||||
9065 | Kind.getLocation(), | ||||||||||
9066 | S.PDiag(diag::err_ovl_no_viable_function_in_init) | ||||||||||
9067 | << DestType << ArgsRange), | ||||||||||
9068 | S, OCD_AllCandidates, Args); | ||||||||||
9069 | break; | ||||||||||
9070 | |||||||||||
9071 | case OR_Deleted: { | ||||||||||
9072 | OverloadCandidateSet::iterator Best; | ||||||||||
9073 | OverloadingResult Ovl | ||||||||||
9074 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | ||||||||||
9075 | if (Ovl != OR_Deleted) { | ||||||||||
9076 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | ||||||||||
9077 | << DestType << ArgsRange; | ||||||||||
9078 | llvm_unreachable("Inconsistent overload resolution?")::llvm::llvm_unreachable_internal("Inconsistent overload resolution?" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9078); | ||||||||||
9079 | break; | ||||||||||
9080 | } | ||||||||||
9081 | |||||||||||
9082 | // If this is a defaulted or implicitly-declared function, then | ||||||||||
9083 | // it was implicitly deleted. Make it clear that the deletion was | ||||||||||
9084 | // implicit. | ||||||||||
9085 | if (S.isImplicitlyDeleted(Best->Function)) | ||||||||||
9086 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init) | ||||||||||
9087 | << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)) | ||||||||||
9088 | << DestType << ArgsRange; | ||||||||||
9089 | else | ||||||||||
9090 | S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init) | ||||||||||
9091 | << DestType << ArgsRange; | ||||||||||
9092 | |||||||||||
9093 | S.NoteDeletedFunction(Best->Function); | ||||||||||
9094 | break; | ||||||||||
9095 | } | ||||||||||
9096 | |||||||||||
9097 | case OR_Success: | ||||||||||
9098 | llvm_unreachable("Conversion did not fail!")::llvm::llvm_unreachable_internal("Conversion did not fail!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9098); | ||||||||||
9099 | } | ||||||||||
9100 | } | ||||||||||
9101 | break; | ||||||||||
9102 | |||||||||||
9103 | case FK_DefaultInitOfConst: | ||||||||||
9104 | if (Entity.getKind() == InitializedEntity::EK_Member && | ||||||||||
9105 | isa<CXXConstructorDecl>(S.CurContext)) { | ||||||||||
9106 | // This is implicit default-initialization of a const member in | ||||||||||
9107 | // a constructor. Complain that it needs to be explicitly | ||||||||||
9108 | // initialized. | ||||||||||
9109 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext); | ||||||||||
9110 | S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor) | ||||||||||
9111 | << (Constructor->getInheritedConstructor() ? 2 : | ||||||||||
9112 | Constructor->isImplicit() ? 1 : 0) | ||||||||||
9113 | << S.Context.getTypeDeclType(Constructor->getParent()) | ||||||||||
9114 | << /*const=*/1 | ||||||||||
9115 | << Entity.getName(); | ||||||||||
9116 | S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl) | ||||||||||
9117 | << Entity.getName(); | ||||||||||
9118 | } else { | ||||||||||
9119 | S.Diag(Kind.getLocation(), diag::err_default_init_const) | ||||||||||
9120 | << DestType << (bool)DestType->getAs<RecordType>(); | ||||||||||
9121 | } | ||||||||||
9122 | break; | ||||||||||
9123 | |||||||||||
9124 | case FK_Incomplete: | ||||||||||
9125 | S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType, | ||||||||||
9126 | diag::err_init_incomplete_type); | ||||||||||
9127 | break; | ||||||||||
9128 | |||||||||||
9129 | case FK_ListInitializationFailed: { | ||||||||||
9130 | // Run the init list checker again to emit diagnostics. | ||||||||||
9131 | InitListExpr *InitList = cast<InitListExpr>(Args[0]); | ||||||||||
9132 | diagnoseListInit(S, Entity, InitList); | ||||||||||
9133 | break; | ||||||||||
9134 | } | ||||||||||
9135 | |||||||||||
9136 | case FK_PlaceholderType: { | ||||||||||
9137 | // FIXME: Already diagnosed! | ||||||||||
9138 | break; | ||||||||||
9139 | } | ||||||||||
9140 | |||||||||||
9141 | case FK_ExplicitConstructor: { | ||||||||||
9142 | S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor) | ||||||||||
9143 | << Args[0]->getSourceRange(); | ||||||||||
9144 | OverloadCandidateSet::iterator Best; | ||||||||||
9145 | OverloadingResult Ovl | ||||||||||
9146 | = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best); | ||||||||||
9147 | (void)Ovl; | ||||||||||
9148 | assert(Ovl == OR_Success && "Inconsistent overload resolution")((Ovl == OR_Success && "Inconsistent overload resolution" ) ? static_cast<void> (0) : __assert_fail ("Ovl == OR_Success && \"Inconsistent overload resolution\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9148, __PRETTY_FUNCTION__)); | ||||||||||
9149 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function); | ||||||||||
9150 | S.Diag(CtorDecl->getLocation(), | ||||||||||
9151 | diag::note_explicit_ctor_deduction_guide_here) << false; | ||||||||||
9152 | break; | ||||||||||
9153 | } | ||||||||||
9154 | } | ||||||||||
9155 | |||||||||||
9156 | PrintInitLocationNote(S, Entity); | ||||||||||
9157 | return true; | ||||||||||
9158 | } | ||||||||||
9159 | |||||||||||
9160 | void InitializationSequence::dump(raw_ostream &OS) const { | ||||||||||
9161 | switch (SequenceKind) { | ||||||||||
9162 | case FailedSequence: { | ||||||||||
9163 | OS << "Failed sequence: "; | ||||||||||
9164 | switch (Failure) { | ||||||||||
9165 | case FK_TooManyInitsForReference: | ||||||||||
9166 | OS << "too many initializers for reference"; | ||||||||||
9167 | break; | ||||||||||
9168 | |||||||||||
9169 | case FK_ParenthesizedListInitForReference: | ||||||||||
9170 | OS << "parenthesized list init for reference"; | ||||||||||
9171 | break; | ||||||||||
9172 | |||||||||||
9173 | case FK_ArrayNeedsInitList: | ||||||||||
9174 | OS << "array requires initializer list"; | ||||||||||
9175 | break; | ||||||||||
9176 | |||||||||||
9177 | case FK_AddressOfUnaddressableFunction: | ||||||||||
9178 | OS << "address of unaddressable function was taken"; | ||||||||||
9179 | break; | ||||||||||
9180 | |||||||||||
9181 | case FK_ArrayNeedsInitListOrStringLiteral: | ||||||||||
9182 | OS << "array requires initializer list or string literal"; | ||||||||||
9183 | break; | ||||||||||
9184 | |||||||||||
9185 | case FK_ArrayNeedsInitListOrWideStringLiteral: | ||||||||||
9186 | OS << "array requires initializer list or wide string literal"; | ||||||||||
9187 | break; | ||||||||||
9188 | |||||||||||
9189 | case FK_NarrowStringIntoWideCharArray: | ||||||||||
9190 | OS << "narrow string into wide char array"; | ||||||||||
9191 | break; | ||||||||||
9192 | |||||||||||
9193 | case FK_WideStringIntoCharArray: | ||||||||||
9194 | OS << "wide string into char array"; | ||||||||||
9195 | break; | ||||||||||
9196 | |||||||||||
9197 | case FK_IncompatWideStringIntoWideChar: | ||||||||||
9198 | OS << "incompatible wide string into wide char array"; | ||||||||||
9199 | break; | ||||||||||
9200 | |||||||||||
9201 | case FK_PlainStringIntoUTF8Char: | ||||||||||
9202 | OS << "plain string literal into char8_t array"; | ||||||||||
9203 | break; | ||||||||||
9204 | |||||||||||
9205 | case FK_UTF8StringIntoPlainChar: | ||||||||||
9206 | OS << "u8 string literal into char array"; | ||||||||||
9207 | break; | ||||||||||
9208 | |||||||||||
9209 | case FK_ArrayTypeMismatch: | ||||||||||
9210 | OS << "array type mismatch"; | ||||||||||
9211 | break; | ||||||||||
9212 | |||||||||||
9213 | case FK_NonConstantArrayInit: | ||||||||||
9214 | OS << "non-constant array initializer"; | ||||||||||
9215 | break; | ||||||||||
9216 | |||||||||||
9217 | case FK_AddressOfOverloadFailed: | ||||||||||
9218 | OS << "address of overloaded function failed"; | ||||||||||
9219 | break; | ||||||||||
9220 | |||||||||||
9221 | case FK_ReferenceInitOverloadFailed: | ||||||||||
9222 | OS << "overload resolution for reference initialization failed"; | ||||||||||
9223 | break; | ||||||||||
9224 | |||||||||||
9225 | case FK_NonConstLValueReferenceBindingToTemporary: | ||||||||||
9226 | OS << "non-const lvalue reference bound to temporary"; | ||||||||||
9227 | break; | ||||||||||
9228 | |||||||||||
9229 | case FK_NonConstLValueReferenceBindingToBitfield: | ||||||||||
9230 | OS << "non-const lvalue reference bound to bit-field"; | ||||||||||
9231 | break; | ||||||||||
9232 | |||||||||||
9233 | case FK_NonConstLValueReferenceBindingToVectorElement: | ||||||||||
9234 | OS << "non-const lvalue reference bound to vector element"; | ||||||||||
9235 | break; | ||||||||||
9236 | |||||||||||
9237 | case FK_NonConstLValueReferenceBindingToUnrelated: | ||||||||||
9238 | OS << "non-const lvalue reference bound to unrelated type"; | ||||||||||
9239 | break; | ||||||||||
9240 | |||||||||||
9241 | case FK_RValueReferenceBindingToLValue: | ||||||||||
9242 | OS << "rvalue reference bound to an lvalue"; | ||||||||||
9243 | break; | ||||||||||
9244 | |||||||||||
9245 | case FK_ReferenceInitDropsQualifiers: | ||||||||||
9246 | OS << "reference initialization drops qualifiers"; | ||||||||||
9247 | break; | ||||||||||
9248 | |||||||||||
9249 | case FK_ReferenceAddrspaceMismatchTemporary: | ||||||||||
9250 | OS << "reference with mismatching address space bound to temporary"; | ||||||||||
9251 | break; | ||||||||||
9252 | |||||||||||
9253 | case FK_ReferenceInitFailed: | ||||||||||
9254 | OS << "reference initialization failed"; | ||||||||||
9255 | break; | ||||||||||
9256 | |||||||||||
9257 | case FK_ConversionFailed: | ||||||||||
9258 | OS << "conversion failed"; | ||||||||||
9259 | break; | ||||||||||
9260 | |||||||||||
9261 | case FK_ConversionFromPropertyFailed: | ||||||||||
9262 | OS << "conversion from property failed"; | ||||||||||
9263 | break; | ||||||||||
9264 | |||||||||||
9265 | case FK_TooManyInitsForScalar: | ||||||||||
9266 | OS << "too many initializers for scalar"; | ||||||||||
9267 | break; | ||||||||||
9268 | |||||||||||
9269 | case FK_ParenthesizedListInitForScalar: | ||||||||||
9270 | OS << "parenthesized list init for reference"; | ||||||||||
9271 | break; | ||||||||||
9272 | |||||||||||
9273 | case FK_ReferenceBindingToInitList: | ||||||||||
9274 | OS << "referencing binding to initializer list"; | ||||||||||
9275 | break; | ||||||||||
9276 | |||||||||||
9277 | case FK_InitListBadDestinationType: | ||||||||||
9278 | OS << "initializer list for non-aggregate, non-scalar type"; | ||||||||||
9279 | break; | ||||||||||
9280 | |||||||||||
9281 | case FK_UserConversionOverloadFailed: | ||||||||||
9282 | OS << "overloading failed for user-defined conversion"; | ||||||||||
9283 | break; | ||||||||||
9284 | |||||||||||
9285 | case FK_ConstructorOverloadFailed: | ||||||||||
9286 | OS << "constructor overloading failed"; | ||||||||||
9287 | break; | ||||||||||
9288 | |||||||||||
9289 | case FK_DefaultInitOfConst: | ||||||||||
9290 | OS << "default initialization of a const variable"; | ||||||||||
9291 | break; | ||||||||||
9292 | |||||||||||
9293 | case FK_Incomplete: | ||||||||||
9294 | OS << "initialization of incomplete type"; | ||||||||||
9295 | break; | ||||||||||
9296 | |||||||||||
9297 | case FK_ListInitializationFailed: | ||||||||||
9298 | OS << "list initialization checker failure"; | ||||||||||
9299 | break; | ||||||||||
9300 | |||||||||||
9301 | case FK_VariableLengthArrayHasInitializer: | ||||||||||
9302 | OS << "variable length array has an initializer"; | ||||||||||
9303 | break; | ||||||||||
9304 | |||||||||||
9305 | case FK_PlaceholderType: | ||||||||||
9306 | OS << "initializer expression isn't contextually valid"; | ||||||||||
9307 | break; | ||||||||||
9308 | |||||||||||
9309 | case FK_ListConstructorOverloadFailed: | ||||||||||
9310 | OS << "list constructor overloading failed"; | ||||||||||
9311 | break; | ||||||||||
9312 | |||||||||||
9313 | case FK_ExplicitConstructor: | ||||||||||
9314 | OS << "list copy initialization chose explicit constructor"; | ||||||||||
9315 | break; | ||||||||||
9316 | } | ||||||||||
9317 | OS << '\n'; | ||||||||||
9318 | return; | ||||||||||
9319 | } | ||||||||||
9320 | |||||||||||
9321 | case DependentSequence: | ||||||||||
9322 | OS << "Dependent sequence\n"; | ||||||||||
9323 | return; | ||||||||||
9324 | |||||||||||
9325 | case NormalSequence: | ||||||||||
9326 | OS << "Normal sequence: "; | ||||||||||
9327 | break; | ||||||||||
9328 | } | ||||||||||
9329 | |||||||||||
9330 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { | ||||||||||
9331 | if (S != step_begin()) { | ||||||||||
9332 | OS << " -> "; | ||||||||||
9333 | } | ||||||||||
9334 | |||||||||||
9335 | switch (S->Kind) { | ||||||||||
9336 | case SK_ResolveAddressOfOverloadedFunction: | ||||||||||
9337 | OS << "resolve address of overloaded function"; | ||||||||||
9338 | break; | ||||||||||
9339 | |||||||||||
9340 | case SK_CastDerivedToBaseRValue: | ||||||||||
9341 | OS << "derived-to-base (rvalue)"; | ||||||||||
9342 | break; | ||||||||||
9343 | |||||||||||
9344 | case SK_CastDerivedToBaseXValue: | ||||||||||
9345 | OS << "derived-to-base (xvalue)"; | ||||||||||
9346 | break; | ||||||||||
9347 | |||||||||||
9348 | case SK_CastDerivedToBaseLValue: | ||||||||||
9349 | OS << "derived-to-base (lvalue)"; | ||||||||||
9350 | break; | ||||||||||
9351 | |||||||||||
9352 | case SK_BindReference: | ||||||||||
9353 | OS << "bind reference to lvalue"; | ||||||||||
9354 | break; | ||||||||||
9355 | |||||||||||
9356 | case SK_BindReferenceToTemporary: | ||||||||||
9357 | OS << "bind reference to a temporary"; | ||||||||||
9358 | break; | ||||||||||
9359 | |||||||||||
9360 | case SK_FinalCopy: | ||||||||||
9361 | OS << "final copy in class direct-initialization"; | ||||||||||
9362 | break; | ||||||||||
9363 | |||||||||||
9364 | case SK_ExtraneousCopyToTemporary: | ||||||||||
9365 | OS << "extraneous C++03 copy to temporary"; | ||||||||||
9366 | break; | ||||||||||
9367 | |||||||||||
9368 | case SK_UserConversion: | ||||||||||
9369 | OS << "user-defined conversion via " << *S->Function.Function; | ||||||||||
9370 | break; | ||||||||||
9371 | |||||||||||
9372 | case SK_QualificationConversionRValue: | ||||||||||
9373 | OS << "qualification conversion (rvalue)"; | ||||||||||
9374 | break; | ||||||||||
9375 | |||||||||||
9376 | case SK_QualificationConversionXValue: | ||||||||||
9377 | OS << "qualification conversion (xvalue)"; | ||||||||||
9378 | break; | ||||||||||
9379 | |||||||||||
9380 | case SK_QualificationConversionLValue: | ||||||||||
9381 | OS << "qualification conversion (lvalue)"; | ||||||||||
9382 | break; | ||||||||||
9383 | |||||||||||
9384 | case SK_AtomicConversion: | ||||||||||
9385 | OS << "non-atomic-to-atomic conversion"; | ||||||||||
9386 | break; | ||||||||||
9387 | |||||||||||
9388 | case SK_ConversionSequence: | ||||||||||
9389 | OS << "implicit conversion sequence ("; | ||||||||||
9390 | S->ICS->dump(); // FIXME: use OS | ||||||||||
9391 | OS << ")"; | ||||||||||
9392 | break; | ||||||||||
9393 | |||||||||||
9394 | case SK_ConversionSequenceNoNarrowing: | ||||||||||
9395 | OS << "implicit conversion sequence with narrowing prohibited ("; | ||||||||||
9396 | S->ICS->dump(); // FIXME: use OS | ||||||||||
9397 | OS << ")"; | ||||||||||
9398 | break; | ||||||||||
9399 | |||||||||||
9400 | case SK_ListInitialization: | ||||||||||
9401 | OS << "list aggregate initialization"; | ||||||||||
9402 | break; | ||||||||||
9403 | |||||||||||
9404 | case SK_UnwrapInitList: | ||||||||||
9405 | OS << "unwrap reference initializer list"; | ||||||||||
9406 | break; | ||||||||||
9407 | |||||||||||
9408 | case SK_RewrapInitList: | ||||||||||
9409 | OS << "rewrap reference initializer list"; | ||||||||||
9410 | break; | ||||||||||
9411 | |||||||||||
9412 | case SK_ConstructorInitialization: | ||||||||||
9413 | OS << "constructor initialization"; | ||||||||||
9414 | break; | ||||||||||
9415 | |||||||||||
9416 | case SK_ConstructorInitializationFromList: | ||||||||||
9417 | OS << "list initialization via constructor"; | ||||||||||
9418 | break; | ||||||||||
9419 | |||||||||||
9420 | case SK_ZeroInitialization: | ||||||||||
9421 | OS << "zero initialization"; | ||||||||||
9422 | break; | ||||||||||
9423 | |||||||||||
9424 | case SK_CAssignment: | ||||||||||
9425 | OS << "C assignment"; | ||||||||||
9426 | break; | ||||||||||
9427 | |||||||||||
9428 | case SK_StringInit: | ||||||||||
9429 | OS << "string initialization"; | ||||||||||
9430 | break; | ||||||||||
9431 | |||||||||||
9432 | case SK_ObjCObjectConversion: | ||||||||||
9433 | OS << "Objective-C object conversion"; | ||||||||||
9434 | break; | ||||||||||
9435 | |||||||||||
9436 | case SK_ArrayLoopIndex: | ||||||||||
9437 | OS << "indexing for array initialization loop"; | ||||||||||
9438 | break; | ||||||||||
9439 | |||||||||||
9440 | case SK_ArrayLoopInit: | ||||||||||
9441 | OS << "array initialization loop"; | ||||||||||
9442 | break; | ||||||||||
9443 | |||||||||||
9444 | case SK_ArrayInit: | ||||||||||
9445 | OS << "array initialization"; | ||||||||||
9446 | break; | ||||||||||
9447 | |||||||||||
9448 | case SK_GNUArrayInit: | ||||||||||
9449 | OS << "array initialization (GNU extension)"; | ||||||||||
9450 | break; | ||||||||||
9451 | |||||||||||
9452 | case SK_ParenthesizedArrayInit: | ||||||||||
9453 | OS << "parenthesized array initialization"; | ||||||||||
9454 | break; | ||||||||||
9455 | |||||||||||
9456 | case SK_PassByIndirectCopyRestore: | ||||||||||
9457 | OS << "pass by indirect copy and restore"; | ||||||||||
9458 | break; | ||||||||||
9459 | |||||||||||
9460 | case SK_PassByIndirectRestore: | ||||||||||
9461 | OS << "pass by indirect restore"; | ||||||||||
9462 | break; | ||||||||||
9463 | |||||||||||
9464 | case SK_ProduceObjCObject: | ||||||||||
9465 | OS << "Objective-C object retension"; | ||||||||||
9466 | break; | ||||||||||
9467 | |||||||||||
9468 | case SK_StdInitializerList: | ||||||||||
9469 | OS << "std::initializer_list from initializer list"; | ||||||||||
9470 | break; | ||||||||||
9471 | |||||||||||
9472 | case SK_StdInitializerListConstructorCall: | ||||||||||
9473 | OS << "list initialization from std::initializer_list"; | ||||||||||
9474 | break; | ||||||||||
9475 | |||||||||||
9476 | case SK_OCLSamplerInit: | ||||||||||
9477 | OS << "OpenCL sampler_t from integer constant"; | ||||||||||
9478 | break; | ||||||||||
9479 | |||||||||||
9480 | case SK_OCLZeroOpaqueType: | ||||||||||
9481 | OS << "OpenCL opaque type from zero"; | ||||||||||
9482 | break; | ||||||||||
9483 | } | ||||||||||
9484 | |||||||||||
9485 | OS << " [" << S->Type.getAsString() << ']'; | ||||||||||
9486 | } | ||||||||||
9487 | |||||||||||
9488 | OS << '\n'; | ||||||||||
9489 | } | ||||||||||
9490 | |||||||||||
9491 | void InitializationSequence::dump() const { | ||||||||||
9492 | dump(llvm::errs()); | ||||||||||
9493 | } | ||||||||||
9494 | |||||||||||
9495 | static bool NarrowingErrs(const LangOptions &L) { | ||||||||||
9496 | return L.CPlusPlus11 && | ||||||||||
9497 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)); | ||||||||||
9498 | } | ||||||||||
9499 | |||||||||||
9500 | static void DiagnoseNarrowingInInitList(Sema &S, | ||||||||||
9501 | const ImplicitConversionSequence &ICS, | ||||||||||
9502 | QualType PreNarrowingType, | ||||||||||
9503 | QualType EntityType, | ||||||||||
9504 | const Expr *PostInit) { | ||||||||||
9505 | const StandardConversionSequence *SCS = nullptr; | ||||||||||
9506 | switch (ICS.getKind()) { | ||||||||||
9507 | case ImplicitConversionSequence::StandardConversion: | ||||||||||
9508 | SCS = &ICS.Standard; | ||||||||||
9509 | break; | ||||||||||
9510 | case ImplicitConversionSequence::UserDefinedConversion: | ||||||||||
9511 | SCS = &ICS.UserDefined.After; | ||||||||||
9512 | break; | ||||||||||
9513 | case ImplicitConversionSequence::AmbiguousConversion: | ||||||||||
9514 | case ImplicitConversionSequence::EllipsisConversion: | ||||||||||
9515 | case ImplicitConversionSequence::BadConversion: | ||||||||||
9516 | return; | ||||||||||
9517 | } | ||||||||||
9518 | |||||||||||
9519 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. | ||||||||||
9520 | APValue ConstantValue; | ||||||||||
9521 | QualType ConstantType; | ||||||||||
9522 | switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue, | ||||||||||
9523 | ConstantType)) { | ||||||||||
9524 | case NK_Not_Narrowing: | ||||||||||
9525 | case NK_Dependent_Narrowing: | ||||||||||
9526 | // No narrowing occurred. | ||||||||||
9527 | return; | ||||||||||
9528 | |||||||||||
9529 | case NK_Type_Narrowing: | ||||||||||
9530 | // This was a floating-to-integer conversion, which is always considered a | ||||||||||
9531 | // narrowing conversion even if the value is a constant and can be | ||||||||||
9532 | // represented exactly as an integer. | ||||||||||
9533 | S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts()) | ||||||||||
9534 | ? diag::ext_init_list_type_narrowing | ||||||||||
9535 | : diag::warn_init_list_type_narrowing) | ||||||||||
9536 | << PostInit->getSourceRange() | ||||||||||
9537 | << PreNarrowingType.getLocalUnqualifiedType() | ||||||||||
9538 | << EntityType.getLocalUnqualifiedType(); | ||||||||||
9539 | break; | ||||||||||
9540 | |||||||||||
9541 | case NK_Constant_Narrowing: | ||||||||||
9542 | // A constant value was narrowed. | ||||||||||
9543 | S.Diag(PostInit->getBeginLoc(), | ||||||||||
9544 | NarrowingErrs(S.getLangOpts()) | ||||||||||
9545 | ? diag::ext_init_list_constant_narrowing | ||||||||||
9546 | : diag::warn_init_list_constant_narrowing) | ||||||||||
9547 | << PostInit->getSourceRange() | ||||||||||
9548 | << ConstantValue.getAsString(S.getASTContext(), ConstantType) | ||||||||||
9549 | << EntityType.getLocalUnqualifiedType(); | ||||||||||
9550 | break; | ||||||||||
9551 | |||||||||||
9552 | case NK_Variable_Narrowing: | ||||||||||
9553 | // A variable's value may have been narrowed. | ||||||||||
9554 | S.Diag(PostInit->getBeginLoc(), | ||||||||||
9555 | NarrowingErrs(S.getLangOpts()) | ||||||||||
9556 | ? diag::ext_init_list_variable_narrowing | ||||||||||
9557 | : diag::warn_init_list_variable_narrowing) | ||||||||||
9558 | << PostInit->getSourceRange() | ||||||||||
9559 | << PreNarrowingType.getLocalUnqualifiedType() | ||||||||||
9560 | << EntityType.getLocalUnqualifiedType(); | ||||||||||
9561 | break; | ||||||||||
9562 | } | ||||||||||
9563 | |||||||||||
9564 | SmallString<128> StaticCast; | ||||||||||
9565 | llvm::raw_svector_ostream OS(StaticCast); | ||||||||||
9566 | OS << "static_cast<"; | ||||||||||
9567 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { | ||||||||||
9568 | // It's important to use the typedef's name if there is one so that the | ||||||||||
9569 | // fixit doesn't break code using types like int64_t. | ||||||||||
9570 | // | ||||||||||
9571 | // FIXME: This will break if the typedef requires qualification. But | ||||||||||
9572 | // getQualifiedNameAsString() includes non-machine-parsable components. | ||||||||||
9573 | OS << *TT->getDecl(); | ||||||||||
9574 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) | ||||||||||
9575 | OS << BT->getName(S.getLangOpts()); | ||||||||||
9576 | else { | ||||||||||
9577 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit | ||||||||||
9578 | // with a broken cast. | ||||||||||
9579 | return; | ||||||||||
9580 | } | ||||||||||
9581 | OS << ">("; | ||||||||||
9582 | S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence) | ||||||||||
9583 | << PostInit->getSourceRange() | ||||||||||
9584 | << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str()) | ||||||||||
9585 | << FixItHint::CreateInsertion( | ||||||||||
9586 | S.getLocForEndOfToken(PostInit->getEndLoc()), ")"); | ||||||||||
9587 | } | ||||||||||
9588 | |||||||||||
9589 | //===----------------------------------------------------------------------===// | ||||||||||
9590 | // Initialization helper functions | ||||||||||
9591 | //===----------------------------------------------------------------------===// | ||||||||||
9592 | bool | ||||||||||
9593 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, | ||||||||||
9594 | ExprResult Init) { | ||||||||||
9595 | if (Init.isInvalid()) | ||||||||||
9596 | return false; | ||||||||||
9597 | |||||||||||
9598 | Expr *InitE = Init.get(); | ||||||||||
9599 | assert(InitE && "No initialization expression")((InitE && "No initialization expression") ? static_cast <void> (0) : __assert_fail ("InitE && \"No initialization expression\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9599, __PRETTY_FUNCTION__)); | ||||||||||
9600 | |||||||||||
9601 | InitializationKind Kind = | ||||||||||
9602 | InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation()); | ||||||||||
9603 | InitializationSequence Seq(*this, Entity, Kind, InitE); | ||||||||||
9604 | return !Seq.Failed(); | ||||||||||
9605 | } | ||||||||||
9606 | |||||||||||
9607 | ExprResult | ||||||||||
9608 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, | ||||||||||
9609 | SourceLocation EqualLoc, | ||||||||||
9610 | ExprResult Init, | ||||||||||
9611 | bool TopLevelOfInitList, | ||||||||||
9612 | bool AllowExplicit) { | ||||||||||
9613 | if (Init.isInvalid()) | ||||||||||
9614 | return ExprError(); | ||||||||||
9615 | |||||||||||
9616 | Expr *InitE = Init.get(); | ||||||||||
9617 | assert(InitE && "No initialization expression?")((InitE && "No initialization expression?") ? static_cast <void> (0) : __assert_fail ("InitE && \"No initialization expression?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9617, __PRETTY_FUNCTION__)); | ||||||||||
9618 | |||||||||||
9619 | if (EqualLoc.isInvalid()) | ||||||||||
9620 | EqualLoc = InitE->getBeginLoc(); | ||||||||||
9621 | |||||||||||
9622 | InitializationKind Kind = InitializationKind::CreateCopy( | ||||||||||
9623 | InitE->getBeginLoc(), EqualLoc, AllowExplicit); | ||||||||||
9624 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); | ||||||||||
9625 | |||||||||||
9626 | // Prevent infinite recursion when performing parameter copy-initialization. | ||||||||||
9627 | const bool ShouldTrackCopy = | ||||||||||
9628 | Entity.isParameterKind() && Seq.isConstructorInitialization(); | ||||||||||
9629 | if (ShouldTrackCopy) { | ||||||||||
9630 | if (llvm::find(CurrentParameterCopyTypes, Entity.getType()) != | ||||||||||
9631 | CurrentParameterCopyTypes.end()) { | ||||||||||
9632 | Seq.SetOverloadFailure( | ||||||||||
9633 | InitializationSequence::FK_ConstructorOverloadFailed, | ||||||||||
9634 | OR_No_Viable_Function); | ||||||||||
9635 | |||||||||||
9636 | // Try to give a meaningful diagnostic note for the problematic | ||||||||||
9637 | // constructor. | ||||||||||
9638 | const auto LastStep = Seq.step_end() - 1; | ||||||||||
9639 | assert(LastStep->Kind ==((LastStep->Kind == InitializationSequence::SK_ConstructorInitialization ) ? static_cast<void> (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9640, __PRETTY_FUNCTION__)) | ||||||||||
9640 | InitializationSequence::SK_ConstructorInitialization)((LastStep->Kind == InitializationSequence::SK_ConstructorInitialization ) ? static_cast<void> (0) : __assert_fail ("LastStep->Kind == InitializationSequence::SK_ConstructorInitialization" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9640, __PRETTY_FUNCTION__)); | ||||||||||
9641 | const FunctionDecl *Function = LastStep->Function.Function; | ||||||||||
9642 | auto Candidate = | ||||||||||
9643 | llvm::find_if(Seq.getFailedCandidateSet(), | ||||||||||
9644 | [Function](const OverloadCandidate &Candidate) -> bool { | ||||||||||
9645 | return Candidate.Viable && | ||||||||||
9646 | Candidate.Function == Function && | ||||||||||
9647 | Candidate.Conversions.size() > 0; | ||||||||||
9648 | }); | ||||||||||
9649 | if (Candidate != Seq.getFailedCandidateSet().end() && | ||||||||||
9650 | Function->getNumParams() > 0) { | ||||||||||
9651 | Candidate->Viable = false; | ||||||||||
9652 | Candidate->FailureKind = ovl_fail_bad_conversion; | ||||||||||
9653 | Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion, | ||||||||||
9654 | InitE, | ||||||||||
9655 | Function->getParamDecl(0)->getType()); | ||||||||||
9656 | } | ||||||||||
9657 | } | ||||||||||
9658 | CurrentParameterCopyTypes.push_back(Entity.getType()); | ||||||||||
9659 | } | ||||||||||
9660 | |||||||||||
9661 | ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE); | ||||||||||
9662 | |||||||||||
9663 | if (ShouldTrackCopy) | ||||||||||
9664 | CurrentParameterCopyTypes.pop_back(); | ||||||||||
9665 | |||||||||||
9666 | return Result; | ||||||||||
9667 | } | ||||||||||
9668 | |||||||||||
9669 | /// Determine whether RD is, or is derived from, a specialization of CTD. | ||||||||||
9670 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, | ||||||||||
9671 | ClassTemplateDecl *CTD) { | ||||||||||
9672 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { | ||||||||||
9673 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate); | ||||||||||
9674 | return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD); | ||||||||||
9675 | }; | ||||||||||
9676 | return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization)); | ||||||||||
9677 | } | ||||||||||
9678 | |||||||||||
9679 | QualType Sema::DeduceTemplateSpecializationFromInitializer( | ||||||||||
9680 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, | ||||||||||
9681 | const InitializationKind &Kind, MultiExprArg Inits) { | ||||||||||
9682 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( | ||||||||||
9683 | TSInfo->getType()->getContainedDeducedType()); | ||||||||||
9684 | assert(DeducedTST && "not a deduced template specialization type")((DeducedTST && "not a deduced template specialization type" ) ? static_cast<void> (0) : __assert_fail ("DeducedTST && \"not a deduced template specialization type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaInit.cpp" , 9684, __PRETTY_FUNCTION__)); | ||||||||||
9685 | |||||||||||
9686 | auto TemplateName = DeducedTST->getTemplateName(); | ||||||||||
9687 | if (TemplateName.isDependent()) | ||||||||||
9688 | return Context.DependentTy; | ||||||||||
9689 | |||||||||||
9690 | // We can only perform deduction for class templates. | ||||||||||
9691 | auto *Template = | ||||||||||
9692 | dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl()); | ||||||||||
9693 | if (!Template) { | ||||||||||
9694 | Diag(Kind.getLocation(), | ||||||||||
9695 | diag::err_deduced_non_class_template_specialization_type) | ||||||||||
9696 | << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName; | ||||||||||
9697 | if (auto *TD = TemplateName.getAsTemplateDecl()) | ||||||||||
9698 | Diag(TD->getLocation(), diag::note_template_decl_here); | ||||||||||
9699 | return QualType(); | ||||||||||
9700 | } | ||||||||||
9701 | |||||||||||
9702 | // Can't deduce from dependent arguments. | ||||||||||
9703 | if (Expr::hasAnyTypeDependentArguments(Inits)) { | ||||||||||
9704 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | ||||||||||
9705 | diag::warn_cxx14_compat_class_template_argument_deduction) | ||||||||||
9706 | << TSInfo->getTypeLoc().getSourceRange() << 0; | ||||||||||
9707 | return Context.DependentTy; | ||||||||||
9708 | } | ||||||||||
9709 | |||||||||||
9710 | // FIXME: Perform "exact type" matching first, per CWG discussion? | ||||||||||
9711 | // Or implement this via an implied 'T(T) -> T' deduction guide? | ||||||||||
9712 | |||||||||||
9713 | // FIXME: Do we need/want a std::initializer_list<T> special case? | ||||||||||
9714 | |||||||||||
9715 | // Look up deduction guides, including those synthesized from constructors. | ||||||||||
9716 | // | ||||||||||
9717 | // C++1z [over.match.class.deduct]p1: | ||||||||||
9718 | // A set of functions and function templates is formed comprising: | ||||||||||
9719 | // - For each constructor of the class template designated by the | ||||||||||
9720 | // template-name, a function template [...] | ||||||||||
9721 | // - For each deduction-guide, a function or function template [...] | ||||||||||
9722 | DeclarationNameInfo NameInfo( | ||||||||||
9723 | Context.DeclarationNames.getCXXDeductionGuideName(Template), | ||||||||||
9724 | TSInfo->getTypeLoc().getEndLoc()); | ||||||||||
9725 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); | ||||||||||
9726 | LookupQualifiedName(Guides, Template->getDeclContext()); | ||||||||||
9727 | |||||||||||
9728 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't | ||||||||||
9729 | // clear on this, but they're not found by name so access does not apply. | ||||||||||
9730 | Guides.suppressDiagnostics(); | ||||||||||
9731 | |||||||||||
9732 | // Figure out if this is list-initialization. | ||||||||||
9733 | InitListExpr *ListInit = | ||||||||||
9734 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) | ||||||||||
9735 | ? dyn_cast<InitListExpr>(Inits[0]) | ||||||||||
9736 | : nullptr; | ||||||||||
9737 | |||||||||||
9738 | // C++1z [over.match.class.deduct]p1: | ||||||||||
9739 | // Initialization and overload resolution are performed as described in | ||||||||||
9740 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] | ||||||||||
9741 | // (as appropriate for the type of initialization performed) for an object | ||||||||||
9742 | // of a hypothetical class type, where the selected functions and function | ||||||||||
9743 | // templates are considered to be the constructors of that class type | ||||||||||
9744 | // | ||||||||||
9745 | // Since we know we're initializing a class type of a type unrelated to that | ||||||||||
9746 | // of the initializer, this reduces to something fairly reasonable. | ||||||||||
9747 | OverloadCandidateSet Candidates(Kind.getLocation(), | ||||||||||
9748 | OverloadCandidateSet::CSK_Normal); | ||||||||||
9749 | OverloadCandidateSet::iterator Best; | ||||||||||
9750 | |||||||||||
9751 | bool HasAnyDeductionGuide = false; | ||||||||||
9752 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; | ||||||||||
9753 | |||||||||||
9754 | auto tryToResolveOverload = | ||||||||||
9755 | [&](bool OnlyListConstructors) -> OverloadingResult { | ||||||||||
9756 | Candidates.clear(OverloadCandidateSet::CSK_Normal); | ||||||||||
9757 | HasAnyDeductionGuide = false; | ||||||||||
9758 | |||||||||||
9759 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { | ||||||||||
9760 | NamedDecl *D = (*I)->getUnderlyingDecl(); | ||||||||||
9761 | if (D->isInvalidDecl()) | ||||||||||
9762 | continue; | ||||||||||
9763 | |||||||||||
9764 | auto *TD = dyn_cast<FunctionTemplateDecl>(D); | ||||||||||
9765 | auto *GD = dyn_cast_or_null<CXXDeductionGuideDecl>( | ||||||||||
9766 | TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D)); | ||||||||||
9767 | if (!GD) | ||||||||||
9768 | continue; | ||||||||||
9769 | |||||||||||
9770 | if (!GD->isImplicit()) | ||||||||||
9771 | HasAnyDeductionGuide = true; | ||||||||||
9772 | |||||||||||
9773 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) | ||||||||||
9774 | // For copy-initialization, the candidate functions are all the | ||||||||||
9775 | // converting constructors (12.3.1) of that class. | ||||||||||
9776 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) | ||||||||||
9777 | // The converting constructors of T are candidate functions. | ||||||||||
9778 | if (!AllowExplicit) { | ||||||||||
9779 | // Overload resolution checks whether the deduction guide is declared | ||||||||||
9780 | // explicit for us. | ||||||||||
9781 | |||||||||||
9782 | // When looking for a converting constructor, deduction guides that | ||||||||||
9783 | // could never be called with one argument are not interesting to | ||||||||||
9784 | // check or note. | ||||||||||
9785 | if (GD->getMinRequiredArguments() > 1 || | ||||||||||
9786 | (GD->getNumParams() == 0 && !GD->isVariadic())) | ||||||||||
9787 | continue; | ||||||||||
9788 | } | ||||||||||
9789 | |||||||||||
9790 | // C++ [over.match.list]p1.1: (first phase list initialization) | ||||||||||
9791 | // Initially, the candidate functions are the initializer-list | ||||||||||
9792 | // constructors of the class T | ||||||||||
9793 | if (OnlyListConstructors && !isInitListConstructor(GD)) | ||||||||||
9794 | continue; | ||||||||||
9795 | |||||||||||
9796 | // C++ [over.match.list]p1.2: (second phase list initialization) | ||||||||||
9797 | // the candidate functions are all the constructors of the class T | ||||||||||
9798 | // C++ [over.match.ctor]p1: (all other cases) | ||||||||||
9799 | // the candidate functions are all the constructors of the class of | ||||||||||
9800 | // the object being initialized | ||||||||||
9801 | |||||||||||
9802 | // C++ [over.best.ics]p4: | ||||||||||
9803 | // When [...] the constructor [...] is a candidate by | ||||||||||
9804 | // - [over.match.copy] (in all cases) | ||||||||||
9805 | // FIXME: The "second phase of [over.match.list] case can also | ||||||||||
9806 | // theoretically happen here, but it's not clear whether we can | ||||||||||
9807 | // ever have a parameter of the right type. | ||||||||||
9808 | bool SuppressUserConversions = Kind.isCopyInit(); | ||||||||||
9809 | |||||||||||
9810 | if (TD) | ||||||||||
9811 | AddTemplateOverloadCandidate(TD, I.getPair(), /*ExplicitArgs*/ nullptr, | ||||||||||
9812 | Inits, Candidates, SuppressUserConversions, | ||||||||||
9813 | /*PartialOverloading*/ false, | ||||||||||
9814 | AllowExplicit); | ||||||||||
9815 | else | ||||||||||
9816 | AddOverloadCandidate(GD, I.getPair(), Inits, Candidates, | ||||||||||
9817 | SuppressUserConversions, | ||||||||||
9818 | /*PartialOverloading*/ false, AllowExplicit); | ||||||||||
9819 | } | ||||||||||
9820 | return Candidates.BestViableFunction(*this, Kind.getLocation(), Best); | ||||||||||
9821 | }; | ||||||||||
9822 | |||||||||||
9823 | OverloadingResult Result = OR_No_Viable_Function; | ||||||||||
9824 | |||||||||||
9825 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first | ||||||||||
9826 | // try initializer-list constructors. | ||||||||||
9827 | if (ListInit) { | ||||||||||
9828 | bool TryListConstructors = true; | ||||||||||
9829 | |||||||||||
9830 | // Try list constructors unless the list is empty and the class has one or | ||||||||||
9831 | // more default constructors, in which case those constructors win. | ||||||||||
9832 | if (!ListInit->getNumInits()) { | ||||||||||
9833 | for (NamedDecl *D : Guides) { | ||||||||||
9834 | auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl()); | ||||||||||
9835 | if (FD && FD->getMinRequiredArguments() == 0) { | ||||||||||
9836 | TryListConstructors = false; | ||||||||||
9837 | break; | ||||||||||
9838 | } | ||||||||||
9839 | } | ||||||||||
9840 | } else if (ListInit->getNumInits() == 1) { | ||||||||||
9841 | // C++ [over.match.class.deduct]: | ||||||||||
9842 | // As an exception, the first phase in [over.match.list] (considering | ||||||||||
9843 | // initializer-list constructors) is omitted if the initializer list | ||||||||||
9844 | // consists of a single expression of type cv U, where U is a | ||||||||||
9845 | // specialization of C or a class derived from a specialization of C. | ||||||||||
9846 | Expr *E = ListInit->getInit(0); | ||||||||||
9847 | auto *RD = E->getType()->getAsCXXRecordDecl(); | ||||||||||
9848 | if (!isa<InitListExpr>(E) && RD && | ||||||||||
9849 | isCompleteType(Kind.getLocation(), E->getType()) && | ||||||||||
9850 | isOrIsDerivedFromSpecializationOf(RD, Template)) | ||||||||||
9851 | TryListConstructors = false; | ||||||||||
9852 | } | ||||||||||
9853 | |||||||||||
9854 | if (TryListConstructors) | ||||||||||
9855 | Result = tryToResolveOverload(/*OnlyListConstructor*/true); | ||||||||||
9856 | // Then unwrap the initializer list and try again considering all | ||||||||||
9857 | // constructors. | ||||||||||
9858 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); | ||||||||||
9859 | } | ||||||||||
9860 | |||||||||||
9861 | // If list-initialization fails, or if we're doing any other kind of | ||||||||||
9862 | // initialization, we (eventually) consider constructors. | ||||||||||
9863 | if (Result == OR_No_Viable_Function) | ||||||||||
9864 | Result = tryToResolveOverload(/*OnlyListConstructor*/false); | ||||||||||
9865 | |||||||||||
9866 | switch (Result) { | ||||||||||
9867 | case OR_Ambiguous: | ||||||||||
9868 | // FIXME: For list-initialization candidates, it'd usually be better to | ||||||||||
9869 | // list why they were not viable when given the initializer list itself as | ||||||||||
9870 | // an argument. | ||||||||||
9871 | Candidates.NoteCandidates( | ||||||||||
9872 | PartialDiagnosticAt( | ||||||||||
9873 | Kind.getLocation(), | ||||||||||
9874 | PDiag(diag::err_deduced_class_template_ctor_ambiguous) | ||||||||||
9875 | << TemplateName), | ||||||||||
9876 | *this, OCD_AmbiguousCandidates, Inits); | ||||||||||
9877 | return QualType(); | ||||||||||
9878 | |||||||||||
9879 | case OR_No_Viable_Function: { | ||||||||||
9880 | CXXRecordDecl *Primary = | ||||||||||
9881 | cast<ClassTemplateDecl>(Template)->getTemplatedDecl(); | ||||||||||
9882 | bool Complete = | ||||||||||
9883 | isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary)); | ||||||||||
9884 | Candidates.NoteCandidates( | ||||||||||
9885 | PartialDiagnosticAt( | ||||||||||
9886 | Kind.getLocation(), | ||||||||||
9887 | PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable | ||||||||||
9888 | : diag::err_deduced_class_template_incomplete) | ||||||||||
9889 | << TemplateName << !Guides.empty()), | ||||||||||
9890 | *this, OCD_AllCandidates, Inits); | ||||||||||
9891 | return QualType(); | ||||||||||
9892 | } | ||||||||||
9893 | |||||||||||
9894 | case OR_Deleted: { | ||||||||||
9895 | Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted) | ||||||||||
9896 | << TemplateName; | ||||||||||
9897 | NoteDeletedFunction(Best->Function); | ||||||||||
9898 | return QualType(); | ||||||||||
9899 | } | ||||||||||
9900 | |||||||||||
9901 | case OR_Success: | ||||||||||
9902 | // C++ [over.match.list]p1: | ||||||||||
9903 | // In copy-list-initialization, if an explicit constructor is chosen, the | ||||||||||
9904 | // initialization is ill-formed. | ||||||||||
9905 | if (Kind.isCopyInit() && ListInit && | ||||||||||
9906 | cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) { | ||||||||||
9907 | bool IsDeductionGuide = !Best->Function->isImplicit(); | ||||||||||
9908 | Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit) | ||||||||||
9909 | << TemplateName << IsDeductionGuide; | ||||||||||
9910 | Diag(Best->Function->getLocation(), | ||||||||||
9911 | diag::note_explicit_ctor_deduction_guide_here) | ||||||||||
9912 | << IsDeductionGuide; | ||||||||||
9913 | return QualType(); | ||||||||||
9914 | } | ||||||||||
9915 | |||||||||||
9916 | // Make sure we didn't select an unusable deduction guide, and mark it | ||||||||||
9917 | // as referenced. | ||||||||||
9918 | DiagnoseUseOfDecl(Best->Function, Kind.getLocation()); | ||||||||||
9919 | MarkFunctionReferenced(Kind.getLocation(), Best->Function); | ||||||||||
9920 | break; | ||||||||||
9921 | } | ||||||||||
9922 | |||||||||||
9923 | // C++ [dcl.type.class.deduct]p1: | ||||||||||
9924 | // The placeholder is replaced by the return type of the function selected | ||||||||||
9925 | // by overload resolution for class template deduction. | ||||||||||
9926 | QualType DeducedType = | ||||||||||
9927 | SubstAutoType(TSInfo->getType(), Best->Function->getReturnType()); | ||||||||||
9928 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | ||||||||||
9929 | diag::warn_cxx14_compat_class_template_argument_deduction) | ||||||||||
9930 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; | ||||||||||
9931 | |||||||||||
9932 | // Warn if CTAD was used on a type that does not have any user-defined | ||||||||||
9933 | // deduction guides. | ||||||||||
9934 | if (!HasAnyDeductionGuide) { | ||||||||||
9935 | Diag(TSInfo->getTypeLoc().getBeginLoc(), | ||||||||||
9936 | diag::warn_ctad_maybe_unsupported) | ||||||||||
9937 | << TemplateName; | ||||||||||
9938 | Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported); | ||||||||||
9939 | } | ||||||||||
9940 | |||||||||||
9941 | return DeducedType; | ||||||||||
9942 | } |
1 | //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// |
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 | /// \file |
10 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/NestedNameSpecifier.h" |
21 | #include "clang/AST/TemplateName.h" |
22 | #include "clang/Basic/AddressSpaces.h" |
23 | #include "clang/Basic/AttrKinds.h" |
24 | #include "clang/Basic/Diagnostic.h" |
25 | #include "clang/Basic/ExceptionSpecificationType.h" |
26 | #include "clang/Basic/LLVM.h" |
27 | #include "clang/Basic/Linkage.h" |
28 | #include "clang/Basic/PartialDiagnostic.h" |
29 | #include "clang/Basic/SourceLocation.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Basic/Visibility.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/ADT/APSInt.h" |
34 | #include "llvm/ADT/ArrayRef.h" |
35 | #include "llvm/ADT/FoldingSet.h" |
36 | #include "llvm/ADT/None.h" |
37 | #include "llvm/ADT/Optional.h" |
38 | #include "llvm/ADT/PointerIntPair.h" |
39 | #include "llvm/ADT/PointerUnion.h" |
40 | #include "llvm/ADT/StringRef.h" |
41 | #include "llvm/ADT/Twine.h" |
42 | #include "llvm/ADT/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include "llvm/Support/PointerLikeTypeTraits.h" |
47 | #include "llvm/Support/type_traits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include <cassert> |
50 | #include <cstddef> |
51 | #include <cstdint> |
52 | #include <cstring> |
53 | #include <string> |
54 | #include <type_traits> |
55 | #include <utility> |
56 | |
57 | namespace clang { |
58 | |
59 | class ExtQuals; |
60 | class QualType; |
61 | class TagDecl; |
62 | class Type; |
63 | |
64 | enum { |
65 | TypeAlignmentInBits = 4, |
66 | TypeAlignment = 1 << TypeAlignmentInBits |
67 | }; |
68 | |
69 | namespace serialization { |
70 | template <class T> class AbstractTypeReader; |
71 | template <class T> class AbstractTypeWriter; |
72 | } |
73 | |
74 | } // namespace clang |
75 | |
76 | namespace llvm { |
77 | |
78 | template <typename T> |
79 | struct PointerLikeTypeTraits; |
80 | template<> |
81 | struct PointerLikeTypeTraits< ::clang::Type*> { |
82 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
83 | |
84 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
85 | return static_cast< ::clang::Type*>(P); |
86 | } |
87 | |
88 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
89 | }; |
90 | |
91 | template<> |
92 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
93 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
94 | |
95 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
96 | return static_cast< ::clang::ExtQuals*>(P); |
97 | } |
98 | |
99 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
100 | }; |
101 | |
102 | } // namespace llvm |
103 | |
104 | namespace clang { |
105 | |
106 | class ASTContext; |
107 | template <typename> class CanQual; |
108 | class CXXRecordDecl; |
109 | class DeclContext; |
110 | class EnumDecl; |
111 | class Expr; |
112 | class ExtQualsTypeCommonBase; |
113 | class FunctionDecl; |
114 | class IdentifierInfo; |
115 | class NamedDecl; |
116 | class ObjCInterfaceDecl; |
117 | class ObjCProtocolDecl; |
118 | class ObjCTypeParamDecl; |
119 | struct PrintingPolicy; |
120 | class RecordDecl; |
121 | class Stmt; |
122 | class TagDecl; |
123 | class TemplateArgument; |
124 | class TemplateArgumentListInfo; |
125 | class TemplateArgumentLoc; |
126 | class TemplateTypeParmDecl; |
127 | class TypedefNameDecl; |
128 | class UnresolvedUsingTypenameDecl; |
129 | |
130 | using CanQualType = CanQual<Type>; |
131 | |
132 | // Provide forward declarations for all of the *Type classes. |
133 | #define TYPE(Class, Base) class Class##Type; |
134 | #include "clang/AST/TypeNodes.inc" |
135 | |
136 | /// The collection of all-type qualifiers we support. |
137 | /// Clang supports five independent qualifiers: |
138 | /// * C99: const, volatile, and restrict |
139 | /// * MS: __unaligned |
140 | /// * Embedded C (TR18037): address spaces |
141 | /// * Objective C: the GC attributes (none, weak, or strong) |
142 | class Qualifiers { |
143 | public: |
144 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
145 | Const = 0x1, |
146 | Restrict = 0x2, |
147 | Volatile = 0x4, |
148 | CVRMask = Const | Volatile | Restrict |
149 | }; |
150 | |
151 | enum GC { |
152 | GCNone = 0, |
153 | Weak, |
154 | Strong |
155 | }; |
156 | |
157 | enum ObjCLifetime { |
158 | /// There is no lifetime qualification on this type. |
159 | OCL_None, |
160 | |
161 | /// This object can be modified without requiring retains or |
162 | /// releases. |
163 | OCL_ExplicitNone, |
164 | |
165 | /// Assigning into this object requires the old value to be |
166 | /// released and the new value to be retained. The timing of the |
167 | /// release of the old value is inexact: it may be moved to |
168 | /// immediately after the last known point where the value is |
169 | /// live. |
170 | OCL_Strong, |
171 | |
172 | /// Reading or writing from this object requires a barrier call. |
173 | OCL_Weak, |
174 | |
175 | /// Assigning into this object requires a lifetime extension. |
176 | OCL_Autoreleasing |
177 | }; |
178 | |
179 | enum { |
180 | /// The maximum supported address space number. |
181 | /// 23 bits should be enough for anyone. |
182 | MaxAddressSpace = 0x7fffffu, |
183 | |
184 | /// The width of the "fast" qualifier mask. |
185 | FastWidth = 3, |
186 | |
187 | /// The fast qualifier mask. |
188 | FastMask = (1 << FastWidth) - 1 |
189 | }; |
190 | |
191 | /// Returns the common set of qualifiers while removing them from |
192 | /// the given sets. |
193 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
194 | // If both are only CVR-qualified, bit operations are sufficient. |
195 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
196 | Qualifiers Q; |
197 | Q.Mask = L.Mask & R.Mask; |
198 | L.Mask &= ~Q.Mask; |
199 | R.Mask &= ~Q.Mask; |
200 | return Q; |
201 | } |
202 | |
203 | Qualifiers Q; |
204 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
205 | Q.addCVRQualifiers(CommonCRV); |
206 | L.removeCVRQualifiers(CommonCRV); |
207 | R.removeCVRQualifiers(CommonCRV); |
208 | |
209 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
210 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
211 | L.removeObjCGCAttr(); |
212 | R.removeObjCGCAttr(); |
213 | } |
214 | |
215 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
216 | Q.setObjCLifetime(L.getObjCLifetime()); |
217 | L.removeObjCLifetime(); |
218 | R.removeObjCLifetime(); |
219 | } |
220 | |
221 | if (L.getAddressSpace() == R.getAddressSpace()) { |
222 | Q.setAddressSpace(L.getAddressSpace()); |
223 | L.removeAddressSpace(); |
224 | R.removeAddressSpace(); |
225 | } |
226 | return Q; |
227 | } |
228 | |
229 | static Qualifiers fromFastMask(unsigned Mask) { |
230 | Qualifiers Qs; |
231 | Qs.addFastQualifiers(Mask); |
232 | return Qs; |
233 | } |
234 | |
235 | static Qualifiers fromCVRMask(unsigned CVR) { |
236 | Qualifiers Qs; |
237 | Qs.addCVRQualifiers(CVR); |
238 | return Qs; |
239 | } |
240 | |
241 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
242 | Qualifiers Qs; |
243 | Qs.addCVRUQualifiers(CVRU); |
244 | return Qs; |
245 | } |
246 | |
247 | // Deserialize qualifiers from an opaque representation. |
248 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
249 | Qualifiers Qs; |
250 | Qs.Mask = opaque; |
251 | return Qs; |
252 | } |
253 | |
254 | // Serialize these qualifiers into an opaque representation. |
255 | unsigned getAsOpaqueValue() const { |
256 | return Mask; |
257 | } |
258 | |
259 | bool hasConst() const { return Mask & Const; } |
260 | bool hasOnlyConst() const { return Mask == Const; } |
261 | void removeConst() { Mask &= ~Const; } |
262 | void addConst() { Mask |= Const; } |
263 | |
264 | bool hasVolatile() const { return Mask & Volatile; } |
265 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
266 | void removeVolatile() { Mask &= ~Volatile; } |
267 | void addVolatile() { Mask |= Volatile; } |
268 | |
269 | bool hasRestrict() const { return Mask & Restrict; } |
270 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
271 | void removeRestrict() { Mask &= ~Restrict; } |
272 | void addRestrict() { Mask |= Restrict; } |
273 | |
274 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
275 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
276 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
277 | |
278 | void setCVRQualifiers(unsigned mask) { |
279 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 279, __PRETTY_FUNCTION__)); |
280 | Mask = (Mask & ~CVRMask) | mask; |
281 | } |
282 | void removeCVRQualifiers(unsigned mask) { |
283 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 283, __PRETTY_FUNCTION__)); |
284 | Mask &= ~mask; |
285 | } |
286 | void removeCVRQualifiers() { |
287 | removeCVRQualifiers(CVRMask); |
288 | } |
289 | void addCVRQualifiers(unsigned mask) { |
290 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 290, __PRETTY_FUNCTION__)); |
291 | Mask |= mask; |
292 | } |
293 | void addCVRUQualifiers(unsigned mask) { |
294 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 294, __PRETTY_FUNCTION__)); |
295 | Mask |= mask; |
296 | } |
297 | |
298 | bool hasUnaligned() const { return Mask & UMask; } |
299 | void setUnaligned(bool flag) { |
300 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
301 | } |
302 | void removeUnaligned() { Mask &= ~UMask; } |
303 | void addUnaligned() { Mask |= UMask; } |
304 | |
305 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
306 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
307 | void setObjCGCAttr(GC type) { |
308 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
309 | } |
310 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
311 | void addObjCGCAttr(GC type) { |
312 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 312, __PRETTY_FUNCTION__)); |
313 | setObjCGCAttr(type); |
314 | } |
315 | Qualifiers withoutObjCGCAttr() const { |
316 | Qualifiers qs = *this; |
317 | qs.removeObjCGCAttr(); |
318 | return qs; |
319 | } |
320 | Qualifiers withoutObjCLifetime() const { |
321 | Qualifiers qs = *this; |
322 | qs.removeObjCLifetime(); |
323 | return qs; |
324 | } |
325 | Qualifiers withoutAddressSpace() const { |
326 | Qualifiers qs = *this; |
327 | qs.removeAddressSpace(); |
328 | return qs; |
329 | } |
330 | |
331 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
332 | ObjCLifetime getObjCLifetime() const { |
333 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
334 | } |
335 | void setObjCLifetime(ObjCLifetime type) { |
336 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
337 | } |
338 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
339 | void addObjCLifetime(ObjCLifetime type) { |
340 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 340, __PRETTY_FUNCTION__)); |
341 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 341, __PRETTY_FUNCTION__)); |
342 | Mask |= (type << LifetimeShift); |
343 | } |
344 | |
345 | /// True if the lifetime is neither None or ExplicitNone. |
346 | bool hasNonTrivialObjCLifetime() const { |
347 | ObjCLifetime lifetime = getObjCLifetime(); |
348 | return (lifetime > OCL_ExplicitNone); |
349 | } |
350 | |
351 | /// True if the lifetime is either strong or weak. |
352 | bool hasStrongOrWeakObjCLifetime() const { |
353 | ObjCLifetime lifetime = getObjCLifetime(); |
354 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
355 | } |
356 | |
357 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
358 | LangAS getAddressSpace() const { |
359 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
360 | } |
361 | bool hasTargetSpecificAddressSpace() const { |
362 | return isTargetAddressSpace(getAddressSpace()); |
363 | } |
364 | /// Get the address space attribute value to be printed by diagnostics. |
365 | unsigned getAddressSpaceAttributePrintValue() const { |
366 | auto Addr = getAddressSpace(); |
367 | // This function is not supposed to be used with language specific |
368 | // address spaces. If that happens, the diagnostic message should consider |
369 | // printing the QualType instead of the address space value. |
370 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 370, __PRETTY_FUNCTION__)); |
371 | if (Addr != LangAS::Default) |
372 | return toTargetAddressSpace(Addr); |
373 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
374 | // since it cannot differentiate the situation where 0 denotes the default |
375 | // address space or user specified __attribute__((address_space(0))). |
376 | return 0; |
377 | } |
378 | void setAddressSpace(LangAS space) { |
379 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 379, __PRETTY_FUNCTION__)); |
380 | Mask = (Mask & ~AddressSpaceMask) |
381 | | (((uint32_t) space) << AddressSpaceShift); |
382 | } |
383 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
384 | void addAddressSpace(LangAS space) { |
385 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 385, __PRETTY_FUNCTION__)); |
386 | setAddressSpace(space); |
387 | } |
388 | |
389 | // Fast qualifiers are those that can be allocated directly |
390 | // on a QualType object. |
391 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
392 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
393 | void setFastQualifiers(unsigned mask) { |
394 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 394, __PRETTY_FUNCTION__)); |
395 | Mask = (Mask & ~FastMask) | mask; |
396 | } |
397 | void removeFastQualifiers(unsigned mask) { |
398 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 398, __PRETTY_FUNCTION__)); |
399 | Mask &= ~mask; |
400 | } |
401 | void removeFastQualifiers() { |
402 | removeFastQualifiers(FastMask); |
403 | } |
404 | void addFastQualifiers(unsigned mask) { |
405 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 405, __PRETTY_FUNCTION__)); |
406 | Mask |= mask; |
407 | } |
408 | |
409 | /// Return true if the set contains any qualifiers which require an ExtQuals |
410 | /// node to be allocated. |
411 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
412 | Qualifiers getNonFastQualifiers() const { |
413 | Qualifiers Quals = *this; |
414 | Quals.setFastQualifiers(0); |
415 | return Quals; |
416 | } |
417 | |
418 | /// Return true if the set contains any qualifiers. |
419 | bool hasQualifiers() const { return Mask; } |
420 | bool empty() const { return !Mask; } |
421 | |
422 | /// Add the qualifiers from the given set to this set. |
423 | void addQualifiers(Qualifiers Q) { |
424 | // If the other set doesn't have any non-boolean qualifiers, just |
425 | // bit-or it in. |
426 | if (!(Q.Mask & ~CVRMask)) |
427 | Mask |= Q.Mask; |
428 | else { |
429 | Mask |= (Q.Mask & CVRMask); |
430 | if (Q.hasAddressSpace()) |
431 | addAddressSpace(Q.getAddressSpace()); |
432 | if (Q.hasObjCGCAttr()) |
433 | addObjCGCAttr(Q.getObjCGCAttr()); |
434 | if (Q.hasObjCLifetime()) |
435 | addObjCLifetime(Q.getObjCLifetime()); |
436 | } |
437 | } |
438 | |
439 | /// Remove the qualifiers from the given set from this set. |
440 | void removeQualifiers(Qualifiers Q) { |
441 | // If the other set doesn't have any non-boolean qualifiers, just |
442 | // bit-and the inverse in. |
443 | if (!(Q.Mask & ~CVRMask)) |
444 | Mask &= ~Q.Mask; |
445 | else { |
446 | Mask &= ~(Q.Mask & CVRMask); |
447 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
448 | removeObjCGCAttr(); |
449 | if (getObjCLifetime() == Q.getObjCLifetime()) |
450 | removeObjCLifetime(); |
451 | if (getAddressSpace() == Q.getAddressSpace()) |
452 | removeAddressSpace(); |
453 | } |
454 | } |
455 | |
456 | /// Add the qualifiers from the given set to this set, given that |
457 | /// they don't conflict. |
458 | void addConsistentQualifiers(Qualifiers qs) { |
459 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 460, __PRETTY_FUNCTION__)) |
460 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 460, __PRETTY_FUNCTION__)); |
461 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 462, __PRETTY_FUNCTION__)) |
462 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 462, __PRETTY_FUNCTION__)); |
463 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 464, __PRETTY_FUNCTION__)) |
464 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 464, __PRETTY_FUNCTION__)); |
465 | Mask |= qs.Mask; |
466 | } |
467 | |
468 | /// Returns true if address space A is equal to or a superset of B. |
469 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
470 | /// overlapping address spaces. |
471 | /// CL1.1 or CL1.2: |
472 | /// every address space is a superset of itself. |
473 | /// CL2.0 adds: |
474 | /// __generic is a superset of any address space except for __constant. |
475 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
476 | // Address spaces must match exactly. |
477 | return A == B || |
478 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
479 | // for __constant can be used as __generic. |
480 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || |
481 | // Consider pointer size address spaces to be equivalent to default. |
482 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
483 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)); |
484 | } |
485 | |
486 | /// Returns true if the address space in these qualifiers is equal to or |
487 | /// a superset of the address space in the argument qualifiers. |
488 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
489 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
490 | } |
491 | |
492 | /// Determines if these qualifiers compatibly include another set. |
493 | /// Generally this answers the question of whether an object with the other |
494 | /// qualifiers can be safely used as an object with these qualifiers. |
495 | bool compatiblyIncludes(Qualifiers other) const { |
496 | return isAddressSpaceSupersetOf(other) && |
497 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
498 | // be changed. |
499 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
500 | !other.hasObjCGCAttr()) && |
501 | // ObjC lifetime qualifiers must match exactly. |
502 | getObjCLifetime() == other.getObjCLifetime() && |
503 | // CVR qualifiers may subset. |
504 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
505 | // U qualifier may superset. |
506 | (!other.hasUnaligned() || hasUnaligned()); |
507 | } |
508 | |
509 | /// Determines if these qualifiers compatibly include another set of |
510 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
511 | /// |
512 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
513 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
514 | /// including set also contains the 'const' qualifier, or both are non-__weak |
515 | /// and one is None (which can only happen in non-ARC modes). |
516 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
517 | if (getObjCLifetime() == other.getObjCLifetime()) |
518 | return true; |
519 | |
520 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
521 | return false; |
522 | |
523 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
524 | return true; |
525 | |
526 | return hasConst(); |
527 | } |
528 | |
529 | /// Determine whether this set of qualifiers is a strict superset of |
530 | /// another set of qualifiers, not considering qualifier compatibility. |
531 | bool isStrictSupersetOf(Qualifiers Other) const; |
532 | |
533 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
534 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
535 | |
536 | explicit operator bool() const { return hasQualifiers(); } |
537 | |
538 | Qualifiers &operator+=(Qualifiers R) { |
539 | addQualifiers(R); |
540 | return *this; |
541 | } |
542 | |
543 | // Union two qualifier sets. If an enumerated qualifier appears |
544 | // in both sets, use the one from the right. |
545 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
546 | L += R; |
547 | return L; |
548 | } |
549 | |
550 | Qualifiers &operator-=(Qualifiers R) { |
551 | removeQualifiers(R); |
552 | return *this; |
553 | } |
554 | |
555 | /// Compute the difference between two qualifier sets. |
556 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
557 | L -= R; |
558 | return L; |
559 | } |
560 | |
561 | std::string getAsString() const; |
562 | std::string getAsString(const PrintingPolicy &Policy) const; |
563 | |
564 | static std::string getAddrSpaceAsString(LangAS AS); |
565 | |
566 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
567 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
568 | bool appendSpaceIfNonEmpty = false) const; |
569 | |
570 | void Profile(llvm::FoldingSetNodeID &ID) const { |
571 | ID.AddInteger(Mask); |
572 | } |
573 | |
574 | private: |
575 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
576 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
577 | uint32_t Mask = 0; |
578 | |
579 | static const uint32_t UMask = 0x8; |
580 | static const uint32_t UShift = 3; |
581 | static const uint32_t GCAttrMask = 0x30; |
582 | static const uint32_t GCAttrShift = 4; |
583 | static const uint32_t LifetimeMask = 0x1C0; |
584 | static const uint32_t LifetimeShift = 6; |
585 | static const uint32_t AddressSpaceMask = |
586 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
587 | static const uint32_t AddressSpaceShift = 9; |
588 | }; |
589 | |
590 | /// A std::pair-like structure for storing a qualified type split |
591 | /// into its local qualifiers and its locally-unqualified type. |
592 | struct SplitQualType { |
593 | /// The locally-unqualified type. |
594 | const Type *Ty = nullptr; |
595 | |
596 | /// The local qualifiers. |
597 | Qualifiers Quals; |
598 | |
599 | SplitQualType() = default; |
600 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
601 | |
602 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
603 | |
604 | // Make std::tie work. |
605 | std::pair<const Type *,Qualifiers> asPair() const { |
606 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
607 | } |
608 | |
609 | friend bool operator==(SplitQualType a, SplitQualType b) { |
610 | return a.Ty == b.Ty && a.Quals == b.Quals; |
611 | } |
612 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
613 | return a.Ty != b.Ty || a.Quals != b.Quals; |
614 | } |
615 | }; |
616 | |
617 | /// The kind of type we are substituting Objective-C type arguments into. |
618 | /// |
619 | /// The kind of substitution affects the replacement of type parameters when |
620 | /// no concrete type information is provided, e.g., when dealing with an |
621 | /// unspecialized type. |
622 | enum class ObjCSubstitutionContext { |
623 | /// An ordinary type. |
624 | Ordinary, |
625 | |
626 | /// The result type of a method or function. |
627 | Result, |
628 | |
629 | /// The parameter type of a method or function. |
630 | Parameter, |
631 | |
632 | /// The type of a property. |
633 | Property, |
634 | |
635 | /// The superclass of a type. |
636 | Superclass, |
637 | }; |
638 | |
639 | /// A (possibly-)qualified type. |
640 | /// |
641 | /// For efficiency, we don't store CV-qualified types as nodes on their |
642 | /// own: instead each reference to a type stores the qualifiers. This |
643 | /// greatly reduces the number of nodes we need to allocate for types (for |
644 | /// example we only need one for 'int', 'const int', 'volatile int', |
645 | /// 'const volatile int', etc). |
646 | /// |
647 | /// As an added efficiency bonus, instead of making this a pair, we |
648 | /// just store the two bits we care about in the low bits of the |
649 | /// pointer. To handle the packing/unpacking, we make QualType be a |
650 | /// simple wrapper class that acts like a smart pointer. A third bit |
651 | /// indicates whether there are extended qualifiers present, in which |
652 | /// case the pointer points to a special structure. |
653 | class QualType { |
654 | friend class QualifierCollector; |
655 | |
656 | // Thankfully, these are efficiently composable. |
657 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
658 | Qualifiers::FastWidth> Value; |
659 | |
660 | const ExtQuals *getExtQualsUnsafe() const { |
661 | return Value.getPointer().get<const ExtQuals*>(); |
662 | } |
663 | |
664 | const Type *getTypePtrUnsafe() const { |
665 | return Value.getPointer().get<const Type*>(); |
666 | } |
667 | |
668 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
669 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 669, __PRETTY_FUNCTION__)); |
670 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
671 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
672 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
673 | } |
674 | |
675 | public: |
676 | QualType() = default; |
677 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
678 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
679 | |
680 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
681 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
682 | |
683 | /// Retrieves a pointer to the underlying (unqualified) type. |
684 | /// |
685 | /// This function requires that the type not be NULL. If the type might be |
686 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
687 | const Type *getTypePtr() const; |
688 | |
689 | const Type *getTypePtrOrNull() const; |
690 | |
691 | /// Retrieves a pointer to the name of the base type. |
692 | const IdentifierInfo *getBaseTypeIdentifier() const; |
693 | |
694 | /// Divides a QualType into its unqualified type and a set of local |
695 | /// qualifiers. |
696 | SplitQualType split() const; |
697 | |
698 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
699 | |
700 | static QualType getFromOpaquePtr(const void *Ptr) { |
701 | QualType T; |
702 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
703 | return T; |
704 | } |
705 | |
706 | const Type &operator*() const { |
707 | return *getTypePtr(); |
708 | } |
709 | |
710 | const Type *operator->() const { |
711 | return getTypePtr(); |
712 | } |
713 | |
714 | bool isCanonical() const; |
715 | bool isCanonicalAsParam() const; |
716 | |
717 | /// Return true if this QualType doesn't point to a type yet. |
718 | bool isNull() const { |
719 | return Value.getPointer().isNull(); |
720 | } |
721 | |
722 | /// Determine whether this particular QualType instance has the |
723 | /// "const" qualifier set, without looking through typedefs that may have |
724 | /// added "const" at a different level. |
725 | bool isLocalConstQualified() const { |
726 | return (getLocalFastQualifiers() & Qualifiers::Const); |
727 | } |
728 | |
729 | /// Determine whether this type is const-qualified. |
730 | bool isConstQualified() const; |
731 | |
732 | /// Determine whether this particular QualType instance has the |
733 | /// "restrict" qualifier set, without looking through typedefs that may have |
734 | /// added "restrict" at a different level. |
735 | bool isLocalRestrictQualified() const { |
736 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
737 | } |
738 | |
739 | /// Determine whether this type is restrict-qualified. |
740 | bool isRestrictQualified() const; |
741 | |
742 | /// Determine whether this particular QualType instance has the |
743 | /// "volatile" qualifier set, without looking through typedefs that may have |
744 | /// added "volatile" at a different level. |
745 | bool isLocalVolatileQualified() const { |
746 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
747 | } |
748 | |
749 | /// Determine whether this type is volatile-qualified. |
750 | bool isVolatileQualified() const; |
751 | |
752 | /// Determine whether this particular QualType instance has any |
753 | /// qualifiers, without looking through any typedefs that might add |
754 | /// qualifiers at a different level. |
755 | bool hasLocalQualifiers() const { |
756 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
757 | } |
758 | |
759 | /// Determine whether this type has any qualifiers. |
760 | bool hasQualifiers() const; |
761 | |
762 | /// Determine whether this particular QualType instance has any |
763 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
764 | /// instance. |
765 | bool hasLocalNonFastQualifiers() const { |
766 | return Value.getPointer().is<const ExtQuals*>(); |
767 | } |
768 | |
769 | /// Retrieve the set of qualifiers local to this particular QualType |
770 | /// instance, not including any qualifiers acquired through typedefs or |
771 | /// other sugar. |
772 | Qualifiers getLocalQualifiers() const; |
773 | |
774 | /// Retrieve the set of qualifiers applied to this type. |
775 | Qualifiers getQualifiers() const; |
776 | |
777 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
778 | /// local to this particular QualType instance, not including any qualifiers |
779 | /// acquired through typedefs or other sugar. |
780 | unsigned getLocalCVRQualifiers() const { |
781 | return getLocalFastQualifiers(); |
782 | } |
783 | |
784 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
785 | /// applied to this type. |
786 | unsigned getCVRQualifiers() const; |
787 | |
788 | bool isConstant(const ASTContext& Ctx) const { |
789 | return QualType::isConstant(*this, Ctx); |
790 | } |
791 | |
792 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
793 | bool isPODType(const ASTContext &Context) const; |
794 | |
795 | /// Return true if this is a POD type according to the rules of the C++98 |
796 | /// standard, regardless of the current compilation's language. |
797 | bool isCXX98PODType(const ASTContext &Context) const; |
798 | |
799 | /// Return true if this is a POD type according to the more relaxed rules |
800 | /// of the C++11 standard, regardless of the current compilation's language. |
801 | /// (C++0x [basic.types]p9). Note that, unlike |
802 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
803 | bool isCXX11PODType(const ASTContext &Context) const; |
804 | |
805 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
806 | bool isTrivialType(const ASTContext &Context) const; |
807 | |
808 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
809 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
810 | |
811 | |
812 | /// Returns true if it is a class and it might be dynamic. |
813 | bool mayBeDynamicClass() const; |
814 | |
815 | /// Returns true if it is not a class or if the class might not be dynamic. |
816 | bool mayBeNotDynamicClass() const; |
817 | |
818 | // Don't promise in the API that anything besides 'const' can be |
819 | // easily added. |
820 | |
821 | /// Add the `const` type qualifier to this QualType. |
822 | void addConst() { |
823 | addFastQualifiers(Qualifiers::Const); |
824 | } |
825 | QualType withConst() const { |
826 | return withFastQualifiers(Qualifiers::Const); |
827 | } |
828 | |
829 | /// Add the `volatile` type qualifier to this QualType. |
830 | void addVolatile() { |
831 | addFastQualifiers(Qualifiers::Volatile); |
832 | } |
833 | QualType withVolatile() const { |
834 | return withFastQualifiers(Qualifiers::Volatile); |
835 | } |
836 | |
837 | /// Add the `restrict` qualifier to this QualType. |
838 | void addRestrict() { |
839 | addFastQualifiers(Qualifiers::Restrict); |
840 | } |
841 | QualType withRestrict() const { |
842 | return withFastQualifiers(Qualifiers::Restrict); |
843 | } |
844 | |
845 | QualType withCVRQualifiers(unsigned CVR) const { |
846 | return withFastQualifiers(CVR); |
847 | } |
848 | |
849 | void addFastQualifiers(unsigned TQs) { |
850 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 851, __PRETTY_FUNCTION__)) |
851 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 851, __PRETTY_FUNCTION__)); |
852 | Value.setInt(Value.getInt() | TQs); |
853 | } |
854 | |
855 | void removeLocalConst(); |
856 | void removeLocalVolatile(); |
857 | void removeLocalRestrict(); |
858 | void removeLocalCVRQualifiers(unsigned Mask); |
859 | |
860 | void removeLocalFastQualifiers() { Value.setInt(0); } |
861 | void removeLocalFastQualifiers(unsigned Mask) { |
862 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 862, __PRETTY_FUNCTION__)); |
863 | Value.setInt(Value.getInt() & ~Mask); |
864 | } |
865 | |
866 | // Creates a type with the given qualifiers in addition to any |
867 | // qualifiers already on this type. |
868 | QualType withFastQualifiers(unsigned TQs) const { |
869 | QualType T = *this; |
870 | T.addFastQualifiers(TQs); |
871 | return T; |
872 | } |
873 | |
874 | // Creates a type with exactly the given fast qualifiers, removing |
875 | // any existing fast qualifiers. |
876 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
877 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
878 | } |
879 | |
880 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
881 | QualType withoutLocalFastQualifiers() const { |
882 | QualType T = *this; |
883 | T.removeLocalFastQualifiers(); |
884 | return T; |
885 | } |
886 | |
887 | QualType getCanonicalType() const; |
888 | |
889 | /// Return this type with all of the instance-specific qualifiers |
890 | /// removed, but without removing any qualifiers that may have been applied |
891 | /// through typedefs. |
892 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
893 | |
894 | /// Retrieve the unqualified variant of the given type, |
895 | /// removing as little sugar as possible. |
896 | /// |
897 | /// This routine looks through various kinds of sugar to find the |
898 | /// least-desugared type that is unqualified. For example, given: |
899 | /// |
900 | /// \code |
901 | /// typedef int Integer; |
902 | /// typedef const Integer CInteger; |
903 | /// typedef CInteger DifferenceType; |
904 | /// \endcode |
905 | /// |
906 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
907 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
908 | /// |
909 | /// The resulting type might still be qualified if it's sugar for an array |
910 | /// type. To strip qualifiers even from within a sugared array type, use |
911 | /// ASTContext::getUnqualifiedArrayType. |
912 | inline QualType getUnqualifiedType() const; |
913 | |
914 | /// Retrieve the unqualified variant of the given type, removing as little |
915 | /// sugar as possible. |
916 | /// |
917 | /// Like getUnqualifiedType(), but also returns the set of |
918 | /// qualifiers that were built up. |
919 | /// |
920 | /// The resulting type might still be qualified if it's sugar for an array |
921 | /// type. To strip qualifiers even from within a sugared array type, use |
922 | /// ASTContext::getUnqualifiedArrayType. |
923 | inline SplitQualType getSplitUnqualifiedType() const; |
924 | |
925 | /// Determine whether this type is more qualified than the other |
926 | /// given type, requiring exact equality for non-CVR qualifiers. |
927 | bool isMoreQualifiedThan(QualType Other) const; |
928 | |
929 | /// Determine whether this type is at least as qualified as the other |
930 | /// given type, requiring exact equality for non-CVR qualifiers. |
931 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
932 | |
933 | QualType getNonReferenceType() const; |
934 | |
935 | /// Determine the type of a (typically non-lvalue) expression with the |
936 | /// specified result type. |
937 | /// |
938 | /// This routine should be used for expressions for which the return type is |
939 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
940 | /// an lvalue. It removes a top-level reference (since there are no |
941 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
942 | /// from non-class types (in C++) or all types (in C). |
943 | QualType getNonLValueExprType(const ASTContext &Context) const; |
944 | |
945 | /// Return the specified type with any "sugar" removed from |
946 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
947 | /// the type is already concrete, it returns it unmodified. This is similar |
948 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
949 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
950 | /// concrete. |
951 | /// |
952 | /// Qualifiers are left in place. |
953 | QualType getDesugaredType(const ASTContext &Context) const { |
954 | return getDesugaredType(*this, Context); |
955 | } |
956 | |
957 | SplitQualType getSplitDesugaredType() const { |
958 | return getSplitDesugaredType(*this); |
959 | } |
960 | |
961 | /// Return the specified type with one level of "sugar" removed from |
962 | /// the type. |
963 | /// |
964 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
965 | /// of the type is already concrete, it returns it unmodified. |
966 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
967 | return getSingleStepDesugaredTypeImpl(*this, Context); |
968 | } |
969 | |
970 | /// Returns the specified type after dropping any |
971 | /// outer-level parentheses. |
972 | QualType IgnoreParens() const { |
973 | if (isa<ParenType>(*this)) |
974 | return QualType::IgnoreParens(*this); |
975 | return *this; |
976 | } |
977 | |
978 | /// Indicate whether the specified types and qualifiers are identical. |
979 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
980 | return LHS.Value == RHS.Value; |
981 | } |
982 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
983 | return LHS.Value != RHS.Value; |
984 | } |
985 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
986 | return LHS.Value < RHS.Value; |
987 | } |
988 | |
989 | static std::string getAsString(SplitQualType split, |
990 | const PrintingPolicy &Policy) { |
991 | return getAsString(split.Ty, split.Quals, Policy); |
992 | } |
993 | static std::string getAsString(const Type *ty, Qualifiers qs, |
994 | const PrintingPolicy &Policy); |
995 | |
996 | std::string getAsString() const; |
997 | std::string getAsString(const PrintingPolicy &Policy) const; |
998 | |
999 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1000 | const Twine &PlaceHolder = Twine(), |
1001 | unsigned Indentation = 0) const; |
1002 | |
1003 | static void print(SplitQualType split, raw_ostream &OS, |
1004 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1005 | unsigned Indentation = 0) { |
1006 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1007 | } |
1008 | |
1009 | static void print(const Type *ty, Qualifiers qs, |
1010 | raw_ostream &OS, const PrintingPolicy &policy, |
1011 | const Twine &PlaceHolder, |
1012 | unsigned Indentation = 0); |
1013 | |
1014 | void getAsStringInternal(std::string &Str, |
1015 | const PrintingPolicy &Policy) const; |
1016 | |
1017 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1018 | const PrintingPolicy &policy) { |
1019 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1020 | } |
1021 | |
1022 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1023 | std::string &out, |
1024 | const PrintingPolicy &policy); |
1025 | |
1026 | class StreamedQualTypeHelper { |
1027 | const QualType &T; |
1028 | const PrintingPolicy &Policy; |
1029 | const Twine &PlaceHolder; |
1030 | unsigned Indentation; |
1031 | |
1032 | public: |
1033 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1034 | const Twine &PlaceHolder, unsigned Indentation) |
1035 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1036 | Indentation(Indentation) {} |
1037 | |
1038 | friend raw_ostream &operator<<(raw_ostream &OS, |
1039 | const StreamedQualTypeHelper &SQT) { |
1040 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1041 | return OS; |
1042 | } |
1043 | }; |
1044 | |
1045 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1046 | const Twine &PlaceHolder = Twine(), |
1047 | unsigned Indentation = 0) const { |
1048 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1049 | } |
1050 | |
1051 | void dump(const char *s) const; |
1052 | void dump() const; |
1053 | void dump(llvm::raw_ostream &OS) const; |
1054 | |
1055 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1056 | ID.AddPointer(getAsOpaquePtr()); |
1057 | } |
1058 | |
1059 | /// Check if this type has any address space qualifier. |
1060 | inline bool hasAddressSpace() const; |
1061 | |
1062 | /// Return the address space of this type. |
1063 | inline LangAS getAddressSpace() const; |
1064 | |
1065 | /// Returns gc attribute of this type. |
1066 | inline Qualifiers::GC getObjCGCAttr() const; |
1067 | |
1068 | /// true when Type is objc's weak. |
1069 | bool isObjCGCWeak() const { |
1070 | return getObjCGCAttr() == Qualifiers::Weak; |
1071 | } |
1072 | |
1073 | /// true when Type is objc's strong. |
1074 | bool isObjCGCStrong() const { |
1075 | return getObjCGCAttr() == Qualifiers::Strong; |
1076 | } |
1077 | |
1078 | /// Returns lifetime attribute of this type. |
1079 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1080 | return getQualifiers().getObjCLifetime(); |
1081 | } |
1082 | |
1083 | bool hasNonTrivialObjCLifetime() const { |
1084 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1085 | } |
1086 | |
1087 | bool hasStrongOrWeakObjCLifetime() const { |
1088 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1089 | } |
1090 | |
1091 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1092 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1093 | |
1094 | enum PrimitiveDefaultInitializeKind { |
1095 | /// The type does not fall into any of the following categories. Note that |
1096 | /// this case is zero-valued so that values of this enum can be used as a |
1097 | /// boolean condition for non-triviality. |
1098 | PDIK_Trivial, |
1099 | |
1100 | /// The type is an Objective-C retainable pointer type that is qualified |
1101 | /// with the ARC __strong qualifier. |
1102 | PDIK_ARCStrong, |
1103 | |
1104 | /// The type is an Objective-C retainable pointer type that is qualified |
1105 | /// with the ARC __weak qualifier. |
1106 | PDIK_ARCWeak, |
1107 | |
1108 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1109 | PDIK_Struct |
1110 | }; |
1111 | |
1112 | /// Functions to query basic properties of non-trivial C struct types. |
1113 | |
1114 | /// Check if this is a non-trivial type that would cause a C struct |
1115 | /// transitively containing this type to be non-trivial to default initialize |
1116 | /// and return the kind. |
1117 | PrimitiveDefaultInitializeKind |
1118 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1119 | |
1120 | enum PrimitiveCopyKind { |
1121 | /// The type does not fall into any of the following categories. Note that |
1122 | /// this case is zero-valued so that values of this enum can be used as a |
1123 | /// boolean condition for non-triviality. |
1124 | PCK_Trivial, |
1125 | |
1126 | /// The type would be trivial except that it is volatile-qualified. Types |
1127 | /// that fall into one of the other non-trivial cases may additionally be |
1128 | /// volatile-qualified. |
1129 | PCK_VolatileTrivial, |
1130 | |
1131 | /// The type is an Objective-C retainable pointer type that is qualified |
1132 | /// with the ARC __strong qualifier. |
1133 | PCK_ARCStrong, |
1134 | |
1135 | /// The type is an Objective-C retainable pointer type that is qualified |
1136 | /// with the ARC __weak qualifier. |
1137 | PCK_ARCWeak, |
1138 | |
1139 | /// The type is a struct containing a field whose type is neither |
1140 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1141 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1142 | /// semantics are too complex to express here, in part because they depend |
1143 | /// on the exact constructor or assignment operator that is chosen by |
1144 | /// overload resolution to do the copy. |
1145 | PCK_Struct |
1146 | }; |
1147 | |
1148 | /// Check if this is a non-trivial type that would cause a C struct |
1149 | /// transitively containing this type to be non-trivial to copy and return the |
1150 | /// kind. |
1151 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1152 | |
1153 | /// Check if this is a non-trivial type that would cause a C struct |
1154 | /// transitively containing this type to be non-trivial to destructively |
1155 | /// move and return the kind. Destructive move in this context is a C++-style |
1156 | /// move in which the source object is placed in a valid but unspecified state |
1157 | /// after it is moved, as opposed to a truly destructive move in which the |
1158 | /// source object is placed in an uninitialized state. |
1159 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1160 | |
1161 | enum DestructionKind { |
1162 | DK_none, |
1163 | DK_cxx_destructor, |
1164 | DK_objc_strong_lifetime, |
1165 | DK_objc_weak_lifetime, |
1166 | DK_nontrivial_c_struct |
1167 | }; |
1168 | |
1169 | /// Returns a nonzero value if objects of this type require |
1170 | /// non-trivial work to clean up after. Non-zero because it's |
1171 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1172 | /// something require destruction. |
1173 | DestructionKind isDestructedType() const { |
1174 | return isDestructedTypeImpl(*this); |
1175 | } |
1176 | |
1177 | /// Check if this is or contains a C union that is non-trivial to |
1178 | /// default-initialize, which is a union that has a member that is non-trivial |
1179 | /// to default-initialize. If this returns true, |
1180 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1181 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1182 | |
1183 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1184 | /// which is a union that has a member that is non-trivial to destruct. If |
1185 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1186 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1187 | |
1188 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1189 | /// is a union that has a member that is non-trivial to copy. If this returns |
1190 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1191 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1192 | |
1193 | /// Determine whether expressions of the given type are forbidden |
1194 | /// from being lvalues in C. |
1195 | /// |
1196 | /// The expression types that are forbidden to be lvalues are: |
1197 | /// - 'void', but not qualified void |
1198 | /// - function types |
1199 | /// |
1200 | /// The exact rule here is C99 6.3.2.1: |
1201 | /// An lvalue is an expression with an object type or an incomplete |
1202 | /// type other than void. |
1203 | bool isCForbiddenLValueType() const; |
1204 | |
1205 | /// Substitute type arguments for the Objective-C type parameters used in the |
1206 | /// subject type. |
1207 | /// |
1208 | /// \param ctx ASTContext in which the type exists. |
1209 | /// |
1210 | /// \param typeArgs The type arguments that will be substituted for the |
1211 | /// Objective-C type parameters in the subject type, which are generally |
1212 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1213 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1214 | /// for the context. |
1215 | /// |
1216 | /// \param context The context in which the subject type was written. |
1217 | /// |
1218 | /// \returns the resulting type. |
1219 | QualType substObjCTypeArgs(ASTContext &ctx, |
1220 | ArrayRef<QualType> typeArgs, |
1221 | ObjCSubstitutionContext context) const; |
1222 | |
1223 | /// Substitute type arguments from an object type for the Objective-C type |
1224 | /// parameters used in the subject type. |
1225 | /// |
1226 | /// This operation combines the computation of type arguments for |
1227 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1228 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1229 | /// callers that need to perform a single substitution in isolation. |
1230 | /// |
1231 | /// \param objectType The type of the object whose member type we're |
1232 | /// substituting into. For example, this might be the receiver of a message |
1233 | /// or the base of a property access. |
1234 | /// |
1235 | /// \param dc The declaration context from which the subject type was |
1236 | /// retrieved, which indicates (for example) which type parameters should |
1237 | /// be substituted. |
1238 | /// |
1239 | /// \param context The context in which the subject type was written. |
1240 | /// |
1241 | /// \returns the subject type after replacing all of the Objective-C type |
1242 | /// parameters with their corresponding arguments. |
1243 | QualType substObjCMemberType(QualType objectType, |
1244 | const DeclContext *dc, |
1245 | ObjCSubstitutionContext context) const; |
1246 | |
1247 | /// Strip Objective-C "__kindof" types from the given type. |
1248 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1249 | |
1250 | /// Remove all qualifiers including _Atomic. |
1251 | QualType getAtomicUnqualifiedType() const; |
1252 | |
1253 | private: |
1254 | // These methods are implemented in a separate translation unit; |
1255 | // "static"-ize them to avoid creating temporary QualTypes in the |
1256 | // caller. |
1257 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1258 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1259 | static SplitQualType getSplitDesugaredType(QualType T); |
1260 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1261 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1262 | const ASTContext &C); |
1263 | static QualType IgnoreParens(QualType T); |
1264 | static DestructionKind isDestructedTypeImpl(QualType type); |
1265 | |
1266 | /// Check if \param RD is or contains a non-trivial C union. |
1267 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1268 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1269 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1270 | }; |
1271 | |
1272 | } // namespace clang |
1273 | |
1274 | namespace llvm { |
1275 | |
1276 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1277 | /// to a specific Type class. |
1278 | template<> struct simplify_type< ::clang::QualType> { |
1279 | using SimpleType = const ::clang::Type *; |
1280 | |
1281 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1282 | return Val.getTypePtr(); |
1283 | } |
1284 | }; |
1285 | |
1286 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1287 | template<> |
1288 | struct PointerLikeTypeTraits<clang::QualType> { |
1289 | static inline void *getAsVoidPointer(clang::QualType P) { |
1290 | return P.getAsOpaquePtr(); |
1291 | } |
1292 | |
1293 | static inline clang::QualType getFromVoidPointer(void *P) { |
1294 | return clang::QualType::getFromOpaquePtr(P); |
1295 | } |
1296 | |
1297 | // Various qualifiers go in low bits. |
1298 | enum { NumLowBitsAvailable = 0 }; |
1299 | }; |
1300 | |
1301 | } // namespace llvm |
1302 | |
1303 | namespace clang { |
1304 | |
1305 | /// Base class that is common to both the \c ExtQuals and \c Type |
1306 | /// classes, which allows \c QualType to access the common fields between the |
1307 | /// two. |
1308 | class ExtQualsTypeCommonBase { |
1309 | friend class ExtQuals; |
1310 | friend class QualType; |
1311 | friend class Type; |
1312 | |
1313 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1314 | /// a self-referential pointer (for \c Type). |
1315 | /// |
1316 | /// This pointer allows an efficient mapping from a QualType to its |
1317 | /// underlying type pointer. |
1318 | const Type *const BaseType; |
1319 | |
1320 | /// The canonical type of this type. A QualType. |
1321 | QualType CanonicalType; |
1322 | |
1323 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1324 | : BaseType(baseType), CanonicalType(canon) {} |
1325 | }; |
1326 | |
1327 | /// We can encode up to four bits in the low bits of a |
1328 | /// type pointer, but there are many more type qualifiers that we want |
1329 | /// to be able to apply to an arbitrary type. Therefore we have this |
1330 | /// struct, intended to be heap-allocated and used by QualType to |
1331 | /// store qualifiers. |
1332 | /// |
1333 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1334 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1335 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1336 | /// Objective-C GC attributes) are much more rare. |
1337 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1338 | // NOTE: changing the fast qualifiers should be straightforward as |
1339 | // long as you don't make 'const' non-fast. |
1340 | // 1. Qualifiers: |
1341 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1342 | // Fast qualifiers must occupy the low-order bits. |
1343 | // b) Update Qualifiers::FastWidth and FastMask. |
1344 | // 2. QualType: |
1345 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1346 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1347 | // this header. |
1348 | // 3. ASTContext: |
1349 | // a) Update get{Volatile,Restrict}Type. |
1350 | |
1351 | /// The immutable set of qualifiers applied by this node. Always contains |
1352 | /// extended qualifiers. |
1353 | Qualifiers Quals; |
1354 | |
1355 | ExtQuals *this_() { return this; } |
1356 | |
1357 | public: |
1358 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1359 | : ExtQualsTypeCommonBase(baseType, |
1360 | canon.isNull() ? QualType(this_(), 0) : canon), |
1361 | Quals(quals) { |
1362 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1363, __PRETTY_FUNCTION__)) |
1363 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1363, __PRETTY_FUNCTION__)); |
1364 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1365, __PRETTY_FUNCTION__)) |
1365 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1365, __PRETTY_FUNCTION__)); |
1366 | } |
1367 | |
1368 | Qualifiers getQualifiers() const { return Quals; } |
1369 | |
1370 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1371 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1372 | |
1373 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1374 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1375 | return Quals.getObjCLifetime(); |
1376 | } |
1377 | |
1378 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1379 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1380 | |
1381 | const Type *getBaseType() const { return BaseType; } |
1382 | |
1383 | public: |
1384 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1385 | Profile(ID, getBaseType(), Quals); |
1386 | } |
1387 | |
1388 | static void Profile(llvm::FoldingSetNodeID &ID, |
1389 | const Type *BaseType, |
1390 | Qualifiers Quals) { |
1391 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1391, __PRETTY_FUNCTION__)); |
1392 | ID.AddPointer(BaseType); |
1393 | Quals.Profile(ID); |
1394 | } |
1395 | }; |
1396 | |
1397 | /// The kind of C++11 ref-qualifier associated with a function type. |
1398 | /// This determines whether a member function's "this" object can be an |
1399 | /// lvalue, rvalue, or neither. |
1400 | enum RefQualifierKind { |
1401 | /// No ref-qualifier was provided. |
1402 | RQ_None = 0, |
1403 | |
1404 | /// An lvalue ref-qualifier was provided (\c &). |
1405 | RQ_LValue, |
1406 | |
1407 | /// An rvalue ref-qualifier was provided (\c &&). |
1408 | RQ_RValue |
1409 | }; |
1410 | |
1411 | /// Which keyword(s) were used to create an AutoType. |
1412 | enum class AutoTypeKeyword { |
1413 | /// auto |
1414 | Auto, |
1415 | |
1416 | /// decltype(auto) |
1417 | DecltypeAuto, |
1418 | |
1419 | /// __auto_type (GNU extension) |
1420 | GNUAutoType |
1421 | }; |
1422 | |
1423 | /// The base class of the type hierarchy. |
1424 | /// |
1425 | /// A central concept with types is that each type always has a canonical |
1426 | /// type. A canonical type is the type with any typedef names stripped out |
1427 | /// of it or the types it references. For example, consider: |
1428 | /// |
1429 | /// typedef int foo; |
1430 | /// typedef foo* bar; |
1431 | /// 'int *' 'foo *' 'bar' |
1432 | /// |
1433 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1434 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1435 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1436 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1437 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1438 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1439 | /// is also 'int*'. |
1440 | /// |
1441 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1442 | /// information about typedefs being used. Canonical types are useful for type |
1443 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1444 | /// about whether something has a particular form (e.g. is a function type), |
1445 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1446 | /// |
1447 | /// Types, once created, are immutable. |
1448 | /// |
1449 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1450 | public: |
1451 | enum TypeClass { |
1452 | #define TYPE(Class, Base) Class, |
1453 | #define LAST_TYPE(Class) TypeLast = Class |
1454 | #define ABSTRACT_TYPE(Class, Base) |
1455 | #include "clang/AST/TypeNodes.inc" |
1456 | }; |
1457 | |
1458 | private: |
1459 | /// Bitfields required by the Type class. |
1460 | class TypeBitfields { |
1461 | friend class Type; |
1462 | template <class T> friend class TypePropertyCache; |
1463 | |
1464 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1465 | unsigned TC : 8; |
1466 | |
1467 | /// Whether this type is a dependent type (C++ [temp.dep.type]). |
1468 | unsigned Dependent : 1; |
1469 | |
1470 | /// Whether this type somehow involves a template parameter, even |
1471 | /// if the resolution of the type does not depend on a template parameter. |
1472 | unsigned InstantiationDependent : 1; |
1473 | |
1474 | /// Whether this type is a variably-modified type (C99 6.7.5). |
1475 | unsigned VariablyModified : 1; |
1476 | |
1477 | /// Whether this type contains an unexpanded parameter pack |
1478 | /// (for C++11 variadic templates). |
1479 | unsigned ContainsUnexpandedParameterPack : 1; |
1480 | |
1481 | /// True if the cache (i.e. the bitfields here starting with |
1482 | /// 'Cache') is valid. |
1483 | mutable unsigned CacheValid : 1; |
1484 | |
1485 | /// Linkage of this type. |
1486 | mutable unsigned CachedLinkage : 3; |
1487 | |
1488 | /// Whether this type involves and local or unnamed types. |
1489 | mutable unsigned CachedLocalOrUnnamed : 1; |
1490 | |
1491 | /// Whether this type comes from an AST file. |
1492 | mutable unsigned FromAST : 1; |
1493 | |
1494 | bool isCacheValid() const { |
1495 | return CacheValid; |
1496 | } |
1497 | |
1498 | Linkage getLinkage() const { |
1499 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1499, __PRETTY_FUNCTION__)); |
1500 | return static_cast<Linkage>(CachedLinkage); |
1501 | } |
1502 | |
1503 | bool hasLocalOrUnnamedType() const { |
1504 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 1504, __PRETTY_FUNCTION__)); |
1505 | return CachedLocalOrUnnamed; |
1506 | } |
1507 | }; |
1508 | enum { NumTypeBits = 18 }; |
1509 | |
1510 | protected: |
1511 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1512 | // into Type. |
1513 | |
1514 | class ArrayTypeBitfields { |
1515 | friend class ArrayType; |
1516 | |
1517 | unsigned : NumTypeBits; |
1518 | |
1519 | /// CVR qualifiers from declarations like |
1520 | /// 'int X[static restrict 4]'. For function parameters only. |
1521 | unsigned IndexTypeQuals : 3; |
1522 | |
1523 | /// Storage class qualifiers from declarations like |
1524 | /// 'int X[static restrict 4]'. For function parameters only. |
1525 | /// Actually an ArrayType::ArraySizeModifier. |
1526 | unsigned SizeModifier : 3; |
1527 | }; |
1528 | |
1529 | class ConstantArrayTypeBitfields { |
1530 | friend class ConstantArrayType; |
1531 | |
1532 | unsigned : NumTypeBits + 3 + 3; |
1533 | |
1534 | /// Whether we have a stored size expression. |
1535 | unsigned HasStoredSizeExpr : 1; |
1536 | }; |
1537 | |
1538 | class BuiltinTypeBitfields { |
1539 | friend class BuiltinType; |
1540 | |
1541 | unsigned : NumTypeBits; |
1542 | |
1543 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1544 | unsigned Kind : 8; |
1545 | }; |
1546 | |
1547 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1548 | /// Only common bits are stored here. Additional uncommon bits are stored |
1549 | /// in a trailing object after FunctionProtoType. |
1550 | class FunctionTypeBitfields { |
1551 | friend class FunctionProtoType; |
1552 | friend class FunctionType; |
1553 | |
1554 | unsigned : NumTypeBits; |
1555 | |
1556 | /// Extra information which affects how the function is called, like |
1557 | /// regparm and the calling convention. |
1558 | unsigned ExtInfo : 12; |
1559 | |
1560 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1561 | /// |
1562 | /// This is a value of type \c RefQualifierKind. |
1563 | unsigned RefQualifier : 2; |
1564 | |
1565 | /// Used only by FunctionProtoType, put here to pack with the |
1566 | /// other bitfields. |
1567 | /// The qualifiers are part of FunctionProtoType because... |
1568 | /// |
1569 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1570 | /// cv-qualifier-seq, [...], are part of the function type. |
1571 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1572 | /// Whether this function has extended Qualifiers. |
1573 | unsigned HasExtQuals : 1; |
1574 | |
1575 | /// The number of parameters this function has, not counting '...'. |
1576 | /// According to [implimits] 8 bits should be enough here but this is |
1577 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1578 | /// keep NumParams as wide as reasonably possible. |
1579 | unsigned NumParams : 16; |
1580 | |
1581 | /// The type of exception specification this function has. |
1582 | unsigned ExceptionSpecType : 4; |
1583 | |
1584 | /// Whether this function has extended parameter information. |
1585 | unsigned HasExtParameterInfos : 1; |
1586 | |
1587 | /// Whether the function is variadic. |
1588 | unsigned Variadic : 1; |
1589 | |
1590 | /// Whether this function has a trailing return type. |
1591 | unsigned HasTrailingReturn : 1; |
1592 | }; |
1593 | |
1594 | class ObjCObjectTypeBitfields { |
1595 | friend class ObjCObjectType; |
1596 | |
1597 | unsigned : NumTypeBits; |
1598 | |
1599 | /// The number of type arguments stored directly on this object type. |
1600 | unsigned NumTypeArgs : 7; |
1601 | |
1602 | /// The number of protocols stored directly on this object type. |
1603 | unsigned NumProtocols : 6; |
1604 | |
1605 | /// Whether this is a "kindof" type. |
1606 | unsigned IsKindOf : 1; |
1607 | }; |
1608 | |
1609 | class ReferenceTypeBitfields { |
1610 | friend class ReferenceType; |
1611 | |
1612 | unsigned : NumTypeBits; |
1613 | |
1614 | /// True if the type was originally spelled with an lvalue sigil. |
1615 | /// This is never true of rvalue references but can also be false |
1616 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1617 | /// as follows: |
1618 | /// |
1619 | /// typedef int &ref; // lvalue, spelled lvalue |
1620 | /// typedef int &&rvref; // rvalue |
1621 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1622 | /// ref &&a; // lvalue, inner ref |
1623 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1624 | /// rvref &&a; // rvalue, inner ref |
1625 | unsigned SpelledAsLValue : 1; |
1626 | |
1627 | /// True if the inner type is a reference type. This only happens |
1628 | /// in non-canonical forms. |
1629 | unsigned InnerRef : 1; |
1630 | }; |
1631 | |
1632 | class TypeWithKeywordBitfields { |
1633 | friend class TypeWithKeyword; |
1634 | |
1635 | unsigned : NumTypeBits; |
1636 | |
1637 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1638 | unsigned Keyword : 8; |
1639 | }; |
1640 | |
1641 | enum { NumTypeWithKeywordBits = 8 }; |
1642 | |
1643 | class ElaboratedTypeBitfields { |
1644 | friend class ElaboratedType; |
1645 | |
1646 | unsigned : NumTypeBits; |
1647 | unsigned : NumTypeWithKeywordBits; |
1648 | |
1649 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1650 | unsigned HasOwnedTagDecl : 1; |
1651 | }; |
1652 | |
1653 | class VectorTypeBitfields { |
1654 | friend class VectorType; |
1655 | friend class DependentVectorType; |
1656 | |
1657 | unsigned : NumTypeBits; |
1658 | |
1659 | /// The kind of vector, either a generic vector type or some |
1660 | /// target-specific vector type such as for AltiVec or Neon. |
1661 | unsigned VecKind : 3; |
1662 | |
1663 | /// The number of elements in the vector. |
1664 | unsigned NumElements : 29 - NumTypeBits; |
1665 | |
1666 | enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 }; |
1667 | }; |
1668 | |
1669 | class AttributedTypeBitfields { |
1670 | friend class AttributedType; |
1671 | |
1672 | unsigned : NumTypeBits; |
1673 | |
1674 | /// An AttributedType::Kind |
1675 | unsigned AttrKind : 32 - NumTypeBits; |
1676 | }; |
1677 | |
1678 | class AutoTypeBitfields { |
1679 | friend class AutoType; |
1680 | |
1681 | unsigned : NumTypeBits; |
1682 | |
1683 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1684 | /// or '__auto_type'? AutoTypeKeyword value. |
1685 | unsigned Keyword : 2; |
1686 | }; |
1687 | |
1688 | class SubstTemplateTypeParmPackTypeBitfields { |
1689 | friend class SubstTemplateTypeParmPackType; |
1690 | |
1691 | unsigned : NumTypeBits; |
1692 | |
1693 | /// The number of template arguments in \c Arguments, which is |
1694 | /// expected to be able to hold at least 1024 according to [implimits]. |
1695 | /// However as this limit is somewhat easy to hit with template |
1696 | /// metaprogramming we'd prefer to keep it as large as possible. |
1697 | /// At the moment it has been left as a non-bitfield since this type |
1698 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1699 | /// introduce the performance impact of a bitfield. |
1700 | unsigned NumArgs; |
1701 | }; |
1702 | |
1703 | class TemplateSpecializationTypeBitfields { |
1704 | friend class TemplateSpecializationType; |
1705 | |
1706 | unsigned : NumTypeBits; |
1707 | |
1708 | /// Whether this template specialization type is a substituted type alias. |
1709 | unsigned TypeAlias : 1; |
1710 | |
1711 | /// The number of template arguments named in this class template |
1712 | /// specialization, which is expected to be able to hold at least 1024 |
1713 | /// according to [implimits]. However, as this limit is somewhat easy to |
1714 | /// hit with template metaprogramming we'd prefer to keep it as large |
1715 | /// as possible. At the moment it has been left as a non-bitfield since |
1716 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1717 | /// to introduce the performance impact of a bitfield. |
1718 | unsigned NumArgs; |
1719 | }; |
1720 | |
1721 | class DependentTemplateSpecializationTypeBitfields { |
1722 | friend class DependentTemplateSpecializationType; |
1723 | |
1724 | unsigned : NumTypeBits; |
1725 | unsigned : NumTypeWithKeywordBits; |
1726 | |
1727 | /// The number of template arguments named in this class template |
1728 | /// specialization, which is expected to be able to hold at least 1024 |
1729 | /// according to [implimits]. However, as this limit is somewhat easy to |
1730 | /// hit with template metaprogramming we'd prefer to keep it as large |
1731 | /// as possible. At the moment it has been left as a non-bitfield since |
1732 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1733 | /// to introduce the performance impact of a bitfield. |
1734 | unsigned NumArgs; |
1735 | }; |
1736 | |
1737 | class PackExpansionTypeBitfields { |
1738 | friend class PackExpansionType; |
1739 | |
1740 | unsigned : NumTypeBits; |
1741 | |
1742 | /// The number of expansions that this pack expansion will |
1743 | /// generate when substituted (+1), which is expected to be able to |
1744 | /// hold at least 1024 according to [implimits]. However, as this limit |
1745 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1746 | /// keep it as large as possible. At the moment it has been left as a |
1747 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1748 | /// there is no reason to introduce the performance impact of a bitfield. |
1749 | /// |
1750 | /// This field will only have a non-zero value when some of the parameter |
1751 | /// packs that occur within the pattern have been substituted but others |
1752 | /// have not. |
1753 | unsigned NumExpansions; |
1754 | }; |
1755 | |
1756 | union { |
1757 | TypeBitfields TypeBits; |
1758 | ArrayTypeBitfields ArrayTypeBits; |
1759 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1760 | AttributedTypeBitfields AttributedTypeBits; |
1761 | AutoTypeBitfields AutoTypeBits; |
1762 | BuiltinTypeBitfields BuiltinTypeBits; |
1763 | FunctionTypeBitfields FunctionTypeBits; |
1764 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1765 | ReferenceTypeBitfields ReferenceTypeBits; |
1766 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1767 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1768 | VectorTypeBitfields VectorTypeBits; |
1769 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1770 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1771 | DependentTemplateSpecializationTypeBitfields |
1772 | DependentTemplateSpecializationTypeBits; |
1773 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1774 | |
1775 | static_assert(sizeof(TypeBitfields) <= 8, |
1776 | "TypeBitfields is larger than 8 bytes!"); |
1777 | static_assert(sizeof(ArrayTypeBitfields) <= 8, |
1778 | "ArrayTypeBitfields is larger than 8 bytes!"); |
1779 | static_assert(sizeof(AttributedTypeBitfields) <= 8, |
1780 | "AttributedTypeBitfields is larger than 8 bytes!"); |
1781 | static_assert(sizeof(AutoTypeBitfields) <= 8, |
1782 | "AutoTypeBitfields is larger than 8 bytes!"); |
1783 | static_assert(sizeof(BuiltinTypeBitfields) <= 8, |
1784 | "BuiltinTypeBitfields is larger than 8 bytes!"); |
1785 | static_assert(sizeof(FunctionTypeBitfields) <= 8, |
1786 | "FunctionTypeBitfields is larger than 8 bytes!"); |
1787 | static_assert(sizeof(ObjCObjectTypeBitfields) <= 8, |
1788 | "ObjCObjectTypeBitfields is larger than 8 bytes!"); |
1789 | static_assert(sizeof(ReferenceTypeBitfields) <= 8, |
1790 | "ReferenceTypeBitfields is larger than 8 bytes!"); |
1791 | static_assert(sizeof(TypeWithKeywordBitfields) <= 8, |
1792 | "TypeWithKeywordBitfields is larger than 8 bytes!"); |
1793 | static_assert(sizeof(ElaboratedTypeBitfields) <= 8, |
1794 | "ElaboratedTypeBitfields is larger than 8 bytes!"); |
1795 | static_assert(sizeof(VectorTypeBitfields) <= 8, |
1796 | "VectorTypeBitfields is larger than 8 bytes!"); |
1797 | static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8, |
1798 | "SubstTemplateTypeParmPackTypeBitfields is larger" |
1799 | " than 8 bytes!"); |
1800 | static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8, |
1801 | "TemplateSpecializationTypeBitfields is larger" |
1802 | " than 8 bytes!"); |
1803 | static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8, |
1804 | "DependentTemplateSpecializationTypeBitfields is larger" |
1805 | " than 8 bytes!"); |
1806 | static_assert(sizeof(PackExpansionTypeBitfields) <= 8, |
1807 | "PackExpansionTypeBitfields is larger than 8 bytes"); |
1808 | }; |
1809 | |
1810 | private: |
1811 | template <class T> friend class TypePropertyCache; |
1812 | |
1813 | /// Set whether this type comes from an AST file. |
1814 | void setFromAST(bool V = true) const { |
1815 | TypeBits.FromAST = V; |
1816 | } |
1817 | |
1818 | protected: |
1819 | friend class ASTContext; |
1820 | |
1821 | Type(TypeClass tc, QualType canon, bool Dependent, |
1822 | bool InstantiationDependent, bool VariablyModified, |
1823 | bool ContainsUnexpandedParameterPack) |
1824 | : ExtQualsTypeCommonBase(this, |
1825 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1826 | TypeBits.TC = tc; |
1827 | TypeBits.Dependent = Dependent; |
1828 | TypeBits.InstantiationDependent = Dependent || InstantiationDependent; |
1829 | TypeBits.VariablyModified = VariablyModified; |
1830 | TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1831 | TypeBits.CacheValid = false; |
1832 | TypeBits.CachedLocalOrUnnamed = false; |
1833 | TypeBits.CachedLinkage = NoLinkage; |
1834 | TypeBits.FromAST = false; |
1835 | } |
1836 | |
1837 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1838 | Type *this_() { return this; } |
1839 | |
1840 | void setDependent(bool D = true) { |
1841 | TypeBits.Dependent = D; |
1842 | if (D) |
1843 | TypeBits.InstantiationDependent = true; |
1844 | } |
1845 | |
1846 | void setInstantiationDependent(bool D = true) { |
1847 | TypeBits.InstantiationDependent = D; } |
1848 | |
1849 | void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; } |
1850 | |
1851 | void setContainsUnexpandedParameterPack(bool PP = true) { |
1852 | TypeBits.ContainsUnexpandedParameterPack = PP; |
1853 | } |
1854 | |
1855 | public: |
1856 | friend class ASTReader; |
1857 | friend class ASTWriter; |
1858 | template <class T> friend class serialization::AbstractTypeReader; |
1859 | template <class T> friend class serialization::AbstractTypeWriter; |
1860 | |
1861 | Type(const Type &) = delete; |
1862 | Type(Type &&) = delete; |
1863 | Type &operator=(const Type &) = delete; |
1864 | Type &operator=(Type &&) = delete; |
1865 | |
1866 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1867 | |
1868 | /// Whether this type comes from an AST file. |
1869 | bool isFromAST() const { return TypeBits.FromAST; } |
1870 | |
1871 | /// Whether this type is or contains an unexpanded parameter |
1872 | /// pack, used to support C++0x variadic templates. |
1873 | /// |
1874 | /// A type that contains a parameter pack shall be expanded by the |
1875 | /// ellipsis operator at some point. For example, the typedef in the |
1876 | /// following example contains an unexpanded parameter pack 'T': |
1877 | /// |
1878 | /// \code |
1879 | /// template<typename ...T> |
1880 | /// struct X { |
1881 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1882 | /// }; |
1883 | /// \endcode |
1884 | /// |
1885 | /// Note that this routine does not specify which |
1886 | bool containsUnexpandedParameterPack() const { |
1887 | return TypeBits.ContainsUnexpandedParameterPack; |
1888 | } |
1889 | |
1890 | /// Determines if this type would be canonical if it had no further |
1891 | /// qualification. |
1892 | bool isCanonicalUnqualified() const { |
1893 | return CanonicalType == QualType(this, 0); |
1894 | } |
1895 | |
1896 | /// Pull a single level of sugar off of this locally-unqualified type. |
1897 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1898 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1899 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1900 | |
1901 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1902 | /// object types, function types, and incomplete types. |
1903 | |
1904 | /// Return true if this is an incomplete type. |
1905 | /// A type that can describe objects, but which lacks information needed to |
1906 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1907 | /// routine will need to determine if the size is actually required. |
1908 | /// |
1909 | /// Def If non-null, and the type refers to some kind of declaration |
1910 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1911 | /// class), will be set to the declaration. |
1912 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1913 | |
1914 | /// Return true if this is an incomplete or object |
1915 | /// type, in other words, not a function type. |
1916 | bool isIncompleteOrObjectType() const { |
1917 | return !isFunctionType(); |
1918 | } |
1919 | |
1920 | /// Determine whether this type is an object type. |
1921 | bool isObjectType() const { |
1922 | // C++ [basic.types]p8: |
1923 | // An object type is a (possibly cv-qualified) type that is not a |
1924 | // function type, not a reference type, and not a void type. |
1925 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1926 | } |
1927 | |
1928 | /// Return true if this is a literal type |
1929 | /// (C++11 [basic.types]p10) |
1930 | bool isLiteralType(const ASTContext &Ctx) const; |
1931 | |
1932 | /// Test if this type is a standard-layout type. |
1933 | /// (C++0x [basic.type]p9) |
1934 | bool isStandardLayoutType() const; |
1935 | |
1936 | /// Helper methods to distinguish type categories. All type predicates |
1937 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1938 | |
1939 | /// Returns true if the type is a builtin type. |
1940 | bool isBuiltinType() const; |
1941 | |
1942 | /// Test for a particular builtin type. |
1943 | bool isSpecificBuiltinType(unsigned K) const; |
1944 | |
1945 | /// Test for a type which does not represent an actual type-system type but |
1946 | /// is instead used as a placeholder for various convenient purposes within |
1947 | /// Clang. All such types are BuiltinTypes. |
1948 | bool isPlaceholderType() const; |
1949 | const BuiltinType *getAsPlaceholderType() const; |
1950 | |
1951 | /// Test for a specific placeholder type. |
1952 | bool isSpecificPlaceholderType(unsigned K) const; |
1953 | |
1954 | /// Test for a placeholder type other than Overload; see |
1955 | /// BuiltinType::isNonOverloadPlaceholderType. |
1956 | bool isNonOverloadPlaceholderType() const; |
1957 | |
1958 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1959 | /// isComplexIntegerType() can be used to test for complex integers. |
1960 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1961 | bool isEnumeralType() const; |
1962 | |
1963 | /// Determine whether this type is a scoped enumeration type. |
1964 | bool isScopedEnumeralType() const; |
1965 | bool isBooleanType() const; |
1966 | bool isCharType() const; |
1967 | bool isWideCharType() const; |
1968 | bool isChar8Type() const; |
1969 | bool isChar16Type() const; |
1970 | bool isChar32Type() const; |
1971 | bool isAnyCharacterType() const; |
1972 | bool isIntegralType(const ASTContext &Ctx) const; |
1973 | |
1974 | /// Determine whether this type is an integral or enumeration type. |
1975 | bool isIntegralOrEnumerationType() const; |
1976 | |
1977 | /// Determine whether this type is an integral or unscoped enumeration type. |
1978 | bool isIntegralOrUnscopedEnumerationType() const; |
1979 | bool isUnscopedEnumerationType() const; |
1980 | |
1981 | /// Floating point categories. |
1982 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1983 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1984 | /// isComplexIntegerType() can be used to test for complex integers. |
1985 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1986 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1987 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1988 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1989 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1990 | bool isFloat128Type() const; |
1991 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1992 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1993 | bool isVoidType() const; // C99 6.2.5p19 |
1994 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1995 | bool isAggregateType() const; |
1996 | bool isFundamentalType() const; |
1997 | bool isCompoundType() const; |
1998 | |
1999 | // Type Predicates: Check to see if this type is structurally the specified |
2000 | // type, ignoring typedefs and qualifiers. |
2001 | bool isFunctionType() const; |
2002 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2003 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2004 | bool isPointerType() const; |
2005 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2006 | bool isBlockPointerType() const; |
2007 | bool isVoidPointerType() const; |
2008 | bool isReferenceType() const; |
2009 | bool isLValueReferenceType() const; |
2010 | bool isRValueReferenceType() const; |
2011 | bool isObjectPointerType() const; |
2012 | bool isFunctionPointerType() const; |
2013 | bool isFunctionReferenceType() const; |
2014 | bool isMemberPointerType() const; |
2015 | bool isMemberFunctionPointerType() const; |
2016 | bool isMemberDataPointerType() const; |
2017 | bool isArrayType() const; |
2018 | bool isConstantArrayType() const; |
2019 | bool isIncompleteArrayType() const; |
2020 | bool isVariableArrayType() const; |
2021 | bool isDependentSizedArrayType() const; |
2022 | bool isRecordType() const; |
2023 | bool isClassType() const; |
2024 | bool isStructureType() const; |
2025 | bool isObjCBoxableRecordType() const; |
2026 | bool isInterfaceType() const; |
2027 | bool isStructureOrClassType() const; |
2028 | bool isUnionType() const; |
2029 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2030 | bool isVectorType() const; // GCC vector type. |
2031 | bool isExtVectorType() const; // Extended vector type. |
2032 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2033 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2034 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2035 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2036 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2037 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2038 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2039 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2040 | // for the common case. |
2041 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2042 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2043 | bool isObjCQualifiedIdType() const; // id<foo> |
2044 | bool isObjCQualifiedClassType() const; // Class<foo> |
2045 | bool isObjCObjectOrInterfaceType() const; |
2046 | bool isObjCIdType() const; // id |
2047 | bool isDecltypeType() const; |
2048 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2049 | /// qualifier? |
2050 | /// |
2051 | /// This approximates the answer to the following question: if this |
2052 | /// translation unit were compiled in ARC, would this type be qualified |
2053 | /// with __unsafe_unretained? |
2054 | bool isObjCInertUnsafeUnretainedType() const { |
2055 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2056 | } |
2057 | |
2058 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2059 | /// object type, e.g., __kindof NSView * or __kindof id |
2060 | /// <NSCopying>. |
2061 | /// |
2062 | /// \param bound Will be set to the bound on non-id subtype types, |
2063 | /// which will be (possibly specialized) Objective-C class type, or |
2064 | /// null for 'id. |
2065 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2066 | const ObjCObjectType *&bound) const; |
2067 | |
2068 | bool isObjCClassType() const; // Class |
2069 | |
2070 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2071 | /// Class type, e.g., __kindof Class <NSCopying>. |
2072 | /// |
2073 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2074 | /// here because Objective-C's type system cannot express "a class |
2075 | /// object for a subclass of NSFoo". |
2076 | bool isObjCClassOrClassKindOfType() const; |
2077 | |
2078 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2079 | bool isObjCSelType() const; // Class |
2080 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2081 | bool isObjCARCBridgableType() const; |
2082 | bool isCARCBridgableType() const; |
2083 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2084 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2085 | bool isNothrowT() const; // C++ std::nothrow_t |
2086 | bool isAlignValT() const; // C++17 std::align_val_t |
2087 | bool isStdByteType() const; // C++17 std::byte |
2088 | bool isAtomicType() const; // C11 _Atomic() |
2089 | bool isUndeducedAutoType() const; // C++11 auto or |
2090 | // C++14 decltype(auto) |
2091 | |
2092 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2093 | bool is##Id##Type() const; |
2094 | #include "clang/Basic/OpenCLImageTypes.def" |
2095 | |
2096 | bool isImageType() const; // Any OpenCL image type |
2097 | |
2098 | bool isSamplerT() const; // OpenCL sampler_t |
2099 | bool isEventT() const; // OpenCL event_t |
2100 | bool isClkEventT() const; // OpenCL clk_event_t |
2101 | bool isQueueT() const; // OpenCL queue_t |
2102 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2103 | |
2104 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2105 | bool is##Id##Type() const; |
2106 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2107 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2108 | bool isOCLIntelSubgroupAVCType() const; |
2109 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2110 | |
2111 | bool isPipeType() const; // OpenCL pipe type |
2112 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2113 | |
2114 | /// Determines if this type, which must satisfy |
2115 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2116 | /// than implicitly __strong. |
2117 | bool isObjCARCImplicitlyUnretainedType() const; |
2118 | |
2119 | /// Return the implicit lifetime for this type, which must not be dependent. |
2120 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2121 | |
2122 | enum ScalarTypeKind { |
2123 | STK_CPointer, |
2124 | STK_BlockPointer, |
2125 | STK_ObjCObjectPointer, |
2126 | STK_MemberPointer, |
2127 | STK_Bool, |
2128 | STK_Integral, |
2129 | STK_Floating, |
2130 | STK_IntegralComplex, |
2131 | STK_FloatingComplex, |
2132 | STK_FixedPoint |
2133 | }; |
2134 | |
2135 | /// Given that this is a scalar type, classify it. |
2136 | ScalarTypeKind getScalarTypeKind() const; |
2137 | |
2138 | /// Whether this type is a dependent type, meaning that its definition |
2139 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2140 | bool isDependentType() const { return TypeBits.Dependent; } |
2141 | |
2142 | /// Determine whether this type is an instantiation-dependent type, |
2143 | /// meaning that the type involves a template parameter (even if the |
2144 | /// definition does not actually depend on the type substituted for that |
2145 | /// template parameter). |
2146 | bool isInstantiationDependentType() const { |
2147 | return TypeBits.InstantiationDependent; |
2148 | } |
2149 | |
2150 | /// Determine whether this type is an undeduced type, meaning that |
2151 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2152 | /// deduced. |
2153 | bool isUndeducedType() const; |
2154 | |
2155 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2156 | bool isVariablyModifiedType() const { return TypeBits.VariablyModified; } |
2157 | |
2158 | /// Whether this type involves a variable-length array type |
2159 | /// with a definite size. |
2160 | bool hasSizedVLAType() const; |
2161 | |
2162 | /// Whether this type is or contains a local or unnamed type. |
2163 | bool hasUnnamedOrLocalType() const; |
2164 | |
2165 | bool isOverloadableType() const; |
2166 | |
2167 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2168 | bool isElaboratedTypeSpecifier() const; |
2169 | |
2170 | bool canDecayToPointerType() const; |
2171 | |
2172 | /// Whether this type is represented natively as a pointer. This includes |
2173 | /// pointers, references, block pointers, and Objective-C interface, |
2174 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2175 | bool hasPointerRepresentation() const; |
2176 | |
2177 | /// Whether this type can represent an objective pointer type for the |
2178 | /// purpose of GC'ability |
2179 | bool hasObjCPointerRepresentation() const; |
2180 | |
2181 | /// Determine whether this type has an integer representation |
2182 | /// of some sort, e.g., it is an integer type or a vector. |
2183 | bool hasIntegerRepresentation() const; |
2184 | |
2185 | /// Determine whether this type has an signed integer representation |
2186 | /// of some sort, e.g., it is an signed integer type or a vector. |
2187 | bool hasSignedIntegerRepresentation() const; |
2188 | |
2189 | /// Determine whether this type has an unsigned integer representation |
2190 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2191 | bool hasUnsignedIntegerRepresentation() const; |
2192 | |
2193 | /// Determine whether this type has a floating-point representation |
2194 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2195 | bool hasFloatingRepresentation() const; |
2196 | |
2197 | // Type Checking Functions: Check to see if this type is structurally the |
2198 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2199 | // the best type we can. |
2200 | const RecordType *getAsStructureType() const; |
2201 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2202 | const RecordType *getAsUnionType() const; |
2203 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2204 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2205 | |
2206 | // The following is a convenience method that returns an ObjCObjectPointerType |
2207 | // for object declared using an interface. |
2208 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2209 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2210 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2211 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2212 | |
2213 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2214 | /// because the type is a RecordType or because it is the injected-class-name |
2215 | /// type of a class template or class template partial specialization. |
2216 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2217 | |
2218 | /// Retrieves the RecordDecl this type refers to. |
2219 | RecordDecl *getAsRecordDecl() const; |
2220 | |
2221 | /// Retrieves the TagDecl that this type refers to, either |
2222 | /// because the type is a TagType or because it is the injected-class-name |
2223 | /// type of a class template or class template partial specialization. |
2224 | TagDecl *getAsTagDecl() const; |
2225 | |
2226 | /// If this is a pointer or reference to a RecordType, return the |
2227 | /// CXXRecordDecl that the type refers to. |
2228 | /// |
2229 | /// If this is not a pointer or reference, or the type being pointed to does |
2230 | /// not refer to a CXXRecordDecl, returns NULL. |
2231 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2232 | |
2233 | /// Get the DeducedType whose type will be deduced for a variable with |
2234 | /// an initializer of this type. This looks through declarators like pointer |
2235 | /// types, but not through decltype or typedefs. |
2236 | DeducedType *getContainedDeducedType() const; |
2237 | |
2238 | /// Get the AutoType whose type will be deduced for a variable with |
2239 | /// an initializer of this type. This looks through declarators like pointer |
2240 | /// types, but not through decltype or typedefs. |
2241 | AutoType *getContainedAutoType() const { |
2242 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2243 | } |
2244 | |
2245 | /// Determine whether this type was written with a leading 'auto' |
2246 | /// corresponding to a trailing return type (possibly for a nested |
2247 | /// function type within a pointer to function type or similar). |
2248 | bool hasAutoForTrailingReturnType() const; |
2249 | |
2250 | /// Member-template getAs<specific type>'. Look through sugar for |
2251 | /// an instance of \<specific type>. This scheme will eventually |
2252 | /// replace the specific getAsXXXX methods above. |
2253 | /// |
2254 | /// There are some specializations of this member template listed |
2255 | /// immediately following this class. |
2256 | template <typename T> const T *getAs() const; |
2257 | |
2258 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2259 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2260 | /// This is used when you need to walk over sugar nodes that represent some |
2261 | /// kind of type adjustment from a type that was written as a \<specific type> |
2262 | /// to another type that is still canonically a \<specific type>. |
2263 | template <typename T> const T *getAsAdjusted() const; |
2264 | |
2265 | /// A variant of getAs<> for array types which silently discards |
2266 | /// qualifiers from the outermost type. |
2267 | const ArrayType *getAsArrayTypeUnsafe() const; |
2268 | |
2269 | /// Member-template castAs<specific type>. Look through sugar for |
2270 | /// the underlying instance of \<specific type>. |
2271 | /// |
2272 | /// This method has the same relationship to getAs<T> as cast<T> has |
2273 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2274 | /// have the intended type, and this method will never return null. |
2275 | template <typename T> const T *castAs() const; |
2276 | |
2277 | /// A variant of castAs<> for array type which silently discards |
2278 | /// qualifiers from the outermost type. |
2279 | const ArrayType *castAsArrayTypeUnsafe() const; |
2280 | |
2281 | /// Determine whether this type had the specified attribute applied to it |
2282 | /// (looking through top-level type sugar). |
2283 | bool hasAttr(attr::Kind AK) const; |
2284 | |
2285 | /// Get the base element type of this type, potentially discarding type |
2286 | /// qualifiers. This should never be used when type qualifiers |
2287 | /// are meaningful. |
2288 | const Type *getBaseElementTypeUnsafe() const; |
2289 | |
2290 | /// If this is an array type, return the element type of the array, |
2291 | /// potentially with type qualifiers missing. |
2292 | /// This should never be used when type qualifiers are meaningful. |
2293 | const Type *getArrayElementTypeNoTypeQual() const; |
2294 | |
2295 | /// If this is a pointer type, return the pointee type. |
2296 | /// If this is an array type, return the array element type. |
2297 | /// This should never be used when type qualifiers are meaningful. |
2298 | const Type *getPointeeOrArrayElementType() const; |
2299 | |
2300 | /// If this is a pointer, ObjC object pointer, or block |
2301 | /// pointer, this returns the respective pointee. |
2302 | QualType getPointeeType() const; |
2303 | |
2304 | /// Return the specified type with any "sugar" removed from the type, |
2305 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2306 | const Type *getUnqualifiedDesugaredType() const; |
2307 | |
2308 | /// More type predicates useful for type checking/promotion |
2309 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2310 | |
2311 | /// Return true if this is an integer type that is |
2312 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2313 | /// or an enum decl which has a signed representation. |
2314 | bool isSignedIntegerType() const; |
2315 | |
2316 | /// Return true if this is an integer type that is |
2317 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2318 | /// or an enum decl which has an unsigned representation. |
2319 | bool isUnsignedIntegerType() const; |
2320 | |
2321 | /// Determines whether this is an integer type that is signed or an |
2322 | /// enumeration types whose underlying type is a signed integer type. |
2323 | bool isSignedIntegerOrEnumerationType() const; |
2324 | |
2325 | /// Determines whether this is an integer type that is unsigned or an |
2326 | /// enumeration types whose underlying type is a unsigned integer type. |
2327 | bool isUnsignedIntegerOrEnumerationType() const; |
2328 | |
2329 | /// Return true if this is a fixed point type according to |
2330 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2331 | bool isFixedPointType() const; |
2332 | |
2333 | /// Return true if this is a fixed point or integer type. |
2334 | bool isFixedPointOrIntegerType() const; |
2335 | |
2336 | /// Return true if this is a saturated fixed point type according to |
2337 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2338 | bool isSaturatedFixedPointType() const; |
2339 | |
2340 | /// Return true if this is a saturated fixed point type according to |
2341 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2342 | bool isUnsaturatedFixedPointType() const; |
2343 | |
2344 | /// Return true if this is a fixed point type that is signed according |
2345 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2346 | bool isSignedFixedPointType() const; |
2347 | |
2348 | /// Return true if this is a fixed point type that is unsigned according |
2349 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2350 | bool isUnsignedFixedPointType() const; |
2351 | |
2352 | /// Return true if this is not a variable sized type, |
2353 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2354 | /// incomplete types. |
2355 | bool isConstantSizeType() const; |
2356 | |
2357 | /// Returns true if this type can be represented by some |
2358 | /// set of type specifiers. |
2359 | bool isSpecifierType() const; |
2360 | |
2361 | /// Determine the linkage of this type. |
2362 | Linkage getLinkage() const; |
2363 | |
2364 | /// Determine the visibility of this type. |
2365 | Visibility getVisibility() const { |
2366 | return getLinkageAndVisibility().getVisibility(); |
2367 | } |
2368 | |
2369 | /// Return true if the visibility was explicitly set is the code. |
2370 | bool isVisibilityExplicit() const { |
2371 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2372 | } |
2373 | |
2374 | /// Determine the linkage and visibility of this type. |
2375 | LinkageInfo getLinkageAndVisibility() const; |
2376 | |
2377 | /// True if the computed linkage is valid. Used for consistency |
2378 | /// checking. Should always return true. |
2379 | bool isLinkageValid() const; |
2380 | |
2381 | /// Determine the nullability of the given type. |
2382 | /// |
2383 | /// Note that nullability is only captured as sugar within the type |
2384 | /// system, not as part of the canonical type, so nullability will |
2385 | /// be lost by canonicalization and desugaring. |
2386 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2387 | |
2388 | /// Determine whether the given type can have a nullability |
2389 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2390 | /// |
2391 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2392 | /// this type can have nullability because it is dependent. |
2393 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2394 | |
2395 | /// Retrieve the set of substitutions required when accessing a member |
2396 | /// of the Objective-C receiver type that is declared in the given context. |
2397 | /// |
2398 | /// \c *this is the type of the object we're operating on, e.g., the |
2399 | /// receiver for a message send or the base of a property access, and is |
2400 | /// expected to be of some object or object pointer type. |
2401 | /// |
2402 | /// \param dc The declaration context for which we are building up a |
2403 | /// substitution mapping, which should be an Objective-C class, extension, |
2404 | /// category, or method within. |
2405 | /// |
2406 | /// \returns an array of type arguments that can be substituted for |
2407 | /// the type parameters of the given declaration context in any type described |
2408 | /// within that context, or an empty optional to indicate that no |
2409 | /// substitution is required. |
2410 | Optional<ArrayRef<QualType>> |
2411 | getObjCSubstitutions(const DeclContext *dc) const; |
2412 | |
2413 | /// Determines if this is an ObjC interface type that may accept type |
2414 | /// parameters. |
2415 | bool acceptsObjCTypeParams() const; |
2416 | |
2417 | const char *getTypeClassName() const; |
2418 | |
2419 | QualType getCanonicalTypeInternal() const { |
2420 | return CanonicalType; |
2421 | } |
2422 | |
2423 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2424 | void dump() const; |
2425 | void dump(llvm::raw_ostream &OS) const; |
2426 | }; |
2427 | |
2428 | /// This will check for a TypedefType by removing any existing sugar |
2429 | /// until it reaches a TypedefType or a non-sugared type. |
2430 | template <> const TypedefType *Type::getAs() const; |
2431 | |
2432 | /// This will check for a TemplateSpecializationType by removing any |
2433 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2434 | /// non-sugared type. |
2435 | template <> const TemplateSpecializationType *Type::getAs() const; |
2436 | |
2437 | /// This will check for an AttributedType by removing any existing sugar |
2438 | /// until it reaches an AttributedType or a non-sugared type. |
2439 | template <> const AttributedType *Type::getAs() const; |
2440 | |
2441 | // We can do canonical leaf types faster, because we don't have to |
2442 | // worry about preserving child type decoration. |
2443 | #define TYPE(Class, Base) |
2444 | #define LEAF_TYPE(Class) \ |
2445 | template <> inline const Class##Type *Type::getAs() const { \ |
2446 | return dyn_cast<Class##Type>(CanonicalType); \ |
2447 | } \ |
2448 | template <> inline const Class##Type *Type::castAs() const { \ |
2449 | return cast<Class##Type>(CanonicalType); \ |
2450 | } |
2451 | #include "clang/AST/TypeNodes.inc" |
2452 | |
2453 | /// This class is used for builtin types like 'int'. Builtin |
2454 | /// types are always canonical and have a literal name field. |
2455 | class BuiltinType : public Type { |
2456 | public: |
2457 | enum Kind { |
2458 | // OpenCL image types |
2459 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2460 | #include "clang/Basic/OpenCLImageTypes.def" |
2461 | // OpenCL extension types |
2462 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2463 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2464 | // SVE Types |
2465 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2466 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2467 | // All other builtin types |
2468 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2469 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2470 | #include "clang/AST/BuiltinTypes.def" |
2471 | }; |
2472 | |
2473 | private: |
2474 | friend class ASTContext; // ASTContext creates these. |
2475 | |
2476 | BuiltinType(Kind K) |
2477 | : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent), |
2478 | /*InstantiationDependent=*/(K == Dependent), |
2479 | /*VariablyModified=*/false, |
2480 | /*Unexpanded parameter pack=*/false) { |
2481 | BuiltinTypeBits.Kind = K; |
2482 | } |
2483 | |
2484 | public: |
2485 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2486 | StringRef getName(const PrintingPolicy &Policy) const; |
2487 | |
2488 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2489 | // The StringRef is null-terminated. |
2490 | StringRef str = getName(Policy); |
2491 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 2491, __PRETTY_FUNCTION__)); |
2492 | return str.data(); |
2493 | } |
2494 | |
2495 | bool isSugared() const { return false; } |
2496 | QualType desugar() const { return QualType(this, 0); } |
2497 | |
2498 | bool isInteger() const { |
2499 | return getKind() >= Bool && getKind() <= Int128; |
2500 | } |
2501 | |
2502 | bool isSignedInteger() const { |
2503 | return getKind() >= Char_S && getKind() <= Int128; |
2504 | } |
2505 | |
2506 | bool isUnsignedInteger() const { |
2507 | return getKind() >= Bool && getKind() <= UInt128; |
2508 | } |
2509 | |
2510 | bool isFloatingPoint() const { |
2511 | return getKind() >= Half && getKind() <= Float128; |
2512 | } |
2513 | |
2514 | /// Determines whether the given kind corresponds to a placeholder type. |
2515 | static bool isPlaceholderTypeKind(Kind K) { |
2516 | return K >= Overload; |
2517 | } |
2518 | |
2519 | /// Determines whether this type is a placeholder type, i.e. a type |
2520 | /// which cannot appear in arbitrary positions in a fully-formed |
2521 | /// expression. |
2522 | bool isPlaceholderType() const { |
2523 | return isPlaceholderTypeKind(getKind()); |
2524 | } |
2525 | |
2526 | /// Determines whether this type is a placeholder type other than |
2527 | /// Overload. Most placeholder types require only syntactic |
2528 | /// information about their context in order to be resolved (e.g. |
2529 | /// whether it is a call expression), which means they can (and |
2530 | /// should) be resolved in an earlier "phase" of analysis. |
2531 | /// Overload expressions sometimes pick up further information |
2532 | /// from their context, like whether the context expects a |
2533 | /// specific function-pointer type, and so frequently need |
2534 | /// special treatment. |
2535 | bool isNonOverloadPlaceholderType() const { |
2536 | return getKind() > Overload; |
2537 | } |
2538 | |
2539 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2540 | }; |
2541 | |
2542 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2543 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2544 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2545 | friend class ASTContext; // ASTContext creates these. |
2546 | |
2547 | QualType ElementType; |
2548 | |
2549 | ComplexType(QualType Element, QualType CanonicalPtr) |
2550 | : Type(Complex, CanonicalPtr, Element->isDependentType(), |
2551 | Element->isInstantiationDependentType(), |
2552 | Element->isVariablyModifiedType(), |
2553 | Element->containsUnexpandedParameterPack()), |
2554 | ElementType(Element) {} |
2555 | |
2556 | public: |
2557 | QualType getElementType() const { return ElementType; } |
2558 | |
2559 | bool isSugared() const { return false; } |
2560 | QualType desugar() const { return QualType(this, 0); } |
2561 | |
2562 | void Profile(llvm::FoldingSetNodeID &ID) { |
2563 | Profile(ID, getElementType()); |
2564 | } |
2565 | |
2566 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2567 | ID.AddPointer(Element.getAsOpaquePtr()); |
2568 | } |
2569 | |
2570 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2571 | }; |
2572 | |
2573 | /// Sugar for parentheses used when specifying types. |
2574 | class ParenType : public Type, public llvm::FoldingSetNode { |
2575 | friend class ASTContext; // ASTContext creates these. |
2576 | |
2577 | QualType Inner; |
2578 | |
2579 | ParenType(QualType InnerType, QualType CanonType) |
2580 | : Type(Paren, CanonType, InnerType->isDependentType(), |
2581 | InnerType->isInstantiationDependentType(), |
2582 | InnerType->isVariablyModifiedType(), |
2583 | InnerType->containsUnexpandedParameterPack()), |
2584 | Inner(InnerType) {} |
2585 | |
2586 | public: |
2587 | QualType getInnerType() const { return Inner; } |
2588 | |
2589 | bool isSugared() const { return true; } |
2590 | QualType desugar() const { return getInnerType(); } |
2591 | |
2592 | void Profile(llvm::FoldingSetNodeID &ID) { |
2593 | Profile(ID, getInnerType()); |
2594 | } |
2595 | |
2596 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2597 | Inner.Profile(ID); |
2598 | } |
2599 | |
2600 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2601 | }; |
2602 | |
2603 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2604 | class PointerType : public Type, public llvm::FoldingSetNode { |
2605 | friend class ASTContext; // ASTContext creates these. |
2606 | |
2607 | QualType PointeeType; |
2608 | |
2609 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2610 | : Type(Pointer, CanonicalPtr, Pointee->isDependentType(), |
2611 | Pointee->isInstantiationDependentType(), |
2612 | Pointee->isVariablyModifiedType(), |
2613 | Pointee->containsUnexpandedParameterPack()), |
2614 | PointeeType(Pointee) {} |
2615 | |
2616 | public: |
2617 | QualType getPointeeType() const { return PointeeType; } |
2618 | |
2619 | /// Returns true if address spaces of pointers overlap. |
2620 | /// OpenCL v2.0 defines conversion rules for pointers to different |
2621 | /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping |
2622 | /// address spaces. |
2623 | /// CL1.1 or CL1.2: |
2624 | /// address spaces overlap iff they are they same. |
2625 | /// CL2.0 adds: |
2626 | /// __generic overlaps with any address space except for __constant. |
2627 | bool isAddressSpaceOverlapping(const PointerType &other) const { |
2628 | Qualifiers thisQuals = PointeeType.getQualifiers(); |
2629 | Qualifiers otherQuals = other.getPointeeType().getQualifiers(); |
2630 | // Address spaces overlap if at least one of them is a superset of another |
2631 | return thisQuals.isAddressSpaceSupersetOf(otherQuals) || |
2632 | otherQuals.isAddressSpaceSupersetOf(thisQuals); |
2633 | } |
2634 | |
2635 | bool isSugared() const { return false; } |
2636 | QualType desugar() const { return QualType(this, 0); } |
2637 | |
2638 | void Profile(llvm::FoldingSetNodeID &ID) { |
2639 | Profile(ID, getPointeeType()); |
2640 | } |
2641 | |
2642 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2643 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2644 | } |
2645 | |
2646 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2647 | }; |
2648 | |
2649 | /// Represents a type which was implicitly adjusted by the semantic |
2650 | /// engine for arbitrary reasons. For example, array and function types can |
2651 | /// decay, and function types can have their calling conventions adjusted. |
2652 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2653 | QualType OriginalTy; |
2654 | QualType AdjustedTy; |
2655 | |
2656 | protected: |
2657 | friend class ASTContext; // ASTContext creates these. |
2658 | |
2659 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2660 | QualType CanonicalPtr) |
2661 | : Type(TC, CanonicalPtr, OriginalTy->isDependentType(), |
2662 | OriginalTy->isInstantiationDependentType(), |
2663 | OriginalTy->isVariablyModifiedType(), |
2664 | OriginalTy->containsUnexpandedParameterPack()), |
2665 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2666 | |
2667 | public: |
2668 | QualType getOriginalType() const { return OriginalTy; } |
2669 | QualType getAdjustedType() const { return AdjustedTy; } |
2670 | |
2671 | bool isSugared() const { return true; } |
2672 | QualType desugar() const { return AdjustedTy; } |
2673 | |
2674 | void Profile(llvm::FoldingSetNodeID &ID) { |
2675 | Profile(ID, OriginalTy, AdjustedTy); |
2676 | } |
2677 | |
2678 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2679 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2680 | ID.AddPointer(New.getAsOpaquePtr()); |
2681 | } |
2682 | |
2683 | static bool classof(const Type *T) { |
2684 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2685 | } |
2686 | }; |
2687 | |
2688 | /// Represents a pointer type decayed from an array or function type. |
2689 | class DecayedType : public AdjustedType { |
2690 | friend class ASTContext; // ASTContext creates these. |
2691 | |
2692 | inline |
2693 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2694 | |
2695 | public: |
2696 | QualType getDecayedType() const { return getAdjustedType(); } |
2697 | |
2698 | inline QualType getPointeeType() const; |
2699 | |
2700 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2701 | }; |
2702 | |
2703 | /// Pointer to a block type. |
2704 | /// This type is to represent types syntactically represented as |
2705 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2706 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2707 | friend class ASTContext; // ASTContext creates these. |
2708 | |
2709 | // Block is some kind of pointer type |
2710 | QualType PointeeType; |
2711 | |
2712 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2713 | : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(), |
2714 | Pointee->isInstantiationDependentType(), |
2715 | Pointee->isVariablyModifiedType(), |
2716 | Pointee->containsUnexpandedParameterPack()), |
2717 | PointeeType(Pointee) {} |
2718 | |
2719 | public: |
2720 | // Get the pointee type. Pointee is required to always be a function type. |
2721 | QualType getPointeeType() const { return PointeeType; } |
2722 | |
2723 | bool isSugared() const { return false; } |
2724 | QualType desugar() const { return QualType(this, 0); } |
2725 | |
2726 | void Profile(llvm::FoldingSetNodeID &ID) { |
2727 | Profile(ID, getPointeeType()); |
2728 | } |
2729 | |
2730 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2731 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2732 | } |
2733 | |
2734 | static bool classof(const Type *T) { |
2735 | return T->getTypeClass() == BlockPointer; |
2736 | } |
2737 | }; |
2738 | |
2739 | /// Base for LValueReferenceType and RValueReferenceType |
2740 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2741 | QualType PointeeType; |
2742 | |
2743 | protected: |
2744 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2745 | bool SpelledAsLValue) |
2746 | : Type(tc, CanonicalRef, Referencee->isDependentType(), |
2747 | Referencee->isInstantiationDependentType(), |
2748 | Referencee->isVariablyModifiedType(), |
2749 | Referencee->containsUnexpandedParameterPack()), |
2750 | PointeeType(Referencee) { |
2751 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2752 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2753 | } |
2754 | |
2755 | public: |
2756 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2757 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2758 | |
2759 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2760 | |
2761 | QualType getPointeeType() const { |
2762 | // FIXME: this might strip inner qualifiers; okay? |
2763 | const ReferenceType *T = this; |
2764 | while (T->isInnerRef()) |
2765 | T = T->PointeeType->castAs<ReferenceType>(); |
2766 | return T->PointeeType; |
2767 | } |
2768 | |
2769 | void Profile(llvm::FoldingSetNodeID &ID) { |
2770 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2771 | } |
2772 | |
2773 | static void Profile(llvm::FoldingSetNodeID &ID, |
2774 | QualType Referencee, |
2775 | bool SpelledAsLValue) { |
2776 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2777 | ID.AddBoolean(SpelledAsLValue); |
2778 | } |
2779 | |
2780 | static bool classof(const Type *T) { |
2781 | return T->getTypeClass() == LValueReference || |
2782 | T->getTypeClass() == RValueReference; |
2783 | } |
2784 | }; |
2785 | |
2786 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2787 | class LValueReferenceType : public ReferenceType { |
2788 | friend class ASTContext; // ASTContext creates these |
2789 | |
2790 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2791 | bool SpelledAsLValue) |
2792 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2793 | SpelledAsLValue) {} |
2794 | |
2795 | public: |
2796 | bool isSugared() const { return false; } |
2797 | QualType desugar() const { return QualType(this, 0); } |
2798 | |
2799 | static bool classof(const Type *T) { |
2800 | return T->getTypeClass() == LValueReference; |
2801 | } |
2802 | }; |
2803 | |
2804 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2805 | class RValueReferenceType : public ReferenceType { |
2806 | friend class ASTContext; // ASTContext creates these |
2807 | |
2808 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2809 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2810 | |
2811 | public: |
2812 | bool isSugared() const { return false; } |
2813 | QualType desugar() const { return QualType(this, 0); } |
2814 | |
2815 | static bool classof(const Type *T) { |
2816 | return T->getTypeClass() == RValueReference; |
2817 | } |
2818 | }; |
2819 | |
2820 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2821 | /// |
2822 | /// This includes both pointers to data members and pointer to member functions. |
2823 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2824 | friend class ASTContext; // ASTContext creates these. |
2825 | |
2826 | QualType PointeeType; |
2827 | |
2828 | /// The class of which the pointee is a member. Must ultimately be a |
2829 | /// RecordType, but could be a typedef or a template parameter too. |
2830 | const Type *Class; |
2831 | |
2832 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2833 | : Type(MemberPointer, CanonicalPtr, |
2834 | Cls->isDependentType() || Pointee->isDependentType(), |
2835 | (Cls->isInstantiationDependentType() || |
2836 | Pointee->isInstantiationDependentType()), |
2837 | Pointee->isVariablyModifiedType(), |
2838 | (Cls->containsUnexpandedParameterPack() || |
2839 | Pointee->containsUnexpandedParameterPack())), |
2840 | PointeeType(Pointee), Class(Cls) {} |
2841 | |
2842 | public: |
2843 | QualType getPointeeType() const { return PointeeType; } |
2844 | |
2845 | /// Returns true if the member type (i.e. the pointee type) is a |
2846 | /// function type rather than a data-member type. |
2847 | bool isMemberFunctionPointer() const { |
2848 | return PointeeType->isFunctionProtoType(); |
2849 | } |
2850 | |
2851 | /// Returns true if the member type (i.e. the pointee type) is a |
2852 | /// data type rather than a function type. |
2853 | bool isMemberDataPointer() const { |
2854 | return !PointeeType->isFunctionProtoType(); |
2855 | } |
2856 | |
2857 | const Type *getClass() const { return Class; } |
2858 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2859 | |
2860 | bool isSugared() const { return false; } |
2861 | QualType desugar() const { return QualType(this, 0); } |
2862 | |
2863 | void Profile(llvm::FoldingSetNodeID &ID) { |
2864 | Profile(ID, getPointeeType(), getClass()); |
2865 | } |
2866 | |
2867 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2868 | const Type *Class) { |
2869 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2870 | ID.AddPointer(Class); |
2871 | } |
2872 | |
2873 | static bool classof(const Type *T) { |
2874 | return T->getTypeClass() == MemberPointer; |
2875 | } |
2876 | }; |
2877 | |
2878 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2879 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2880 | public: |
2881 | /// Capture whether this is a normal array (e.g. int X[4]) |
2882 | /// an array with a static size (e.g. int X[static 4]), or an array |
2883 | /// with a star size (e.g. int X[*]). |
2884 | /// 'static' is only allowed on function parameters. |
2885 | enum ArraySizeModifier { |
2886 | Normal, Static, Star |
2887 | }; |
2888 | |
2889 | private: |
2890 | /// The element type of the array. |
2891 | QualType ElementType; |
2892 | |
2893 | protected: |
2894 | friend class ASTContext; // ASTContext creates these. |
2895 | |
2896 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2897 | unsigned tq, const Expr *sz = nullptr); |
2898 | |
2899 | public: |
2900 | QualType getElementType() const { return ElementType; } |
2901 | |
2902 | ArraySizeModifier getSizeModifier() const { |
2903 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2904 | } |
2905 | |
2906 | Qualifiers getIndexTypeQualifiers() const { |
2907 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2908 | } |
2909 | |
2910 | unsigned getIndexTypeCVRQualifiers() const { |
2911 | return ArrayTypeBits.IndexTypeQuals; |
2912 | } |
2913 | |
2914 | static bool classof(const Type *T) { |
2915 | return T->getTypeClass() == ConstantArray || |
2916 | T->getTypeClass() == VariableArray || |
2917 | T->getTypeClass() == IncompleteArray || |
2918 | T->getTypeClass() == DependentSizedArray; |
2919 | } |
2920 | }; |
2921 | |
2922 | /// Represents the canonical version of C arrays with a specified constant size. |
2923 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2924 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2925 | class ConstantArrayType final |
2926 | : public ArrayType, |
2927 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2928 | friend class ASTContext; // ASTContext creates these. |
2929 | friend TrailingObjects; |
2930 | |
2931 | llvm::APInt Size; // Allows us to unique the type. |
2932 | |
2933 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2934 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2935 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2936 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2937 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2938 | assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size" ) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 2938, __PRETTY_FUNCTION__)); |
2939 | *getTrailingObjects<const Expr*>() = sz; |
2940 | } |
2941 | } |
2942 | |
2943 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2944 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2945 | } |
2946 | |
2947 | public: |
2948 | const llvm::APInt &getSize() const { return Size; } |
2949 | const Expr *getSizeExpr() const { |
2950 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2951 | ? *getTrailingObjects<const Expr *>() |
2952 | : nullptr; |
2953 | } |
2954 | bool isSugared() const { return false; } |
2955 | QualType desugar() const { return QualType(this, 0); } |
2956 | |
2957 | /// Determine the number of bits required to address a member of |
2958 | // an array with the given element type and number of elements. |
2959 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2960 | QualType ElementType, |
2961 | const llvm::APInt &NumElements); |
2962 | |
2963 | /// Determine the maximum number of active bits that an array's size |
2964 | /// can require, which limits the maximum size of the array. |
2965 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2966 | |
2967 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2968 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2969 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2970 | } |
2971 | |
2972 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2973 | QualType ET, const llvm::APInt &ArraySize, |
2974 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2975 | unsigned TypeQuals); |
2976 | |
2977 | static bool classof(const Type *T) { |
2978 | return T->getTypeClass() == ConstantArray; |
2979 | } |
2980 | }; |
2981 | |
2982 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2983 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2984 | /// unspecified. |
2985 | class IncompleteArrayType : public ArrayType { |
2986 | friend class ASTContext; // ASTContext creates these. |
2987 | |
2988 | IncompleteArrayType(QualType et, QualType can, |
2989 | ArraySizeModifier sm, unsigned tq) |
2990 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2991 | |
2992 | public: |
2993 | friend class StmtIteratorBase; |
2994 | |
2995 | bool isSugared() const { return false; } |
2996 | QualType desugar() const { return QualType(this, 0); } |
2997 | |
2998 | static bool classof(const Type *T) { |
2999 | return T->getTypeClass() == IncompleteArray; |
3000 | } |
3001 | |
3002 | void Profile(llvm::FoldingSetNodeID &ID) { |
3003 | Profile(ID, getElementType(), getSizeModifier(), |
3004 | getIndexTypeCVRQualifiers()); |
3005 | } |
3006 | |
3007 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
3008 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
3009 | ID.AddPointer(ET.getAsOpaquePtr()); |
3010 | ID.AddInteger(SizeMod); |
3011 | ID.AddInteger(TypeQuals); |
3012 | } |
3013 | }; |
3014 | |
3015 | /// Represents a C array with a specified size that is not an |
3016 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
3017 | /// Since the size expression is an arbitrary expression, we store it as such. |
3018 | /// |
3019 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3020 | /// should not be: two lexically equivalent variable array types could mean |
3021 | /// different things, for example, these variables do not have the same type |
3022 | /// dynamically: |
3023 | /// |
3024 | /// void foo(int x) { |
3025 | /// int Y[x]; |
3026 | /// ++x; |
3027 | /// int Z[x]; |
3028 | /// } |
3029 | class VariableArrayType : public ArrayType { |
3030 | friend class ASTContext; // ASTContext creates these. |
3031 | |
3032 | /// An assignment-expression. VLA's are only permitted within |
3033 | /// a function block. |
3034 | Stmt *SizeExpr; |
3035 | |
3036 | /// The range spanned by the left and right array brackets. |
3037 | SourceRange Brackets; |
3038 | |
3039 | VariableArrayType(QualType et, QualType can, Expr *e, |
3040 | ArraySizeModifier sm, unsigned tq, |
3041 | SourceRange brackets) |
3042 | : ArrayType(VariableArray, et, can, sm, tq, e), |
3043 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3044 | |
3045 | public: |
3046 | friend class StmtIteratorBase; |
3047 | |
3048 | Expr *getSizeExpr() const { |
3049 | // We use C-style casts instead of cast<> here because we do not wish |
3050 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3051 | return (Expr*) SizeExpr; |
3052 | } |
3053 | |
3054 | SourceRange getBracketsRange() const { return Brackets; } |
3055 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3056 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3057 | |
3058 | bool isSugared() const { return false; } |
3059 | QualType desugar() const { return QualType(this, 0); } |
3060 | |
3061 | static bool classof(const Type *T) { |
3062 | return T->getTypeClass() == VariableArray; |
3063 | } |
3064 | |
3065 | void Profile(llvm::FoldingSetNodeID &ID) { |
3066 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 3066); |
3067 | } |
3068 | }; |
3069 | |
3070 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3071 | /// |
3072 | /// For example: |
3073 | /// \code |
3074 | /// template<typename T, int Size> |
3075 | /// class array { |
3076 | /// T data[Size]; |
3077 | /// }; |
3078 | /// \endcode |
3079 | /// |
3080 | /// For these types, we won't actually know what the array bound is |
3081 | /// until template instantiation occurs, at which point this will |
3082 | /// become either a ConstantArrayType or a VariableArrayType. |
3083 | class DependentSizedArrayType : public ArrayType { |
3084 | friend class ASTContext; // ASTContext creates these. |
3085 | |
3086 | const ASTContext &Context; |
3087 | |
3088 | /// An assignment expression that will instantiate to the |
3089 | /// size of the array. |
3090 | /// |
3091 | /// The expression itself might be null, in which case the array |
3092 | /// type will have its size deduced from an initializer. |
3093 | Stmt *SizeExpr; |
3094 | |
3095 | /// The range spanned by the left and right array brackets. |
3096 | SourceRange Brackets; |
3097 | |
3098 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3099 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3100 | SourceRange brackets); |
3101 | |
3102 | public: |
3103 | friend class StmtIteratorBase; |
3104 | |
3105 | Expr *getSizeExpr() const { |
3106 | // We use C-style casts instead of cast<> here because we do not wish |
3107 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3108 | return (Expr*) SizeExpr; |
3109 | } |
3110 | |
3111 | SourceRange getBracketsRange() const { return Brackets; } |
3112 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3113 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3114 | |
3115 | bool isSugared() const { return false; } |
3116 | QualType desugar() const { return QualType(this, 0); } |
3117 | |
3118 | static bool classof(const Type *T) { |
3119 | return T->getTypeClass() == DependentSizedArray; |
3120 | } |
3121 | |
3122 | void Profile(llvm::FoldingSetNodeID &ID) { |
3123 | Profile(ID, Context, getElementType(), |
3124 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3125 | } |
3126 | |
3127 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3128 | QualType ET, ArraySizeModifier SizeMod, |
3129 | unsigned TypeQuals, Expr *E); |
3130 | }; |
3131 | |
3132 | /// Represents an extended address space qualifier where the input address space |
3133 | /// value is dependent. Non-dependent address spaces are not represented with a |
3134 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3135 | /// |
3136 | /// For example: |
3137 | /// \code |
3138 | /// template<typename T, int AddrSpace> |
3139 | /// class AddressSpace { |
3140 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3141 | /// } |
3142 | /// \endcode |
3143 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3144 | friend class ASTContext; |
3145 | |
3146 | const ASTContext &Context; |
3147 | Expr *AddrSpaceExpr; |
3148 | QualType PointeeType; |
3149 | SourceLocation loc; |
3150 | |
3151 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3152 | QualType can, Expr *AddrSpaceExpr, |
3153 | SourceLocation loc); |
3154 | |
3155 | public: |
3156 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3157 | QualType getPointeeType() const { return PointeeType; } |
3158 | SourceLocation getAttributeLoc() const { return loc; } |
3159 | |
3160 | bool isSugared() const { return false; } |
3161 | QualType desugar() const { return QualType(this, 0); } |
3162 | |
3163 | static bool classof(const Type *T) { |
3164 | return T->getTypeClass() == DependentAddressSpace; |
3165 | } |
3166 | |
3167 | void Profile(llvm::FoldingSetNodeID &ID) { |
3168 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3169 | } |
3170 | |
3171 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3172 | QualType PointeeType, Expr *AddrSpaceExpr); |
3173 | }; |
3174 | |
3175 | /// Represents an extended vector type where either the type or size is |
3176 | /// dependent. |
3177 | /// |
3178 | /// For example: |
3179 | /// \code |
3180 | /// template<typename T, int Size> |
3181 | /// class vector { |
3182 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3183 | /// } |
3184 | /// \endcode |
3185 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3186 | friend class ASTContext; |
3187 | |
3188 | const ASTContext &Context; |
3189 | Expr *SizeExpr; |
3190 | |
3191 | /// The element type of the array. |
3192 | QualType ElementType; |
3193 | |
3194 | SourceLocation loc; |
3195 | |
3196 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3197 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3198 | |
3199 | public: |
3200 | Expr *getSizeExpr() const { return SizeExpr; } |
3201 | QualType getElementType() const { return ElementType; } |
3202 | SourceLocation getAttributeLoc() const { return loc; } |
3203 | |
3204 | bool isSugared() const { return false; } |
3205 | QualType desugar() const { return QualType(this, 0); } |
3206 | |
3207 | static bool classof(const Type *T) { |
3208 | return T->getTypeClass() == DependentSizedExtVector; |
3209 | } |
3210 | |
3211 | void Profile(llvm::FoldingSetNodeID &ID) { |
3212 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3213 | } |
3214 | |
3215 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3216 | QualType ElementType, Expr *SizeExpr); |
3217 | }; |
3218 | |
3219 | |
3220 | /// Represents a GCC generic vector type. This type is created using |
3221 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3222 | /// bytes; or from an Altivec __vector or vector declaration. |
3223 | /// Since the constructor takes the number of vector elements, the |
3224 | /// client is responsible for converting the size into the number of elements. |
3225 | class VectorType : public Type, public llvm::FoldingSetNode { |
3226 | public: |
3227 | enum VectorKind { |
3228 | /// not a target-specific vector type |
3229 | GenericVector, |
3230 | |
3231 | /// is AltiVec vector |
3232 | AltiVecVector, |
3233 | |
3234 | /// is AltiVec 'vector Pixel' |
3235 | AltiVecPixel, |
3236 | |
3237 | /// is AltiVec 'vector bool ...' |
3238 | AltiVecBool, |
3239 | |
3240 | /// is ARM Neon vector |
3241 | NeonVector, |
3242 | |
3243 | /// is ARM Neon polynomial vector |
3244 | NeonPolyVector |
3245 | }; |
3246 | |
3247 | protected: |
3248 | friend class ASTContext; // ASTContext creates these. |
3249 | |
3250 | /// The element type of the vector. |
3251 | QualType ElementType; |
3252 | |
3253 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3254 | VectorKind vecKind); |
3255 | |
3256 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3257 | QualType canonType, VectorKind vecKind); |
3258 | |
3259 | public: |
3260 | QualType getElementType() const { return ElementType; } |
3261 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3262 | |
3263 | static bool isVectorSizeTooLarge(unsigned NumElements) { |
3264 | return NumElements > VectorTypeBitfields::MaxNumElements; |
3265 | } |
3266 | |
3267 | bool isSugared() const { return false; } |
3268 | QualType desugar() const { return QualType(this, 0); } |
3269 | |
3270 | VectorKind getVectorKind() const { |
3271 | return VectorKind(VectorTypeBits.VecKind); |
3272 | } |
3273 | |
3274 | void Profile(llvm::FoldingSetNodeID &ID) { |
3275 | Profile(ID, getElementType(), getNumElements(), |
3276 | getTypeClass(), getVectorKind()); |
3277 | } |
3278 | |
3279 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3280 | unsigned NumElements, TypeClass TypeClass, |
3281 | VectorKind VecKind) { |
3282 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3283 | ID.AddInteger(NumElements); |
3284 | ID.AddInteger(TypeClass); |
3285 | ID.AddInteger(VecKind); |
3286 | } |
3287 | |
3288 | static bool classof(const Type *T) { |
3289 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3290 | } |
3291 | }; |
3292 | |
3293 | /// Represents a vector type where either the type or size is dependent. |
3294 | //// |
3295 | /// For example: |
3296 | /// \code |
3297 | /// template<typename T, int Size> |
3298 | /// class vector { |
3299 | /// typedef T __attribute__((vector_size(Size))) type; |
3300 | /// } |
3301 | /// \endcode |
3302 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3303 | friend class ASTContext; |
3304 | |
3305 | const ASTContext &Context; |
3306 | QualType ElementType; |
3307 | Expr *SizeExpr; |
3308 | SourceLocation Loc; |
3309 | |
3310 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3311 | QualType CanonType, Expr *SizeExpr, |
3312 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3313 | |
3314 | public: |
3315 | Expr *getSizeExpr() const { return SizeExpr; } |
3316 | QualType getElementType() const { return ElementType; } |
3317 | SourceLocation getAttributeLoc() const { return Loc; } |
3318 | VectorType::VectorKind getVectorKind() const { |
3319 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3320 | } |
3321 | |
3322 | bool isSugared() const { return false; } |
3323 | QualType desugar() const { return QualType(this, 0); } |
3324 | |
3325 | static bool classof(const Type *T) { |
3326 | return T->getTypeClass() == DependentVector; |
3327 | } |
3328 | |
3329 | void Profile(llvm::FoldingSetNodeID &ID) { |
3330 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3331 | } |
3332 | |
3333 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3334 | QualType ElementType, const Expr *SizeExpr, |
3335 | VectorType::VectorKind VecKind); |
3336 | }; |
3337 | |
3338 | /// ExtVectorType - Extended vector type. This type is created using |
3339 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3340 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3341 | /// class enables syntactic extensions, like Vector Components for accessing |
3342 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3343 | /// Shading Language). |
3344 | class ExtVectorType : public VectorType { |
3345 | friend class ASTContext; // ASTContext creates these. |
3346 | |
3347 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3348 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3349 | |
3350 | public: |
3351 | static int getPointAccessorIdx(char c) { |
3352 | switch (c) { |
3353 | default: return -1; |
3354 | case 'x': case 'r': return 0; |
3355 | case 'y': case 'g': return 1; |
3356 | case 'z': case 'b': return 2; |
3357 | case 'w': case 'a': return 3; |
3358 | } |
3359 | } |
3360 | |
3361 | static int getNumericAccessorIdx(char c) { |
3362 | switch (c) { |
3363 | default: return -1; |
3364 | case '0': return 0; |
3365 | case '1': return 1; |
3366 | case '2': return 2; |
3367 | case '3': return 3; |
3368 | case '4': return 4; |
3369 | case '5': return 5; |
3370 | case '6': return 6; |
3371 | case '7': return 7; |
3372 | case '8': return 8; |
3373 | case '9': return 9; |
3374 | case 'A': |
3375 | case 'a': return 10; |
3376 | case 'B': |
3377 | case 'b': return 11; |
3378 | case 'C': |
3379 | case 'c': return 12; |
3380 | case 'D': |
3381 | case 'd': return 13; |
3382 | case 'E': |
3383 | case 'e': return 14; |
3384 | case 'F': |
3385 | case 'f': return 15; |
3386 | } |
3387 | } |
3388 | |
3389 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3390 | if (isNumericAccessor) |
3391 | return getNumericAccessorIdx(c); |
3392 | else |
3393 | return getPointAccessorIdx(c); |
3394 | } |
3395 | |
3396 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3397 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3398 | return unsigned(idx-1) < getNumElements(); |
3399 | return false; |
3400 | } |
3401 | |
3402 | bool isSugared() const { return false; } |
3403 | QualType desugar() const { return QualType(this, 0); } |
3404 | |
3405 | static bool classof(const Type *T) { |
3406 | return T->getTypeClass() == ExtVector; |
3407 | } |
3408 | }; |
3409 | |
3410 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3411 | /// class of FunctionNoProtoType and FunctionProtoType. |
3412 | class FunctionType : public Type { |
3413 | // The type returned by the function. |
3414 | QualType ResultType; |
3415 | |
3416 | public: |
3417 | /// Interesting information about a specific parameter that can't simply |
3418 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3419 | /// but is in FunctionType to make this class available during the |
3420 | /// specification of the bases of FunctionProtoType. |
3421 | /// |
3422 | /// It makes sense to model language features this way when there's some |
3423 | /// sort of parameter-specific override (such as an attribute) that |
3424 | /// affects how the function is called. For example, the ARC ns_consumed |
3425 | /// attribute changes whether a parameter is passed at +0 (the default) |
3426 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3427 | /// but isn't really a change to the parameter type. |
3428 | /// |
3429 | /// One serious disadvantage of modelling language features this way is |
3430 | /// that they generally do not work with language features that attempt |
3431 | /// to destructure types. For example, template argument deduction will |
3432 | /// not be able to match a parameter declared as |
3433 | /// T (*)(U) |
3434 | /// against an argument of type |
3435 | /// void (*)(__attribute__((ns_consumed)) id) |
3436 | /// because the substitution of T=void, U=id into the former will |
3437 | /// not produce the latter. |
3438 | class ExtParameterInfo { |
3439 | enum { |
3440 | ABIMask = 0x0F, |
3441 | IsConsumed = 0x10, |
3442 | HasPassObjSize = 0x20, |
3443 | IsNoEscape = 0x40, |
3444 | }; |
3445 | unsigned char Data = 0; |
3446 | |
3447 | public: |
3448 | ExtParameterInfo() = default; |
3449 | |
3450 | /// Return the ABI treatment of this parameter. |
3451 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3452 | ExtParameterInfo withABI(ParameterABI kind) const { |
3453 | ExtParameterInfo copy = *this; |
3454 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3455 | return copy; |
3456 | } |
3457 | |
3458 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3459 | /// Consumed parameters must have retainable object type. |
3460 | bool isConsumed() const { return (Data & IsConsumed); } |
3461 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3462 | ExtParameterInfo copy = *this; |
3463 | if (consumed) |
3464 | copy.Data |= IsConsumed; |
3465 | else |
3466 | copy.Data &= ~IsConsumed; |
3467 | return copy; |
3468 | } |
3469 | |
3470 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3471 | ExtParameterInfo withHasPassObjectSize() const { |
3472 | ExtParameterInfo Copy = *this; |
3473 | Copy.Data |= HasPassObjSize; |
3474 | return Copy; |
3475 | } |
3476 | |
3477 | bool isNoEscape() const { return Data & IsNoEscape; } |
3478 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3479 | ExtParameterInfo Copy = *this; |
3480 | if (NoEscape) |
3481 | Copy.Data |= IsNoEscape; |
3482 | else |
3483 | Copy.Data &= ~IsNoEscape; |
3484 | return Copy; |
3485 | } |
3486 | |
3487 | unsigned char getOpaqueValue() const { return Data; } |
3488 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3489 | ExtParameterInfo result; |
3490 | result.Data = data; |
3491 | return result; |
3492 | } |
3493 | |
3494 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3495 | return lhs.Data == rhs.Data; |
3496 | } |
3497 | |
3498 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3499 | return lhs.Data != rhs.Data; |
3500 | } |
3501 | }; |
3502 | |
3503 | /// A class which abstracts out some details necessary for |
3504 | /// making a call. |
3505 | /// |
3506 | /// It is not actually used directly for storing this information in |
3507 | /// a FunctionType, although FunctionType does currently use the |
3508 | /// same bit-pattern. |
3509 | /// |
3510 | // If you add a field (say Foo), other than the obvious places (both, |
3511 | // constructors, compile failures), what you need to update is |
3512 | // * Operator== |
3513 | // * getFoo |
3514 | // * withFoo |
3515 | // * functionType. Add Foo, getFoo. |
3516 | // * ASTContext::getFooType |
3517 | // * ASTContext::mergeFunctionTypes |
3518 | // * FunctionNoProtoType::Profile |
3519 | // * FunctionProtoType::Profile |
3520 | // * TypePrinter::PrintFunctionProto |
3521 | // * AST read and write |
3522 | // * Codegen |
3523 | class ExtInfo { |
3524 | friend class FunctionType; |
3525 | |
3526 | // Feel free to rearrange or add bits, but if you go over 12, |
3527 | // you'll need to adjust both the Bits field below and |
3528 | // Type::FunctionTypeBitfields. |
3529 | |
3530 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck| |
3531 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | |
3532 | // |
3533 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3534 | enum { CallConvMask = 0x1F }; |
3535 | enum { NoReturnMask = 0x20 }; |
3536 | enum { ProducesResultMask = 0x40 }; |
3537 | enum { NoCallerSavedRegsMask = 0x80 }; |
3538 | enum { NoCfCheckMask = 0x800 }; |
3539 | enum { |
3540 | RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask | |
3541 | NoCallerSavedRegsMask | NoCfCheckMask), |
3542 | RegParmOffset = 8 |
3543 | }; // Assumed to be the last field |
3544 | uint16_t Bits = CC_C; |
3545 | |
3546 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3547 | |
3548 | public: |
3549 | // Constructor with no defaults. Use this when you know that you |
3550 | // have all the elements (when reading an AST file for example). |
3551 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3552 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) { |
3553 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 3553, __PRETTY_FUNCTION__)); |
3554 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3555 | (producesResult ? ProducesResultMask : 0) | |
3556 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3557 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3558 | (NoCfCheck ? NoCfCheckMask : 0); |
3559 | } |
3560 | |
3561 | // Constructor with all defaults. Use when for example creating a |
3562 | // function known to use defaults. |
3563 | ExtInfo() = default; |
3564 | |
3565 | // Constructor with just the calling convention, which is an important part |
3566 | // of the canonical type. |
3567 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3568 | |
3569 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3570 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3571 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3572 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3573 | bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; } |
3574 | |
3575 | unsigned getRegParm() const { |
3576 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3577 | if (RegParm > 0) |
3578 | --RegParm; |
3579 | return RegParm; |
3580 | } |
3581 | |
3582 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3583 | |
3584 | bool operator==(ExtInfo Other) const { |
3585 | return Bits == Other.Bits; |
3586 | } |
3587 | bool operator!=(ExtInfo Other) const { |
3588 | return Bits != Other.Bits; |
3589 | } |
3590 | |
3591 | // Note that we don't have setters. That is by design, use |
3592 | // the following with methods instead of mutating these objects. |
3593 | |
3594 | ExtInfo withNoReturn(bool noReturn) const { |
3595 | if (noReturn) |
3596 | return ExtInfo(Bits | NoReturnMask); |
3597 | else |
3598 | return ExtInfo(Bits & ~NoReturnMask); |
3599 | } |
3600 | |
3601 | ExtInfo withProducesResult(bool producesResult) const { |
3602 | if (producesResult) |
3603 | return ExtInfo(Bits | ProducesResultMask); |
3604 | else |
3605 | return ExtInfo(Bits & ~ProducesResultMask); |
3606 | } |
3607 | |
3608 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3609 | if (noCallerSavedRegs) |
3610 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3611 | else |
3612 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3613 | } |
3614 | |
3615 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3616 | if (noCfCheck) |
3617 | return ExtInfo(Bits | NoCfCheckMask); |
3618 | else |
3619 | return ExtInfo(Bits & ~NoCfCheckMask); |
3620 | } |
3621 | |
3622 | ExtInfo withRegParm(unsigned RegParm) const { |
3623 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 3623, __PRETTY_FUNCTION__)); |
3624 | return ExtInfo((Bits & ~RegParmMask) | |
3625 | ((RegParm + 1) << RegParmOffset)); |
3626 | } |
3627 | |
3628 | ExtInfo withCallingConv(CallingConv cc) const { |
3629 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3630 | } |
3631 | |
3632 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3633 | ID.AddInteger(Bits); |
3634 | } |
3635 | }; |
3636 | |
3637 | /// A simple holder for a QualType representing a type in an |
3638 | /// exception specification. Unfortunately needed by FunctionProtoType |
3639 | /// because TrailingObjects cannot handle repeated types. |
3640 | struct ExceptionType { QualType Type; }; |
3641 | |
3642 | /// A simple holder for various uncommon bits which do not fit in |
3643 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3644 | /// alignment of subsequent objects in TrailingObjects. You must update |
3645 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3646 | struct alignas(void *) FunctionTypeExtraBitfields { |
3647 | /// The number of types in the exception specification. |
3648 | /// A whole unsigned is not needed here and according to |
3649 | /// [implimits] 8 bits would be enough here. |
3650 | unsigned NumExceptionType; |
3651 | }; |
3652 | |
3653 | protected: |
3654 | FunctionType(TypeClass tc, QualType res, |
3655 | QualType Canonical, bool Dependent, |
3656 | bool InstantiationDependent, |
3657 | bool VariablyModified, bool ContainsUnexpandedParameterPack, |
3658 | ExtInfo Info) |
3659 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
3660 | ContainsUnexpandedParameterPack), |
3661 | ResultType(res) { |
3662 | FunctionTypeBits.ExtInfo = Info.Bits; |
3663 | } |
3664 | |
3665 | Qualifiers getFastTypeQuals() const { |
3666 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3667 | } |
3668 | |
3669 | public: |
3670 | QualType getReturnType() const { return ResultType; } |
3671 | |
3672 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3673 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3674 | |
3675 | /// Determine whether this function type includes the GNU noreturn |
3676 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3677 | /// type. |
3678 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3679 | |
3680 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3681 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3682 | |
3683 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3684 | "Const, volatile and restrict are assumed to be a subset of " |
3685 | "the fast qualifiers."); |
3686 | |
3687 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3688 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3689 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3690 | |
3691 | /// Determine the type of an expression that calls a function of |
3692 | /// this type. |
3693 | QualType getCallResultType(const ASTContext &Context) const { |
3694 | return getReturnType().getNonLValueExprType(Context); |
3695 | } |
3696 | |
3697 | static StringRef getNameForCallConv(CallingConv CC); |
3698 | |
3699 | static bool classof(const Type *T) { |
3700 | return T->getTypeClass() == FunctionNoProto || |
3701 | T->getTypeClass() == FunctionProto; |
3702 | } |
3703 | }; |
3704 | |
3705 | /// Represents a K&R-style 'int foo()' function, which has |
3706 | /// no information available about its arguments. |
3707 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3708 | friend class ASTContext; // ASTContext creates these. |
3709 | |
3710 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3711 | : FunctionType(FunctionNoProto, Result, Canonical, |
3712 | /*Dependent=*/false, /*InstantiationDependent=*/false, |
3713 | Result->isVariablyModifiedType(), |
3714 | /*ContainsUnexpandedParameterPack=*/false, Info) {} |
3715 | |
3716 | public: |
3717 | // No additional state past what FunctionType provides. |
3718 | |
3719 | bool isSugared() const { return false; } |
3720 | QualType desugar() const { return QualType(this, 0); } |
3721 | |
3722 | void Profile(llvm::FoldingSetNodeID &ID) { |
3723 | Profile(ID, getReturnType(), getExtInfo()); |
3724 | } |
3725 | |
3726 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3727 | ExtInfo Info) { |
3728 | Info.Profile(ID); |
3729 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3730 | } |
3731 | |
3732 | static bool classof(const Type *T) { |
3733 | return T->getTypeClass() == FunctionNoProto; |
3734 | } |
3735 | }; |
3736 | |
3737 | /// Represents a prototype with parameter type info, e.g. |
3738 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3739 | /// parameters, not as having a single void parameter. Such a type can have |
3740 | /// an exception specification, but this specification is not part of the |
3741 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3742 | /// which optional. For more information about the trailing objects see |
3743 | /// the first comment inside FunctionProtoType. |
3744 | class FunctionProtoType final |
3745 | : public FunctionType, |
3746 | public llvm::FoldingSetNode, |
3747 | private llvm::TrailingObjects< |
3748 | FunctionProtoType, QualType, SourceLocation, |
3749 | FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, |
3750 | Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { |
3751 | friend class ASTContext; // ASTContext creates these. |
3752 | friend TrailingObjects; |
3753 | |
3754 | // FunctionProtoType is followed by several trailing objects, some of |
3755 | // which optional. They are in order: |
3756 | // |
3757 | // * An array of getNumParams() QualType holding the parameter types. |
3758 | // Always present. Note that for the vast majority of FunctionProtoType, |
3759 | // these will be the only trailing objects. |
3760 | // |
3761 | // * Optionally if the function is variadic, the SourceLocation of the |
3762 | // ellipsis. |
3763 | // |
3764 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3765 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3766 | // a single FunctionTypeExtraBitfields. Present if and only if |
3767 | // hasExtraBitfields() is true. |
3768 | // |
3769 | // * Optionally exactly one of: |
3770 | // * an array of getNumExceptions() ExceptionType, |
3771 | // * a single Expr *, |
3772 | // * a pair of FunctionDecl *, |
3773 | // * a single FunctionDecl * |
3774 | // used to store information about the various types of exception |
3775 | // specification. See getExceptionSpecSize for the details. |
3776 | // |
3777 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3778 | // an ExtParameterInfo for each of the parameters. Present if and |
3779 | // only if hasExtParameterInfos() is true. |
3780 | // |
3781 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3782 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3783 | // if hasExtQualifiers() is true. |
3784 | // |
3785 | // The optional FunctionTypeExtraBitfields has to be before the data |
3786 | // related to the exception specification since it contains the number |
3787 | // of exception types. |
3788 | // |
3789 | // We put the ExtParameterInfos last. If all were equal, it would make |
3790 | // more sense to put these before the exception specification, because |
3791 | // it's much easier to skip past them compared to the elaborate switch |
3792 | // required to skip the exception specification. However, all is not |
3793 | // equal; ExtParameterInfos are used to model very uncommon features, |
3794 | // and it's better not to burden the more common paths. |
3795 | |
3796 | public: |
3797 | /// Holds information about the various types of exception specification. |
3798 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3799 | /// used to group together the various bits of information about the |
3800 | /// exception specification. |
3801 | struct ExceptionSpecInfo { |
3802 | /// The kind of exception specification this is. |
3803 | ExceptionSpecificationType Type = EST_None; |
3804 | |
3805 | /// Explicitly-specified list of exception types. |
3806 | ArrayRef<QualType> Exceptions; |
3807 | |
3808 | /// Noexcept expression, if this is a computed noexcept specification. |
3809 | Expr *NoexceptExpr = nullptr; |
3810 | |
3811 | /// The function whose exception specification this is, for |
3812 | /// EST_Unevaluated and EST_Uninstantiated. |
3813 | FunctionDecl *SourceDecl = nullptr; |
3814 | |
3815 | /// The function template whose exception specification this is instantiated |
3816 | /// from, for EST_Uninstantiated. |
3817 | FunctionDecl *SourceTemplate = nullptr; |
3818 | |
3819 | ExceptionSpecInfo() = default; |
3820 | |
3821 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3822 | }; |
3823 | |
3824 | /// Extra information about a function prototype. ExtProtoInfo is not |
3825 | /// stored as such in FunctionProtoType but is used to group together |
3826 | /// the various bits of extra information about a function prototype. |
3827 | struct ExtProtoInfo { |
3828 | FunctionType::ExtInfo ExtInfo; |
3829 | bool Variadic : 1; |
3830 | bool HasTrailingReturn : 1; |
3831 | Qualifiers TypeQuals; |
3832 | RefQualifierKind RefQualifier = RQ_None; |
3833 | ExceptionSpecInfo ExceptionSpec; |
3834 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3835 | SourceLocation EllipsisLoc; |
3836 | |
3837 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3838 | |
3839 | ExtProtoInfo(CallingConv CC) |
3840 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3841 | |
3842 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3843 | ExtProtoInfo Result(*this); |
3844 | Result.ExceptionSpec = ESI; |
3845 | return Result; |
3846 | } |
3847 | }; |
3848 | |
3849 | private: |
3850 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3851 | return getNumParams(); |
3852 | } |
3853 | |
3854 | unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { |
3855 | return isVariadic(); |
3856 | } |
3857 | |
3858 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3859 | return hasExtraBitfields(); |
3860 | } |
3861 | |
3862 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3863 | return getExceptionSpecSize().NumExceptionType; |
3864 | } |
3865 | |
3866 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
3867 | return getExceptionSpecSize().NumExprPtr; |
3868 | } |
3869 | |
3870 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
3871 | return getExceptionSpecSize().NumFunctionDeclPtr; |
3872 | } |
3873 | |
3874 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
3875 | return hasExtParameterInfos() ? getNumParams() : 0; |
3876 | } |
3877 | |
3878 | /// Determine whether there are any argument types that |
3879 | /// contain an unexpanded parameter pack. |
3880 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
3881 | unsigned numArgs) { |
3882 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
3883 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
3884 | return true; |
3885 | |
3886 | return false; |
3887 | } |
3888 | |
3889 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
3890 | QualType canonical, const ExtProtoInfo &epi); |
3891 | |
3892 | /// This struct is returned by getExceptionSpecSize and is used to |
3893 | /// translate an ExceptionSpecificationType to the number and kind |
3894 | /// of trailing objects related to the exception specification. |
3895 | struct ExceptionSpecSizeHolder { |
3896 | unsigned NumExceptionType; |
3897 | unsigned NumExprPtr; |
3898 | unsigned NumFunctionDeclPtr; |
3899 | }; |
3900 | |
3901 | /// Return the number and kind of trailing objects |
3902 | /// related to the exception specification. |
3903 | static ExceptionSpecSizeHolder |
3904 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
3905 | switch (EST) { |
3906 | case EST_None: |
3907 | case EST_DynamicNone: |
3908 | case EST_MSAny: |
3909 | case EST_BasicNoexcept: |
3910 | case EST_Unparsed: |
3911 | case EST_NoThrow: |
3912 | return {0, 0, 0}; |
3913 | |
3914 | case EST_Dynamic: |
3915 | return {NumExceptions, 0, 0}; |
3916 | |
3917 | case EST_DependentNoexcept: |
3918 | case EST_NoexceptFalse: |
3919 | case EST_NoexceptTrue: |
3920 | return {0, 1, 0}; |
3921 | |
3922 | case EST_Uninstantiated: |
3923 | return {0, 0, 2}; |
3924 | |
3925 | case EST_Unevaluated: |
3926 | return {0, 0, 1}; |
3927 | } |
3928 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 3928); |
3929 | } |
3930 | |
3931 | /// Return the number and kind of trailing objects |
3932 | /// related to the exception specification. |
3933 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
3934 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
3935 | } |
3936 | |
3937 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3938 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
3939 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
3940 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
3941 | return EST == EST_Dynamic; |
3942 | } |
3943 | |
3944 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3945 | bool hasExtraBitfields() const { |
3946 | return hasExtraBitfields(getExceptionSpecType()); |
3947 | } |
3948 | |
3949 | bool hasExtQualifiers() const { |
3950 | return FunctionTypeBits.HasExtQuals; |
3951 | } |
3952 | |
3953 | public: |
3954 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
3955 | |
3956 | QualType getParamType(unsigned i) const { |
3957 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 3957, __PRETTY_FUNCTION__)); |
3958 | return param_type_begin()[i]; |
3959 | } |
3960 | |
3961 | ArrayRef<QualType> getParamTypes() const { |
3962 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
3963 | } |
3964 | |
3965 | ExtProtoInfo getExtProtoInfo() const { |
3966 | ExtProtoInfo EPI; |
3967 | EPI.ExtInfo = getExtInfo(); |
3968 | EPI.Variadic = isVariadic(); |
3969 | EPI.EllipsisLoc = getEllipsisLoc(); |
3970 | EPI.HasTrailingReturn = hasTrailingReturn(); |
3971 | EPI.ExceptionSpec = getExceptionSpecInfo(); |
3972 | EPI.TypeQuals = getMethodQuals(); |
3973 | EPI.RefQualifier = getRefQualifier(); |
3974 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
3975 | return EPI; |
3976 | } |
3977 | |
3978 | /// Get the kind of exception specification on this function. |
3979 | ExceptionSpecificationType getExceptionSpecType() const { |
3980 | return static_cast<ExceptionSpecificationType>( |
3981 | FunctionTypeBits.ExceptionSpecType); |
3982 | } |
3983 | |
3984 | /// Return whether this function has any kind of exception spec. |
3985 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
3986 | |
3987 | /// Return whether this function has a dynamic (throw) exception spec. |
3988 | bool hasDynamicExceptionSpec() const { |
3989 | return isDynamicExceptionSpec(getExceptionSpecType()); |
3990 | } |
3991 | |
3992 | /// Return whether this function has a noexcept exception spec. |
3993 | bool hasNoexceptExceptionSpec() const { |
3994 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
3995 | } |
3996 | |
3997 | /// Return whether this function has a dependent exception spec. |
3998 | bool hasDependentExceptionSpec() const; |
3999 | |
4000 | /// Return whether this function has an instantiation-dependent exception |
4001 | /// spec. |
4002 | bool hasInstantiationDependentExceptionSpec() const; |
4003 | |
4004 | /// Return all the available information about this type's exception spec. |
4005 | ExceptionSpecInfo getExceptionSpecInfo() const { |
4006 | ExceptionSpecInfo Result; |
4007 | Result.Type = getExceptionSpecType(); |
4008 | if (Result.Type == EST_Dynamic) { |
4009 | Result.Exceptions = exceptions(); |
4010 | } else if (isComputedNoexcept(Result.Type)) { |
4011 | Result.NoexceptExpr = getNoexceptExpr(); |
4012 | } else if (Result.Type == EST_Uninstantiated) { |
4013 | Result.SourceDecl = getExceptionSpecDecl(); |
4014 | Result.SourceTemplate = getExceptionSpecTemplate(); |
4015 | } else if (Result.Type == EST_Unevaluated) { |
4016 | Result.SourceDecl = getExceptionSpecDecl(); |
4017 | } |
4018 | return Result; |
4019 | } |
4020 | |
4021 | /// Return the number of types in the exception specification. |
4022 | unsigned getNumExceptions() const { |
4023 | return getExceptionSpecType() == EST_Dynamic |
4024 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
4025 | ->NumExceptionType |
4026 | : 0; |
4027 | } |
4028 | |
4029 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
4030 | QualType getExceptionType(unsigned i) const { |
4031 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4031, __PRETTY_FUNCTION__)); |
4032 | return exception_begin()[i]; |
4033 | } |
4034 | |
4035 | /// Return the expression inside noexcept(expression), or a null pointer |
4036 | /// if there is none (because the exception spec is not of this form). |
4037 | Expr *getNoexceptExpr() const { |
4038 | if (!isComputedNoexcept(getExceptionSpecType())) |
4039 | return nullptr; |
4040 | return *getTrailingObjects<Expr *>(); |
4041 | } |
4042 | |
4043 | /// If this function type has an exception specification which hasn't |
4044 | /// been determined yet (either because it has not been evaluated or because |
4045 | /// it has not been instantiated), this is the function whose exception |
4046 | /// specification is represented by this type. |
4047 | FunctionDecl *getExceptionSpecDecl() const { |
4048 | if (getExceptionSpecType() != EST_Uninstantiated && |
4049 | getExceptionSpecType() != EST_Unevaluated) |
4050 | return nullptr; |
4051 | return getTrailingObjects<FunctionDecl *>()[0]; |
4052 | } |
4053 | |
4054 | /// If this function type has an uninstantiated exception |
4055 | /// specification, this is the function whose exception specification |
4056 | /// should be instantiated to find the exception specification for |
4057 | /// this type. |
4058 | FunctionDecl *getExceptionSpecTemplate() const { |
4059 | if (getExceptionSpecType() != EST_Uninstantiated) |
4060 | return nullptr; |
4061 | return getTrailingObjects<FunctionDecl *>()[1]; |
4062 | } |
4063 | |
4064 | /// Determine whether this function type has a non-throwing exception |
4065 | /// specification. |
4066 | CanThrowResult canThrow() const; |
4067 | |
4068 | /// Determine whether this function type has a non-throwing exception |
4069 | /// specification. If this depends on template arguments, returns |
4070 | /// \c ResultIfDependent. |
4071 | bool isNothrow(bool ResultIfDependent = false) const { |
4072 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4073 | } |
4074 | |
4075 | /// Whether this function prototype is variadic. |
4076 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4077 | |
4078 | SourceLocation getEllipsisLoc() const { |
4079 | return isVariadic() ? *getTrailingObjects<SourceLocation>() |
4080 | : SourceLocation(); |
4081 | } |
4082 | |
4083 | /// Determines whether this function prototype contains a |
4084 | /// parameter pack at the end. |
4085 | /// |
4086 | /// A function template whose last parameter is a parameter pack can be |
4087 | /// called with an arbitrary number of arguments, much like a variadic |
4088 | /// function. |
4089 | bool isTemplateVariadic() const; |
4090 | |
4091 | /// Whether this function prototype has a trailing return type. |
4092 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4093 | |
4094 | Qualifiers getMethodQuals() const { |
4095 | if (hasExtQualifiers()) |
4096 | return *getTrailingObjects<Qualifiers>(); |
4097 | else |
4098 | return getFastTypeQuals(); |
4099 | } |
4100 | |
4101 | /// Retrieve the ref-qualifier associated with this function type. |
4102 | RefQualifierKind getRefQualifier() const { |
4103 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4104 | } |
4105 | |
4106 | using param_type_iterator = const QualType *; |
4107 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4108 | |
4109 | param_type_range param_types() const { |
4110 | return param_type_range(param_type_begin(), param_type_end()); |
4111 | } |
4112 | |
4113 | param_type_iterator param_type_begin() const { |
4114 | return getTrailingObjects<QualType>(); |
4115 | } |
4116 | |
4117 | param_type_iterator param_type_end() const { |
4118 | return param_type_begin() + getNumParams(); |
4119 | } |
4120 | |
4121 | using exception_iterator = const QualType *; |
4122 | |
4123 | ArrayRef<QualType> exceptions() const { |
4124 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4125 | } |
4126 | |
4127 | exception_iterator exception_begin() const { |
4128 | return reinterpret_cast<exception_iterator>( |
4129 | getTrailingObjects<ExceptionType>()); |
4130 | } |
4131 | |
4132 | exception_iterator exception_end() const { |
4133 | return exception_begin() + getNumExceptions(); |
4134 | } |
4135 | |
4136 | /// Is there any interesting extra information for any of the parameters |
4137 | /// of this function type? |
4138 | bool hasExtParameterInfos() const { |
4139 | return FunctionTypeBits.HasExtParameterInfos; |
4140 | } |
4141 | |
4142 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4143 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4143, __PRETTY_FUNCTION__)); |
4144 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4145 | getNumParams()); |
4146 | } |
4147 | |
4148 | /// Return a pointer to the beginning of the array of extra parameter |
4149 | /// information, if present, or else null if none of the parameters |
4150 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4151 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4152 | if (!hasExtParameterInfos()) |
4153 | return nullptr; |
4154 | return getTrailingObjects<ExtParameterInfo>(); |
4155 | } |
4156 | |
4157 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4158 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4158, __PRETTY_FUNCTION__)); |
4159 | if (hasExtParameterInfos()) |
4160 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4161 | return ExtParameterInfo(); |
4162 | } |
4163 | |
4164 | ParameterABI getParameterABI(unsigned I) const { |
4165 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4165, __PRETTY_FUNCTION__)); |
4166 | if (hasExtParameterInfos()) |
4167 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4168 | return ParameterABI::Ordinary; |
4169 | } |
4170 | |
4171 | bool isParamConsumed(unsigned I) const { |
4172 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4172, __PRETTY_FUNCTION__)); |
4173 | if (hasExtParameterInfos()) |
4174 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4175 | return false; |
4176 | } |
4177 | |
4178 | bool isSugared() const { return false; } |
4179 | QualType desugar() const { return QualType(this, 0); } |
4180 | |
4181 | void printExceptionSpecification(raw_ostream &OS, |
4182 | const PrintingPolicy &Policy) const; |
4183 | |
4184 | static bool classof(const Type *T) { |
4185 | return T->getTypeClass() == FunctionProto; |
4186 | } |
4187 | |
4188 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4189 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4190 | param_type_iterator ArgTys, unsigned NumArgs, |
4191 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4192 | bool Canonical); |
4193 | }; |
4194 | |
4195 | /// Represents the dependent type named by a dependently-scoped |
4196 | /// typename using declaration, e.g. |
4197 | /// using typename Base<T>::foo; |
4198 | /// |
4199 | /// Template instantiation turns these into the underlying type. |
4200 | class UnresolvedUsingType : public Type { |
4201 | friend class ASTContext; // ASTContext creates these. |
4202 | |
4203 | UnresolvedUsingTypenameDecl *Decl; |
4204 | |
4205 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4206 | : Type(UnresolvedUsing, QualType(), true, true, false, |
4207 | /*ContainsUnexpandedParameterPack=*/false), |
4208 | Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {} |
4209 | |
4210 | public: |
4211 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4212 | |
4213 | bool isSugared() const { return false; } |
4214 | QualType desugar() const { return QualType(this, 0); } |
4215 | |
4216 | static bool classof(const Type *T) { |
4217 | return T->getTypeClass() == UnresolvedUsing; |
4218 | } |
4219 | |
4220 | void Profile(llvm::FoldingSetNodeID &ID) { |
4221 | return Profile(ID, Decl); |
4222 | } |
4223 | |
4224 | static void Profile(llvm::FoldingSetNodeID &ID, |
4225 | UnresolvedUsingTypenameDecl *D) { |
4226 | ID.AddPointer(D); |
4227 | } |
4228 | }; |
4229 | |
4230 | class TypedefType : public Type { |
4231 | TypedefNameDecl *Decl; |
4232 | |
4233 | protected: |
4234 | friend class ASTContext; // ASTContext creates these. |
4235 | |
4236 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can) |
4237 | : Type(tc, can, can->isDependentType(), |
4238 | can->isInstantiationDependentType(), |
4239 | can->isVariablyModifiedType(), |
4240 | /*ContainsUnexpandedParameterPack=*/false), |
4241 | Decl(const_cast<TypedefNameDecl*>(D)) { |
4242 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4242, __PRETTY_FUNCTION__)); |
4243 | } |
4244 | |
4245 | public: |
4246 | TypedefNameDecl *getDecl() const { return Decl; } |
4247 | |
4248 | bool isSugared() const { return true; } |
4249 | QualType desugar() const; |
4250 | |
4251 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4252 | }; |
4253 | |
4254 | /// Sugar type that represents a type that was qualified by a qualifier written |
4255 | /// as a macro invocation. |
4256 | class MacroQualifiedType : public Type { |
4257 | friend class ASTContext; // ASTContext creates these. |
4258 | |
4259 | QualType UnderlyingTy; |
4260 | const IdentifierInfo *MacroII; |
4261 | |
4262 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4263 | const IdentifierInfo *MacroII) |
4264 | : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(), |
4265 | UnderlyingTy->isInstantiationDependentType(), |
4266 | UnderlyingTy->isVariablyModifiedType(), |
4267 | UnderlyingTy->containsUnexpandedParameterPack()), |
4268 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4269 | assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4270, __PRETTY_FUNCTION__)) |
4270 | "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4270, __PRETTY_FUNCTION__)); |
4271 | } |
4272 | |
4273 | public: |
4274 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4275 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4276 | |
4277 | /// Return this attributed type's modified type with no qualifiers attached to |
4278 | /// it. |
4279 | QualType getModifiedType() const; |
4280 | |
4281 | bool isSugared() const { return true; } |
4282 | QualType desugar() const; |
4283 | |
4284 | static bool classof(const Type *T) { |
4285 | return T->getTypeClass() == MacroQualified; |
4286 | } |
4287 | }; |
4288 | |
4289 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4290 | class TypeOfExprType : public Type { |
4291 | Expr *TOExpr; |
4292 | |
4293 | protected: |
4294 | friend class ASTContext; // ASTContext creates these. |
4295 | |
4296 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4297 | |
4298 | public: |
4299 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4300 | |
4301 | /// Remove a single level of sugar. |
4302 | QualType desugar() const; |
4303 | |
4304 | /// Returns whether this type directly provides sugar. |
4305 | bool isSugared() const; |
4306 | |
4307 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4308 | }; |
4309 | |
4310 | /// Internal representation of canonical, dependent |
4311 | /// `typeof(expr)` types. |
4312 | /// |
4313 | /// This class is used internally by the ASTContext to manage |
4314 | /// canonical, dependent types, only. Clients will only see instances |
4315 | /// of this class via TypeOfExprType nodes. |
4316 | class DependentTypeOfExprType |
4317 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4318 | const ASTContext &Context; |
4319 | |
4320 | public: |
4321 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4322 | : TypeOfExprType(E), Context(Context) {} |
4323 | |
4324 | void Profile(llvm::FoldingSetNodeID &ID) { |
4325 | Profile(ID, Context, getUnderlyingExpr()); |
4326 | } |
4327 | |
4328 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4329 | Expr *E); |
4330 | }; |
4331 | |
4332 | /// Represents `typeof(type)`, a GCC extension. |
4333 | class TypeOfType : public Type { |
4334 | friend class ASTContext; // ASTContext creates these. |
4335 | |
4336 | QualType TOType; |
4337 | |
4338 | TypeOfType(QualType T, QualType can) |
4339 | : Type(TypeOf, can, T->isDependentType(), |
4340 | T->isInstantiationDependentType(), |
4341 | T->isVariablyModifiedType(), |
4342 | T->containsUnexpandedParameterPack()), |
4343 | TOType(T) { |
4344 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4344, __PRETTY_FUNCTION__)); |
4345 | } |
4346 | |
4347 | public: |
4348 | QualType getUnderlyingType() const { return TOType; } |
4349 | |
4350 | /// Remove a single level of sugar. |
4351 | QualType desugar() const { return getUnderlyingType(); } |
4352 | |
4353 | /// Returns whether this type directly provides sugar. |
4354 | bool isSugared() const { return true; } |
4355 | |
4356 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4357 | }; |
4358 | |
4359 | /// Represents the type `decltype(expr)` (C++11). |
4360 | class DecltypeType : public Type { |
4361 | Expr *E; |
4362 | QualType UnderlyingType; |
4363 | |
4364 | protected: |
4365 | friend class ASTContext; // ASTContext creates these. |
4366 | |
4367 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4368 | |
4369 | public: |
4370 | Expr *getUnderlyingExpr() const { return E; } |
4371 | QualType getUnderlyingType() const { return UnderlyingType; } |
4372 | |
4373 | /// Remove a single level of sugar. |
4374 | QualType desugar() const; |
4375 | |
4376 | /// Returns whether this type directly provides sugar. |
4377 | bool isSugared() const; |
4378 | |
4379 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4380 | }; |
4381 | |
4382 | /// Internal representation of canonical, dependent |
4383 | /// decltype(expr) types. |
4384 | /// |
4385 | /// This class is used internally by the ASTContext to manage |
4386 | /// canonical, dependent types, only. Clients will only see instances |
4387 | /// of this class via DecltypeType nodes. |
4388 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4389 | const ASTContext &Context; |
4390 | |
4391 | public: |
4392 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4393 | |
4394 | void Profile(llvm::FoldingSetNodeID &ID) { |
4395 | Profile(ID, Context, getUnderlyingExpr()); |
4396 | } |
4397 | |
4398 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4399 | Expr *E); |
4400 | }; |
4401 | |
4402 | /// A unary type transform, which is a type constructed from another. |
4403 | class UnaryTransformType : public Type { |
4404 | public: |
4405 | enum UTTKind { |
4406 | EnumUnderlyingType |
4407 | }; |
4408 | |
4409 | private: |
4410 | /// The untransformed type. |
4411 | QualType BaseType; |
4412 | |
4413 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4414 | QualType UnderlyingType; |
4415 | |
4416 | UTTKind UKind; |
4417 | |
4418 | protected: |
4419 | friend class ASTContext; |
4420 | |
4421 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4422 | QualType CanonicalTy); |
4423 | |
4424 | public: |
4425 | bool isSugared() const { return !isDependentType(); } |
4426 | QualType desugar() const { return UnderlyingType; } |
4427 | |
4428 | QualType getUnderlyingType() const { return UnderlyingType; } |
4429 | QualType getBaseType() const { return BaseType; } |
4430 | |
4431 | UTTKind getUTTKind() const { return UKind; } |
4432 | |
4433 | static bool classof(const Type *T) { |
4434 | return T->getTypeClass() == UnaryTransform; |
4435 | } |
4436 | }; |
4437 | |
4438 | /// Internal representation of canonical, dependent |
4439 | /// __underlying_type(type) types. |
4440 | /// |
4441 | /// This class is used internally by the ASTContext to manage |
4442 | /// canonical, dependent types, only. Clients will only see instances |
4443 | /// of this class via UnaryTransformType nodes. |
4444 | class DependentUnaryTransformType : public UnaryTransformType, |
4445 | public llvm::FoldingSetNode { |
4446 | public: |
4447 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4448 | UTTKind UKind); |
4449 | |
4450 | void Profile(llvm::FoldingSetNodeID &ID) { |
4451 | Profile(ID, getBaseType(), getUTTKind()); |
4452 | } |
4453 | |
4454 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4455 | UTTKind UKind) { |
4456 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4457 | ID.AddInteger((unsigned)UKind); |
4458 | } |
4459 | }; |
4460 | |
4461 | class TagType : public Type { |
4462 | friend class ASTReader; |
4463 | template <class T> friend class serialization::AbstractTypeReader; |
4464 | |
4465 | /// Stores the TagDecl associated with this type. The decl may point to any |
4466 | /// TagDecl that declares the entity. |
4467 | TagDecl *decl; |
4468 | |
4469 | protected: |
4470 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4471 | |
4472 | public: |
4473 | TagDecl *getDecl() const; |
4474 | |
4475 | /// Determines whether this type is in the process of being defined. |
4476 | bool isBeingDefined() const; |
4477 | |
4478 | static bool classof(const Type *T) { |
4479 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4480 | } |
4481 | }; |
4482 | |
4483 | /// A helper class that allows the use of isa/cast/dyncast |
4484 | /// to detect TagType objects of structs/unions/classes. |
4485 | class RecordType : public TagType { |
4486 | protected: |
4487 | friend class ASTContext; // ASTContext creates these. |
4488 | |
4489 | explicit RecordType(const RecordDecl *D) |
4490 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4491 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4492 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4493 | |
4494 | public: |
4495 | RecordDecl *getDecl() const { |
4496 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4497 | } |
4498 | |
4499 | /// Recursively check all fields in the record for const-ness. If any field |
4500 | /// is declared const, return true. Otherwise, return false. |
4501 | bool hasConstFields() const; |
4502 | |
4503 | bool isSugared() const { return false; } |
4504 | QualType desugar() const { return QualType(this, 0); } |
4505 | |
4506 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4507 | }; |
4508 | |
4509 | /// A helper class that allows the use of isa/cast/dyncast |
4510 | /// to detect TagType objects of enums. |
4511 | class EnumType : public TagType { |
4512 | friend class ASTContext; // ASTContext creates these. |
4513 | |
4514 | explicit EnumType(const EnumDecl *D) |
4515 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4516 | |
4517 | public: |
4518 | EnumDecl *getDecl() const { |
4519 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4520 | } |
4521 | |
4522 | bool isSugared() const { return false; } |
4523 | QualType desugar() const { return QualType(this, 0); } |
4524 | |
4525 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4526 | }; |
4527 | |
4528 | /// An attributed type is a type to which a type attribute has been applied. |
4529 | /// |
4530 | /// The "modified type" is the fully-sugared type to which the attributed |
4531 | /// type was applied; generally it is not canonically equivalent to the |
4532 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4533 | /// which the type is canonically equivalent to. |
4534 | /// |
4535 | /// For example, in the following attributed type: |
4536 | /// int32_t __attribute__((vector_size(16))) |
4537 | /// - the modified type is the TypedefType for int32_t |
4538 | /// - the equivalent type is VectorType(16, int32_t) |
4539 | /// - the canonical type is VectorType(16, int) |
4540 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4541 | public: |
4542 | using Kind = attr::Kind; |
4543 | |
4544 | private: |
4545 | friend class ASTContext; // ASTContext creates these |
4546 | |
4547 | QualType ModifiedType; |
4548 | QualType EquivalentType; |
4549 | |
4550 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4551 | QualType equivalent) |
4552 | : Type(Attributed, canon, equivalent->isDependentType(), |
4553 | equivalent->isInstantiationDependentType(), |
4554 | equivalent->isVariablyModifiedType(), |
4555 | equivalent->containsUnexpandedParameterPack()), |
4556 | ModifiedType(modified), EquivalentType(equivalent) { |
4557 | AttributedTypeBits.AttrKind = attrKind; |
4558 | } |
4559 | |
4560 | public: |
4561 | Kind getAttrKind() const { |
4562 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4563 | } |
4564 | |
4565 | QualType getModifiedType() const { return ModifiedType; } |
4566 | QualType getEquivalentType() const { return EquivalentType; } |
4567 | |
4568 | bool isSugared() const { return true; } |
4569 | QualType desugar() const { return getEquivalentType(); } |
4570 | |
4571 | /// Does this attribute behave like a type qualifier? |
4572 | /// |
4573 | /// A type qualifier adjusts a type to provide specialized rules for |
4574 | /// a specific object, like the standard const and volatile qualifiers. |
4575 | /// This includes attributes controlling things like nullability, |
4576 | /// address spaces, and ARC ownership. The value of the object is still |
4577 | /// largely described by the modified type. |
4578 | /// |
4579 | /// In contrast, many type attributes "rewrite" their modified type to |
4580 | /// produce a fundamentally different type, not necessarily related in any |
4581 | /// formalizable way to the original type. For example, calling convention |
4582 | /// and vector attributes are not simple type qualifiers. |
4583 | /// |
4584 | /// Type qualifiers are often, but not always, reflected in the canonical |
4585 | /// type. |
4586 | bool isQualifier() const; |
4587 | |
4588 | bool isMSTypeSpec() const; |
4589 | |
4590 | bool isCallingConv() const; |
4591 | |
4592 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4593 | |
4594 | /// Retrieve the attribute kind corresponding to the given |
4595 | /// nullability kind. |
4596 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4597 | switch (kind) { |
4598 | case NullabilityKind::NonNull: |
4599 | return attr::TypeNonNull; |
4600 | |
4601 | case NullabilityKind::Nullable: |
4602 | return attr::TypeNullable; |
4603 | |
4604 | case NullabilityKind::Unspecified: |
4605 | return attr::TypeNullUnspecified; |
4606 | } |
4607 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 4607); |
4608 | } |
4609 | |
4610 | /// Strip off the top-level nullability annotation on the given |
4611 | /// type, if it's there. |
4612 | /// |
4613 | /// \param T The type to strip. If the type is exactly an |
4614 | /// AttributedType specifying nullability (without looking through |
4615 | /// type sugar), the nullability is returned and this type changed |
4616 | /// to the underlying modified type. |
4617 | /// |
4618 | /// \returns the top-level nullability, if present. |
4619 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4620 | |
4621 | void Profile(llvm::FoldingSetNodeID &ID) { |
4622 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4623 | } |
4624 | |
4625 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4626 | QualType modified, QualType equivalent) { |
4627 | ID.AddInteger(attrKind); |
4628 | ID.AddPointer(modified.getAsOpaquePtr()); |
4629 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4630 | } |
4631 | |
4632 | static bool classof(const Type *T) { |
4633 | return T->getTypeClass() == Attributed; |
4634 | } |
4635 | }; |
4636 | |
4637 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4638 | friend class ASTContext; // ASTContext creates these |
4639 | |
4640 | // Helper data collector for canonical types. |
4641 | struct CanonicalTTPTInfo { |
4642 | unsigned Depth : 15; |
4643 | unsigned ParameterPack : 1; |
4644 | unsigned Index : 16; |
4645 | }; |
4646 | |
4647 | union { |
4648 | // Info for the canonical type. |
4649 | CanonicalTTPTInfo CanTTPTInfo; |
4650 | |
4651 | // Info for the non-canonical type. |
4652 | TemplateTypeParmDecl *TTPDecl; |
4653 | }; |
4654 | |
4655 | /// Build a non-canonical type. |
4656 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4657 | : Type(TemplateTypeParm, Canon, /*Dependent=*/true, |
4658 | /*InstantiationDependent=*/true, |
4659 | /*VariablyModified=*/false, |
4660 | Canon->containsUnexpandedParameterPack()), |
4661 | TTPDecl(TTPDecl) {} |
4662 | |
4663 | /// Build the canonical type. |
4664 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4665 | : Type(TemplateTypeParm, QualType(this, 0), |
4666 | /*Dependent=*/true, |
4667 | /*InstantiationDependent=*/true, |
4668 | /*VariablyModified=*/false, PP) { |
4669 | CanTTPTInfo.Depth = D; |
4670 | CanTTPTInfo.Index = I; |
4671 | CanTTPTInfo.ParameterPack = PP; |
4672 | } |
4673 | |
4674 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4675 | QualType Can = getCanonicalTypeInternal(); |
4676 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4677 | } |
4678 | |
4679 | public: |
4680 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4681 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4682 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4683 | |
4684 | TemplateTypeParmDecl *getDecl() const { |
4685 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4686 | } |
4687 | |
4688 | IdentifierInfo *getIdentifier() const; |
4689 | |
4690 | bool isSugared() const { return false; } |
4691 | QualType desugar() const { return QualType(this, 0); } |
4692 | |
4693 | void Profile(llvm::FoldingSetNodeID &ID) { |
4694 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4695 | } |
4696 | |
4697 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4698 | unsigned Index, bool ParameterPack, |
4699 | TemplateTypeParmDecl *TTPDecl) { |
4700 | ID.AddInteger(Depth); |
4701 | ID.AddInteger(Index); |
4702 | ID.AddBoolean(ParameterPack); |
4703 | ID.AddPointer(TTPDecl); |
4704 | } |
4705 | |
4706 | static bool classof(const Type *T) { |
4707 | return T->getTypeClass() == TemplateTypeParm; |
4708 | } |
4709 | }; |
4710 | |
4711 | /// Represents the result of substituting a type for a template |
4712 | /// type parameter. |
4713 | /// |
4714 | /// Within an instantiated template, all template type parameters have |
4715 | /// been replaced with these. They are used solely to record that a |
4716 | /// type was originally written as a template type parameter; |
4717 | /// therefore they are never canonical. |
4718 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4719 | friend class ASTContext; |
4720 | |
4721 | // The original type parameter. |
4722 | const TemplateTypeParmType *Replaced; |
4723 | |
4724 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4725 | : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(), |
4726 | Canon->isInstantiationDependentType(), |
4727 | Canon->isVariablyModifiedType(), |
4728 | Canon->containsUnexpandedParameterPack()), |
4729 | Replaced(Param) {} |
4730 | |
4731 | public: |
4732 | /// Gets the template parameter that was substituted for. |
4733 | const TemplateTypeParmType *getReplacedParameter() const { |
4734 | return Replaced; |
4735 | } |
4736 | |
4737 | /// Gets the type that was substituted for the template |
4738 | /// parameter. |
4739 | QualType getReplacementType() const { |
4740 | return getCanonicalTypeInternal(); |
4741 | } |
4742 | |
4743 | bool isSugared() const { return true; } |
4744 | QualType desugar() const { return getReplacementType(); } |
4745 | |
4746 | void Profile(llvm::FoldingSetNodeID &ID) { |
4747 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4748 | } |
4749 | |
4750 | static void Profile(llvm::FoldingSetNodeID &ID, |
4751 | const TemplateTypeParmType *Replaced, |
4752 | QualType Replacement) { |
4753 | ID.AddPointer(Replaced); |
4754 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4755 | } |
4756 | |
4757 | static bool classof(const Type *T) { |
4758 | return T->getTypeClass() == SubstTemplateTypeParm; |
4759 | } |
4760 | }; |
4761 | |
4762 | /// Represents the result of substituting a set of types for a template |
4763 | /// type parameter pack. |
4764 | /// |
4765 | /// When a pack expansion in the source code contains multiple parameter packs |
4766 | /// and those parameter packs correspond to different levels of template |
4767 | /// parameter lists, this type node is used to represent a template type |
4768 | /// parameter pack from an outer level, which has already had its argument pack |
4769 | /// substituted but that still lives within a pack expansion that itself |
4770 | /// could not be instantiated. When actually performing a substitution into |
4771 | /// that pack expansion (e.g., when all template parameters have corresponding |
4772 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4773 | /// at the current pack substitution index. |
4774 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4775 | friend class ASTContext; |
4776 | |
4777 | /// The original type parameter. |
4778 | const TemplateTypeParmType *Replaced; |
4779 | |
4780 | /// A pointer to the set of template arguments that this |
4781 | /// parameter pack is instantiated with. |
4782 | const TemplateArgument *Arguments; |
4783 | |
4784 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4785 | QualType Canon, |
4786 | const TemplateArgument &ArgPack); |
4787 | |
4788 | public: |
4789 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4790 | |
4791 | /// Gets the template parameter that was substituted for. |
4792 | const TemplateTypeParmType *getReplacedParameter() const { |
4793 | return Replaced; |
4794 | } |
4795 | |
4796 | unsigned getNumArgs() const { |
4797 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4798 | } |
4799 | |
4800 | bool isSugared() const { return false; } |
4801 | QualType desugar() const { return QualType(this, 0); } |
4802 | |
4803 | TemplateArgument getArgumentPack() const; |
4804 | |
4805 | void Profile(llvm::FoldingSetNodeID &ID); |
4806 | static void Profile(llvm::FoldingSetNodeID &ID, |
4807 | const TemplateTypeParmType *Replaced, |
4808 | const TemplateArgument &ArgPack); |
4809 | |
4810 | static bool classof(const Type *T) { |
4811 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4812 | } |
4813 | }; |
4814 | |
4815 | /// Common base class for placeholders for types that get replaced by |
4816 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4817 | /// class template types, and (eventually) constrained type names from the C++ |
4818 | /// Concepts TS. |
4819 | /// |
4820 | /// These types are usually a placeholder for a deduced type. However, before |
4821 | /// the initializer is attached, or (usually) if the initializer is |
4822 | /// type-dependent, there is no deduced type and the type is canonical. In |
4823 | /// the latter case, it is also a dependent type. |
4824 | class DeducedType : public Type { |
4825 | protected: |
4826 | DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent, |
4827 | bool IsInstantiationDependent, bool ContainsParameterPack) |
4828 | : Type(TC, |
4829 | // FIXME: Retain the sugared deduced type? |
4830 | DeducedAsType.isNull() ? QualType(this, 0) |
4831 | : DeducedAsType.getCanonicalType(), |
4832 | IsDependent, IsInstantiationDependent, |
4833 | /*VariablyModified=*/false, ContainsParameterPack) { |
4834 | if (!DeducedAsType.isNull()) { |
4835 | if (DeducedAsType->isDependentType()) |
4836 | setDependent(); |
4837 | if (DeducedAsType->isInstantiationDependentType()) |
4838 | setInstantiationDependent(); |
4839 | if (DeducedAsType->containsUnexpandedParameterPack()) |
4840 | setContainsUnexpandedParameterPack(); |
4841 | } |
4842 | } |
4843 | |
4844 | public: |
4845 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4846 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4847 | |
4848 | /// Get the type deduced for this placeholder type, or null if it's |
4849 | /// either not been deduced or was deduced to a dependent type. |
4850 | QualType getDeducedType() const { |
4851 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4852 | } |
4853 | bool isDeduced() const { |
4854 | return !isCanonicalUnqualified() || isDependentType(); |
4855 | } |
4856 | |
4857 | static bool classof(const Type *T) { |
4858 | return T->getTypeClass() == Auto || |
4859 | T->getTypeClass() == DeducedTemplateSpecialization; |
4860 | } |
4861 | }; |
4862 | |
4863 | /// Represents a C++11 auto or C++14 decltype(auto) type. |
4864 | class AutoType : public DeducedType, public llvm::FoldingSetNode { |
4865 | friend class ASTContext; // ASTContext creates these |
4866 | |
4867 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4868 | bool IsDeducedAsDependent, bool IsDeducedAsPack) |
4869 | : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent, |
4870 | IsDeducedAsDependent, IsDeducedAsPack) { |
4871 | AutoTypeBits.Keyword = (unsigned)Keyword; |
4872 | } |
4873 | |
4874 | public: |
4875 | bool isDecltypeAuto() const { |
4876 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
4877 | } |
4878 | |
4879 | AutoTypeKeyword getKeyword() const { |
4880 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
4881 | } |
4882 | |
4883 | void Profile(llvm::FoldingSetNodeID &ID) { |
4884 | Profile(ID, getDeducedType(), getKeyword(), isDependentType(), |
4885 | containsUnexpandedParameterPack()); |
4886 | } |
4887 | |
4888 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced, |
4889 | AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) { |
4890 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4891 | ID.AddInteger((unsigned)Keyword); |
4892 | ID.AddBoolean(IsDependent); |
4893 | ID.AddBoolean(IsPack); |
4894 | } |
4895 | |
4896 | static bool classof(const Type *T) { |
4897 | return T->getTypeClass() == Auto; |
4898 | } |
4899 | }; |
4900 | |
4901 | /// Represents a C++17 deduced template specialization type. |
4902 | class DeducedTemplateSpecializationType : public DeducedType, |
4903 | public llvm::FoldingSetNode { |
4904 | friend class ASTContext; // ASTContext creates these |
4905 | |
4906 | /// The name of the template whose arguments will be deduced. |
4907 | TemplateName Template; |
4908 | |
4909 | DeducedTemplateSpecializationType(TemplateName Template, |
4910 | QualType DeducedAsType, |
4911 | bool IsDeducedAsDependent) |
4912 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
4913 | IsDeducedAsDependent || Template.isDependent(), |
4914 | IsDeducedAsDependent || Template.isInstantiationDependent(), |
4915 | Template.containsUnexpandedParameterPack()), |
4916 | Template(Template) {} |
4917 | |
4918 | public: |
4919 | /// Retrieve the name of the template that we are deducing. |
4920 | TemplateName getTemplateName() const { return Template;} |
4921 | |
4922 | void Profile(llvm::FoldingSetNodeID &ID) { |
4923 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
4924 | } |
4925 | |
4926 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
4927 | QualType Deduced, bool IsDependent) { |
4928 | Template.Profile(ID); |
4929 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4930 | ID.AddBoolean(IsDependent); |
4931 | } |
4932 | |
4933 | static bool classof(const Type *T) { |
4934 | return T->getTypeClass() == DeducedTemplateSpecialization; |
4935 | } |
4936 | }; |
4937 | |
4938 | /// Represents a type template specialization; the template |
4939 | /// must be a class template, a type alias template, or a template |
4940 | /// template parameter. A template which cannot be resolved to one of |
4941 | /// these, e.g. because it is written with a dependent scope |
4942 | /// specifier, is instead represented as a |
4943 | /// @c DependentTemplateSpecializationType. |
4944 | /// |
4945 | /// A non-dependent template specialization type is always "sugar", |
4946 | /// typically for a \c RecordType. For example, a class template |
4947 | /// specialization type of \c vector<int> will refer to a tag type for |
4948 | /// the instantiation \c std::vector<int, std::allocator<int>> |
4949 | /// |
4950 | /// Template specializations are dependent if either the template or |
4951 | /// any of the template arguments are dependent, in which case the |
4952 | /// type may also be canonical. |
4953 | /// |
4954 | /// Instances of this type are allocated with a trailing array of |
4955 | /// TemplateArguments, followed by a QualType representing the |
4956 | /// non-canonical aliased type when the template is a type alias |
4957 | /// template. |
4958 | class alignas(8) TemplateSpecializationType |
4959 | : public Type, |
4960 | public llvm::FoldingSetNode { |
4961 | friend class ASTContext; // ASTContext creates these |
4962 | |
4963 | /// The name of the template being specialized. This is |
4964 | /// either a TemplateName::Template (in which case it is a |
4965 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
4966 | /// TypeAliasTemplateDecl*), a |
4967 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
4968 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
4969 | /// replacement must, recursively, be one of these). |
4970 | TemplateName Template; |
4971 | |
4972 | TemplateSpecializationType(TemplateName T, |
4973 | ArrayRef<TemplateArgument> Args, |
4974 | QualType Canon, |
4975 | QualType Aliased); |
4976 | |
4977 | public: |
4978 | /// Determine whether any of the given template arguments are dependent. |
4979 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
4980 | bool &InstantiationDependent); |
4981 | |
4982 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
4983 | bool &InstantiationDependent); |
4984 | |
4985 | /// True if this template specialization type matches a current |
4986 | /// instantiation in the context in which it is found. |
4987 | bool isCurrentInstantiation() const { |
4988 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
4989 | } |
4990 | |
4991 | /// Determine if this template specialization type is for a type alias |
4992 | /// template that has been substituted. |
4993 | /// |
4994 | /// Nearly every template specialization type whose template is an alias |
4995 | /// template will be substituted. However, this is not the case when |
4996 | /// the specialization contains a pack expansion but the template alias |
4997 | /// does not have a corresponding parameter pack, e.g., |
4998 | /// |
4999 | /// \code |
5000 | /// template<typename T, typename U, typename V> struct S; |
5001 | /// template<typename T, typename U> using A = S<T, int, U>; |
5002 | /// template<typename... Ts> struct X { |
5003 | /// typedef A<Ts...> type; // not a type alias |
5004 | /// }; |
5005 | /// \endcode |
5006 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
5007 | |
5008 | /// Get the aliased type, if this is a specialization of a type alias |
5009 | /// template. |
5010 | QualType getAliasedType() const { |
5011 | assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization" ) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5011, __PRETTY_FUNCTION__)); |
5012 | return *reinterpret_cast<const QualType*>(end()); |
5013 | } |
5014 | |
5015 | using iterator = const TemplateArgument *; |
5016 | |
5017 | iterator begin() const { return getArgs(); } |
5018 | iterator end() const; // defined inline in TemplateBase.h |
5019 | |
5020 | /// Retrieve the name of the template that we are specializing. |
5021 | TemplateName getTemplateName() const { return Template; } |
5022 | |
5023 | /// Retrieve the template arguments. |
5024 | const TemplateArgument *getArgs() const { |
5025 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
5026 | } |
5027 | |
5028 | /// Retrieve the number of template arguments. |
5029 | unsigned getNumArgs() const { |
5030 | return TemplateSpecializationTypeBits.NumArgs; |
5031 | } |
5032 | |
5033 | /// Retrieve a specific template argument as a type. |
5034 | /// \pre \c isArgType(Arg) |
5035 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5036 | |
5037 | ArrayRef<TemplateArgument> template_arguments() const { |
5038 | return {getArgs(), getNumArgs()}; |
5039 | } |
5040 | |
5041 | bool isSugared() const { |
5042 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5043 | } |
5044 | |
5045 | QualType desugar() const { |
5046 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5047 | } |
5048 | |
5049 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5050 | Profile(ID, Template, template_arguments(), Ctx); |
5051 | if (isTypeAlias()) |
5052 | getAliasedType().Profile(ID); |
5053 | } |
5054 | |
5055 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5056 | ArrayRef<TemplateArgument> Args, |
5057 | const ASTContext &Context); |
5058 | |
5059 | static bool classof(const Type *T) { |
5060 | return T->getTypeClass() == TemplateSpecialization; |
5061 | } |
5062 | }; |
5063 | |
5064 | /// Print a template argument list, including the '<' and '>' |
5065 | /// enclosing the template arguments. |
5066 | void printTemplateArgumentList(raw_ostream &OS, |
5067 | ArrayRef<TemplateArgument> Args, |
5068 | const PrintingPolicy &Policy); |
5069 | |
5070 | void printTemplateArgumentList(raw_ostream &OS, |
5071 | ArrayRef<TemplateArgumentLoc> Args, |
5072 | const PrintingPolicy &Policy); |
5073 | |
5074 | void printTemplateArgumentList(raw_ostream &OS, |
5075 | const TemplateArgumentListInfo &Args, |
5076 | const PrintingPolicy &Policy); |
5077 | |
5078 | /// The injected class name of a C++ class template or class |
5079 | /// template partial specialization. Used to record that a type was |
5080 | /// spelled with a bare identifier rather than as a template-id; the |
5081 | /// equivalent for non-templated classes is just RecordType. |
5082 | /// |
5083 | /// Injected class name types are always dependent. Template |
5084 | /// instantiation turns these into RecordTypes. |
5085 | /// |
5086 | /// Injected class name types are always canonical. This works |
5087 | /// because it is impossible to compare an injected class name type |
5088 | /// with the corresponding non-injected template type, for the same |
5089 | /// reason that it is impossible to directly compare template |
5090 | /// parameters from different dependent contexts: injected class name |
5091 | /// types can only occur within the scope of a particular templated |
5092 | /// declaration, and within that scope every template specialization |
5093 | /// will canonicalize to the injected class name (when appropriate |
5094 | /// according to the rules of the language). |
5095 | class InjectedClassNameType : public Type { |
5096 | friend class ASTContext; // ASTContext creates these. |
5097 | friend class ASTNodeImporter; |
5098 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5099 | // currently suitable for AST reading, too much |
5100 | // interdependencies. |
5101 | template <class T> friend class serialization::AbstractTypeReader; |
5102 | |
5103 | CXXRecordDecl *Decl; |
5104 | |
5105 | /// The template specialization which this type represents. |
5106 | /// For example, in |
5107 | /// template <class T> class A { ... }; |
5108 | /// this is A<T>, whereas in |
5109 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5110 | /// this is A<B<X,Y> >. |
5111 | /// |
5112 | /// It is always unqualified, always a template specialization type, |
5113 | /// and always dependent. |
5114 | QualType InjectedType; |
5115 | |
5116 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5117 | : Type(InjectedClassName, QualType(), /*Dependent=*/true, |
5118 | /*InstantiationDependent=*/true, |
5119 | /*VariablyModified=*/false, |
5120 | /*ContainsUnexpandedParameterPack=*/false), |
5121 | Decl(D), InjectedType(TST) { |
5122 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5122, __PRETTY_FUNCTION__)); |
5123 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5123, __PRETTY_FUNCTION__)); |
5124 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5124, __PRETTY_FUNCTION__)); |
5125 | } |
5126 | |
5127 | public: |
5128 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5129 | |
5130 | const TemplateSpecializationType *getInjectedTST() const { |
5131 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5132 | } |
5133 | |
5134 | TemplateName getTemplateName() const { |
5135 | return getInjectedTST()->getTemplateName(); |
5136 | } |
5137 | |
5138 | CXXRecordDecl *getDecl() const; |
5139 | |
5140 | bool isSugared() const { return false; } |
5141 | QualType desugar() const { return QualType(this, 0); } |
5142 | |
5143 | static bool classof(const Type *T) { |
5144 | return T->getTypeClass() == InjectedClassName; |
5145 | } |
5146 | }; |
5147 | |
5148 | /// The kind of a tag type. |
5149 | enum TagTypeKind { |
5150 | /// The "struct" keyword. |
5151 | TTK_Struct, |
5152 | |
5153 | /// The "__interface" keyword. |
5154 | TTK_Interface, |
5155 | |
5156 | /// The "union" keyword. |
5157 | TTK_Union, |
5158 | |
5159 | /// The "class" keyword. |
5160 | TTK_Class, |
5161 | |
5162 | /// The "enum" keyword. |
5163 | TTK_Enum |
5164 | }; |
5165 | |
5166 | /// The elaboration keyword that precedes a qualified type name or |
5167 | /// introduces an elaborated-type-specifier. |
5168 | enum ElaboratedTypeKeyword { |
5169 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5170 | ETK_Struct, |
5171 | |
5172 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5173 | ETK_Interface, |
5174 | |
5175 | /// The "union" keyword introduces the elaborated-type-specifier. |
5176 | ETK_Union, |
5177 | |
5178 | /// The "class" keyword introduces the elaborated-type-specifier. |
5179 | ETK_Class, |
5180 | |
5181 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5182 | ETK_Enum, |
5183 | |
5184 | /// The "typename" keyword precedes the qualified type name, e.g., |
5185 | /// \c typename T::type. |
5186 | ETK_Typename, |
5187 | |
5188 | /// No keyword precedes the qualified type name. |
5189 | ETK_None |
5190 | }; |
5191 | |
5192 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5193 | /// The keyword in stored in the free bits of the base class. |
5194 | /// Also provides a few static helpers for converting and printing |
5195 | /// elaborated type keyword and tag type kind enumerations. |
5196 | class TypeWithKeyword : public Type { |
5197 | protected: |
5198 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5199 | QualType Canonical, bool Dependent, |
5200 | bool InstantiationDependent, bool VariablyModified, |
5201 | bool ContainsUnexpandedParameterPack) |
5202 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
5203 | ContainsUnexpandedParameterPack) { |
5204 | TypeWithKeywordBits.Keyword = Keyword; |
5205 | } |
5206 | |
5207 | public: |
5208 | ElaboratedTypeKeyword getKeyword() const { |
5209 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5210 | } |
5211 | |
5212 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5213 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5214 | |
5215 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5216 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5217 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5218 | |
5219 | /// Converts a TagTypeKind into an elaborated type keyword. |
5220 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5221 | |
5222 | /// Converts an elaborated type keyword into a TagTypeKind. |
5223 | /// It is an error to provide an elaborated type keyword |
5224 | /// which *isn't* a tag kind here. |
5225 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5226 | |
5227 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5228 | |
5229 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5230 | |
5231 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5232 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5233 | } |
5234 | |
5235 | class CannotCastToThisType {}; |
5236 | static CannotCastToThisType classof(const Type *); |
5237 | }; |
5238 | |
5239 | /// Represents a type that was referred to using an elaborated type |
5240 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5241 | /// or both. |
5242 | /// |
5243 | /// This type is used to keep track of a type name as written in the |
5244 | /// source code, including tag keywords and any nested-name-specifiers. |
5245 | /// The type itself is always "sugar", used to express what was written |
5246 | /// in the source code but containing no additional semantic information. |
5247 | class ElaboratedType final |
5248 | : public TypeWithKeyword, |
5249 | public llvm::FoldingSetNode, |
5250 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5251 | friend class ASTContext; // ASTContext creates these |
5252 | friend TrailingObjects; |
5253 | |
5254 | /// The nested name specifier containing the qualifier. |
5255 | NestedNameSpecifier *NNS; |
5256 | |
5257 | /// The type that this qualified name refers to. |
5258 | QualType NamedType; |
5259 | |
5260 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5261 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5262 | /// it, or obtain a null pointer if there is none. |
5263 | |
5264 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5265 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5266 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5267 | NamedType->isDependentType(), |
5268 | NamedType->isInstantiationDependentType(), |
5269 | NamedType->isVariablyModifiedType(), |
5270 | NamedType->containsUnexpandedParameterPack()), |
5271 | NNS(NNS), NamedType(NamedType) { |
5272 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5273 | if (OwnedTagDecl) { |
5274 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5275 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5276 | } |
5277 | assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5279, __PRETTY_FUNCTION__)) |
5278 | "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5279, __PRETTY_FUNCTION__)) |
5279 | "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5279, __PRETTY_FUNCTION__)); |
5280 | } |
5281 | |
5282 | public: |
5283 | /// Retrieve the qualification on this type. |
5284 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5285 | |
5286 | /// Retrieve the type named by the qualified-id. |
5287 | QualType getNamedType() const { return NamedType; } |
5288 | |
5289 | /// Remove a single level of sugar. |
5290 | QualType desugar() const { return getNamedType(); } |
5291 | |
5292 | /// Returns whether this type directly provides sugar. |
5293 | bool isSugared() const { return true; } |
5294 | |
5295 | /// Return the (re)declaration of this type owned by this occurrence of this |
5296 | /// type, or nullptr if there is none. |
5297 | TagDecl *getOwnedTagDecl() const { |
5298 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5299 | : nullptr; |
5300 | } |
5301 | |
5302 | void Profile(llvm::FoldingSetNodeID &ID) { |
5303 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5304 | } |
5305 | |
5306 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5307 | NestedNameSpecifier *NNS, QualType NamedType, |
5308 | TagDecl *OwnedTagDecl) { |
5309 | ID.AddInteger(Keyword); |
5310 | ID.AddPointer(NNS); |
5311 | NamedType.Profile(ID); |
5312 | ID.AddPointer(OwnedTagDecl); |
5313 | } |
5314 | |
5315 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5316 | }; |
5317 | |
5318 | /// Represents a qualified type name for which the type name is |
5319 | /// dependent. |
5320 | /// |
5321 | /// DependentNameType represents a class of dependent types that involve a |
5322 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5323 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5324 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5325 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5326 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5327 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5328 | /// mode, this type is used with non-dependent names to delay name lookup until |
5329 | /// instantiation. |
5330 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5331 | friend class ASTContext; // ASTContext creates these |
5332 | |
5333 | /// The nested name specifier containing the qualifier. |
5334 | NestedNameSpecifier *NNS; |
5335 | |
5336 | /// The type that this typename specifier refers to. |
5337 | const IdentifierInfo *Name; |
5338 | |
5339 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5340 | const IdentifierInfo *Name, QualType CanonType) |
5341 | : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true, |
5342 | /*InstantiationDependent=*/true, |
5343 | /*VariablyModified=*/false, |
5344 | NNS->containsUnexpandedParameterPack()), |
5345 | NNS(NNS), Name(Name) {} |
5346 | |
5347 | public: |
5348 | /// Retrieve the qualification on this type. |
5349 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5350 | |
5351 | /// Retrieve the type named by the typename specifier as an identifier. |
5352 | /// |
5353 | /// This routine will return a non-NULL identifier pointer when the |
5354 | /// form of the original typename was terminated by an identifier, |
5355 | /// e.g., "typename T::type". |
5356 | const IdentifierInfo *getIdentifier() const { |
5357 | return Name; |
5358 | } |
5359 | |
5360 | bool isSugared() const { return false; } |
5361 | QualType desugar() const { return QualType(this, 0); } |
5362 | |
5363 | void Profile(llvm::FoldingSetNodeID &ID) { |
5364 | Profile(ID, getKeyword(), NNS, Name); |
5365 | } |
5366 | |
5367 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5368 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5369 | ID.AddInteger(Keyword); |
5370 | ID.AddPointer(NNS); |
5371 | ID.AddPointer(Name); |
5372 | } |
5373 | |
5374 | static bool classof(const Type *T) { |
5375 | return T->getTypeClass() == DependentName; |
5376 | } |
5377 | }; |
5378 | |
5379 | /// Represents a template specialization type whose template cannot be |
5380 | /// resolved, e.g. |
5381 | /// A<T>::template B<T> |
5382 | class alignas(8) DependentTemplateSpecializationType |
5383 | : public TypeWithKeyword, |
5384 | public llvm::FoldingSetNode { |
5385 | friend class ASTContext; // ASTContext creates these |
5386 | |
5387 | /// The nested name specifier containing the qualifier. |
5388 | NestedNameSpecifier *NNS; |
5389 | |
5390 | /// The identifier of the template. |
5391 | const IdentifierInfo *Name; |
5392 | |
5393 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5394 | NestedNameSpecifier *NNS, |
5395 | const IdentifierInfo *Name, |
5396 | ArrayRef<TemplateArgument> Args, |
5397 | QualType Canon); |
5398 | |
5399 | const TemplateArgument *getArgBuffer() const { |
5400 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5401 | } |
5402 | |
5403 | TemplateArgument *getArgBuffer() { |
5404 | return reinterpret_cast<TemplateArgument*>(this+1); |
5405 | } |
5406 | |
5407 | public: |
5408 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5409 | const IdentifierInfo *getIdentifier() const { return Name; } |
5410 | |
5411 | /// Retrieve the template arguments. |
5412 | const TemplateArgument *getArgs() const { |
5413 | return getArgBuffer(); |
5414 | } |
5415 | |
5416 | /// Retrieve the number of template arguments. |
5417 | unsigned getNumArgs() const { |
5418 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5419 | } |
5420 | |
5421 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5422 | |
5423 | ArrayRef<TemplateArgument> template_arguments() const { |
5424 | return {getArgs(), getNumArgs()}; |
5425 | } |
5426 | |
5427 | using iterator = const TemplateArgument *; |
5428 | |
5429 | iterator begin() const { return getArgs(); } |
5430 | iterator end() const; // inline in TemplateBase.h |
5431 | |
5432 | bool isSugared() const { return false; } |
5433 | QualType desugar() const { return QualType(this, 0); } |
5434 | |
5435 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5436 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5437 | } |
5438 | |
5439 | static void Profile(llvm::FoldingSetNodeID &ID, |
5440 | const ASTContext &Context, |
5441 | ElaboratedTypeKeyword Keyword, |
5442 | NestedNameSpecifier *Qualifier, |
5443 | const IdentifierInfo *Name, |
5444 | ArrayRef<TemplateArgument> Args); |
5445 | |
5446 | static bool classof(const Type *T) { |
5447 | return T->getTypeClass() == DependentTemplateSpecialization; |
5448 | } |
5449 | }; |
5450 | |
5451 | /// Represents a pack expansion of types. |
5452 | /// |
5453 | /// Pack expansions are part of C++11 variadic templates. A pack |
5454 | /// expansion contains a pattern, which itself contains one or more |
5455 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5456 | /// produces a series of types, each instantiated from the pattern of |
5457 | /// the expansion, where the Ith instantiation of the pattern uses the |
5458 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5459 | /// pack expansion is considered to "expand" these unexpanded |
5460 | /// parameter packs. |
5461 | /// |
5462 | /// \code |
5463 | /// template<typename ...Types> struct tuple; |
5464 | /// |
5465 | /// template<typename ...Types> |
5466 | /// struct tuple_of_references { |
5467 | /// typedef tuple<Types&...> type; |
5468 | /// }; |
5469 | /// \endcode |
5470 | /// |
5471 | /// Here, the pack expansion \c Types&... is represented via a |
5472 | /// PackExpansionType whose pattern is Types&. |
5473 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5474 | friend class ASTContext; // ASTContext creates these |
5475 | |
5476 | /// The pattern of the pack expansion. |
5477 | QualType Pattern; |
5478 | |
5479 | PackExpansionType(QualType Pattern, QualType Canon, |
5480 | Optional<unsigned> NumExpansions) |
5481 | : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(), |
5482 | /*InstantiationDependent=*/true, |
5483 | /*VariablyModified=*/Pattern->isVariablyModifiedType(), |
5484 | /*ContainsUnexpandedParameterPack=*/false), |
5485 | Pattern(Pattern) { |
5486 | PackExpansionTypeBits.NumExpansions = |
5487 | NumExpansions ? *NumExpansions + 1 : 0; |
5488 | } |
5489 | |
5490 | public: |
5491 | /// Retrieve the pattern of this pack expansion, which is the |
5492 | /// type that will be repeatedly instantiated when instantiating the |
5493 | /// pack expansion itself. |
5494 | QualType getPattern() const { return Pattern; } |
5495 | |
5496 | /// Retrieve the number of expansions that this pack expansion will |
5497 | /// generate, if known. |
5498 | Optional<unsigned> getNumExpansions() const { |
5499 | if (PackExpansionTypeBits.NumExpansions) |
5500 | return PackExpansionTypeBits.NumExpansions - 1; |
5501 | return None; |
5502 | } |
5503 | |
5504 | bool isSugared() const { return !Pattern->isDependentType(); } |
5505 | QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); } |
5506 | |
5507 | void Profile(llvm::FoldingSetNodeID &ID) { |
5508 | Profile(ID, getPattern(), getNumExpansions()); |
5509 | } |
5510 | |
5511 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5512 | Optional<unsigned> NumExpansions) { |
5513 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5514 | ID.AddBoolean(NumExpansions.hasValue()); |
5515 | if (NumExpansions) |
5516 | ID.AddInteger(*NumExpansions); |
5517 | } |
5518 | |
5519 | static bool classof(const Type *T) { |
5520 | return T->getTypeClass() == PackExpansion; |
5521 | } |
5522 | }; |
5523 | |
5524 | /// This class wraps the list of protocol qualifiers. For types that can |
5525 | /// take ObjC protocol qualifers, they can subclass this class. |
5526 | template <class T> |
5527 | class ObjCProtocolQualifiers { |
5528 | protected: |
5529 | ObjCProtocolQualifiers() = default; |
5530 | |
5531 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5532 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5533 | } |
5534 | |
5535 | ObjCProtocolDecl **getProtocolStorage() { |
5536 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5537 | } |
5538 | |
5539 | void setNumProtocols(unsigned N) { |
5540 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5541 | } |
5542 | |
5543 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5544 | setNumProtocols(protocols.size()); |
5545 | assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5546, __PRETTY_FUNCTION__)) |
5546 | "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5546, __PRETTY_FUNCTION__)); |
5547 | if (!protocols.empty()) |
5548 | memcpy(getProtocolStorage(), protocols.data(), |
5549 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5550 | } |
5551 | |
5552 | public: |
5553 | using qual_iterator = ObjCProtocolDecl * const *; |
5554 | using qual_range = llvm::iterator_range<qual_iterator>; |
5555 | |
5556 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5557 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5558 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5559 | |
5560 | bool qual_empty() const { return getNumProtocols() == 0; } |
5561 | |
5562 | /// Return the number of qualifying protocols in this type, or 0 if |
5563 | /// there are none. |
5564 | unsigned getNumProtocols() const { |
5565 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5566 | } |
5567 | |
5568 | /// Fetch a protocol by index. |
5569 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5570 | assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access" ) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5570, __PRETTY_FUNCTION__)); |
5571 | return qual_begin()[I]; |
5572 | } |
5573 | |
5574 | /// Retrieve all of the protocol qualifiers. |
5575 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5576 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5577 | } |
5578 | }; |
5579 | |
5580 | /// Represents a type parameter type in Objective C. It can take |
5581 | /// a list of protocols. |
5582 | class ObjCTypeParamType : public Type, |
5583 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5584 | public llvm::FoldingSetNode { |
5585 | friend class ASTContext; |
5586 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5587 | |
5588 | /// The number of protocols stored on this type. |
5589 | unsigned NumProtocols : 6; |
5590 | |
5591 | ObjCTypeParamDecl *OTPDecl; |
5592 | |
5593 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5594 | /// canonical type, the list of protocols are sorted alphabetically |
5595 | /// and uniqued. |
5596 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5597 | |
5598 | /// Return the number of qualifying protocols in this interface type, |
5599 | /// or 0 if there are none. |
5600 | unsigned getNumProtocolsImpl() const { |
5601 | return NumProtocols; |
5602 | } |
5603 | |
5604 | void setNumProtocolsImpl(unsigned N) { |
5605 | NumProtocols = N; |
5606 | } |
5607 | |
5608 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5609 | QualType can, |
5610 | ArrayRef<ObjCProtocolDecl *> protocols); |
5611 | |
5612 | public: |
5613 | bool isSugared() const { return true; } |
5614 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5615 | |
5616 | static bool classof(const Type *T) { |
5617 | return T->getTypeClass() == ObjCTypeParam; |
5618 | } |
5619 | |
5620 | void Profile(llvm::FoldingSetNodeID &ID); |
5621 | static void Profile(llvm::FoldingSetNodeID &ID, |
5622 | const ObjCTypeParamDecl *OTPDecl, |
5623 | ArrayRef<ObjCProtocolDecl *> protocols); |
5624 | |
5625 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5626 | }; |
5627 | |
5628 | /// Represents a class type in Objective C. |
5629 | /// |
5630 | /// Every Objective C type is a combination of a base type, a set of |
5631 | /// type arguments (optional, for parameterized classes) and a list of |
5632 | /// protocols. |
5633 | /// |
5634 | /// Given the following declarations: |
5635 | /// \code |
5636 | /// \@class C<T>; |
5637 | /// \@protocol P; |
5638 | /// \endcode |
5639 | /// |
5640 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5641 | /// with base C and no protocols. |
5642 | /// |
5643 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5644 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5645 | /// protocol list. |
5646 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5647 | /// and protocol list [P]. |
5648 | /// |
5649 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5650 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5651 | /// and no protocols. |
5652 | /// |
5653 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5654 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5655 | /// this should get its own sugar class to better represent the source. |
5656 | class ObjCObjectType : public Type, |
5657 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5658 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5659 | |
5660 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5661 | // after the ObjCObjectPointerType node. |
5662 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5663 | // after the type arguments of ObjCObjectPointerType node. |
5664 | // |
5665 | // These protocols are those written directly on the type. If |
5666 | // protocol qualifiers ever become additive, the iterators will need |
5667 | // to get kindof complicated. |
5668 | // |
5669 | // In the canonical object type, these are sorted alphabetically |
5670 | // and uniqued. |
5671 | |
5672 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5673 | QualType BaseType; |
5674 | |
5675 | /// Cached superclass type. |
5676 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5677 | CachedSuperClassType; |
5678 | |
5679 | QualType *getTypeArgStorage(); |
5680 | const QualType *getTypeArgStorage() const { |
5681 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5682 | } |
5683 | |
5684 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5685 | /// Return the number of qualifying protocols in this interface type, |
5686 | /// or 0 if there are none. |
5687 | unsigned getNumProtocolsImpl() const { |
5688 | return ObjCObjectTypeBits.NumProtocols; |
5689 | } |
5690 | void setNumProtocolsImpl(unsigned N) { |
5691 | ObjCObjectTypeBits.NumProtocols = N; |
5692 | } |
5693 | |
5694 | protected: |
5695 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5696 | |
5697 | ObjCObjectType(QualType Canonical, QualType Base, |
5698 | ArrayRef<QualType> typeArgs, |
5699 | ArrayRef<ObjCProtocolDecl *> protocols, |
5700 | bool isKindOf); |
5701 | |
5702 | ObjCObjectType(enum Nonce_ObjCInterface) |
5703 | : Type(ObjCInterface, QualType(), false, false, false, false), |
5704 | BaseType(QualType(this_(), 0)) { |
5705 | ObjCObjectTypeBits.NumProtocols = 0; |
5706 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5707 | ObjCObjectTypeBits.IsKindOf = 0; |
5708 | } |
5709 | |
5710 | void computeSuperClassTypeSlow() const; |
5711 | |
5712 | public: |
5713 | /// Gets the base type of this object type. This is always (possibly |
5714 | /// sugar for) one of: |
5715 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5716 | /// user, which is a typedef for an ObjCObjectPointerType) |
5717 | /// - the 'Class' builtin type (same caveat) |
5718 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5719 | QualType getBaseType() const { return BaseType; } |
5720 | |
5721 | bool isObjCId() const { |
5722 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5723 | } |
5724 | |
5725 | bool isObjCClass() const { |
5726 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5727 | } |
5728 | |
5729 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5730 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5731 | bool isObjCUnqualifiedIdOrClass() const { |
5732 | if (!qual_empty()) return false; |
5733 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5734 | return T->getKind() == BuiltinType::ObjCId || |
5735 | T->getKind() == BuiltinType::ObjCClass; |
5736 | return false; |
5737 | } |
5738 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5739 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5740 | |
5741 | /// Gets the interface declaration for this object type, if the base type |
5742 | /// really is an interface. |
5743 | ObjCInterfaceDecl *getInterface() const; |
5744 | |
5745 | /// Determine whether this object type is "specialized", meaning |
5746 | /// that it has type arguments. |
5747 | bool isSpecialized() const; |
5748 | |
5749 | /// Determine whether this object type was written with type arguments. |
5750 | bool isSpecializedAsWritten() const { |
5751 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5752 | } |
5753 | |
5754 | /// Determine whether this object type is "unspecialized", meaning |
5755 | /// that it has no type arguments. |
5756 | bool isUnspecialized() const { return !isSpecialized(); } |
5757 | |
5758 | /// Determine whether this object type is "unspecialized" as |
5759 | /// written, meaning that it has no type arguments. |
5760 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5761 | |
5762 | /// Retrieve the type arguments of this object type (semantically). |
5763 | ArrayRef<QualType> getTypeArgs() const; |
5764 | |
5765 | /// Retrieve the type arguments of this object type as they were |
5766 | /// written. |
5767 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5768 | return llvm::makeArrayRef(getTypeArgStorage(), |
5769 | ObjCObjectTypeBits.NumTypeArgs); |
5770 | } |
5771 | |
5772 | /// Whether this is a "__kindof" type as written. |
5773 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5774 | |
5775 | /// Whether this ia a "__kindof" type (semantically). |
5776 | bool isKindOfType() const; |
5777 | |
5778 | /// Retrieve the type of the superclass of this object type. |
5779 | /// |
5780 | /// This operation substitutes any type arguments into the |
5781 | /// superclass of the current class type, potentially producing a |
5782 | /// specialization of the superclass type. Produces a null type if |
5783 | /// there is no superclass. |
5784 | QualType getSuperClassType() const { |
5785 | if (!CachedSuperClassType.getInt()) |
5786 | computeSuperClassTypeSlow(); |
5787 | |
5788 | assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?" ) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 5788, __PRETTY_FUNCTION__)); |
5789 | return QualType(CachedSuperClassType.getPointer(), 0); |
5790 | } |
5791 | |
5792 | /// Strip off the Objective-C "kindof" type and (with it) any |
5793 | /// protocol qualifiers. |
5794 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5795 | |
5796 | bool isSugared() const { return false; } |
5797 | QualType desugar() const { return QualType(this, 0); } |
5798 | |
5799 | static bool classof(const Type *T) { |
5800 | return T->getTypeClass() == ObjCObject || |
5801 | T->getTypeClass() == ObjCInterface; |
5802 | } |
5803 | }; |
5804 | |
5805 | /// A class providing a concrete implementation |
5806 | /// of ObjCObjectType, so as to not increase the footprint of |
5807 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5808 | /// system should not reference this type. |
5809 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5810 | friend class ASTContext; |
5811 | |
5812 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5813 | // will need to be modified. |
5814 | |
5815 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5816 | ArrayRef<QualType> typeArgs, |
5817 | ArrayRef<ObjCProtocolDecl *> protocols, |
5818 | bool isKindOf) |
5819 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5820 | |
5821 | public: |
5822 | void Profile(llvm::FoldingSetNodeID &ID); |
5823 | static void Profile(llvm::FoldingSetNodeID &ID, |
5824 | QualType Base, |
5825 | ArrayRef<QualType> typeArgs, |
5826 | ArrayRef<ObjCProtocolDecl *> protocols, |
5827 | bool isKindOf); |
5828 | }; |
5829 | |
5830 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5831 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5832 | } |
5833 | |
5834 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5835 | return reinterpret_cast<ObjCProtocolDecl**>( |
5836 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5837 | } |
5838 | |
5839 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5840 | return reinterpret_cast<ObjCProtocolDecl**>( |
5841 | static_cast<ObjCTypeParamType*>(this)+1); |
5842 | } |
5843 | |
5844 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5845 | /// They basically correspond to C++ classes. There are two kinds of interface |
5846 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5847 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5848 | /// |
5849 | /// ObjCInterfaceType guarantees the following properties when considered |
5850 | /// as a subtype of its superclass, ObjCObjectType: |
5851 | /// - There are no protocol qualifiers. To reinforce this, code which |
5852 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5853 | /// fail to compile. |
5854 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5855 | /// T->getBaseType() == QualType(T, 0). |
5856 | class ObjCInterfaceType : public ObjCObjectType { |
5857 | friend class ASTContext; // ASTContext creates these. |
5858 | friend class ASTReader; |
5859 | friend class ObjCInterfaceDecl; |
5860 | template <class T> friend class serialization::AbstractTypeReader; |
5861 | |
5862 | mutable ObjCInterfaceDecl *Decl; |
5863 | |
5864 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5865 | : ObjCObjectType(Nonce_ObjCInterface), |
5866 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5867 | |
5868 | public: |
5869 | /// Get the declaration of this interface. |
5870 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5871 | |
5872 | bool isSugared() const { return false; } |
5873 | QualType desugar() const { return QualType(this, 0); } |
5874 | |
5875 | static bool classof(const Type *T) { |
5876 | return T->getTypeClass() == ObjCInterface; |
5877 | } |
5878 | |
5879 | // Nonsense to "hide" certain members of ObjCObjectType within this |
5880 | // class. People asking for protocols on an ObjCInterfaceType are |
5881 | // not going to get what they want: ObjCInterfaceTypes are |
5882 | // guaranteed to have no protocols. |
5883 | enum { |
5884 | qual_iterator, |
5885 | qual_begin, |
5886 | qual_end, |
5887 | getNumProtocols, |
5888 | getProtocol |
5889 | }; |
5890 | }; |
5891 | |
5892 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
5893 | QualType baseType = getBaseType(); |
5894 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
5895 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
5896 | return T->getDecl(); |
5897 | |
5898 | baseType = ObjT->getBaseType(); |
5899 | } |
5900 | |
5901 | return nullptr; |
5902 | } |
5903 | |
5904 | /// Represents a pointer to an Objective C object. |
5905 | /// |
5906 | /// These are constructed from pointer declarators when the pointee type is |
5907 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
5908 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
5909 | /// and 'Class<P>' are translated into these. |
5910 | /// |
5911 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
5912 | /// only the first level of pointer gets it own type implementation. |
5913 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
5914 | friend class ASTContext; // ASTContext creates these. |
5915 | |
5916 | QualType PointeeType; |
5917 | |
5918 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
5919 | : Type(ObjCObjectPointer, Canonical, |
5920 | Pointee->isDependentType(), |
5921 | Pointee->isInstantiationDependentType(), |
5922 | Pointee->isVariablyModifiedType(), |
5923 | Pointee->containsUnexpandedParameterPack()), |
5924 | PointeeType(Pointee) {} |
5925 | |
5926 | public: |
5927 | /// Gets the type pointed to by this ObjC pointer. |
5928 | /// The result will always be an ObjCObjectType or sugar thereof. |
5929 | QualType getPointeeType() const { return PointeeType; } |
5930 | |
5931 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
5932 | /// |
5933 | /// This method is equivalent to getPointeeType() except that |
5934 | /// it discards any typedefs (or other sugar) between this |
5935 | /// type and the "outermost" object type. So for: |
5936 | /// \code |
5937 | /// \@class A; \@protocol P; \@protocol Q; |
5938 | /// typedef A<P> AP; |
5939 | /// typedef A A1; |
5940 | /// typedef A1<P> A1P; |
5941 | /// typedef A1P<Q> A1PQ; |
5942 | /// \endcode |
5943 | /// For 'A*', getObjectType() will return 'A'. |
5944 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
5945 | /// For 'AP*', getObjectType() will return 'A<P>'. |
5946 | /// For 'A1*', getObjectType() will return 'A'. |
5947 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
5948 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
5949 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
5950 | /// adding protocols to a protocol-qualified base discards the |
5951 | /// old qualifiers (for now). But if it didn't, getObjectType() |
5952 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
5953 | /// qualifiers more complicated). |
5954 | const ObjCObjectType *getObjectType() const { |
5955 | return PointeeType->castAs<ObjCObjectType>(); |
5956 | } |
5957 | |
5958 | /// If this pointer points to an Objective C |
5959 | /// \@interface type, gets the type for that interface. Any protocol |
5960 | /// qualifiers on the interface are ignored. |
5961 | /// |
5962 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5963 | const ObjCInterfaceType *getInterfaceType() const; |
5964 | |
5965 | /// If this pointer points to an Objective \@interface |
5966 | /// type, gets the declaration for that interface. |
5967 | /// |
5968 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5969 | ObjCInterfaceDecl *getInterfaceDecl() const { |
5970 | return getObjectType()->getInterface(); |
5971 | } |
5972 | |
5973 | /// True if this is equivalent to the 'id' type, i.e. if |
5974 | /// its object type is the primitive 'id' type with no protocols. |
5975 | bool isObjCIdType() const { |
5976 | return getObjectType()->isObjCUnqualifiedId(); |
5977 | } |
5978 | |
5979 | /// True if this is equivalent to the 'Class' type, |
5980 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
5981 | bool isObjCClassType() const { |
5982 | return getObjectType()->isObjCUnqualifiedClass(); |
5983 | } |
5984 | |
5985 | /// True if this is equivalent to the 'id' or 'Class' type, |
5986 | bool isObjCIdOrClassType() const { |
5987 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
5988 | } |
5989 | |
5990 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
5991 | /// protocols. |
5992 | bool isObjCQualifiedIdType() const { |
5993 | return getObjectType()->isObjCQualifiedId(); |
5994 | } |
5995 | |
5996 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
5997 | /// protocols. |
5998 | bool isObjCQualifiedClassType() const { |
5999 | return getObjectType()->isObjCQualifiedClass(); |
6000 | } |
6001 | |
6002 | /// Whether this is a "__kindof" type. |
6003 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
6004 | |
6005 | /// Whether this type is specialized, meaning that it has type arguments. |
6006 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
6007 | |
6008 | /// Whether this type is specialized, meaning that it has type arguments. |
6009 | bool isSpecializedAsWritten() const { |
6010 | return getObjectType()->isSpecializedAsWritten(); |
6011 | } |
6012 | |
6013 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
6014 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
6015 | |
6016 | /// Determine whether this object type is "unspecialized" as |
6017 | /// written, meaning that it has no type arguments. |
6018 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
6019 | |
6020 | /// Retrieve the type arguments for this type. |
6021 | ArrayRef<QualType> getTypeArgs() const { |
6022 | return getObjectType()->getTypeArgs(); |
6023 | } |
6024 | |
6025 | /// Retrieve the type arguments for this type. |
6026 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
6027 | return getObjectType()->getTypeArgsAsWritten(); |
6028 | } |
6029 | |
6030 | /// An iterator over the qualifiers on the object type. Provided |
6031 | /// for convenience. This will always iterate over the full set of |
6032 | /// protocols on a type, not just those provided directly. |
6033 | using qual_iterator = ObjCObjectType::qual_iterator; |
6034 | using qual_range = llvm::iterator_range<qual_iterator>; |
6035 | |
6036 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
6037 | |
6038 | qual_iterator qual_begin() const { |
6039 | return getObjectType()->qual_begin(); |
6040 | } |
6041 | |
6042 | qual_iterator qual_end() const { |
6043 | return getObjectType()->qual_end(); |
6044 | } |
6045 | |
6046 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6047 | |
6048 | /// Return the number of qualifying protocols on the object type. |
6049 | unsigned getNumProtocols() const { |
6050 | return getObjectType()->getNumProtocols(); |
6051 | } |
6052 | |
6053 | /// Retrieve a qualifying protocol by index on the object type. |
6054 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6055 | return getObjectType()->getProtocol(I); |
6056 | } |
6057 | |
6058 | bool isSugared() const { return false; } |
6059 | QualType desugar() const { return QualType(this, 0); } |
6060 | |
6061 | /// Retrieve the type of the superclass of this object pointer type. |
6062 | /// |
6063 | /// This operation substitutes any type arguments into the |
6064 | /// superclass of the current class type, potentially producing a |
6065 | /// pointer to a specialization of the superclass type. Produces a |
6066 | /// null type if there is no superclass. |
6067 | QualType getSuperClassType() const; |
6068 | |
6069 | /// Strip off the Objective-C "kindof" type and (with it) any |
6070 | /// protocol qualifiers. |
6071 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6072 | const ASTContext &ctx) const; |
6073 | |
6074 | void Profile(llvm::FoldingSetNodeID &ID) { |
6075 | Profile(ID, getPointeeType()); |
6076 | } |
6077 | |
6078 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6079 | ID.AddPointer(T.getAsOpaquePtr()); |
6080 | } |
6081 | |
6082 | static bool classof(const Type *T) { |
6083 | return T->getTypeClass() == ObjCObjectPointer; |
6084 | } |
6085 | }; |
6086 | |
6087 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6088 | friend class ASTContext; // ASTContext creates these. |
6089 | |
6090 | QualType ValueType; |
6091 | |
6092 | AtomicType(QualType ValTy, QualType Canonical) |
6093 | : Type(Atomic, Canonical, ValTy->isDependentType(), |
6094 | ValTy->isInstantiationDependentType(), |
6095 | ValTy->isVariablyModifiedType(), |
6096 | ValTy->containsUnexpandedParameterPack()), |
6097 | ValueType(ValTy) {} |
6098 | |
6099 | public: |
6100 | /// Gets the type contained by this atomic type, i.e. |
6101 | /// the type returned by performing an atomic load of this atomic type. |
6102 | QualType getValueType() const { return ValueType; } |
6103 | |
6104 | bool isSugared() const { return false; } |
6105 | QualType desugar() const { return QualType(this, 0); } |
6106 | |
6107 | void Profile(llvm::FoldingSetNodeID &ID) { |
6108 | Profile(ID, getValueType()); |
6109 | } |
6110 | |
6111 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6112 | ID.AddPointer(T.getAsOpaquePtr()); |
6113 | } |
6114 | |
6115 | static bool classof(const Type *T) { |
6116 | return T->getTypeClass() == Atomic; |
6117 | } |
6118 | }; |
6119 | |
6120 | /// PipeType - OpenCL20. |
6121 | class PipeType : public Type, public llvm::FoldingSetNode { |
6122 | friend class ASTContext; // ASTContext creates these. |
6123 | |
6124 | QualType ElementType; |
6125 | bool isRead; |
6126 | |
6127 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6128 | : Type(Pipe, CanonicalPtr, elemType->isDependentType(), |
6129 | elemType->isInstantiationDependentType(), |
6130 | elemType->isVariablyModifiedType(), |
6131 | elemType->containsUnexpandedParameterPack()), |
6132 | ElementType(elemType), isRead(isRead) {} |
6133 | |
6134 | public: |
6135 | QualType getElementType() const { return ElementType; } |
6136 | |
6137 | bool isSugared() const { return false; } |
6138 | |
6139 | QualType desugar() const { return QualType(this, 0); } |
6140 | |
6141 | void Profile(llvm::FoldingSetNodeID &ID) { |
6142 | Profile(ID, getElementType(), isReadOnly()); |
6143 | } |
6144 | |
6145 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6146 | ID.AddPointer(T.getAsOpaquePtr()); |
6147 | ID.AddBoolean(isRead); |
6148 | } |
6149 | |
6150 | static bool classof(const Type *T) { |
6151 | return T->getTypeClass() == Pipe; |
6152 | } |
6153 | |
6154 | bool isReadOnly() const { return isRead; } |
6155 | }; |
6156 | |
6157 | /// A qualifier set is used to build a set of qualifiers. |
6158 | class QualifierCollector : public Qualifiers { |
6159 | public: |
6160 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6161 | |
6162 | /// Collect any qualifiers on the given type and return an |
6163 | /// unqualified type. The qualifiers are assumed to be consistent |
6164 | /// with those already in the type. |
6165 | const Type *strip(QualType type) { |
6166 | addFastQualifiers(type.getLocalFastQualifiers()); |
6167 | if (!type.hasLocalNonFastQualifiers()) |
6168 | return type.getTypePtrUnsafe(); |
6169 | |
6170 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6171 | addConsistentQualifiers(extQuals->getQualifiers()); |
6172 | return extQuals->getBaseType(); |
6173 | } |
6174 | |
6175 | /// Apply the collected qualifiers to the given type. |
6176 | QualType apply(const ASTContext &Context, QualType QT) const; |
6177 | |
6178 | /// Apply the collected qualifiers to the given type. |
6179 | QualType apply(const ASTContext &Context, const Type* T) const; |
6180 | }; |
6181 | |
6182 | /// A container of type source information. |
6183 | /// |
6184 | /// A client can read the relevant info using TypeLoc wrappers, e.g: |
6185 | /// @code |
6186 | /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); |
6187 | /// TL.getBeginLoc().print(OS, SrcMgr); |
6188 | /// @endcode |
6189 | class alignas(8) TypeSourceInfo { |
6190 | // Contains a memory block after the class, used for type source information, |
6191 | // allocated by ASTContext. |
6192 | friend class ASTContext; |
6193 | |
6194 | QualType Ty; |
6195 | |
6196 | TypeSourceInfo(QualType ty) : Ty(ty) {} |
6197 | |
6198 | public: |
6199 | /// Return the type wrapped by this type source info. |
6200 | QualType getType() const { return Ty; } |
6201 | |
6202 | /// Return the TypeLoc wrapper for the type source info. |
6203 | TypeLoc getTypeLoc() const; // implemented in TypeLoc.h |
6204 | |
6205 | /// Override the type stored in this TypeSourceInfo. Use with caution! |
6206 | void overrideType(QualType T) { Ty = T; } |
6207 | }; |
6208 | |
6209 | // Inline function definitions. |
6210 | |
6211 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6212 | SplitQualType desugar = |
6213 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6214 | desugar.Quals.addConsistentQualifiers(Quals); |
6215 | return desugar; |
6216 | } |
6217 | |
6218 | inline const Type *QualType::getTypePtr() const { |
6219 | return getCommonPtr()->BaseType; |
6220 | } |
6221 | |
6222 | inline const Type *QualType::getTypePtrOrNull() const { |
6223 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6224 | } |
6225 | |
6226 | inline SplitQualType QualType::split() const { |
6227 | if (!hasLocalNonFastQualifiers()) |
6228 | return SplitQualType(getTypePtrUnsafe(), |
6229 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6230 | |
6231 | const ExtQuals *eq = getExtQualsUnsafe(); |
6232 | Qualifiers qs = eq->getQualifiers(); |
6233 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6234 | return SplitQualType(eq->getBaseType(), qs); |
6235 | } |
6236 | |
6237 | inline Qualifiers QualType::getLocalQualifiers() const { |
6238 | Qualifiers Quals; |
6239 | if (hasLocalNonFastQualifiers()) |
6240 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6241 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6242 | return Quals; |
6243 | } |
6244 | |
6245 | inline Qualifiers QualType::getQualifiers() const { |
6246 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6247 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6248 | return quals; |
6249 | } |
6250 | |
6251 | inline unsigned QualType::getCVRQualifiers() const { |
6252 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6253 | cvr |= getLocalCVRQualifiers(); |
6254 | return cvr; |
6255 | } |
6256 | |
6257 | inline QualType QualType::getCanonicalType() const { |
6258 | QualType canon = getCommonPtr()->CanonicalType; |
6259 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6260 | } |
6261 | |
6262 | inline bool QualType::isCanonical() const { |
6263 | return getTypePtr()->isCanonicalUnqualified(); |
6264 | } |
6265 | |
6266 | inline bool QualType::isCanonicalAsParam() const { |
6267 | if (!isCanonical()) return false; |
6268 | if (hasLocalQualifiers()) return false; |
6269 | |
6270 | const Type *T = getTypePtr(); |
6271 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6272 | return false; |
6273 | |
6274 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6275 | } |
6276 | |
6277 | inline bool QualType::isConstQualified() const { |
6278 | return isLocalConstQualified() || |
6279 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6280 | } |
6281 | |
6282 | inline bool QualType::isRestrictQualified() const { |
6283 | return isLocalRestrictQualified() || |
6284 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6285 | } |
6286 | |
6287 | |
6288 | inline bool QualType::isVolatileQualified() const { |
6289 | return isLocalVolatileQualified() || |
6290 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6291 | } |
6292 | |
6293 | inline bool QualType::hasQualifiers() const { |
6294 | return hasLocalQualifiers() || |
6295 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6296 | } |
6297 | |
6298 | inline QualType QualType::getUnqualifiedType() const { |
6299 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6300 | return QualType(getTypePtr(), 0); |
6301 | |
6302 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6303 | } |
6304 | |
6305 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6306 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6307 | return split(); |
6308 | |
6309 | return getSplitUnqualifiedTypeImpl(*this); |
6310 | } |
6311 | |
6312 | inline void QualType::removeLocalConst() { |
6313 | removeLocalFastQualifiers(Qualifiers::Const); |
6314 | } |
6315 | |
6316 | inline void QualType::removeLocalRestrict() { |
6317 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6318 | } |
6319 | |
6320 | inline void QualType::removeLocalVolatile() { |
6321 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6322 | } |
6323 | |
6324 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6325 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 6325, __PRETTY_FUNCTION__)); |
6326 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6327 | "Fast bits differ from CVR bits!"); |
6328 | |
6329 | // Fast path: we don't need to touch the slow qualifiers. |
6330 | removeLocalFastQualifiers(Mask); |
6331 | } |
6332 | |
6333 | /// Check if this type has any address space qualifier. |
6334 | inline bool QualType::hasAddressSpace() const { |
6335 | return getQualifiers().hasAddressSpace(); |
6336 | } |
6337 | |
6338 | /// Return the address space of this type. |
6339 | inline LangAS QualType::getAddressSpace() const { |
6340 | return getQualifiers().getAddressSpace(); |
6341 | } |
6342 | |
6343 | /// Return the gc attribute of this type. |
6344 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6345 | return getQualifiers().getObjCGCAttr(); |
6346 | } |
6347 | |
6348 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6349 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6350 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6351 | return false; |
6352 | } |
6353 | |
6354 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6355 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6356 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6357 | return false; |
6358 | } |
6359 | |
6360 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6361 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6362 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6363 | return false; |
6364 | } |
6365 | |
6366 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6367 | if (const auto *PT = t.getAs<PointerType>()) { |
6368 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6369 | return FT->getExtInfo(); |
6370 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6371 | return FT->getExtInfo(); |
6372 | |
6373 | return FunctionType::ExtInfo(); |
6374 | } |
6375 | |
6376 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6377 | return getFunctionExtInfo(*t); |
6378 | } |
6379 | |
6380 | /// Determine whether this type is more |
6381 | /// qualified than the Other type. For example, "const volatile int" |
6382 | /// is more qualified than "const int", "volatile int", and |
6383 | /// "int". However, it is not more qualified than "const volatile |
6384 | /// int". |
6385 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6386 | Qualifiers MyQuals = getQualifiers(); |
6387 | Qualifiers OtherQuals = other.getQualifiers(); |
6388 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6389 | } |
6390 | |
6391 | /// Determine whether this type is at last |
6392 | /// as qualified as the Other type. For example, "const volatile |
6393 | /// int" is at least as qualified as "const int", "volatile int", |
6394 | /// "int", and "const volatile int". |
6395 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6396 | Qualifiers OtherQuals = other.getQualifiers(); |
6397 | |
6398 | // Ignore __unaligned qualifier if this type is a void. |
6399 | if (getUnqualifiedType()->isVoidType()) |
6400 | OtherQuals.removeUnaligned(); |
6401 | |
6402 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6403 | } |
6404 | |
6405 | /// If Type is a reference type (e.g., const |
6406 | /// int&), returns the type that the reference refers to ("const |
6407 | /// int"). Otherwise, returns the type itself. This routine is used |
6408 | /// throughout Sema to implement C++ 5p6: |
6409 | /// |
6410 | /// If an expression initially has the type "reference to T" (8.3.2, |
6411 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6412 | /// analysis, the expression designates the object or function |
6413 | /// denoted by the reference, and the expression is an lvalue. |
6414 | inline QualType QualType::getNonReferenceType() const { |
6415 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6416 | return RefType->getPointeeType(); |
6417 | else |
6418 | return *this; |
6419 | } |
6420 | |
6421 | inline bool QualType::isCForbiddenLValueType() const { |
6422 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6423 | getTypePtr()->isFunctionType()); |
6424 | } |
6425 | |
6426 | /// Tests whether the type is categorized as a fundamental type. |
6427 | /// |
6428 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6429 | inline bool Type::isFundamentalType() const { |
6430 | return isVoidType() || |
6431 | isNullPtrType() || |
6432 | // FIXME: It's really annoying that we don't have an |
6433 | // 'isArithmeticType()' which agrees with the standard definition. |
6434 | (isArithmeticType() && !isEnumeralType()); |
6435 | } |
6436 | |
6437 | /// Tests whether the type is categorized as a compound type. |
6438 | /// |
6439 | /// \returns True for types specified in C++0x [basic.compound]. |
6440 | inline bool Type::isCompoundType() const { |
6441 | // C++0x [basic.compound]p1: |
6442 | // Compound types can be constructed in the following ways: |
6443 | // -- arrays of objects of a given type [...]; |
6444 | return isArrayType() || |
6445 | // -- functions, which have parameters of given types [...]; |
6446 | isFunctionType() || |
6447 | // -- pointers to void or objects or functions [...]; |
6448 | isPointerType() || |
6449 | // -- references to objects or functions of a given type. [...] |
6450 | isReferenceType() || |
6451 | // -- classes containing a sequence of objects of various types, [...]; |
6452 | isRecordType() || |
6453 | // -- unions, which are classes capable of containing objects of different |
6454 | // types at different times; |
6455 | isUnionType() || |
6456 | // -- enumerations, which comprise a set of named constant values. [...]; |
6457 | isEnumeralType() || |
6458 | // -- pointers to non-static class members, [...]. |
6459 | isMemberPointerType(); |
6460 | } |
6461 | |
6462 | inline bool Type::isFunctionType() const { |
6463 | return isa<FunctionType>(CanonicalType); |
6464 | } |
6465 | |
6466 | inline bool Type::isPointerType() const { |
6467 | return isa<PointerType>(CanonicalType); |
6468 | } |
6469 | |
6470 | inline bool Type::isAnyPointerType() const { |
6471 | return isPointerType() || isObjCObjectPointerType(); |
6472 | } |
6473 | |
6474 | inline bool Type::isBlockPointerType() const { |
6475 | return isa<BlockPointerType>(CanonicalType); |
6476 | } |
6477 | |
6478 | inline bool Type::isReferenceType() const { |
6479 | return isa<ReferenceType>(CanonicalType); |
6480 | } |
6481 | |
6482 | inline bool Type::isLValueReferenceType() const { |
6483 | return isa<LValueReferenceType>(CanonicalType); |
6484 | } |
6485 | |
6486 | inline bool Type::isRValueReferenceType() const { |
6487 | return isa<RValueReferenceType>(CanonicalType); |
6488 | } |
6489 | |
6490 | inline bool Type::isObjectPointerType() const { |
6491 | // Note: an "object pointer type" is not the same thing as a pointer to an |
6492 | // object type; rather, it is a pointer to an object type or a pointer to cv |
6493 | // void. |
6494 | if (const auto *T = getAs<PointerType>()) |
6495 | return !T->getPointeeType()->isFunctionType(); |
6496 | else |
6497 | return false; |
6498 | } |
6499 | |
6500 | inline bool Type::isFunctionPointerType() const { |
6501 | if (const auto *T = getAs<PointerType>()) |
6502 | return T->getPointeeType()->isFunctionType(); |
6503 | else |
6504 | return false; |
6505 | } |
6506 | |
6507 | inline bool Type::isFunctionReferenceType() const { |
6508 | if (const auto *T = getAs<ReferenceType>()) |
6509 | return T->getPointeeType()->isFunctionType(); |
6510 | else |
6511 | return false; |
6512 | } |
6513 | |
6514 | inline bool Type::isMemberPointerType() const { |
6515 | return isa<MemberPointerType>(CanonicalType); |
6516 | } |
6517 | |
6518 | inline bool Type::isMemberFunctionPointerType() const { |
6519 | if (const auto *T = getAs<MemberPointerType>()) |
6520 | return T->isMemberFunctionPointer(); |
6521 | else |
6522 | return false; |
6523 | } |
6524 | |
6525 | inline bool Type::isMemberDataPointerType() const { |
6526 | if (const auto *T = getAs<MemberPointerType>()) |
6527 | return T->isMemberDataPointer(); |
6528 | else |
6529 | return false; |
6530 | } |
6531 | |
6532 | inline bool Type::isArrayType() const { |
6533 | return isa<ArrayType>(CanonicalType); |
6534 | } |
6535 | |
6536 | inline bool Type::isConstantArrayType() const { |
6537 | return isa<ConstantArrayType>(CanonicalType); |
6538 | } |
6539 | |
6540 | inline bool Type::isIncompleteArrayType() const { |
6541 | return isa<IncompleteArrayType>(CanonicalType); |
6542 | } |
6543 | |
6544 | inline bool Type::isVariableArrayType() const { |
6545 | return isa<VariableArrayType>(CanonicalType); |
6546 | } |
6547 | |
6548 | inline bool Type::isDependentSizedArrayType() const { |
6549 | return isa<DependentSizedArrayType>(CanonicalType); |
6550 | } |
6551 | |
6552 | inline bool Type::isBuiltinType() const { |
6553 | return isa<BuiltinType>(CanonicalType); |
6554 | } |
6555 | |
6556 | inline bool Type::isRecordType() const { |
6557 | return isa<RecordType>(CanonicalType); |
6558 | } |
6559 | |
6560 | inline bool Type::isEnumeralType() const { |
6561 | return isa<EnumType>(CanonicalType); |
6562 | } |
6563 | |
6564 | inline bool Type::isAnyComplexType() const { |
6565 | return isa<ComplexType>(CanonicalType); |
6566 | } |
6567 | |
6568 | inline bool Type::isVectorType() const { |
6569 | return isa<VectorType>(CanonicalType); |
6570 | } |
6571 | |
6572 | inline bool Type::isExtVectorType() const { |
6573 | return isa<ExtVectorType>(CanonicalType); |
6574 | } |
6575 | |
6576 | inline bool Type::isDependentAddressSpaceType() const { |
6577 | return isa<DependentAddressSpaceType>(CanonicalType); |
6578 | } |
6579 | |
6580 | inline bool Type::isObjCObjectPointerType() const { |
6581 | return isa<ObjCObjectPointerType>(CanonicalType); |
6582 | } |
6583 | |
6584 | inline bool Type::isObjCObjectType() const { |
6585 | return isa<ObjCObjectType>(CanonicalType); |
6586 | } |
6587 | |
6588 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6589 | return isa<ObjCInterfaceType>(CanonicalType) || |
6590 | isa<ObjCObjectType>(CanonicalType); |
6591 | } |
6592 | |
6593 | inline bool Type::isAtomicType() const { |
6594 | return isa<AtomicType>(CanonicalType); |
6595 | } |
6596 | |
6597 | inline bool Type::isUndeducedAutoType() const { |
6598 | return isa<AutoType>(CanonicalType); |
6599 | } |
6600 | |
6601 | inline bool Type::isObjCQualifiedIdType() const { |
6602 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6603 | return OPT->isObjCQualifiedIdType(); |
6604 | return false; |
6605 | } |
6606 | |
6607 | inline bool Type::isObjCQualifiedClassType() const { |
6608 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6609 | return OPT->isObjCQualifiedClassType(); |
6610 | return false; |
6611 | } |
6612 | |
6613 | inline bool Type::isObjCIdType() const { |
6614 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6615 | return OPT->isObjCIdType(); |
6616 | return false; |
6617 | } |
6618 | |
6619 | inline bool Type::isObjCClassType() const { |
6620 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6621 | return OPT->isObjCClassType(); |
6622 | return false; |
6623 | } |
6624 | |
6625 | inline bool Type::isObjCSelType() const { |
6626 | if (const auto *OPT = getAs<PointerType>()) |
6627 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6628 | return false; |
6629 | } |
6630 | |
6631 | inline bool Type::isObjCBuiltinType() const { |
6632 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6633 | } |
6634 | |
6635 | inline bool Type::isDecltypeType() const { |
6636 | return isa<DecltypeType>(this); |
6637 | } |
6638 | |
6639 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6640 | inline bool Type::is##Id##Type() const { \ |
6641 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6642 | } |
6643 | #include "clang/Basic/OpenCLImageTypes.def" |
6644 | |
6645 | inline bool Type::isSamplerT() const { |
6646 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6647 | } |
6648 | |
6649 | inline bool Type::isEventT() const { |
6650 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6651 | } |
6652 | |
6653 | inline bool Type::isClkEventT() const { |
6654 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6655 | } |
6656 | |
6657 | inline bool Type::isQueueT() const { |
6658 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6659 | } |
6660 | |
6661 | inline bool Type::isReserveIDT() const { |
6662 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6663 | } |
6664 | |
6665 | inline bool Type::isImageType() const { |
6666 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6667 | return |
6668 | #include "clang/Basic/OpenCLImageTypes.def" |
6669 | false; // end boolean or operation |
6670 | } |
6671 | |
6672 | inline bool Type::isPipeType() const { |
6673 | return isa<PipeType>(CanonicalType); |
6674 | } |
6675 | |
6676 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6677 | inline bool Type::is##Id##Type() const { \ |
6678 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6679 | } |
6680 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6681 | |
6682 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6683 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6684 | isOCLIntelSubgroupAVC##Id##Type() || |
6685 | return |
6686 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6687 | false; // end of boolean or operation |
6688 | } |
6689 | |
6690 | inline bool Type::isOCLExtOpaqueType() const { |
6691 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6692 | return |
6693 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6694 | false; // end of boolean or operation |
6695 | } |
6696 | |
6697 | inline bool Type::isOpenCLSpecificType() const { |
6698 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6699 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6700 | } |
6701 | |
6702 | inline bool Type::isTemplateTypeParmType() const { |
6703 | return isa<TemplateTypeParmType>(CanonicalType); |
6704 | } |
6705 | |
6706 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6707 | if (const BuiltinType *BT = getAs<BuiltinType>()) |
6708 | if (BT->getKind() == (BuiltinType::Kind) K) |
6709 | return true; |
6710 | return false; |
6711 | } |
6712 | |
6713 | inline bool Type::isPlaceholderType() const { |
6714 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6715 | return BT->isPlaceholderType(); |
6716 | return false; |
6717 | } |
6718 | |
6719 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6720 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6721 | if (BT->isPlaceholderType()) |
6722 | return BT; |
6723 | return nullptr; |
6724 | } |
6725 | |
6726 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6727 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ? static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 6727, __PRETTY_FUNCTION__)); |
6728 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6729 | return (BT->getKind() == (BuiltinType::Kind) K); |
6730 | return false; |
6731 | } |
6732 | |
6733 | inline bool Type::isNonOverloadPlaceholderType() const { |
6734 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6735 | return BT->isNonOverloadPlaceholderType(); |
6736 | return false; |
6737 | } |
6738 | |
6739 | inline bool Type::isVoidType() const { |
6740 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6741 | return BT->getKind() == BuiltinType::Void; |
6742 | return false; |
6743 | } |
6744 | |
6745 | inline bool Type::isHalfType() const { |
6746 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6747 | return BT->getKind() == BuiltinType::Half; |
6748 | // FIXME: Should we allow complex __fp16? Probably not. |
6749 | return false; |
6750 | } |
6751 | |
6752 | inline bool Type::isFloat16Type() const { |
6753 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6754 | return BT->getKind() == BuiltinType::Float16; |
6755 | return false; |
6756 | } |
6757 | |
6758 | inline bool Type::isFloat128Type() const { |
6759 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6760 | return BT->getKind() == BuiltinType::Float128; |
6761 | return false; |
6762 | } |
6763 | |
6764 | inline bool Type::isNullPtrType() const { |
6765 | if (const auto *BT = getAs<BuiltinType>()) |
6766 | return BT->getKind() == BuiltinType::NullPtr; |
6767 | return false; |
6768 | } |
6769 | |
6770 | bool IsEnumDeclComplete(EnumDecl *); |
6771 | bool IsEnumDeclScoped(EnumDecl *); |
6772 | |
6773 | inline bool Type::isIntegerType() const { |
6774 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6775 | return BT->getKind() >= BuiltinType::Bool && |
6776 | BT->getKind() <= BuiltinType::Int128; |
6777 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6778 | // Incomplete enum types are not treated as integer types. |
6779 | // FIXME: In C++, enum types are never integer types. |
6780 | return IsEnumDeclComplete(ET->getDecl()) && |
6781 | !IsEnumDeclScoped(ET->getDecl()); |
6782 | } |
6783 | return false; |
6784 | } |
6785 | |
6786 | inline bool Type::isFixedPointType() const { |
6787 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6788 | return BT->getKind() >= BuiltinType::ShortAccum && |
6789 | BT->getKind() <= BuiltinType::SatULongFract; |
6790 | } |
6791 | return false; |
6792 | } |
6793 | |
6794 | inline bool Type::isFixedPointOrIntegerType() const { |
6795 | return isFixedPointType() || isIntegerType(); |
6796 | } |
6797 | |
6798 | inline bool Type::isSaturatedFixedPointType() const { |
6799 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6800 | return BT->getKind() >= BuiltinType::SatShortAccum && |
6801 | BT->getKind() <= BuiltinType::SatULongFract; |
6802 | } |
6803 | return false; |
6804 | } |
6805 | |
6806 | inline bool Type::isUnsaturatedFixedPointType() const { |
6807 | return isFixedPointType() && !isSaturatedFixedPointType(); |
6808 | } |
6809 | |
6810 | inline bool Type::isSignedFixedPointType() const { |
6811 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6812 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
6813 | BT->getKind() <= BuiltinType::LongAccum) || |
6814 | (BT->getKind() >= BuiltinType::ShortFract && |
6815 | BT->getKind() <= BuiltinType::LongFract) || |
6816 | (BT->getKind() >= BuiltinType::SatShortAccum && |
6817 | BT->getKind() <= BuiltinType::SatLongAccum) || |
6818 | (BT->getKind() >= BuiltinType::SatShortFract && |
6819 | BT->getKind() <= BuiltinType::SatLongFract)); |
6820 | } |
6821 | return false; |
6822 | } |
6823 | |
6824 | inline bool Type::isUnsignedFixedPointType() const { |
6825 | return isFixedPointType() && !isSignedFixedPointType(); |
6826 | } |
6827 | |
6828 | inline bool Type::isScalarType() const { |
6829 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6830 | return BT->getKind() > BuiltinType::Void && |
6831 | BT->getKind() <= BuiltinType::NullPtr; |
6832 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
6833 | // Enums are scalar types, but only if they are defined. Incomplete enums |
6834 | // are not treated as scalar types. |
6835 | return IsEnumDeclComplete(ET->getDecl()); |
6836 | return isa<PointerType>(CanonicalType) || |
6837 | isa<BlockPointerType>(CanonicalType) || |
6838 | isa<MemberPointerType>(CanonicalType) || |
6839 | isa<ComplexType>(CanonicalType) || |
6840 | isa<ObjCObjectPointerType>(CanonicalType); |
6841 | } |
6842 | |
6843 | inline bool Type::isIntegralOrEnumerationType() const { |
6844 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6845 | return BT->getKind() >= BuiltinType::Bool && |
6846 | BT->getKind() <= BuiltinType::Int128; |
6847 | |
6848 | // Check for a complete enum type; incomplete enum types are not properly an |
6849 | // enumeration type in the sense required here. |
6850 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
6851 | return IsEnumDeclComplete(ET->getDecl()); |
6852 | |
6853 | return false; |
6854 | } |
6855 | |
6856 | inline bool Type::isBooleanType() const { |
6857 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6858 | return BT->getKind() == BuiltinType::Bool; |
6859 | return false; |
6860 | } |
6861 | |
6862 | inline bool Type::isUndeducedType() const { |
6863 | auto *DT = getContainedDeducedType(); |
6864 | return DT && !DT->isDeduced(); |
6865 | } |
6866 | |
6867 | /// Determines whether this is a type for which one can define |
6868 | /// an overloaded operator. |
6869 | inline bool Type::isOverloadableType() const { |
6870 | return isDependentType() || isRecordType() || isEnumeralType(); |
6871 | } |
6872 | |
6873 | /// Determines whether this type can decay to a pointer type. |
6874 | inline bool Type::canDecayToPointerType() const { |
6875 | return isFunctionType() || isArrayType(); |
6876 | } |
6877 | |
6878 | inline bool Type::hasPointerRepresentation() const { |
6879 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
6880 | isObjCObjectPointerType() || isNullPtrType()); |
6881 | } |
6882 | |
6883 | inline bool Type::hasObjCPointerRepresentation() const { |
6884 | return isObjCObjectPointerType(); |
6885 | } |
6886 | |
6887 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
6888 | const Type *type = this; |
6889 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
6890 | type = arrayType->getElementType().getTypePtr(); |
6891 | return type; |
6892 | } |
6893 | |
6894 | inline const Type *Type::getPointeeOrArrayElementType() const { |
6895 | const Type *type = this; |
6896 | if (type->isAnyPointerType()) |
6897 | return type->getPointeeType().getTypePtr(); |
6898 | else if (type->isArrayType()) |
6899 | return type->getBaseElementTypeUnsafe(); |
6900 | return type; |
6901 | } |
6902 | /// Insertion operator for diagnostics. This allows sending address spaces into |
6903 | /// a diagnostic with <<. |
6904 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6905 | LangAS AS) { |
6906 | DB.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), |
6907 | DiagnosticsEngine::ArgumentKind::ak_addrspace); |
6908 | return DB; |
6909 | } |
6910 | |
6911 | /// Insertion operator for partial diagnostics. This allows sending adress |
6912 | /// spaces into a diagnostic with <<. |
6913 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6914 | LangAS AS) { |
6915 | PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), |
6916 | DiagnosticsEngine::ArgumentKind::ak_addrspace); |
6917 | return PD; |
6918 | } |
6919 | |
6920 | /// Insertion operator for diagnostics. This allows sending Qualifiers into a |
6921 | /// diagnostic with <<. |
6922 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6923 | Qualifiers Q) { |
6924 | DB.AddTaggedVal(Q.getAsOpaqueValue(), |
6925 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6926 | return DB; |
6927 | } |
6928 | |
6929 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
6930 | /// into a diagnostic with <<. |
6931 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6932 | Qualifiers Q) { |
6933 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
6934 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6935 | return PD; |
6936 | } |
6937 | |
6938 | /// Insertion operator for diagnostics. This allows sending QualType's into a |
6939 | /// diagnostic with <<. |
6940 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6941 | QualType T) { |
6942 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6943 | DiagnosticsEngine::ak_qualtype); |
6944 | return DB; |
6945 | } |
6946 | |
6947 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
6948 | /// into a diagnostic with <<. |
6949 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6950 | QualType T) { |
6951 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6952 | DiagnosticsEngine::ak_qualtype); |
6953 | return PD; |
6954 | } |
6955 | |
6956 | // Helper class template that is used by Type::getAs to ensure that one does |
6957 | // not try to look through a qualified type to get to an array type. |
6958 | template <typename T> |
6959 | using TypeIsArrayType = |
6960 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
6961 | std::is_base_of<ArrayType, T>::value>; |
6962 | |
6963 | // Member-template getAs<specific type>'. |
6964 | template <typename T> const T *Type::getAs() const { |
6965 | static_assert(!TypeIsArrayType<T>::value, |
6966 | "ArrayType cannot be used with getAs!"); |
6967 | |
6968 | // If this is directly a T type, return it. |
6969 | if (const auto *Ty = dyn_cast<T>(this)) |
6970 | return Ty; |
6971 | |
6972 | // If the canonical form of this type isn't the right kind, reject it. |
6973 | if (!isa<T>(CanonicalType)) |
6974 | return nullptr; |
6975 | |
6976 | // If this is a typedef for the type, strip the typedef off without |
6977 | // losing all typedef information. |
6978 | return cast<T>(getUnqualifiedDesugaredType()); |
6979 | } |
6980 | |
6981 | template <typename T> const T *Type::getAsAdjusted() const { |
6982 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
6983 | |
6984 | // If this is directly a T type, return it. |
6985 | if (const auto *Ty = dyn_cast<T>(this)) |
6986 | return Ty; |
6987 | |
6988 | // If the canonical form of this type isn't the right kind, reject it. |
6989 | if (!isa<T>(CanonicalType)) |
6990 | return nullptr; |
6991 | |
6992 | // Strip off type adjustments that do not modify the underlying nature of the |
6993 | // type. |
6994 | const Type *Ty = this; |
6995 | while (Ty) { |
6996 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
6997 | Ty = A->getModifiedType().getTypePtr(); |
6998 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
6999 | Ty = E->desugar().getTypePtr(); |
7000 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
7001 | Ty = P->desugar().getTypePtr(); |
7002 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
7003 | Ty = A->desugar().getTypePtr(); |
7004 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
7005 | Ty = M->desugar().getTypePtr(); |
7006 | else |
7007 | break; |
7008 | } |
7009 | |
7010 | // Just because the canonical type is correct does not mean we can use cast<>, |
7011 | // since we may not have stripped off all the sugar down to the base type. |
7012 | return dyn_cast<T>(Ty); |
7013 | } |
7014 | |
7015 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
7016 | // If this is directly an array type, return it. |
7017 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
7018 | return arr; |
7019 | |
7020 | // If the canonical form of this type isn't the right kind, reject it. |
7021 | if (!isa<ArrayType>(CanonicalType)) |
7022 | return nullptr; |
7023 | |
7024 | // If this is a typedef for the type, strip the typedef off without |
7025 | // losing all typedef information. |
7026 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7027 | } |
7028 | |
7029 | template <typename T> const T *Type::castAs() const { |
7030 | static_assert(!TypeIsArrayType<T>::value, |
7031 | "ArrayType cannot be used with castAs!"); |
7032 | |
7033 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
7034 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 7034, __PRETTY_FUNCTION__)); |
7035 | return cast<T>(getUnqualifiedDesugaredType()); |
7036 | } |
7037 | |
7038 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
7039 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 7039, __PRETTY_FUNCTION__)); |
7040 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
7041 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
7042 | } |
7043 | |
7044 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
7045 | QualType CanonicalPtr) |
7046 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
7047 | #ifndef NDEBUG |
7048 | QualType Adjusted = getAdjustedType(); |
7049 | (void)AttributedType::stripOuterNullability(Adjusted); |
7050 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/Type.h" , 7050, __PRETTY_FUNCTION__)); |
7051 | #endif |
7052 | } |
7053 | |
7054 | QualType DecayedType::getPointeeType() const { |
7055 | QualType Decayed = getDecayedType(); |
7056 | (void)AttributedType::stripOuterNullability(Decayed); |
7057 | return cast<PointerType>(Decayed)->getPointeeType(); |
7058 | } |
7059 | |
7060 | // Get the decimal string representation of a fixed point type, represented |
7061 | // as a scaled integer. |
7062 | // TODO: At some point, we should change the arguments to instead just accept an |
7063 | // APFixedPoint instead of APSInt and scale. |
7064 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
7065 | unsigned Scale); |
7066 | |
7067 | } // namespace clang |
7068 | |
7069 | #endif // LLVM_CLANG_AST_TYPE_H |
1 | //===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===// |
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 defines the PointerUnion class, which is a discriminated union of |
10 | // pointer types. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_ADT_POINTERUNION_H |
15 | #define LLVM_ADT_POINTERUNION_H |
16 | |
17 | #include "llvm/ADT/DenseMapInfo.h" |
18 | #include "llvm/ADT/PointerIntPair.h" |
19 | #include "llvm/Support/PointerLikeTypeTraits.h" |
20 | #include <cassert> |
21 | #include <cstddef> |
22 | #include <cstdint> |
23 | |
24 | namespace llvm { |
25 | |
26 | template <typename T> struct PointerUnionTypeSelectorReturn { |
27 | using Return = T; |
28 | }; |
29 | |
30 | /// Get a type based on whether two types are the same or not. |
31 | /// |
32 | /// For: |
33 | /// |
34 | /// \code |
35 | /// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return; |
36 | /// \endcode |
37 | /// |
38 | /// Ret will be EQ type if T1 is same as T2 or NE type otherwise. |
39 | template <typename T1, typename T2, typename RET_EQ, typename RET_NE> |
40 | struct PointerUnionTypeSelector { |
41 | using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return; |
42 | }; |
43 | |
44 | template <typename T, typename RET_EQ, typename RET_NE> |
45 | struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> { |
46 | using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return; |
47 | }; |
48 | |
49 | template <typename T1, typename T2, typename RET_EQ, typename RET_NE> |
50 | struct PointerUnionTypeSelectorReturn< |
51 | PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> { |
52 | using Return = |
53 | typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return; |
54 | }; |
55 | |
56 | namespace pointer_union_detail { |
57 | /// Determine the number of bits required to store integers with values < n. |
58 | /// This is ceil(log2(n)). |
59 | constexpr int bitsRequired(unsigned n) { |
60 | return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0; |
61 | } |
62 | |
63 | template <typename... Ts> constexpr int lowBitsAvailable() { |
64 | return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...}); |
65 | } |
66 | |
67 | /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index |
68 | /// is the index of T in Us, or sizeof...(Us) if T does not appear in the |
69 | /// list. |
70 | template <typename T, typename ...Us> struct TypeIndex; |
71 | template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> { |
72 | static constexpr int Index = 0; |
73 | }; |
74 | template <typename T, typename U, typename... Us> |
75 | struct TypeIndex<T, U, Us...> { |
76 | static constexpr int Index = 1 + TypeIndex<T, Us...>::Index; |
77 | }; |
78 | template <typename T> struct TypeIndex<T> { |
79 | static constexpr int Index = 0; |
80 | }; |
81 | |
82 | /// Find the first type in a list of types. |
83 | template <typename T, typename...> struct GetFirstType { |
84 | using type = T; |
85 | }; |
86 | |
87 | /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion |
88 | /// for the template arguments. |
89 | template <typename ...PTs> class PointerUnionUIntTraits { |
90 | public: |
91 | static inline void *getAsVoidPointer(void *P) { return P; } |
92 | static inline void *getFromVoidPointer(void *P) { return P; } |
93 | static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>(); |
94 | }; |
95 | |
96 | /// Implement assignment in terms of construction. |
97 | template <typename Derived, typename T> struct AssignableFrom { |
98 | Derived &operator=(T t) { |
99 | return static_cast<Derived &>(*this) = Derived(t); |
100 | } |
101 | }; |
102 | |
103 | template <typename Derived, typename ValTy, int I, typename ...Types> |
104 | class PointerUnionMembers; |
105 | |
106 | template <typename Derived, typename ValTy, int I> |
107 | class PointerUnionMembers<Derived, ValTy, I> { |
108 | protected: |
109 | ValTy Val; |
110 | PointerUnionMembers() = default; |
111 | PointerUnionMembers(ValTy Val) : Val(Val) {} |
112 | |
113 | friend struct PointerLikeTypeTraits<Derived>; |
114 | }; |
115 | |
116 | template <typename Derived, typename ValTy, int I, typename Type, |
117 | typename ...Types> |
118 | class PointerUnionMembers<Derived, ValTy, I, Type, Types...> |
119 | : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> { |
120 | using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>; |
121 | public: |
122 | using Base::Base; |
123 | PointerUnionMembers() = default; |
124 | PointerUnionMembers(Type V) |
125 | : Base(ValTy(const_cast<void *>( |
126 | PointerLikeTypeTraits<Type>::getAsVoidPointer(V)), |
127 | I)) {} |
128 | |
129 | using Base::operator=; |
130 | Derived &operator=(Type V) { |
131 | this->Val = ValTy( |
132 | const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)), |
133 | I); |
134 | return static_cast<Derived &>(*this); |
135 | }; |
136 | }; |
137 | } |
138 | |
139 | /// A discriminated union of two or more pointer types, with the discriminator |
140 | /// in the low bit of the pointer. |
141 | /// |
142 | /// This implementation is extremely efficient in space due to leveraging the |
143 | /// low bits of the pointer, while exposing a natural and type-safe API. |
144 | /// |
145 | /// Common use patterns would be something like this: |
146 | /// PointerUnion<int*, float*> P; |
147 | /// P = (int*)0; |
148 | /// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0" |
149 | /// X = P.get<int*>(); // ok. |
150 | /// Y = P.get<float*>(); // runtime assertion failure. |
151 | /// Z = P.get<double*>(); // compile time failure. |
152 | /// P = (float*)0; |
153 | /// Y = P.get<float*>(); // ok. |
154 | /// X = P.get<int*>(); // runtime assertion failure. |
155 | template <typename... PTs> |
156 | class PointerUnion |
157 | : public pointer_union_detail::PointerUnionMembers< |
158 | PointerUnion<PTs...>, |
159 | PointerIntPair< |
160 | void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int, |
161 | pointer_union_detail::PointerUnionUIntTraits<PTs...>>, |
162 | 0, PTs...> { |
163 | // The first type is special because we want to directly cast a pointer to a |
164 | // default-initialized union to a pointer to the first type. But we don't |
165 | // want PointerUnion to be a 'template <typename First, typename ...Rest>' |
166 | // because it's much more convenient to have a name for the whole pack. So |
167 | // split off the first type here. |
168 | using First = typename pointer_union_detail::GetFirstType<PTs...>::type; |
169 | using Base = typename PointerUnion::PointerUnionMembers; |
170 | |
171 | public: |
172 | PointerUnion() = default; |
173 | |
174 | PointerUnion(std::nullptr_t) : PointerUnion() {} |
175 | using Base::Base; |
176 | |
177 | /// Test if the pointer held in the union is null, regardless of |
178 | /// which type it is. |
179 | bool isNull() const { return !this->Val.getPointer(); } |
180 | |
181 | explicit operator bool() const { return !isNull(); } |
182 | |
183 | /// Test if the Union currently holds the type matching T. |
184 | template <typename T> int is() const { |
185 | constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index; |
186 | static_assert(Index < sizeof...(PTs), |
187 | "PointerUnion::is<T> given type not in the union"); |
188 | return this->Val.getInt() == Index; |
189 | } |
190 | |
191 | /// Returns the value of the specified pointer type. |
192 | /// |
193 | /// If the specified pointer type is incorrect, assert. |
194 | template <typename T> T get() const { |
195 | assert(is<T>() && "Invalid accessor called")((is<T>() && "Invalid accessor called") ? static_cast <void> (0) : __assert_fail ("is<T>() && \"Invalid accessor called\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerUnion.h" , 195, __PRETTY_FUNCTION__)); |
196 | return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer()); |
197 | } |
198 | |
199 | /// Returns the current pointer if it is of the specified pointer type, |
200 | /// otherwises returns null. |
201 | template <typename T> T dyn_cast() const { |
202 | if (is<T>()) |
203 | return get<T>(); |
204 | return T(); |
205 | } |
206 | |
207 | /// If the union is set to the first pointer type get an address pointing to |
208 | /// it. |
209 | First const *getAddrOfPtr1() const { |
210 | return const_cast<PointerUnion *>(this)->getAddrOfPtr1(); |
211 | } |
212 | |
213 | /// If the union is set to the first pointer type get an address pointing to |
214 | /// it. |
215 | First *getAddrOfPtr1() { |
216 | assert(is<First>() && "Val is not the first pointer")((is<First>() && "Val is not the first pointer" ) ? static_cast<void> (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerUnion.h" , 216, __PRETTY_FUNCTION__)); |
217 | assert(((PointerLikeTypeTraits<First>::getAsVoidPointer(get< First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerUnion.h" , 220, __PRETTY_FUNCTION__)) |
218 | PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==((PointerLikeTypeTraits<First>::getAsVoidPointer(get< First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerUnion.h" , 220, __PRETTY_FUNCTION__)) |
219 | this->Val.getPointer() &&((PointerLikeTypeTraits<First>::getAsVoidPointer(get< First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerUnion.h" , 220, __PRETTY_FUNCTION__)) |
220 | "Can't get the address because PointerLikeTypeTraits changes the ptr")((PointerLikeTypeTraits<First>::getAsVoidPointer(get< First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr" ) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerUnion.h" , 220, __PRETTY_FUNCTION__)); |
221 | return const_cast<First *>( |
222 | reinterpret_cast<const First *>(this->Val.getAddrOfPointer())); |
223 | } |
224 | |
225 | /// Assignment from nullptr which just clears the union. |
226 | const PointerUnion &operator=(std::nullptr_t) { |
227 | this->Val.initWithPointer(nullptr); |
228 | return *this; |
229 | } |
230 | |
231 | /// Assignment from elements of the union. |
232 | using Base::operator=; |
233 | |
234 | void *getOpaqueValue() const { return this->Val.getOpaqueValue(); } |
235 | static inline PointerUnion getFromOpaqueValue(void *VP) { |
236 | PointerUnion V; |
237 | V.Val = decltype(V.Val)::getFromOpaqueValue(VP); |
238 | return V; |
239 | } |
240 | }; |
241 | |
242 | template <typename ...PTs> |
243 | bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) { |
244 | return lhs.getOpaqueValue() == rhs.getOpaqueValue(); |
245 | } |
246 | |
247 | template <typename ...PTs> |
248 | bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) { |
249 | return lhs.getOpaqueValue() != rhs.getOpaqueValue(); |
250 | } |
251 | |
252 | template <typename ...PTs> |
253 | bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) { |
254 | return lhs.getOpaqueValue() < rhs.getOpaqueValue(); |
255 | } |
256 | |
257 | // Teach SmallPtrSet that PointerUnion is "basically a pointer", that has |
258 | // # low bits available = min(PT1bits,PT2bits)-1. |
259 | template <typename ...PTs> |
260 | struct PointerLikeTypeTraits<PointerUnion<PTs...>> { |
261 | static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) { |
262 | return P.getOpaqueValue(); |
263 | } |
264 | |
265 | static inline PointerUnion<PTs...> getFromVoidPointer(void *P) { |
266 | return PointerUnion<PTs...>::getFromOpaqueValue(P); |
267 | } |
268 | |
269 | // The number of bits available are the min of the pointer types minus the |
270 | // bits needed for the discriminator. |
271 | static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype( |
272 | PointerUnion<PTs...>::Val)>::NumLowBitsAvailable; |
273 | }; |
274 | |
275 | /// A pointer union of three pointer types. See documentation for PointerUnion |
276 | /// for usage. |
277 | template <typename PT1, typename PT2, typename PT3> |
278 | using PointerUnion3 = PointerUnion<PT1, PT2, PT3>; |
279 | |
280 | /// A pointer union of four pointer types. See documentation for PointerUnion |
281 | /// for usage. |
282 | template <typename PT1, typename PT2, typename PT3, typename PT4> |
283 | using PointerUnion4 = PointerUnion<PT1, PT2, PT3, PT4>; |
284 | |
285 | // Teach DenseMap how to use PointerUnions as keys. |
286 | template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> { |
287 | using Union = PointerUnion<PTs...>; |
288 | using FirstInfo = |
289 | DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>; |
290 | |
291 | static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); } |
292 | |
293 | static inline Union getTombstoneKey() { |
294 | return Union(FirstInfo::getTombstoneKey()); |
295 | } |
296 | |
297 | static unsigned getHashValue(const Union &UnionVal) { |
298 | intptr_t key = (intptr_t)UnionVal.getOpaqueValue(); |
299 | return DenseMapInfo<intptr_t>::getHashValue(key); |
300 | } |
301 | |
302 | static bool isEqual(const Union &LHS, const Union &RHS) { |
303 | return LHS == RHS; |
304 | } |
305 | }; |
306 | |
307 | } // end namespace llvm |
308 | |
309 | #endif // LLVM_ADT_POINTERUNION_H |
1 | //===- llvm/ADT/PointerIntPair.h - Pair for pointer and int -----*- C++ -*-===// |
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 defines the PointerIntPair class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_ADT_POINTERINTPAIR_H |
14 | #define LLVM_ADT_POINTERINTPAIR_H |
15 | |
16 | #include "llvm/Support/Compiler.h" |
17 | #include "llvm/Support/PointerLikeTypeTraits.h" |
18 | #include "llvm/Support/type_traits.h" |
19 | #include <cassert> |
20 | #include <cstdint> |
21 | #include <limits> |
22 | |
23 | namespace llvm { |
24 | |
25 | template <typename T> struct DenseMapInfo; |
26 | template <typename PointerT, unsigned IntBits, typename PtrTraits> |
27 | struct PointerIntPairInfo; |
28 | |
29 | /// PointerIntPair - This class implements a pair of a pointer and small |
30 | /// integer. It is designed to represent this in the space required by one |
31 | /// pointer by bitmangling the integer into the low part of the pointer. This |
32 | /// can only be done for small integers: typically up to 3 bits, but it depends |
33 | /// on the number of bits available according to PointerLikeTypeTraits for the |
34 | /// type. |
35 | /// |
36 | /// Note that PointerIntPair always puts the IntVal part in the highest bits |
37 | /// possible. For example, PointerIntPair<void*, 1, bool> will put the bit for |
38 | /// the bool into bit #2, not bit #0, which allows the low two bits to be used |
39 | /// for something else. For example, this allows: |
40 | /// PointerIntPair<PointerIntPair<void*, 1, bool>, 1, bool> |
41 | /// ... and the two bools will land in different bits. |
42 | template <typename PointerTy, unsigned IntBits, typename IntType = unsigned, |
43 | typename PtrTraits = PointerLikeTypeTraits<PointerTy>, |
44 | typename Info = PointerIntPairInfo<PointerTy, IntBits, PtrTraits>> |
45 | class PointerIntPair { |
46 | // Used by MSVC visualizer and generally helpful for debugging/visualizing. |
47 | using InfoTy = Info; |
48 | intptr_t Value = 0; |
49 | |
50 | public: |
51 | constexpr PointerIntPair() = default; |
52 | |
53 | PointerIntPair(PointerTy PtrVal, IntType IntVal) { |
54 | setPointerAndInt(PtrVal, IntVal); |
55 | } |
56 | |
57 | explicit PointerIntPair(PointerTy PtrVal) { initWithPointer(PtrVal); } |
58 | |
59 | PointerTy getPointer() const { return Info::getPointer(Value); } |
60 | |
61 | IntType getInt() const { return (IntType)Info::getInt(Value); } |
62 | |
63 | void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& { |
64 | Value = Info::updatePointer(Value, PtrVal); |
65 | } |
66 | |
67 | void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION& { |
68 | Value = Info::updateInt(Value, static_cast<intptr_t>(IntVal)); |
69 | } |
70 | |
71 | void initWithPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION& { |
72 | Value = Info::updatePointer(0, PtrVal); |
73 | } |
74 | |
75 | void setPointerAndInt(PointerTy PtrVal, IntType IntVal) LLVM_LVALUE_FUNCTION& { |
76 | Value = Info::updateInt(Info::updatePointer(0, PtrVal), |
77 | static_cast<intptr_t>(IntVal)); |
78 | } |
79 | |
80 | PointerTy const *getAddrOfPointer() const { |
81 | return const_cast<PointerIntPair *>(this)->getAddrOfPointer(); |
82 | } |
83 | |
84 | PointerTy *getAddrOfPointer() { |
85 | assert(Value == reinterpret_cast<intptr_t>(getPointer()) &&((Value == reinterpret_cast<intptr_t>(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer" ) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerIntPair.h" , 87, __PRETTY_FUNCTION__)) |
86 | "Can only return the address if IntBits is cleared and "((Value == reinterpret_cast<intptr_t>(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer" ) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerIntPair.h" , 87, __PRETTY_FUNCTION__)) |
87 | "PtrTraits doesn't change the pointer")((Value == reinterpret_cast<intptr_t>(getPointer()) && "Can only return the address if IntBits is cleared and " "PtrTraits doesn't change the pointer" ) ? static_cast<void> (0) : __assert_fail ("Value == reinterpret_cast<intptr_t>(getPointer()) && \"Can only return the address if IntBits is cleared and \" \"PtrTraits doesn't change the pointer\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerIntPair.h" , 87, __PRETTY_FUNCTION__)); |
88 | return reinterpret_cast<PointerTy *>(&Value); |
89 | } |
90 | |
91 | void *getOpaqueValue() const { return reinterpret_cast<void *>(Value); } |
92 | |
93 | void setFromOpaqueValue(void *Val) LLVM_LVALUE_FUNCTION& { |
94 | Value = reinterpret_cast<intptr_t>(Val); |
95 | } |
96 | |
97 | static PointerIntPair getFromOpaqueValue(void *V) { |
98 | PointerIntPair P; |
99 | P.setFromOpaqueValue(V); |
100 | return P; |
101 | } |
102 | |
103 | // Allow PointerIntPairs to be created from const void * if and only if the |
104 | // pointer type could be created from a const void *. |
105 | static PointerIntPair getFromOpaqueValue(const void *V) { |
106 | (void)PtrTraits::getFromVoidPointer(V); |
107 | return getFromOpaqueValue(const_cast<void *>(V)); |
108 | } |
109 | |
110 | bool operator==(const PointerIntPair &RHS) const { |
111 | return Value == RHS.Value; |
112 | } |
113 | |
114 | bool operator!=(const PointerIntPair &RHS) const { |
115 | return Value != RHS.Value; |
116 | } |
117 | |
118 | bool operator<(const PointerIntPair &RHS) const { return Value < RHS.Value; } |
119 | bool operator>(const PointerIntPair &RHS) const { return Value > RHS.Value; } |
120 | |
121 | bool operator<=(const PointerIntPair &RHS) const { |
122 | return Value <= RHS.Value; |
123 | } |
124 | |
125 | bool operator>=(const PointerIntPair &RHS) const { |
126 | return Value >= RHS.Value; |
127 | } |
128 | }; |
129 | |
130 | // Specialize is_trivially_copyable to avoid limitation of llvm::is_trivially_copyable |
131 | // when compiled with gcc 4.9. |
132 | template <typename PointerTy, unsigned IntBits, typename IntType, |
133 | typename PtrTraits, |
134 | typename Info> |
135 | struct is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>> : std::true_type { |
136 | #ifdef HAVE_STD_IS_TRIVIALLY_COPYABLE |
137 | static_assert(std::is_trivially_copyable<PointerIntPair<PointerTy, IntBits, IntType, PtrTraits, Info>>::value, |
138 | "inconsistent behavior between llvm:: and std:: implementation of is_trivially_copyable"); |
139 | #endif |
140 | }; |
141 | |
142 | |
143 | template <typename PointerT, unsigned IntBits, typename PtrTraits> |
144 | struct PointerIntPairInfo { |
145 | static_assert(PtrTraits::NumLowBitsAvailable < |
146 | std::numeric_limits<uintptr_t>::digits, |
147 | "cannot use a pointer type that has all bits free"); |
148 | static_assert(IntBits <= PtrTraits::NumLowBitsAvailable, |
149 | "PointerIntPair with integer size too large for pointer"); |
150 | enum : uintptr_t { |
151 | /// PointerBitMask - The bits that come from the pointer. |
152 | PointerBitMask = |
153 | ~(uintptr_t)(((intptr_t)1 << PtrTraits::NumLowBitsAvailable) - 1), |
154 | |
155 | /// IntShift - The number of low bits that we reserve for other uses, and |
156 | /// keep zero. |
157 | IntShift = (uintptr_t)PtrTraits::NumLowBitsAvailable - IntBits, |
158 | |
159 | /// IntMask - This is the unshifted mask for valid bits of the int type. |
160 | IntMask = (uintptr_t)(((intptr_t)1 << IntBits) - 1), |
161 | |
162 | // ShiftedIntMask - This is the bits for the integer shifted in place. |
163 | ShiftedIntMask = (uintptr_t)(IntMask << IntShift) |
164 | }; |
165 | |
166 | static PointerT getPointer(intptr_t Value) { |
167 | return PtrTraits::getFromVoidPointer( |
168 | reinterpret_cast<void *>(Value & PointerBitMask)); |
169 | } |
170 | |
171 | static intptr_t getInt(intptr_t Value) { |
172 | return (Value >> IntShift) & IntMask; |
173 | } |
174 | |
175 | static intptr_t updatePointer(intptr_t OrigValue, PointerT Ptr) { |
176 | intptr_t PtrWord = |
177 | reinterpret_cast<intptr_t>(PtrTraits::getAsVoidPointer(Ptr)); |
178 | assert((PtrWord & ~PointerBitMask) == 0 &&(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned" ) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerIntPair.h" , 179, __PRETTY_FUNCTION__)) |
179 | "Pointer is not sufficiently aligned")(((PtrWord & ~PointerBitMask) == 0 && "Pointer is not sufficiently aligned" ) ? static_cast<void> (0) : __assert_fail ("(PtrWord & ~PointerBitMask) == 0 && \"Pointer is not sufficiently aligned\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerIntPair.h" , 179, __PRETTY_FUNCTION__)); |
180 | // Preserve all low bits, just update the pointer. |
181 | return PtrWord | (OrigValue & ~PointerBitMask); |
182 | } |
183 | |
184 | static intptr_t updateInt(intptr_t OrigValue, intptr_t Int) { |
185 | intptr_t IntWord = static_cast<intptr_t>(Int); |
186 | assert((IntWord & ~IntMask) == 0 && "Integer too large for field")(((IntWord & ~IntMask) == 0 && "Integer too large for field" ) ? static_cast<void> (0) : __assert_fail ("(IntWord & ~IntMask) == 0 && \"Integer too large for field\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/PointerIntPair.h" , 186, __PRETTY_FUNCTION__)); |
187 | |
188 | // Preserve all bits other than the ones we are updating. |
189 | return (OrigValue & ~ShiftedIntMask) | IntWord << IntShift; |
190 | } |
191 | }; |
192 | |
193 | // Provide specialization of DenseMapInfo for PointerIntPair. |
194 | template <typename PointerTy, unsigned IntBits, typename IntType> |
195 | struct DenseMapInfo<PointerIntPair<PointerTy, IntBits, IntType>> { |
196 | using Ty = PointerIntPair<PointerTy, IntBits, IntType>; |
197 | |
198 | static Ty getEmptyKey() { |
199 | uintptr_t Val = static_cast<uintptr_t>(-1); |
200 | Val <<= PointerLikeTypeTraits<Ty>::NumLowBitsAvailable; |
201 | return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val)); |
202 | } |
203 | |
204 | static Ty getTombstoneKey() { |
205 | uintptr_t Val = static_cast<uintptr_t>(-2); |
206 | Val <<= PointerLikeTypeTraits<PointerTy>::NumLowBitsAvailable; |
207 | return Ty::getFromOpaqueValue(reinterpret_cast<void *>(Val)); |
208 | } |
209 | |
210 | static unsigned getHashValue(Ty V) { |
211 | uintptr_t IV = reinterpret_cast<uintptr_t>(V.getOpaqueValue()); |
212 | return unsigned(IV) ^ unsigned(IV >> 9); |
213 | } |
214 | |
215 | static bool isEqual(const Ty &LHS, const Ty &RHS) { return LHS == RHS; } |
216 | }; |
217 | |
218 | // Teach SmallPtrSet that PointerIntPair is "basically a pointer". |
219 | template <typename PointerTy, unsigned IntBits, typename IntType, |
220 | typename PtrTraits> |
221 | struct PointerLikeTypeTraits< |
222 | PointerIntPair<PointerTy, IntBits, IntType, PtrTraits>> { |
223 | static inline void * |
224 | getAsVoidPointer(const PointerIntPair<PointerTy, IntBits, IntType> &P) { |
225 | return P.getOpaqueValue(); |
226 | } |
227 | |
228 | static inline PointerIntPair<PointerTy, IntBits, IntType> |
229 | getFromVoidPointer(void *P) { |
230 | return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P); |
231 | } |
232 | |
233 | static inline PointerIntPair<PointerTy, IntBits, IntType> |
234 | getFromVoidPointer(const void *P) { |
235 | return PointerIntPair<PointerTy, IntBits, IntType>::getFromOpaqueValue(P); |
236 | } |
237 | |
238 | enum { NumLowBitsAvailable = PtrTraits::NumLowBitsAvailable - IntBits }; |
239 | }; |
240 | |
241 | } // end namespace llvm |
242 | |
243 | #endif // LLVM_ADT_POINTERINTPAIR_H |
1 | //===- Overload.h - C++ Overloading -----------------------------*- C++ -*-===// |
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 defines the data structures and types used in C++ |
10 | // overload resolution. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_CLANG_SEMA_OVERLOAD_H |
15 | #define LLVM_CLANG_SEMA_OVERLOAD_H |
16 | |
17 | #include "clang/AST/Decl.h" |
18 | #include "clang/AST/DeclAccessPair.h" |
19 | #include "clang/AST/DeclBase.h" |
20 | #include "clang/AST/DeclCXX.h" |
21 | #include "clang/AST/DeclTemplate.h" |
22 | #include "clang/AST/Expr.h" |
23 | #include "clang/AST/Type.h" |
24 | #include "clang/Basic/LLVM.h" |
25 | #include "clang/Basic/SourceLocation.h" |
26 | #include "clang/Sema/SemaFixItUtils.h" |
27 | #include "clang/Sema/TemplateDeduction.h" |
28 | #include "llvm/ADT/ArrayRef.h" |
29 | #include "llvm/ADT/None.h" |
30 | #include "llvm/ADT/STLExtras.h" |
31 | #include "llvm/ADT/SmallPtrSet.h" |
32 | #include "llvm/ADT/SmallVector.h" |
33 | #include "llvm/ADT/StringRef.h" |
34 | #include "llvm/Support/AlignOf.h" |
35 | #include "llvm/Support/Allocator.h" |
36 | #include "llvm/Support/Casting.h" |
37 | #include "llvm/Support/ErrorHandling.h" |
38 | #include <cassert> |
39 | #include <cstddef> |
40 | #include <cstdint> |
41 | #include <utility> |
42 | |
43 | namespace clang { |
44 | |
45 | class APValue; |
46 | class ASTContext; |
47 | class Sema; |
48 | |
49 | /// OverloadingResult - Capture the result of performing overload |
50 | /// resolution. |
51 | enum OverloadingResult { |
52 | /// Overload resolution succeeded. |
53 | OR_Success, |
54 | |
55 | /// No viable function found. |
56 | OR_No_Viable_Function, |
57 | |
58 | /// Ambiguous candidates found. |
59 | OR_Ambiguous, |
60 | |
61 | /// Succeeded, but refers to a deleted function. |
62 | OR_Deleted |
63 | }; |
64 | |
65 | enum OverloadCandidateDisplayKind { |
66 | /// Requests that all candidates be shown. Viable candidates will |
67 | /// be printed first. |
68 | OCD_AllCandidates, |
69 | |
70 | /// Requests that only viable candidates be shown. |
71 | OCD_ViableCandidates, |
72 | |
73 | /// Requests that only tied-for-best candidates be shown. |
74 | OCD_AmbiguousCandidates |
75 | }; |
76 | |
77 | /// The parameter ordering that will be used for the candidate. This is |
78 | /// used to represent C++20 binary operator rewrites that reverse the order |
79 | /// of the arguments. If the parameter ordering is Reversed, the Args list is |
80 | /// reversed (but obviously the ParamDecls for the function are not). |
81 | /// |
82 | /// After forming an OverloadCandidate with reversed parameters, the list |
83 | /// of conversions will (as always) be indexed by argument, so will be |
84 | /// in reverse parameter order. |
85 | enum class OverloadCandidateParamOrder : char { Normal, Reversed }; |
86 | |
87 | /// The kinds of rewrite we perform on overload candidates. Note that the |
88 | /// values here are chosen to serve as both bitflags and as a rank (lower |
89 | /// values are preferred by overload resolution). |
90 | enum OverloadCandidateRewriteKind : unsigned { |
91 | /// Candidate is not a rewritten candidate. |
92 | CRK_None = 0x0, |
93 | |
94 | /// Candidate is a rewritten candidate with a different operator name. |
95 | CRK_DifferentOperator = 0x1, |
96 | |
97 | /// Candidate is a rewritten candidate with a reversed order of parameters. |
98 | CRK_Reversed = 0x2, |
99 | }; |
100 | |
101 | /// ImplicitConversionKind - The kind of implicit conversion used to |
102 | /// convert an argument to a parameter's type. The enumerator values |
103 | /// match with the table titled 'Conversions' in [over.ics.scs] and are listed |
104 | /// such that better conversion kinds have smaller values. |
105 | enum ImplicitConversionKind { |
106 | /// Identity conversion (no conversion) |
107 | ICK_Identity = 0, |
108 | |
109 | /// Lvalue-to-rvalue conversion (C++ [conv.lval]) |
110 | ICK_Lvalue_To_Rvalue, |
111 | |
112 | /// Array-to-pointer conversion (C++ [conv.array]) |
113 | ICK_Array_To_Pointer, |
114 | |
115 | /// Function-to-pointer (C++ [conv.array]) |
116 | ICK_Function_To_Pointer, |
117 | |
118 | /// Function pointer conversion (C++17 [conv.fctptr]) |
119 | ICK_Function_Conversion, |
120 | |
121 | /// Qualification conversions (C++ [conv.qual]) |
122 | ICK_Qualification, |
123 | |
124 | /// Integral promotions (C++ [conv.prom]) |
125 | ICK_Integral_Promotion, |
126 | |
127 | /// Floating point promotions (C++ [conv.fpprom]) |
128 | ICK_Floating_Promotion, |
129 | |
130 | /// Complex promotions (Clang extension) |
131 | ICK_Complex_Promotion, |
132 | |
133 | /// Integral conversions (C++ [conv.integral]) |
134 | ICK_Integral_Conversion, |
135 | |
136 | /// Floating point conversions (C++ [conv.double] |
137 | ICK_Floating_Conversion, |
138 | |
139 | /// Complex conversions (C99 6.3.1.6) |
140 | ICK_Complex_Conversion, |
141 | |
142 | /// Floating-integral conversions (C++ [conv.fpint]) |
143 | ICK_Floating_Integral, |
144 | |
145 | /// Pointer conversions (C++ [conv.ptr]) |
146 | ICK_Pointer_Conversion, |
147 | |
148 | /// Pointer-to-member conversions (C++ [conv.mem]) |
149 | ICK_Pointer_Member, |
150 | |
151 | /// Boolean conversions (C++ [conv.bool]) |
152 | ICK_Boolean_Conversion, |
153 | |
154 | /// Conversions between compatible types in C99 |
155 | ICK_Compatible_Conversion, |
156 | |
157 | /// Derived-to-base (C++ [over.best.ics]) |
158 | ICK_Derived_To_Base, |
159 | |
160 | /// Vector conversions |
161 | ICK_Vector_Conversion, |
162 | |
163 | /// A vector splat from an arithmetic type |
164 | ICK_Vector_Splat, |
165 | |
166 | /// Complex-real conversions (C99 6.3.1.7) |
167 | ICK_Complex_Real, |
168 | |
169 | /// Block Pointer conversions |
170 | ICK_Block_Pointer_Conversion, |
171 | |
172 | /// Transparent Union Conversions |
173 | ICK_TransparentUnionConversion, |
174 | |
175 | /// Objective-C ARC writeback conversion |
176 | ICK_Writeback_Conversion, |
177 | |
178 | /// Zero constant to event (OpenCL1.2 6.12.10) |
179 | ICK_Zero_Event_Conversion, |
180 | |
181 | /// Zero constant to queue |
182 | ICK_Zero_Queue_Conversion, |
183 | |
184 | /// Conversions allowed in C, but not C++ |
185 | ICK_C_Only_Conversion, |
186 | |
187 | /// C-only conversion between pointers with incompatible types |
188 | ICK_Incompatible_Pointer_Conversion, |
189 | |
190 | /// The number of conversion kinds |
191 | ICK_Num_Conversion_Kinds, |
192 | }; |
193 | |
194 | /// ImplicitConversionRank - The rank of an implicit conversion |
195 | /// kind. The enumerator values match with Table 9 of (C++ |
196 | /// 13.3.3.1.1) and are listed such that better conversion ranks |
197 | /// have smaller values. |
198 | enum ImplicitConversionRank { |
199 | /// Exact Match |
200 | ICR_Exact_Match = 0, |
201 | |
202 | /// Promotion |
203 | ICR_Promotion, |
204 | |
205 | /// Conversion |
206 | ICR_Conversion, |
207 | |
208 | /// OpenCL Scalar Widening |
209 | ICR_OCL_Scalar_Widening, |
210 | |
211 | /// Complex <-> Real conversion |
212 | ICR_Complex_Real_Conversion, |
213 | |
214 | /// ObjC ARC writeback conversion |
215 | ICR_Writeback_Conversion, |
216 | |
217 | /// Conversion only allowed in the C standard (e.g. void* to char*). |
218 | ICR_C_Conversion, |
219 | |
220 | /// Conversion not allowed by the C standard, but that we accept as an |
221 | /// extension anyway. |
222 | ICR_C_Conversion_Extension |
223 | }; |
224 | |
225 | ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind); |
226 | |
227 | /// NarrowingKind - The kind of narrowing conversion being performed by a |
228 | /// standard conversion sequence according to C++11 [dcl.init.list]p7. |
229 | enum NarrowingKind { |
230 | /// Not a narrowing conversion. |
231 | NK_Not_Narrowing, |
232 | |
233 | /// A narrowing conversion by virtue of the source and destination types. |
234 | NK_Type_Narrowing, |
235 | |
236 | /// A narrowing conversion, because a constant expression got narrowed. |
237 | NK_Constant_Narrowing, |
238 | |
239 | /// A narrowing conversion, because a non-constant-expression variable might |
240 | /// have got narrowed. |
241 | NK_Variable_Narrowing, |
242 | |
243 | /// Cannot tell whether this is a narrowing conversion because the |
244 | /// expression is value-dependent. |
245 | NK_Dependent_Narrowing, |
246 | }; |
247 | |
248 | /// StandardConversionSequence - represents a standard conversion |
249 | /// sequence (C++ 13.3.3.1.1). A standard conversion sequence |
250 | /// contains between zero and three conversions. If a particular |
251 | /// conversion is not needed, it will be set to the identity conversion |
252 | /// (ICK_Identity). Note that the three conversions are |
253 | /// specified as separate members (rather than in an array) so that |
254 | /// we can keep the size of a standard conversion sequence to a |
255 | /// single word. |
256 | class StandardConversionSequence { |
257 | public: |
258 | /// First -- The first conversion can be an lvalue-to-rvalue |
259 | /// conversion, array-to-pointer conversion, or |
260 | /// function-to-pointer conversion. |
261 | ImplicitConversionKind First : 8; |
262 | |
263 | /// Second - The second conversion can be an integral promotion, |
264 | /// floating point promotion, integral conversion, floating point |
265 | /// conversion, floating-integral conversion, pointer conversion, |
266 | /// pointer-to-member conversion, or boolean conversion. |
267 | ImplicitConversionKind Second : 8; |
268 | |
269 | /// Third - The third conversion can be a qualification conversion |
270 | /// or a function conversion. |
271 | ImplicitConversionKind Third : 8; |
272 | |
273 | /// Whether this is the deprecated conversion of a |
274 | /// string literal to a pointer to non-const character data |
275 | /// (C++ 4.2p2). |
276 | unsigned DeprecatedStringLiteralToCharPtr : 1; |
277 | |
278 | /// Whether the qualification conversion involves a change in the |
279 | /// Objective-C lifetime (for automatic reference counting). |
280 | unsigned QualificationIncludesObjCLifetime : 1; |
281 | |
282 | /// IncompatibleObjC - Whether this is an Objective-C conversion |
283 | /// that we should warn about (if we actually use it). |
284 | unsigned IncompatibleObjC : 1; |
285 | |
286 | /// ReferenceBinding - True when this is a reference binding |
287 | /// (C++ [over.ics.ref]). |
288 | unsigned ReferenceBinding : 1; |
289 | |
290 | /// DirectBinding - True when this is a reference binding that is a |
291 | /// direct binding (C++ [dcl.init.ref]). |
292 | unsigned DirectBinding : 1; |
293 | |
294 | /// Whether this is an lvalue reference binding (otherwise, it's |
295 | /// an rvalue reference binding). |
296 | unsigned IsLvalueReference : 1; |
297 | |
298 | /// Whether we're binding to a function lvalue. |
299 | unsigned BindsToFunctionLvalue : 1; |
300 | |
301 | /// Whether we're binding to an rvalue. |
302 | unsigned BindsToRvalue : 1; |
303 | |
304 | /// Whether this binds an implicit object argument to a |
305 | /// non-static member function without a ref-qualifier. |
306 | unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1; |
307 | |
308 | /// Whether this binds a reference to an object with a different |
309 | /// Objective-C lifetime qualifier. |
310 | unsigned ObjCLifetimeConversionBinding : 1; |
311 | |
312 | /// FromType - The type that this conversion is converting |
313 | /// from. This is an opaque pointer that can be translated into a |
314 | /// QualType. |
315 | void *FromTypePtr; |
316 | |
317 | /// ToType - The types that this conversion is converting to in |
318 | /// each step. This is an opaque pointer that can be translated |
319 | /// into a QualType. |
320 | void *ToTypePtrs[3]; |
321 | |
322 | /// CopyConstructor - The copy constructor that is used to perform |
323 | /// this conversion, when the conversion is actually just the |
324 | /// initialization of an object via copy constructor. Such |
325 | /// conversions are either identity conversions or derived-to-base |
326 | /// conversions. |
327 | CXXConstructorDecl *CopyConstructor; |
328 | DeclAccessPair FoundCopyConstructor; |
329 | |
330 | void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); } |
331 | |
332 | void setToType(unsigned Idx, QualType T) { |
333 | assert(Idx < 3 && "To type index is out of range")((Idx < 3 && "To type index is out of range") ? static_cast <void> (0) : __assert_fail ("Idx < 3 && \"To type index is out of range\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 333, __PRETTY_FUNCTION__)); |
334 | ToTypePtrs[Idx] = T.getAsOpaquePtr(); |
335 | } |
336 | |
337 | void setAllToTypes(QualType T) { |
338 | ToTypePtrs[0] = T.getAsOpaquePtr(); |
339 | ToTypePtrs[1] = ToTypePtrs[0]; |
340 | ToTypePtrs[2] = ToTypePtrs[0]; |
341 | } |
342 | |
343 | QualType getFromType() const { |
344 | return QualType::getFromOpaquePtr(FromTypePtr); |
345 | } |
346 | |
347 | QualType getToType(unsigned Idx) const { |
348 | assert(Idx < 3 && "To type index is out of range")((Idx < 3 && "To type index is out of range") ? static_cast <void> (0) : __assert_fail ("Idx < 3 && \"To type index is out of range\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 348, __PRETTY_FUNCTION__)); |
349 | return QualType::getFromOpaquePtr(ToTypePtrs[Idx]); |
350 | } |
351 | |
352 | void setAsIdentityConversion(); |
353 | |
354 | bool isIdentityConversion() const { |
355 | return Second == ICK_Identity && Third == ICK_Identity; |
356 | } |
357 | |
358 | ImplicitConversionRank getRank() const; |
359 | NarrowingKind |
360 | getNarrowingKind(ASTContext &Context, const Expr *Converted, |
361 | APValue &ConstantValue, QualType &ConstantType, |
362 | bool IgnoreFloatToIntegralConversion = false) const; |
363 | bool isPointerConversionToBool() const; |
364 | bool isPointerConversionToVoidPointer(ASTContext& Context) const; |
365 | void dump() const; |
366 | }; |
367 | |
368 | /// UserDefinedConversionSequence - Represents a user-defined |
369 | /// conversion sequence (C++ 13.3.3.1.2). |
370 | struct UserDefinedConversionSequence { |
371 | /// Represents the standard conversion that occurs before |
372 | /// the actual user-defined conversion. |
373 | /// |
374 | /// C++11 13.3.3.1.2p1: |
375 | /// If the user-defined conversion is specified by a constructor |
376 | /// (12.3.1), the initial standard conversion sequence converts |
377 | /// the source type to the type required by the argument of the |
378 | /// constructor. If the user-defined conversion is specified by |
379 | /// a conversion function (12.3.2), the initial standard |
380 | /// conversion sequence converts the source type to the implicit |
381 | /// object parameter of the conversion function. |
382 | StandardConversionSequence Before; |
383 | |
384 | /// EllipsisConversion - When this is true, it means user-defined |
385 | /// conversion sequence starts with a ... (ellipsis) conversion, instead of |
386 | /// a standard conversion. In this case, 'Before' field must be ignored. |
387 | // FIXME. I much rather put this as the first field. But there seems to be |
388 | // a gcc code gen. bug which causes a crash in a test. Putting it here seems |
389 | // to work around the crash. |
390 | bool EllipsisConversion : 1; |
391 | |
392 | /// HadMultipleCandidates - When this is true, it means that the |
393 | /// conversion function was resolved from an overloaded set having |
394 | /// size greater than 1. |
395 | bool HadMultipleCandidates : 1; |
396 | |
397 | /// After - Represents the standard conversion that occurs after |
398 | /// the actual user-defined conversion. |
399 | StandardConversionSequence After; |
400 | |
401 | /// ConversionFunction - The function that will perform the |
402 | /// user-defined conversion. Null if the conversion is an |
403 | /// aggregate initialization from an initializer list. |
404 | FunctionDecl* ConversionFunction; |
405 | |
406 | /// The declaration that we found via name lookup, which might be |
407 | /// the same as \c ConversionFunction or it might be a using declaration |
408 | /// that refers to \c ConversionFunction. |
409 | DeclAccessPair FoundConversionFunction; |
410 | |
411 | void dump() const; |
412 | }; |
413 | |
414 | /// Represents an ambiguous user-defined conversion sequence. |
415 | struct AmbiguousConversionSequence { |
416 | using ConversionSet = |
417 | SmallVector<std::pair<NamedDecl *, FunctionDecl *>, 4>; |
418 | |
419 | void *FromTypePtr; |
420 | void *ToTypePtr; |
421 | char Buffer[sizeof(ConversionSet)]; |
422 | |
423 | QualType getFromType() const { |
424 | return QualType::getFromOpaquePtr(FromTypePtr); |
425 | } |
426 | |
427 | QualType getToType() const { |
428 | return QualType::getFromOpaquePtr(ToTypePtr); |
429 | } |
430 | |
431 | void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); } |
432 | void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); } |
433 | |
434 | ConversionSet &conversions() { |
435 | return *reinterpret_cast<ConversionSet*>(Buffer); |
436 | } |
437 | |
438 | const ConversionSet &conversions() const { |
439 | return *reinterpret_cast<const ConversionSet*>(Buffer); |
440 | } |
441 | |
442 | void addConversion(NamedDecl *Found, FunctionDecl *D) { |
443 | conversions().push_back(std::make_pair(Found, D)); |
444 | } |
445 | |
446 | using iterator = ConversionSet::iterator; |
447 | |
448 | iterator begin() { return conversions().begin(); } |
449 | iterator end() { return conversions().end(); } |
450 | |
451 | using const_iterator = ConversionSet::const_iterator; |
452 | |
453 | const_iterator begin() const { return conversions().begin(); } |
454 | const_iterator end() const { return conversions().end(); } |
455 | |
456 | void construct(); |
457 | void destruct(); |
458 | void copyFrom(const AmbiguousConversionSequence &); |
459 | }; |
460 | |
461 | /// BadConversionSequence - Records information about an invalid |
462 | /// conversion sequence. |
463 | struct BadConversionSequence { |
464 | enum FailureKind { |
465 | no_conversion, |
466 | unrelated_class, |
467 | bad_qualifiers, |
468 | lvalue_ref_to_rvalue, |
469 | rvalue_ref_to_lvalue |
470 | }; |
471 | |
472 | // This can be null, e.g. for implicit object arguments. |
473 | Expr *FromExpr; |
474 | |
475 | FailureKind Kind; |
476 | |
477 | private: |
478 | // The type we're converting from (an opaque QualType). |
479 | void *FromTy; |
480 | |
481 | // The type we're converting to (an opaque QualType). |
482 | void *ToTy; |
483 | |
484 | public: |
485 | void init(FailureKind K, Expr *From, QualType To) { |
486 | init(K, From->getType(), To); |
487 | FromExpr = From; |
488 | } |
489 | |
490 | void init(FailureKind K, QualType From, QualType To) { |
491 | Kind = K; |
492 | FromExpr = nullptr; |
493 | setFromType(From); |
494 | setToType(To); |
495 | } |
496 | |
497 | QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); } |
498 | QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); } |
499 | |
500 | void setFromExpr(Expr *E) { |
501 | FromExpr = E; |
502 | setFromType(E->getType()); |
503 | } |
504 | |
505 | void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); } |
506 | void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); } |
507 | }; |
508 | |
509 | /// ImplicitConversionSequence - Represents an implicit conversion |
510 | /// sequence, which may be a standard conversion sequence |
511 | /// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2), |
512 | /// or an ellipsis conversion sequence (C++ 13.3.3.1.3). |
513 | class ImplicitConversionSequence { |
514 | public: |
515 | /// Kind - The kind of implicit conversion sequence. BadConversion |
516 | /// specifies that there is no conversion from the source type to |
517 | /// the target type. AmbiguousConversion represents the unique |
518 | /// ambiguous conversion (C++0x [over.best.ics]p10). |
519 | enum Kind { |
520 | StandardConversion = 0, |
521 | UserDefinedConversion, |
522 | AmbiguousConversion, |
523 | EllipsisConversion, |
524 | BadConversion |
525 | }; |
526 | |
527 | private: |
528 | enum { |
529 | Uninitialized = BadConversion + 1 |
530 | }; |
531 | |
532 | /// ConversionKind - The kind of implicit conversion sequence. |
533 | unsigned ConversionKind : 30; |
534 | |
535 | /// Whether the target is really a std::initializer_list, and the |
536 | /// sequence only represents the worst element conversion. |
537 | unsigned StdInitializerListElement : 1; |
538 | |
539 | void setKind(Kind K) { |
540 | destruct(); |
541 | ConversionKind = K; |
542 | } |
543 | |
544 | void destruct() { |
545 | if (ConversionKind == AmbiguousConversion) Ambiguous.destruct(); |
546 | } |
547 | |
548 | public: |
549 | union { |
550 | /// When ConversionKind == StandardConversion, provides the |
551 | /// details of the standard conversion sequence. |
552 | StandardConversionSequence Standard; |
553 | |
554 | /// When ConversionKind == UserDefinedConversion, provides the |
555 | /// details of the user-defined conversion sequence. |
556 | UserDefinedConversionSequence UserDefined; |
557 | |
558 | /// When ConversionKind == AmbiguousConversion, provides the |
559 | /// details of the ambiguous conversion. |
560 | AmbiguousConversionSequence Ambiguous; |
561 | |
562 | /// When ConversionKind == BadConversion, provides the details |
563 | /// of the bad conversion. |
564 | BadConversionSequence Bad; |
565 | }; |
566 | |
567 | ImplicitConversionSequence() |
568 | : ConversionKind(Uninitialized), StdInitializerListElement(false) { |
569 | Standard.setAsIdentityConversion(); |
570 | } |
571 | |
572 | ImplicitConversionSequence(const ImplicitConversionSequence &Other) |
573 | : ConversionKind(Other.ConversionKind), |
574 | StdInitializerListElement(Other.StdInitializerListElement) { |
575 | switch (ConversionKind) { |
576 | case Uninitialized: break; |
577 | case StandardConversion: Standard = Other.Standard; break; |
578 | case UserDefinedConversion: UserDefined = Other.UserDefined; break; |
579 | case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break; |
580 | case EllipsisConversion: break; |
581 | case BadConversion: Bad = Other.Bad; break; |
582 | } |
583 | } |
584 | |
585 | ImplicitConversionSequence & |
586 | operator=(const ImplicitConversionSequence &Other) { |
587 | destruct(); |
588 | new (this) ImplicitConversionSequence(Other); |
589 | return *this; |
590 | } |
591 | |
592 | ~ImplicitConversionSequence() { |
593 | destruct(); |
594 | } |
595 | |
596 | Kind getKind() const { |
597 | assert(isInitialized() && "querying uninitialized conversion")((isInitialized() && "querying uninitialized conversion" ) ? static_cast<void> (0) : __assert_fail ("isInitialized() && \"querying uninitialized conversion\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 597, __PRETTY_FUNCTION__)); |
598 | return Kind(ConversionKind); |
599 | } |
600 | |
601 | /// Return a ranking of the implicit conversion sequence |
602 | /// kind, where smaller ranks represent better conversion |
603 | /// sequences. |
604 | /// |
605 | /// In particular, this routine gives user-defined conversion |
606 | /// sequences and ambiguous conversion sequences the same rank, |
607 | /// per C++ [over.best.ics]p10. |
608 | unsigned getKindRank() const { |
609 | switch (getKind()) { |
610 | case StandardConversion: |
611 | return 0; |
612 | |
613 | case UserDefinedConversion: |
614 | case AmbiguousConversion: |
615 | return 1; |
616 | |
617 | case EllipsisConversion: |
618 | return 2; |
619 | |
620 | case BadConversion: |
621 | return 3; |
622 | } |
623 | |
624 | llvm_unreachable("Invalid ImplicitConversionSequence::Kind!")::llvm::llvm_unreachable_internal("Invalid ImplicitConversionSequence::Kind!" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 624); |
625 | } |
626 | |
627 | bool isBad() const { return getKind() == BadConversion; } |
628 | bool isStandard() const { return getKind() == StandardConversion; } |
629 | bool isEllipsis() const { return getKind() == EllipsisConversion; } |
630 | bool isAmbiguous() const { return getKind() == AmbiguousConversion; } |
631 | bool isUserDefined() const { return getKind() == UserDefinedConversion; } |
632 | bool isFailure() const { return isBad() || isAmbiguous(); } |
633 | |
634 | /// Determines whether this conversion sequence has been |
635 | /// initialized. Most operations should never need to query |
636 | /// uninitialized conversions and should assert as above. |
637 | bool isInitialized() const { return ConversionKind != Uninitialized; } |
638 | |
639 | /// Sets this sequence as a bad conversion for an explicit argument. |
640 | void setBad(BadConversionSequence::FailureKind Failure, |
641 | Expr *FromExpr, QualType ToType) { |
642 | setKind(BadConversion); |
643 | Bad.init(Failure, FromExpr, ToType); |
644 | } |
645 | |
646 | /// Sets this sequence as a bad conversion for an implicit argument. |
647 | void setBad(BadConversionSequence::FailureKind Failure, |
648 | QualType FromType, QualType ToType) { |
649 | setKind(BadConversion); |
650 | Bad.init(Failure, FromType, ToType); |
651 | } |
652 | |
653 | void setStandard() { setKind(StandardConversion); } |
654 | void setEllipsis() { setKind(EllipsisConversion); } |
655 | void setUserDefined() { setKind(UserDefinedConversion); } |
656 | |
657 | void setAmbiguous() { |
658 | if (ConversionKind == AmbiguousConversion) return; |
659 | ConversionKind = AmbiguousConversion; |
660 | Ambiguous.construct(); |
661 | } |
662 | |
663 | void setAsIdentityConversion(QualType T) { |
664 | setStandard(); |
665 | Standard.setAsIdentityConversion(); |
666 | Standard.setFromType(T); |
667 | Standard.setAllToTypes(T); |
668 | } |
669 | |
670 | /// Whether the target is really a std::initializer_list, and the |
671 | /// sequence only represents the worst element conversion. |
672 | bool isStdInitializerListElement() const { |
673 | return StdInitializerListElement; |
674 | } |
675 | |
676 | void setStdInitializerListElement(bool V = true) { |
677 | StdInitializerListElement = V; |
678 | } |
679 | |
680 | // The result of a comparison between implicit conversion |
681 | // sequences. Use Sema::CompareImplicitConversionSequences to |
682 | // actually perform the comparison. |
683 | enum CompareKind { |
684 | Better = -1, |
685 | Indistinguishable = 0, |
686 | Worse = 1 |
687 | }; |
688 | |
689 | void DiagnoseAmbiguousConversion(Sema &S, |
690 | SourceLocation CaretLoc, |
691 | const PartialDiagnostic &PDiag) const; |
692 | |
693 | void dump() const; |
694 | }; |
695 | |
696 | enum OverloadFailureKind { |
697 | ovl_fail_too_many_arguments, |
698 | ovl_fail_too_few_arguments, |
699 | ovl_fail_bad_conversion, |
700 | ovl_fail_bad_deduction, |
701 | |
702 | /// This conversion candidate was not considered because it |
703 | /// duplicates the work of a trivial or derived-to-base |
704 | /// conversion. |
705 | ovl_fail_trivial_conversion, |
706 | |
707 | /// This conversion candidate was not considered because it is |
708 | /// an illegal instantiation of a constructor temploid: it is |
709 | /// callable with one argument, we only have one argument, and |
710 | /// its first parameter type is exactly the type of the class. |
711 | /// |
712 | /// Defining such a constructor directly is illegal, and |
713 | /// template-argument deduction is supposed to ignore such |
714 | /// instantiations, but we can still get one with the right |
715 | /// kind of implicit instantiation. |
716 | ovl_fail_illegal_constructor, |
717 | |
718 | /// This conversion candidate is not viable because its result |
719 | /// type is not implicitly convertible to the desired type. |
720 | ovl_fail_bad_final_conversion, |
721 | |
722 | /// This conversion function template specialization candidate is not |
723 | /// viable because the final conversion was not an exact match. |
724 | ovl_fail_final_conversion_not_exact, |
725 | |
726 | /// (CUDA) This candidate was not viable because the callee |
727 | /// was not accessible from the caller's target (i.e. host->device, |
728 | /// global->host, device->host). |
729 | ovl_fail_bad_target, |
730 | |
731 | /// This candidate function was not viable because an enable_if |
732 | /// attribute disabled it. |
733 | ovl_fail_enable_if, |
734 | |
735 | /// This candidate constructor or conversion function is explicit but |
736 | /// the context doesn't permit explicit functions. |
737 | ovl_fail_explicit, |
738 | |
739 | /// This candidate was not viable because its address could not be taken. |
740 | ovl_fail_addr_not_available, |
741 | |
742 | /// This candidate was not viable because its OpenCL extension is disabled. |
743 | ovl_fail_ext_disabled, |
744 | |
745 | /// This inherited constructor is not viable because it would slice the |
746 | /// argument. |
747 | ovl_fail_inhctor_slice, |
748 | |
749 | /// This candidate was not viable because it is a non-default multiversioned |
750 | /// function. |
751 | ovl_non_default_multiversion_function, |
752 | |
753 | /// This constructor/conversion candidate fail due to an address space |
754 | /// mismatch between the object being constructed and the overload |
755 | /// candidate. |
756 | ovl_fail_object_addrspace_mismatch, |
757 | |
758 | /// This candidate was not viable because its associated constraints were |
759 | /// not satisfied. |
760 | ovl_fail_constraints_not_satisfied, |
761 | }; |
762 | |
763 | /// A list of implicit conversion sequences for the arguments of an |
764 | /// OverloadCandidate. |
765 | using ConversionSequenceList = |
766 | llvm::MutableArrayRef<ImplicitConversionSequence>; |
767 | |
768 | /// OverloadCandidate - A single candidate in an overload set (C++ 13.3). |
769 | struct OverloadCandidate { |
770 | /// Function - The actual function that this candidate |
771 | /// represents. When NULL, this is a built-in candidate |
772 | /// (C++ [over.oper]) or a surrogate for a conversion to a |
773 | /// function pointer or reference (C++ [over.call.object]). |
774 | FunctionDecl *Function; |
775 | |
776 | /// FoundDecl - The original declaration that was looked up / |
777 | /// invented / otherwise found, together with its access. |
778 | /// Might be a UsingShadowDecl or a FunctionTemplateDecl. |
779 | DeclAccessPair FoundDecl; |
780 | |
781 | /// BuiltinParamTypes - Provides the parameter types of a built-in overload |
782 | /// candidate. Only valid when Function is NULL. |
783 | QualType BuiltinParamTypes[3]; |
784 | |
785 | /// Surrogate - The conversion function for which this candidate |
786 | /// is a surrogate, but only if IsSurrogate is true. |
787 | CXXConversionDecl *Surrogate; |
788 | |
789 | /// The conversion sequences used to convert the function arguments |
790 | /// to the function parameters. Note that these are indexed by argument, |
791 | /// so may not match the parameter order of Function. |
792 | ConversionSequenceList Conversions; |
793 | |
794 | /// The FixIt hints which can be used to fix the Bad candidate. |
795 | ConversionFixItGenerator Fix; |
796 | |
797 | /// Viable - True to indicate that this overload candidate is viable. |
798 | bool Viable : 1; |
799 | |
800 | /// Whether this candidate is the best viable function, or tied for being |
801 | /// the best viable function. |
802 | /// |
803 | /// For an ambiguous overload resolution, indicates whether this candidate |
804 | /// was part of the ambiguity kernel: the minimal non-empty set of viable |
805 | /// candidates such that all elements of the ambiguity kernel are better |
806 | /// than all viable candidates not in the ambiguity kernel. |
807 | bool Best : 1; |
808 | |
809 | /// IsSurrogate - True to indicate that this candidate is a |
810 | /// surrogate for a conversion to a function pointer or reference |
811 | /// (C++ [over.call.object]). |
812 | bool IsSurrogate : 1; |
813 | |
814 | /// IgnoreObjectArgument - True to indicate that the first |
815 | /// argument's conversion, which for this function represents the |
816 | /// implicit object argument, should be ignored. This will be true |
817 | /// when the candidate is a static member function (where the |
818 | /// implicit object argument is just a placeholder) or a |
819 | /// non-static member function when the call doesn't have an |
820 | /// object argument. |
821 | bool IgnoreObjectArgument : 1; |
822 | |
823 | /// True if the candidate was found using ADL. |
824 | CallExpr::ADLCallKind IsADLCandidate : 1; |
825 | |
826 | /// Whether this is a rewritten candidate, and if so, of what kind? |
827 | unsigned RewriteKind : 2; |
828 | |
829 | /// FailureKind - The reason why this candidate is not viable. |
830 | /// Actually an OverloadFailureKind. |
831 | unsigned char FailureKind; |
832 | |
833 | /// The number of call arguments that were explicitly provided, |
834 | /// to be used while performing partial ordering of function templates. |
835 | unsigned ExplicitCallArguments; |
836 | |
837 | union { |
838 | DeductionFailureInfo DeductionFailure; |
839 | |
840 | /// FinalConversion - For a conversion function (where Function is |
841 | /// a CXXConversionDecl), the standard conversion that occurs |
842 | /// after the call to the overload candidate to convert the result |
843 | /// of calling the conversion function to the required type. |
844 | StandardConversionSequence FinalConversion; |
845 | }; |
846 | |
847 | /// Get RewriteKind value in OverloadCandidateRewriteKind type (This |
848 | /// function is to workaround the spurious GCC bitfield enum warning) |
849 | OverloadCandidateRewriteKind getRewriteKind() const { |
850 | return static_cast<OverloadCandidateRewriteKind>(RewriteKind); |
851 | } |
852 | |
853 | /// hasAmbiguousConversion - Returns whether this overload |
854 | /// candidate requires an ambiguous conversion or not. |
855 | bool hasAmbiguousConversion() const { |
856 | for (auto &C : Conversions) { |
857 | if (!C.isInitialized()) return false; |
858 | if (C.isAmbiguous()) return true; |
859 | } |
860 | return false; |
861 | } |
862 | |
863 | bool TryToFixBadConversion(unsigned Idx, Sema &S) { |
864 | bool CanFix = Fix.tryToFixConversion( |
865 | Conversions[Idx].Bad.FromExpr, |
866 | Conversions[Idx].Bad.getFromType(), |
867 | Conversions[Idx].Bad.getToType(), S); |
868 | |
869 | // If at least one conversion fails, the candidate cannot be fixed. |
870 | if (!CanFix) |
871 | Fix.clear(); |
872 | |
873 | return CanFix; |
874 | } |
875 | |
876 | unsigned getNumParams() const { |
877 | if (IsSurrogate) { |
878 | QualType STy = Surrogate->getConversionType(); |
879 | while (STy->isPointerType() || STy->isReferenceType()) |
880 | STy = STy->getPointeeType(); |
881 | return STy->castAs<FunctionProtoType>()->getNumParams(); |
882 | } |
883 | if (Function) |
884 | return Function->getNumParams(); |
885 | return ExplicitCallArguments; |
886 | } |
887 | |
888 | private: |
889 | friend class OverloadCandidateSet; |
890 | OverloadCandidate() |
891 | : IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {} |
892 | }; |
893 | |
894 | /// OverloadCandidateSet - A set of overload candidates, used in C++ |
895 | /// overload resolution (C++ 13.3). |
896 | class OverloadCandidateSet { |
897 | public: |
898 | enum CandidateSetKind { |
899 | /// Normal lookup. |
900 | CSK_Normal, |
901 | |
902 | /// C++ [over.match.oper]: |
903 | /// Lookup of operator function candidates in a call using operator |
904 | /// syntax. Candidates that have no parameters of class type will be |
905 | /// skipped unless there is a parameter of (reference to) enum type and |
906 | /// the corresponding argument is of the same enum type. |
907 | CSK_Operator, |
908 | |
909 | /// C++ [over.match.copy]: |
910 | /// Copy-initialization of an object of class type by user-defined |
911 | /// conversion. |
912 | CSK_InitByUserDefinedConversion, |
913 | |
914 | /// C++ [over.match.ctor], [over.match.list] |
915 | /// Initialization of an object of class type by constructor, |
916 | /// using either a parenthesized or braced list of arguments. |
917 | CSK_InitByConstructor, |
918 | }; |
919 | |
920 | /// Information about operator rewrites to consider when adding operator |
921 | /// functions to a candidate set. |
922 | struct OperatorRewriteInfo { |
923 | OperatorRewriteInfo() |
924 | : OriginalOperator(OO_None), AllowRewrittenCandidates(false) {} |
925 | OperatorRewriteInfo(OverloadedOperatorKind Op, bool AllowRewritten) |
926 | : OriginalOperator(Op), AllowRewrittenCandidates(AllowRewritten) {} |
927 | |
928 | /// The original operator as written in the source. |
929 | OverloadedOperatorKind OriginalOperator; |
930 | /// Whether we should include rewritten candidates in the overload set. |
931 | bool AllowRewrittenCandidates; |
932 | |
933 | /// Would use of this function result in a rewrite using a different |
934 | /// operator? |
935 | bool isRewrittenOperator(const FunctionDecl *FD) { |
936 | return OriginalOperator && |
937 | FD->getDeclName().getCXXOverloadedOperator() != OriginalOperator; |
938 | } |
939 | |
940 | bool isAcceptableCandidate(const FunctionDecl *FD) { |
941 | if (!OriginalOperator) |
942 | return true; |
943 | |
944 | // For an overloaded operator, we can have candidates with a different |
945 | // name in our unqualified lookup set. Make sure we only consider the |
946 | // ones we're supposed to. |
947 | OverloadedOperatorKind OO = |
948 | FD->getDeclName().getCXXOverloadedOperator(); |
949 | return OO && (OO == OriginalOperator || |
950 | (AllowRewrittenCandidates && |
951 | OO == getRewrittenOverloadedOperator(OriginalOperator))); |
952 | } |
953 | |
954 | /// Determine the kind of rewrite that should be performed for this |
955 | /// candidate. |
956 | OverloadCandidateRewriteKind |
957 | getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO) { |
958 | OverloadCandidateRewriteKind CRK = CRK_None; |
959 | if (isRewrittenOperator(FD)) |
960 | CRK = OverloadCandidateRewriteKind(CRK | CRK_DifferentOperator); |
961 | if (PO == OverloadCandidateParamOrder::Reversed) |
962 | CRK = OverloadCandidateRewriteKind(CRK | CRK_Reversed); |
963 | return CRK; |
964 | } |
965 | |
966 | /// Determine whether we should consider looking for and adding reversed |
967 | /// candidates for operator Op. |
968 | bool shouldAddReversed(OverloadedOperatorKind Op); |
969 | |
970 | /// Determine whether we should add a rewritten candidate for \p FD with |
971 | /// reversed parameter order. |
972 | bool shouldAddReversed(ASTContext &Ctx, const FunctionDecl *FD); |
973 | }; |
974 | |
975 | private: |
976 | SmallVector<OverloadCandidate, 16> Candidates; |
977 | llvm::SmallPtrSet<uintptr_t, 16> Functions; |
978 | |
979 | // Allocator for ConversionSequenceLists. We store the first few of these |
980 | // inline to avoid allocation for small sets. |
981 | llvm::BumpPtrAllocator SlabAllocator; |
982 | |
983 | SourceLocation Loc; |
984 | CandidateSetKind Kind; |
985 | OperatorRewriteInfo RewriteInfo; |
986 | |
987 | constexpr static unsigned NumInlineBytes = |
988 | 24 * sizeof(ImplicitConversionSequence); |
989 | unsigned NumInlineBytesUsed = 0; |
990 | alignas(void *) char InlineSpace[NumInlineBytes]; |
991 | |
992 | // Address space of the object being constructed. |
993 | LangAS DestAS = LangAS::Default; |
994 | |
995 | /// If we have space, allocates from inline storage. Otherwise, allocates |
996 | /// from the slab allocator. |
997 | /// FIXME: It would probably be nice to have a SmallBumpPtrAllocator |
998 | /// instead. |
999 | /// FIXME: Now that this only allocates ImplicitConversionSequences, do we |
1000 | /// want to un-generalize this? |
1001 | template <typename T> |
1002 | T *slabAllocate(unsigned N) { |
1003 | // It's simpler if this doesn't need to consider alignment. |
1004 | static_assert(alignof(T) == alignof(void *), |
1005 | "Only works for pointer-aligned types."); |
1006 | static_assert(std::is_trivial<T>::value || |
1007 | std::is_same<ImplicitConversionSequence, T>::value, |
1008 | "Add destruction logic to OverloadCandidateSet::clear()."); |
1009 | |
1010 | unsigned NBytes = sizeof(T) * N; |
1011 | if (NBytes > NumInlineBytes - NumInlineBytesUsed) |
1012 | return SlabAllocator.Allocate<T>(N); |
1013 | char *FreeSpaceStart = InlineSpace + NumInlineBytesUsed; |
1014 | assert(uintptr_t(FreeSpaceStart) % alignof(void *) == 0 &&((uintptr_t(FreeSpaceStart) % alignof(void *) == 0 && "Misaligned storage!") ? static_cast<void> (0) : __assert_fail ("uintptr_t(FreeSpaceStart) % alignof(void *) == 0 && \"Misaligned storage!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1015, __PRETTY_FUNCTION__)) |
1015 | "Misaligned storage!")((uintptr_t(FreeSpaceStart) % alignof(void *) == 0 && "Misaligned storage!") ? static_cast<void> (0) : __assert_fail ("uintptr_t(FreeSpaceStart) % alignof(void *) == 0 && \"Misaligned storage!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1015, __PRETTY_FUNCTION__)); |
1016 | |
1017 | NumInlineBytesUsed += NBytes; |
1018 | return reinterpret_cast<T *>(FreeSpaceStart); |
1019 | } |
1020 | |
1021 | void destroyCandidates(); |
1022 | |
1023 | public: |
1024 | OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK, |
1025 | OperatorRewriteInfo RewriteInfo = {}) |
1026 | : Loc(Loc), Kind(CSK), RewriteInfo(RewriteInfo) {} |
1027 | OverloadCandidateSet(const OverloadCandidateSet &) = delete; |
1028 | OverloadCandidateSet &operator=(const OverloadCandidateSet &) = delete; |
1029 | ~OverloadCandidateSet() { destroyCandidates(); } |
1030 | |
1031 | SourceLocation getLocation() const { return Loc; } |
1032 | CandidateSetKind getKind() const { return Kind; } |
1033 | OperatorRewriteInfo getRewriteInfo() const { return RewriteInfo; } |
1034 | |
1035 | /// Determine when this overload candidate will be new to the |
1036 | /// overload set. |
1037 | bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO = |
1038 | OverloadCandidateParamOrder::Normal) { |
1039 | uintptr_t Key = reinterpret_cast<uintptr_t>(F->getCanonicalDecl()); |
1040 | Key |= static_cast<uintptr_t>(PO); |
1041 | return Functions.insert(Key).second; |
1042 | } |
1043 | |
1044 | /// Exclude a function from being considered by overload resolution. |
1045 | void exclude(Decl *F) { |
1046 | isNewCandidate(F, OverloadCandidateParamOrder::Normal); |
1047 | isNewCandidate(F, OverloadCandidateParamOrder::Reversed); |
1048 | } |
1049 | |
1050 | /// Clear out all of the candidates. |
1051 | void clear(CandidateSetKind CSK); |
1052 | |
1053 | using iterator = SmallVectorImpl<OverloadCandidate>::iterator; |
1054 | |
1055 | iterator begin() { return Candidates.begin(); } |
1056 | iterator end() { return Candidates.end(); } |
1057 | |
1058 | size_t size() const { return Candidates.size(); } |
1059 | bool empty() const { return Candidates.empty(); } |
1060 | |
1061 | /// Allocate storage for conversion sequences for NumConversions |
1062 | /// conversions. |
1063 | ConversionSequenceList |
1064 | allocateConversionSequences(unsigned NumConversions) { |
1065 | ImplicitConversionSequence *Conversions = |
1066 | slabAllocate<ImplicitConversionSequence>(NumConversions); |
1067 | |
1068 | // Construct the new objects. |
1069 | for (unsigned I = 0; I != NumConversions; ++I) |
1070 | new (&Conversions[I]) ImplicitConversionSequence(); |
1071 | |
1072 | return ConversionSequenceList(Conversions, NumConversions); |
1073 | } |
1074 | |
1075 | /// Add a new candidate with NumConversions conversion sequence slots |
1076 | /// to the overload set. |
1077 | OverloadCandidate &addCandidate(unsigned NumConversions = 0, |
1078 | ConversionSequenceList Conversions = None) { |
1079 | assert((Conversions.empty() || Conversions.size() == NumConversions) &&(((Conversions.empty() || Conversions.size() == NumConversions ) && "preallocated conversion sequence has wrong length" ) ? static_cast<void> (0) : __assert_fail ("(Conversions.empty() || Conversions.size() == NumConversions) && \"preallocated conversion sequence has wrong length\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1080, __PRETTY_FUNCTION__)) |
1080 | "preallocated conversion sequence has wrong length")(((Conversions.empty() || Conversions.size() == NumConversions ) && "preallocated conversion sequence has wrong length" ) ? static_cast<void> (0) : __assert_fail ("(Conversions.empty() || Conversions.size() == NumConversions) && \"preallocated conversion sequence has wrong length\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1080, __PRETTY_FUNCTION__)); |
1081 | |
1082 | Candidates.push_back(OverloadCandidate()); |
1083 | OverloadCandidate &C = Candidates.back(); |
1084 | C.Conversions = Conversions.empty() |
1085 | ? allocateConversionSequences(NumConversions) |
1086 | : Conversions; |
1087 | return C; |
1088 | } |
1089 | |
1090 | /// Find the best viable function on this overload set, if it exists. |
1091 | OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, |
1092 | OverloadCandidateSet::iterator& Best); |
1093 | |
1094 | SmallVector<OverloadCandidate *, 32> CompleteCandidates( |
1095 | Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, |
1096 | SourceLocation OpLoc = SourceLocation(), |
1097 | llvm::function_ref<bool(OverloadCandidate &)> Filter = |
1098 | [](OverloadCandidate &) { return true; }); |
1099 | |
1100 | void NoteCandidates( |
1101 | PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, |
1102 | ArrayRef<Expr *> Args, StringRef Opc = "", |
1103 | SourceLocation Loc = SourceLocation(), |
1104 | llvm::function_ref<bool(OverloadCandidate &)> Filter = |
1105 | [](OverloadCandidate &) { return true; }); |
1106 | |
1107 | void NoteCandidates(Sema &S, ArrayRef<Expr *> Args, |
1108 | ArrayRef<OverloadCandidate *> Cands, |
1109 | StringRef Opc = "", |
1110 | SourceLocation OpLoc = SourceLocation()); |
1111 | |
1112 | LangAS getDestAS() { return DestAS; } |
1113 | |
1114 | void setDestAS(LangAS AS) { |
1115 | assert((Kind == CSK_InitByConstructor ||(((Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion ) && "can't set the destination address space when not constructing an " "object") ? static_cast<void> (0) : __assert_fail ("(Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion) && \"can't set the destination address space when not constructing an \" \"object\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1118, __PRETTY_FUNCTION__)) |
1116 | Kind == CSK_InitByUserDefinedConversion) &&(((Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion ) && "can't set the destination address space when not constructing an " "object") ? static_cast<void> (0) : __assert_fail ("(Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion) && \"can't set the destination address space when not constructing an \" \"object\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1118, __PRETTY_FUNCTION__)) |
1117 | "can't set the destination address space when not constructing an "(((Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion ) && "can't set the destination address space when not constructing an " "object") ? static_cast<void> (0) : __assert_fail ("(Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion) && \"can't set the destination address space when not constructing an \" \"object\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1118, __PRETTY_FUNCTION__)) |
1118 | "object")(((Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion ) && "can't set the destination address space when not constructing an " "object") ? static_cast<void> (0) : __assert_fail ("(Kind == CSK_InitByConstructor || Kind == CSK_InitByUserDefinedConversion) && \"can't set the destination address space when not constructing an \" \"object\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Overload.h" , 1118, __PRETTY_FUNCTION__)); |
1119 | DestAS = AS; |
1120 | } |
1121 | |
1122 | }; |
1123 | |
1124 | bool isBetterOverloadCandidate(Sema &S, |
1125 | const OverloadCandidate &Cand1, |
1126 | const OverloadCandidate &Cand2, |
1127 | SourceLocation Loc, |
1128 | OverloadCandidateSet::CandidateSetKind Kind); |
1129 | |
1130 | struct ConstructorInfo { |
1131 | DeclAccessPair FoundDecl; |
1132 | CXXConstructorDecl *Constructor; |
1133 | FunctionTemplateDecl *ConstructorTmpl; |
1134 | |
1135 | explicit operator bool() const { return Constructor; } |
1136 | }; |
1137 | |
1138 | // FIXME: Add an AddOverloadCandidate / AddTemplateOverloadCandidate overload |
1139 | // that takes one of these. |
1140 | inline ConstructorInfo getConstructorInfo(NamedDecl *ND) { |
1141 | if (isa<UsingDecl>(ND)) |
1142 | return ConstructorInfo{}; |
1143 | |
1144 | // For constructors, the access check is performed against the underlying |
1145 | // declaration, not the found declaration. |
1146 | auto *D = ND->getUnderlyingDecl(); |
1147 | ConstructorInfo Info = {DeclAccessPair::make(ND, D->getAccess()), nullptr, |
1148 | nullptr}; |
1149 | Info.ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D); |
1150 | if (Info.ConstructorTmpl) |
1151 | D = Info.ConstructorTmpl->getTemplatedDecl(); |
1152 | Info.Constructor = dyn_cast<CXXConstructorDecl>(D); |
1153 | return Info; |
1154 | } |
1155 | |
1156 | } // namespace clang |
1157 | |
1158 | #endif // LLVM_CLANG_SEMA_OVERLOAD_H |