File: | clang/lib/Sema/SemaCast.cpp |
Warning: | line 1349, column 14 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// | ||||
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 cast expressions, including | ||||
10 | // 1) C-style casts like '(int) x' | ||||
11 | // 2) C++ functional casts like 'int(x)' | ||||
12 | // 3) C++ named casts like 'static_cast<int>(x)' | ||||
13 | // | ||||
14 | //===----------------------------------------------------------------------===// | ||||
15 | |||||
16 | #include "clang/AST/ASTContext.h" | ||||
17 | #include "clang/AST/ASTStructuralEquivalence.h" | ||||
18 | #include "clang/AST/CXXInheritance.h" | ||||
19 | #include "clang/AST/ExprCXX.h" | ||||
20 | #include "clang/AST/ExprObjC.h" | ||||
21 | #include "clang/AST/RecordLayout.h" | ||||
22 | #include "clang/Basic/PartialDiagnostic.h" | ||||
23 | #include "clang/Basic/TargetInfo.h" | ||||
24 | #include "clang/Lex/Preprocessor.h" | ||||
25 | #include "clang/Sema/Initialization.h" | ||||
26 | #include "clang/Sema/SemaInternal.h" | ||||
27 | #include "llvm/ADT/SmallVector.h" | ||||
28 | #include <set> | ||||
29 | using namespace clang; | ||||
30 | |||||
31 | |||||
32 | |||||
33 | enum TryCastResult { | ||||
34 | TC_NotApplicable, ///< The cast method is not applicable. | ||||
35 | TC_Success, ///< The cast method is appropriate and successful. | ||||
36 | TC_Extension, ///< The cast method is appropriate and accepted as a | ||||
37 | ///< language extension. | ||||
38 | TC_Failed ///< The cast method is appropriate, but failed. A | ||||
39 | ///< diagnostic has been emitted. | ||||
40 | }; | ||||
41 | |||||
42 | static bool isValidCast(TryCastResult TCR) { | ||||
43 | return TCR == TC_Success || TCR == TC_Extension; | ||||
44 | } | ||||
45 | |||||
46 | enum CastType { | ||||
47 | CT_Const, ///< const_cast | ||||
48 | CT_Static, ///< static_cast | ||||
49 | CT_Reinterpret, ///< reinterpret_cast | ||||
50 | CT_Dynamic, ///< dynamic_cast | ||||
51 | CT_CStyle, ///< (Type)expr | ||||
52 | CT_Functional, ///< Type(expr) | ||||
53 | CT_Addrspace ///< addrspace_cast | ||||
54 | }; | ||||
55 | |||||
56 | namespace { | ||||
57 | struct CastOperation { | ||||
58 | CastOperation(Sema &S, QualType destType, ExprResult src) | ||||
59 | : Self(S), SrcExpr(src), DestType(destType), | ||||
60 | ResultType(destType.getNonLValueExprType(S.Context)), | ||||
61 | ValueKind(Expr::getValueKindForType(destType)), | ||||
62 | Kind(CK_Dependent), IsARCUnbridgedCast(false) { | ||||
63 | |||||
64 | if (const BuiltinType *placeholder = | ||||
65 | src.get()->getType()->getAsPlaceholderType()) { | ||||
66 | PlaceholderKind = placeholder->getKind(); | ||||
67 | } else { | ||||
68 | PlaceholderKind = (BuiltinType::Kind) 0; | ||||
69 | } | ||||
70 | } | ||||
71 | |||||
72 | Sema &Self; | ||||
73 | ExprResult SrcExpr; | ||||
74 | QualType DestType; | ||||
75 | QualType ResultType; | ||||
76 | ExprValueKind ValueKind; | ||||
77 | CastKind Kind; | ||||
78 | BuiltinType::Kind PlaceholderKind; | ||||
79 | CXXCastPath BasePath; | ||||
80 | bool IsARCUnbridgedCast; | ||||
81 | |||||
82 | SourceRange OpRange; | ||||
83 | SourceRange DestRange; | ||||
84 | |||||
85 | // Top-level semantics-checking routines. | ||||
86 | void CheckConstCast(); | ||||
87 | void CheckReinterpretCast(); | ||||
88 | void CheckStaticCast(); | ||||
89 | void CheckDynamicCast(); | ||||
90 | void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); | ||||
91 | void CheckCStyleCast(); | ||||
92 | void CheckBuiltinBitCast(); | ||||
93 | void CheckAddrspaceCast(); | ||||
94 | |||||
95 | void updatePartOfExplicitCastFlags(CastExpr *CE) { | ||||
96 | // Walk down from the CE to the OrigSrcExpr, and mark all immediate | ||||
97 | // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE | ||||
98 | // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched. | ||||
99 | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE) | ||||
100 | ICE->setIsPartOfExplicitCast(true); | ||||
101 | } | ||||
102 | |||||
103 | /// Complete an apparently-successful cast operation that yields | ||||
104 | /// the given expression. | ||||
105 | ExprResult complete(CastExpr *castExpr) { | ||||
106 | // If this is an unbridged cast, wrap the result in an implicit | ||||
107 | // cast that yields the unbridged-cast placeholder type. | ||||
108 | if (IsARCUnbridgedCast) { | ||||
109 | castExpr = ImplicitCastExpr::Create( | ||||
110 | Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent, | ||||
111 | castExpr, nullptr, castExpr->getValueKind(), | ||||
112 | Self.CurFPFeatureOverrides()); | ||||
113 | } | ||||
114 | updatePartOfExplicitCastFlags(castExpr); | ||||
115 | return castExpr; | ||||
116 | } | ||||
117 | |||||
118 | // Internal convenience methods. | ||||
119 | |||||
120 | /// Try to handle the given placeholder expression kind. Return | ||||
121 | /// true if the source expression has the appropriate placeholder | ||||
122 | /// kind. A placeholder can only be claimed once. | ||||
123 | bool claimPlaceholder(BuiltinType::Kind K) { | ||||
124 | if (PlaceholderKind != K) return false; | ||||
125 | |||||
126 | PlaceholderKind = (BuiltinType::Kind) 0; | ||||
127 | return true; | ||||
128 | } | ||||
129 | |||||
130 | bool isPlaceholder() const { | ||||
131 | return PlaceholderKind != 0; | ||||
132 | } | ||||
133 | bool isPlaceholder(BuiltinType::Kind K) const { | ||||
134 | return PlaceholderKind == K; | ||||
135 | } | ||||
136 | |||||
137 | // Language specific cast restrictions for address spaces. | ||||
138 | void checkAddressSpaceCast(QualType SrcType, QualType DestType); | ||||
139 | |||||
140 | void checkCastAlign() { | ||||
141 | Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); | ||||
142 | } | ||||
143 | |||||
144 | void checkObjCConversion(Sema::CheckedConversionKind CCK) { | ||||
145 | assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())((Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() ) ? static_cast<void> (0) : __assert_fail ("Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 145, __PRETTY_FUNCTION__)); | ||||
146 | |||||
147 | Expr *src = SrcExpr.get(); | ||||
148 | if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) == | ||||
149 | Sema::ACR_unbridged) | ||||
150 | IsARCUnbridgedCast = true; | ||||
151 | SrcExpr = src; | ||||
152 | } | ||||
153 | |||||
154 | /// Check for and handle non-overload placeholder expressions. | ||||
155 | void checkNonOverloadPlaceholders() { | ||||
156 | if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) | ||||
157 | return; | ||||
158 | |||||
159 | SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); | ||||
160 | if (SrcExpr.isInvalid()) | ||||
161 | return; | ||||
162 | PlaceholderKind = (BuiltinType::Kind) 0; | ||||
163 | } | ||||
164 | }; | ||||
165 | |||||
166 | void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType, | ||||
167 | SourceLocation OpLoc) { | ||||
168 | if (const auto *PtrType = dyn_cast<PointerType>(FromType)) { | ||||
169 | if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
170 | if (const auto *DestType = dyn_cast<PointerType>(ToType)) { | ||||
171 | if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) { | ||||
172 | S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer); | ||||
173 | } | ||||
174 | } | ||||
175 | } | ||||
176 | } | ||||
177 | } | ||||
178 | |||||
179 | struct CheckNoDerefRAII { | ||||
180 | CheckNoDerefRAII(CastOperation &Op) : Op(Op) {} | ||||
181 | ~CheckNoDerefRAII() { | ||||
182 | if (!Op.SrcExpr.isInvalid()) | ||||
183 | CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType, | ||||
184 | Op.OpRange.getBegin()); | ||||
185 | } | ||||
186 | |||||
187 | CastOperation &Op; | ||||
188 | }; | ||||
189 | } | ||||
190 | |||||
191 | static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, | ||||
192 | QualType DestType); | ||||
193 | |||||
194 | // The Try functions attempt a specific way of casting. If they succeed, they | ||||
195 | // return TC_Success. If their way of casting is not appropriate for the given | ||||
196 | // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic | ||||
197 | // to emit if no other way succeeds. If their way of casting is appropriate but | ||||
198 | // fails, they return TC_Failed and *must* set diag; they can set it to 0 if | ||||
199 | // they emit a specialized diagnostic. | ||||
200 | // All diagnostics returned by these functions must expect the same three | ||||
201 | // arguments: | ||||
202 | // %0: Cast Type (a value from the CastType enumeration) | ||||
203 | // %1: Source Type | ||||
204 | // %2: Destination Type | ||||
205 | static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, | ||||
206 | QualType DestType, bool CStyle, | ||||
207 | CastKind &Kind, | ||||
208 | CXXCastPath &BasePath, | ||||
209 | unsigned &msg); | ||||
210 | static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, | ||||
211 | QualType DestType, bool CStyle, | ||||
212 | SourceRange OpRange, | ||||
213 | unsigned &msg, | ||||
214 | CastKind &Kind, | ||||
215 | CXXCastPath &BasePath); | ||||
216 | static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, | ||||
217 | QualType DestType, bool CStyle, | ||||
218 | SourceRange OpRange, | ||||
219 | unsigned &msg, | ||||
220 | CastKind &Kind, | ||||
221 | CXXCastPath &BasePath); | ||||
222 | static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, | ||||
223 | CanQualType DestType, bool CStyle, | ||||
224 | SourceRange OpRange, | ||||
225 | QualType OrigSrcType, | ||||
226 | QualType OrigDestType, unsigned &msg, | ||||
227 | CastKind &Kind, | ||||
228 | CXXCastPath &BasePath); | ||||
229 | static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, | ||||
230 | QualType SrcType, | ||||
231 | QualType DestType,bool CStyle, | ||||
232 | SourceRange OpRange, | ||||
233 | unsigned &msg, | ||||
234 | CastKind &Kind, | ||||
235 | CXXCastPath &BasePath); | ||||
236 | |||||
237 | static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, | ||||
238 | QualType DestType, | ||||
239 | Sema::CheckedConversionKind CCK, | ||||
240 | SourceRange OpRange, | ||||
241 | unsigned &msg, CastKind &Kind, | ||||
242 | bool ListInitialization); | ||||
243 | static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, | ||||
244 | QualType DestType, | ||||
245 | Sema::CheckedConversionKind CCK, | ||||
246 | SourceRange OpRange, | ||||
247 | unsigned &msg, CastKind &Kind, | ||||
248 | CXXCastPath &BasePath, | ||||
249 | bool ListInitialization); | ||||
250 | static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, | ||||
251 | QualType DestType, bool CStyle, | ||||
252 | unsigned &msg); | ||||
253 | static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, | ||||
254 | QualType DestType, bool CStyle, | ||||
255 | SourceRange OpRange, unsigned &msg, | ||||
256 | CastKind &Kind); | ||||
257 | static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, | ||||
258 | QualType DestType, bool CStyle, | ||||
259 | unsigned &msg, CastKind &Kind); | ||||
260 | |||||
261 | /// ActOnCXXNamedCast - Parse | ||||
262 | /// {dynamic,static,reinterpret,const,addrspace}_cast's. | ||||
263 | ExprResult | ||||
264 | Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, | ||||
265 | SourceLocation LAngleBracketLoc, Declarator &D, | ||||
266 | SourceLocation RAngleBracketLoc, | ||||
267 | SourceLocation LParenLoc, Expr *E, | ||||
268 | SourceLocation RParenLoc) { | ||||
269 | |||||
270 | assert(!D.isInvalidType())((!D.isInvalidType()) ? static_cast<void> (0) : __assert_fail ("!D.isInvalidType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 270, __PRETTY_FUNCTION__)); | ||||
| |||||
271 | |||||
272 | TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); | ||||
273 | if (D.isInvalidType()) | ||||
274 | return ExprError(); | ||||
275 | |||||
276 | if (getLangOpts().CPlusPlus) { | ||||
277 | // Check that there are no default arguments (C++ only). | ||||
278 | CheckExtraCXXDefaultArguments(D); | ||||
279 | } | ||||
280 | |||||
281 | return BuildCXXNamedCast(OpLoc, Kind, TInfo, E, | ||||
282 | SourceRange(LAngleBracketLoc, RAngleBracketLoc), | ||||
283 | SourceRange(LParenLoc, RParenLoc)); | ||||
284 | } | ||||
285 | |||||
286 | ExprResult | ||||
287 | Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, | ||||
288 | TypeSourceInfo *DestTInfo, Expr *E, | ||||
289 | SourceRange AngleBrackets, SourceRange Parens) { | ||||
290 | ExprResult Ex = E; | ||||
291 | QualType DestType = DestTInfo->getType(); | ||||
292 | |||||
293 | // If the type is dependent, we won't do the semantic analysis now. | ||||
294 | bool TypeDependent = | ||||
295 | DestType->isDependentType() || Ex.get()->isTypeDependent(); | ||||
296 | |||||
297 | CastOperation Op(*this, DestType, E); | ||||
298 | Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); | ||||
299 | Op.DestRange = AngleBrackets; | ||||
300 | |||||
301 | switch (Kind) { | ||||
302 | default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 302); | ||||
303 | |||||
304 | case tok::kw_addrspace_cast: | ||||
305 | if (!TypeDependent) { | ||||
306 | Op.CheckAddrspaceCast(); | ||||
307 | if (Op.SrcExpr.isInvalid()) | ||||
308 | return ExprError(); | ||||
309 | } | ||||
310 | return Op.complete(CXXAddrspaceCastExpr::Create( | ||||
311 | Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), | ||||
312 | DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); | ||||
313 | |||||
314 | case tok::kw_const_cast: | ||||
315 | if (!TypeDependent) { | ||||
316 | Op.CheckConstCast(); | ||||
317 | if (Op.SrcExpr.isInvalid()) | ||||
318 | return ExprError(); | ||||
319 | DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); | ||||
320 | } | ||||
321 | return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, | ||||
322 | Op.ValueKind, Op.SrcExpr.get(), DestTInfo, | ||||
323 | OpLoc, Parens.getEnd(), | ||||
324 | AngleBrackets)); | ||||
325 | |||||
326 | case tok::kw_dynamic_cast: { | ||||
327 | // dynamic_cast is not supported in C++ for OpenCL. | ||||
328 | if (getLangOpts().OpenCLCPlusPlus) { | ||||
329 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) | ||||
330 | << "dynamic_cast"); | ||||
331 | } | ||||
332 | |||||
333 | if (!TypeDependent) { | ||||
334 | Op.CheckDynamicCast(); | ||||
335 | if (Op.SrcExpr.isInvalid()) | ||||
336 | return ExprError(); | ||||
337 | } | ||||
338 | return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, | ||||
339 | Op.ValueKind, Op.Kind, Op.SrcExpr.get(), | ||||
340 | &Op.BasePath, DestTInfo, | ||||
341 | OpLoc, Parens.getEnd(), | ||||
342 | AngleBrackets)); | ||||
343 | } | ||||
344 | case tok::kw_reinterpret_cast: { | ||||
345 | if (!TypeDependent) { | ||||
346 | Op.CheckReinterpretCast(); | ||||
347 | if (Op.SrcExpr.isInvalid()) | ||||
348 | return ExprError(); | ||||
349 | DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); | ||||
350 | } | ||||
351 | return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, | ||||
352 | Op.ValueKind, Op.Kind, Op.SrcExpr.get(), | ||||
353 | nullptr, DestTInfo, OpLoc, | ||||
354 | Parens.getEnd(), | ||||
355 | AngleBrackets)); | ||||
356 | } | ||||
357 | case tok::kw_static_cast: { | ||||
358 | if (!TypeDependent) { | ||||
359 | Op.CheckStaticCast(); | ||||
360 | if (Op.SrcExpr.isInvalid()) | ||||
361 | return ExprError(); | ||||
362 | DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); | ||||
363 | } | ||||
364 | |||||
365 | return Op.complete(CXXStaticCastExpr::Create( | ||||
366 | Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), | ||||
367 | &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc, | ||||
368 | Parens.getEnd(), AngleBrackets)); | ||||
369 | } | ||||
370 | } | ||||
371 | } | ||||
372 | |||||
373 | ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D, | ||||
374 | ExprResult Operand, | ||||
375 | SourceLocation RParenLoc) { | ||||
376 | assert(!D.isInvalidType())((!D.isInvalidType()) ? static_cast<void> (0) : __assert_fail ("!D.isInvalidType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 376, __PRETTY_FUNCTION__)); | ||||
377 | |||||
378 | TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType()); | ||||
379 | if (D.isInvalidType()) | ||||
380 | return ExprError(); | ||||
381 | |||||
382 | return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc); | ||||
383 | } | ||||
384 | |||||
385 | ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc, | ||||
386 | TypeSourceInfo *TSI, Expr *Operand, | ||||
387 | SourceLocation RParenLoc) { | ||||
388 | CastOperation Op(*this, TSI->getType(), Operand); | ||||
389 | Op.OpRange = SourceRange(KWLoc, RParenLoc); | ||||
390 | TypeLoc TL = TSI->getTypeLoc(); | ||||
391 | Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); | ||||
392 | |||||
393 | if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) { | ||||
394 | Op.CheckBuiltinBitCast(); | ||||
395 | if (Op.SrcExpr.isInvalid()) | ||||
396 | return ExprError(); | ||||
397 | } | ||||
398 | |||||
399 | BuiltinBitCastExpr *BCE = | ||||
400 | new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind, | ||||
401 | Op.SrcExpr.get(), TSI, KWLoc, RParenLoc); | ||||
402 | return Op.complete(BCE); | ||||
403 | } | ||||
404 | |||||
405 | /// Try to diagnose a failed overloaded cast. Returns true if | ||||
406 | /// diagnostics were emitted. | ||||
407 | static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, | ||||
408 | SourceRange range, Expr *src, | ||||
409 | QualType destType, | ||||
410 | bool listInitialization) { | ||||
411 | switch (CT) { | ||||
412 | // These cast kinds don't consider user-defined conversions. | ||||
413 | case CT_Const: | ||||
414 | case CT_Reinterpret: | ||||
415 | case CT_Dynamic: | ||||
416 | case CT_Addrspace: | ||||
417 | return false; | ||||
418 | |||||
419 | // These do. | ||||
420 | case CT_Static: | ||||
421 | case CT_CStyle: | ||||
422 | case CT_Functional: | ||||
423 | break; | ||||
424 | } | ||||
425 | |||||
426 | QualType srcType = src->getType(); | ||||
427 | if (!destType->isRecordType() && !srcType->isRecordType()) | ||||
428 | return false; | ||||
429 | |||||
430 | InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); | ||||
431 | InitializationKind initKind | ||||
432 | = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), | ||||
433 | range, listInitialization) | ||||
434 | : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, | ||||
435 | listInitialization) | ||||
436 | : InitializationKind::CreateCast(/*type range?*/ range); | ||||
437 | InitializationSequence sequence(S, entity, initKind, src); | ||||
438 | |||||
439 | assert(sequence.Failed() && "initialization succeeded on second try?")((sequence.Failed() && "initialization succeeded on second try?" ) ? static_cast<void> (0) : __assert_fail ("sequence.Failed() && \"initialization succeeded on second try?\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 439, __PRETTY_FUNCTION__)); | ||||
440 | switch (sequence.getFailureKind()) { | ||||
441 | default: return false; | ||||
442 | |||||
443 | case InitializationSequence::FK_ConstructorOverloadFailed: | ||||
444 | case InitializationSequence::FK_UserConversionOverloadFailed: | ||||
445 | break; | ||||
446 | } | ||||
447 | |||||
448 | OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); | ||||
449 | |||||
450 | unsigned msg = 0; | ||||
451 | OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; | ||||
452 | |||||
453 | switch (sequence.getFailedOverloadResult()) { | ||||
454 | case OR_Success: llvm_unreachable("successful failed overload")::llvm::llvm_unreachable_internal("successful failed overload" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 454); | ||||
455 | case OR_No_Viable_Function: | ||||
456 | if (candidates.empty()) | ||||
457 | msg = diag::err_ovl_no_conversion_in_cast; | ||||
458 | else | ||||
459 | msg = diag::err_ovl_no_viable_conversion_in_cast; | ||||
460 | howManyCandidates = OCD_AllCandidates; | ||||
461 | break; | ||||
462 | |||||
463 | case OR_Ambiguous: | ||||
464 | msg = diag::err_ovl_ambiguous_conversion_in_cast; | ||||
465 | howManyCandidates = OCD_AmbiguousCandidates; | ||||
466 | break; | ||||
467 | |||||
468 | case OR_Deleted: | ||||
469 | msg = diag::err_ovl_deleted_conversion_in_cast; | ||||
470 | howManyCandidates = OCD_ViableCandidates; | ||||
471 | break; | ||||
472 | } | ||||
473 | |||||
474 | candidates.NoteCandidates( | ||||
475 | PartialDiagnosticAt(range.getBegin(), | ||||
476 | S.PDiag(msg) << CT << srcType << destType << range | ||||
477 | << src->getSourceRange()), | ||||
478 | S, howManyCandidates, src); | ||||
479 | |||||
480 | return true; | ||||
481 | } | ||||
482 | |||||
483 | /// Diagnose a failed cast. | ||||
484 | static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, | ||||
485 | SourceRange opRange, Expr *src, QualType destType, | ||||
486 | bool listInitialization) { | ||||
487 | if (msg == diag::err_bad_cxx_cast_generic && | ||||
488 | tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, | ||||
489 | listInitialization)) | ||||
490 | return; | ||||
491 | |||||
492 | S.Diag(opRange.getBegin(), msg) << castType | ||||
493 | << src->getType() << destType << opRange << src->getSourceRange(); | ||||
494 | |||||
495 | // Detect if both types are (ptr to) class, and note any incompleteness. | ||||
496 | int DifferentPtrness = 0; | ||||
497 | QualType From = destType; | ||||
498 | if (auto Ptr = From->getAs<PointerType>()) { | ||||
499 | From = Ptr->getPointeeType(); | ||||
500 | DifferentPtrness++; | ||||
501 | } | ||||
502 | QualType To = src->getType(); | ||||
503 | if (auto Ptr = To->getAs<PointerType>()) { | ||||
504 | To = Ptr->getPointeeType(); | ||||
505 | DifferentPtrness--; | ||||
506 | } | ||||
507 | if (!DifferentPtrness) { | ||||
508 | auto RecFrom = From->getAs<RecordType>(); | ||||
509 | auto RecTo = To->getAs<RecordType>(); | ||||
510 | if (RecFrom && RecTo) { | ||||
511 | auto DeclFrom = RecFrom->getAsCXXRecordDecl(); | ||||
512 | if (!DeclFrom->isCompleteDefinition()) | ||||
513 | S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom; | ||||
514 | auto DeclTo = RecTo->getAsCXXRecordDecl(); | ||||
515 | if (!DeclTo->isCompleteDefinition()) | ||||
516 | S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo; | ||||
517 | } | ||||
518 | } | ||||
519 | } | ||||
520 | |||||
521 | namespace { | ||||
522 | /// The kind of unwrapping we did when determining whether a conversion casts | ||||
523 | /// away constness. | ||||
524 | enum CastAwayConstnessKind { | ||||
525 | /// The conversion does not cast away constness. | ||||
526 | CACK_None = 0, | ||||
527 | /// We unwrapped similar types. | ||||
528 | CACK_Similar = 1, | ||||
529 | /// We unwrapped dissimilar types with similar representations (eg, a pointer | ||||
530 | /// versus an Objective-C object pointer). | ||||
531 | CACK_SimilarKind = 2, | ||||
532 | /// We unwrapped representationally-unrelated types, such as a pointer versus | ||||
533 | /// a pointer-to-member. | ||||
534 | CACK_Incoherent = 3, | ||||
535 | }; | ||||
536 | } | ||||
537 | |||||
538 | /// Unwrap one level of types for CastsAwayConstness. | ||||
539 | /// | ||||
540 | /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from | ||||
541 | /// both types, provided that they're both pointer-like or array-like. Unlike | ||||
542 | /// the Sema function, doesn't care if the unwrapped pieces are related. | ||||
543 | /// | ||||
544 | /// This function may remove additional levels as necessary for correctness: | ||||
545 | /// the resulting T1 is unwrapped sufficiently that it is never an array type, | ||||
546 | /// so that its qualifiers can be directly compared to those of T2 (which will | ||||
547 | /// have the combined set of qualifiers from all indermediate levels of T2), | ||||
548 | /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers | ||||
549 | /// with those from T2. | ||||
550 | static CastAwayConstnessKind | ||||
551 | unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) { | ||||
552 | enum { None, Ptr, MemPtr, BlockPtr, Array }; | ||||
553 | auto Classify = [](QualType T) { | ||||
554 | if (T->isAnyPointerType()) return Ptr; | ||||
555 | if (T->isMemberPointerType()) return MemPtr; | ||||
556 | if (T->isBlockPointerType()) return BlockPtr; | ||||
557 | // We somewhat-arbitrarily don't look through VLA types here. This is at | ||||
558 | // least consistent with the behavior of UnwrapSimilarTypes. | ||||
559 | if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array; | ||||
560 | return None; | ||||
561 | }; | ||||
562 | |||||
563 | auto Unwrap = [&](QualType T) { | ||||
564 | if (auto *AT = Context.getAsArrayType(T)) | ||||
565 | return AT->getElementType(); | ||||
566 | return T->getPointeeType(); | ||||
567 | }; | ||||
568 | |||||
569 | CastAwayConstnessKind Kind; | ||||
570 | |||||
571 | if (T2->isReferenceType()) { | ||||
572 | // Special case: if the destination type is a reference type, unwrap it as | ||||
573 | // the first level. (The source will have been an lvalue expression in this | ||||
574 | // case, so there is no corresponding "reference to" in T1 to remove.) This | ||||
575 | // simulates removing a "pointer to" from both sides. | ||||
576 | T2 = T2->getPointeeType(); | ||||
577 | Kind = CastAwayConstnessKind::CACK_Similar; | ||||
578 | } else if (Context.UnwrapSimilarTypes(T1, T2)) { | ||||
579 | Kind = CastAwayConstnessKind::CACK_Similar; | ||||
580 | } else { | ||||
581 | // Try unwrapping mismatching levels. | ||||
582 | int T1Class = Classify(T1); | ||||
583 | if (T1Class == None) | ||||
584 | return CastAwayConstnessKind::CACK_None; | ||||
585 | |||||
586 | int T2Class = Classify(T2); | ||||
587 | if (T2Class == None) | ||||
588 | return CastAwayConstnessKind::CACK_None; | ||||
589 | |||||
590 | T1 = Unwrap(T1); | ||||
591 | T2 = Unwrap(T2); | ||||
592 | Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind | ||||
593 | : CastAwayConstnessKind::CACK_Incoherent; | ||||
594 | } | ||||
595 | |||||
596 | // We've unwrapped at least one level. If the resulting T1 is a (possibly | ||||
597 | // multidimensional) array type, any qualifier on any matching layer of | ||||
598 | // T2 is considered to correspond to T1. Decompose down to the element | ||||
599 | // type of T1 so that we can compare properly. | ||||
600 | while (true) { | ||||
601 | Context.UnwrapSimilarArrayTypes(T1, T2); | ||||
602 | |||||
603 | if (Classify(T1) != Array) | ||||
604 | break; | ||||
605 | |||||
606 | auto T2Class = Classify(T2); | ||||
607 | if (T2Class == None) | ||||
608 | break; | ||||
609 | |||||
610 | if (T2Class != Array) | ||||
611 | Kind = CastAwayConstnessKind::CACK_Incoherent; | ||||
612 | else if (Kind != CastAwayConstnessKind::CACK_Incoherent) | ||||
613 | Kind = CastAwayConstnessKind::CACK_SimilarKind; | ||||
614 | |||||
615 | T1 = Unwrap(T1); | ||||
616 | T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers()); | ||||
617 | } | ||||
618 | |||||
619 | return Kind; | ||||
620 | } | ||||
621 | |||||
622 | /// Check if the pointer conversion from SrcType to DestType casts away | ||||
623 | /// constness as defined in C++ [expr.const.cast]. This is used by the cast | ||||
624 | /// checkers. Both arguments must denote pointer (possibly to member) types. | ||||
625 | /// | ||||
626 | /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. | ||||
627 | /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. | ||||
628 | static CastAwayConstnessKind | ||||
629 | CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, | ||||
630 | bool CheckCVR, bool CheckObjCLifetime, | ||||
631 | QualType *TheOffendingSrcType = nullptr, | ||||
632 | QualType *TheOffendingDestType = nullptr, | ||||
633 | Qualifiers *CastAwayQualifiers = nullptr) { | ||||
634 | // If the only checking we care about is for Objective-C lifetime qualifiers, | ||||
635 | // and we're not in ObjC mode, there's nothing to check. | ||||
636 | if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC) | ||||
637 | return CastAwayConstnessKind::CACK_None; | ||||
638 | |||||
639 | if (!DestType->isReferenceType()) { | ||||
640 | assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||(((SrcType->isAnyPointerType() || SrcType->isMemberPointerType () || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member." ) ? static_cast<void> (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 642, __PRETTY_FUNCTION__)) | ||||
641 | SrcType->isBlockPointerType()) &&(((SrcType->isAnyPointerType() || SrcType->isMemberPointerType () || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member." ) ? static_cast<void> (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 642, __PRETTY_FUNCTION__)) | ||||
642 | "Source type is not pointer or pointer to member.")(((SrcType->isAnyPointerType() || SrcType->isMemberPointerType () || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member." ) ? static_cast<void> (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 642, __PRETTY_FUNCTION__)); | ||||
643 | assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||(((DestType->isAnyPointerType() || DestType->isMemberPointerType () || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member." ) ? static_cast<void> (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 645, __PRETTY_FUNCTION__)) | ||||
644 | DestType->isBlockPointerType()) &&(((DestType->isAnyPointerType() || DestType->isMemberPointerType () || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member." ) ? static_cast<void> (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 645, __PRETTY_FUNCTION__)) | ||||
645 | "Destination type is not pointer or pointer to member.")(((DestType->isAnyPointerType() || DestType->isMemberPointerType () || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member." ) ? static_cast<void> (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 645, __PRETTY_FUNCTION__)); | ||||
646 | } | ||||
647 | |||||
648 | QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), | ||||
649 | UnwrappedDestType = Self.Context.getCanonicalType(DestType); | ||||
650 | |||||
651 | // Find the qualifiers. We only care about cvr-qualifiers for the | ||||
652 | // purpose of this check, because other qualifiers (address spaces, | ||||
653 | // Objective-C GC, etc.) are part of the type's identity. | ||||
654 | QualType PrevUnwrappedSrcType = UnwrappedSrcType; | ||||
655 | QualType PrevUnwrappedDestType = UnwrappedDestType; | ||||
656 | auto WorstKind = CastAwayConstnessKind::CACK_Similar; | ||||
657 | bool AllConstSoFar = true; | ||||
658 | while (auto Kind = unwrapCastAwayConstnessLevel( | ||||
659 | Self.Context, UnwrappedSrcType, UnwrappedDestType)) { | ||||
660 | // Track the worst kind of unwrap we needed to do before we found a | ||||
661 | // problem. | ||||
662 | if (Kind > WorstKind) | ||||
663 | WorstKind = Kind; | ||||
664 | |||||
665 | // Determine the relevant qualifiers at this level. | ||||
666 | Qualifiers SrcQuals, DestQuals; | ||||
667 | Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); | ||||
668 | Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); | ||||
669 | |||||
670 | // We do not meaningfully track object const-ness of Objective-C object | ||||
671 | // types. Remove const from the source type if either the source or | ||||
672 | // the destination is an Objective-C object type. | ||||
673 | if (UnwrappedSrcType->isObjCObjectType() || | ||||
674 | UnwrappedDestType->isObjCObjectType()) | ||||
675 | SrcQuals.removeConst(); | ||||
676 | |||||
677 | if (CheckCVR) { | ||||
678 | Qualifiers SrcCvrQuals = | ||||
679 | Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()); | ||||
680 | Qualifiers DestCvrQuals = | ||||
681 | Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()); | ||||
682 | |||||
683 | if (SrcCvrQuals != DestCvrQuals) { | ||||
684 | if (CastAwayQualifiers) | ||||
685 | *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals; | ||||
686 | |||||
687 | // If we removed a cvr-qualifier, this is casting away 'constness'. | ||||
688 | if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) { | ||||
689 | if (TheOffendingSrcType) | ||||
690 | *TheOffendingSrcType = PrevUnwrappedSrcType; | ||||
691 | if (TheOffendingDestType) | ||||
692 | *TheOffendingDestType = PrevUnwrappedDestType; | ||||
693 | return WorstKind; | ||||
694 | } | ||||
695 | |||||
696 | // If any prior level was not 'const', this is also casting away | ||||
697 | // 'constness'. We noted the outermost type missing a 'const' already. | ||||
698 | if (!AllConstSoFar) | ||||
699 | return WorstKind; | ||||
700 | } | ||||
701 | } | ||||
702 | |||||
703 | if (CheckObjCLifetime && | ||||
704 | !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) | ||||
705 | return WorstKind; | ||||
706 | |||||
707 | // If we found our first non-const-qualified type, this may be the place | ||||
708 | // where things start to go wrong. | ||||
709 | if (AllConstSoFar && !DestQuals.hasConst()) { | ||||
710 | AllConstSoFar = false; | ||||
711 | if (TheOffendingSrcType) | ||||
712 | *TheOffendingSrcType = PrevUnwrappedSrcType; | ||||
713 | if (TheOffendingDestType) | ||||
714 | *TheOffendingDestType = PrevUnwrappedDestType; | ||||
715 | } | ||||
716 | |||||
717 | PrevUnwrappedSrcType = UnwrappedSrcType; | ||||
718 | PrevUnwrappedDestType = UnwrappedDestType; | ||||
719 | } | ||||
720 | |||||
721 | return CastAwayConstnessKind::CACK_None; | ||||
722 | } | ||||
723 | |||||
724 | static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK, | ||||
725 | unsigned &DiagID) { | ||||
726 | switch (CACK) { | ||||
727 | case CastAwayConstnessKind::CACK_None: | ||||
728 | llvm_unreachable("did not cast away constness")::llvm::llvm_unreachable_internal("did not cast away constness" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 728); | ||||
729 | |||||
730 | case CastAwayConstnessKind::CACK_Similar: | ||||
731 | // FIXME: Accept these as an extension too? | ||||
732 | case CastAwayConstnessKind::CACK_SimilarKind: | ||||
733 | DiagID = diag::err_bad_cxx_cast_qualifiers_away; | ||||
734 | return TC_Failed; | ||||
735 | |||||
736 | case CastAwayConstnessKind::CACK_Incoherent: | ||||
737 | DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent; | ||||
738 | return TC_Extension; | ||||
739 | } | ||||
740 | |||||
741 | llvm_unreachable("unexpected cast away constness kind")::llvm::llvm_unreachable_internal("unexpected cast away constness kind" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 741); | ||||
742 | } | ||||
743 | |||||
744 | /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. | ||||
745 | /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- | ||||
746 | /// checked downcasts in class hierarchies. | ||||
747 | void CastOperation::CheckDynamicCast() { | ||||
748 | CheckNoDerefRAII NoderefCheck(*this); | ||||
749 | |||||
750 | if (ValueKind == VK_RValue) | ||||
751 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); | ||||
752 | else if (isPlaceholder()) | ||||
753 | SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); | ||||
754 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error | ||||
755 | return; | ||||
756 | |||||
757 | QualType OrigSrcType = SrcExpr.get()->getType(); | ||||
758 | QualType DestType = Self.Context.getCanonicalType(this->DestType); | ||||
759 | |||||
760 | // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, | ||||
761 | // or "pointer to cv void". | ||||
762 | |||||
763 | QualType DestPointee; | ||||
764 | const PointerType *DestPointer = DestType->getAs<PointerType>(); | ||||
765 | const ReferenceType *DestReference = nullptr; | ||||
766 | if (DestPointer) { | ||||
767 | DestPointee = DestPointer->getPointeeType(); | ||||
768 | } else if ((DestReference = DestType->getAs<ReferenceType>())) { | ||||
769 | DestPointee = DestReference->getPointeeType(); | ||||
770 | } else { | ||||
771 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) | ||||
772 | << this->DestType << DestRange; | ||||
773 | SrcExpr = ExprError(); | ||||
774 | return; | ||||
775 | } | ||||
776 | |||||
777 | const RecordType *DestRecord = DestPointee->getAs<RecordType>(); | ||||
778 | if (DestPointee->isVoidType()) { | ||||
779 | assert(DestPointer && "Reference to void is not possible")((DestPointer && "Reference to void is not possible") ? static_cast<void> (0) : __assert_fail ("DestPointer && \"Reference to void is not possible\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 779, __PRETTY_FUNCTION__)); | ||||
780 | } else if (DestRecord) { | ||||
781 | if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, | ||||
782 | diag::err_bad_cast_incomplete, | ||||
783 | DestRange)) { | ||||
784 | SrcExpr = ExprError(); | ||||
785 | return; | ||||
786 | } | ||||
787 | } else { | ||||
788 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) | ||||
789 | << DestPointee.getUnqualifiedType() << DestRange; | ||||
790 | SrcExpr = ExprError(); | ||||
791 | return; | ||||
792 | } | ||||
793 | |||||
794 | // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to | ||||
795 | // complete class type, [...]. If T is an lvalue reference type, v shall be | ||||
796 | // an lvalue of a complete class type, [...]. If T is an rvalue reference | ||||
797 | // type, v shall be an expression having a complete class type, [...] | ||||
798 | QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); | ||||
799 | QualType SrcPointee; | ||||
800 | if (DestPointer) { | ||||
801 | if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { | ||||
802 | SrcPointee = SrcPointer->getPointeeType(); | ||||
803 | } else { | ||||
804 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) | ||||
805 | << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange(); | ||||
806 | SrcExpr = ExprError(); | ||||
807 | return; | ||||
808 | } | ||||
809 | } else if (DestReference->isLValueReferenceType()) { | ||||
810 | if (!SrcExpr.get()->isLValue()) { | ||||
811 | Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) | ||||
812 | << CT_Dynamic << OrigSrcType << this->DestType << OpRange; | ||||
813 | } | ||||
814 | SrcPointee = SrcType; | ||||
815 | } else { | ||||
816 | // If we're dynamic_casting from a prvalue to an rvalue reference, we need | ||||
817 | // to materialize the prvalue before we bind the reference to it. | ||||
818 | if (SrcExpr.get()->isRValue()) | ||||
819 | SrcExpr = Self.CreateMaterializeTemporaryExpr( | ||||
820 | SrcType, SrcExpr.get(), /*IsLValueReference*/ false); | ||||
821 | SrcPointee = SrcType; | ||||
822 | } | ||||
823 | |||||
824 | const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); | ||||
825 | if (SrcRecord) { | ||||
826 | if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, | ||||
827 | diag::err_bad_cast_incomplete, | ||||
828 | SrcExpr.get())) { | ||||
829 | SrcExpr = ExprError(); | ||||
830 | return; | ||||
831 | } | ||||
832 | } else { | ||||
833 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) | ||||
834 | << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); | ||||
835 | SrcExpr = ExprError(); | ||||
836 | return; | ||||
837 | } | ||||
838 | |||||
839 | assert((DestPointer || DestReference) &&(((DestPointer || DestReference) && "Bad destination non-ptr/ref slipped through." ) ? static_cast<void> (0) : __assert_fail ("(DestPointer || DestReference) && \"Bad destination non-ptr/ref slipped through.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 840, __PRETTY_FUNCTION__)) | ||||
840 | "Bad destination non-ptr/ref slipped through.")(((DestPointer || DestReference) && "Bad destination non-ptr/ref slipped through." ) ? static_cast<void> (0) : __assert_fail ("(DestPointer || DestReference) && \"Bad destination non-ptr/ref slipped through.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 840, __PRETTY_FUNCTION__)); | ||||
841 | assert((DestRecord || DestPointee->isVoidType()) &&(((DestRecord || DestPointee->isVoidType()) && "Bad destination pointee slipped through." ) ? static_cast<void> (0) : __assert_fail ("(DestRecord || DestPointee->isVoidType()) && \"Bad destination pointee slipped through.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 842, __PRETTY_FUNCTION__)) | ||||
842 | "Bad destination pointee slipped through.")(((DestRecord || DestPointee->isVoidType()) && "Bad destination pointee slipped through." ) ? static_cast<void> (0) : __assert_fail ("(DestRecord || DestPointee->isVoidType()) && \"Bad destination pointee slipped through.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 842, __PRETTY_FUNCTION__)); | ||||
843 | assert(SrcRecord && "Bad source pointee slipped through.")((SrcRecord && "Bad source pointee slipped through.") ? static_cast<void> (0) : __assert_fail ("SrcRecord && \"Bad source pointee slipped through.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 843, __PRETTY_FUNCTION__)); | ||||
844 | |||||
845 | // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. | ||||
846 | if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { | ||||
847 | Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) | ||||
848 | << CT_Dynamic << OrigSrcType << this->DestType << OpRange; | ||||
849 | SrcExpr = ExprError(); | ||||
850 | return; | ||||
851 | } | ||||
852 | |||||
853 | // C++ 5.2.7p3: If the type of v is the same as the required result type, | ||||
854 | // [except for cv]. | ||||
855 | if (DestRecord == SrcRecord) { | ||||
856 | Kind = CK_NoOp; | ||||
857 | return; | ||||
858 | } | ||||
859 | |||||
860 | // C++ 5.2.7p5 | ||||
861 | // Upcasts are resolved statically. | ||||
862 | if (DestRecord && | ||||
863 | Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { | ||||
864 | if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, | ||||
865 | OpRange.getBegin(), OpRange, | ||||
866 | &BasePath)) { | ||||
867 | SrcExpr = ExprError(); | ||||
868 | return; | ||||
869 | } | ||||
870 | |||||
871 | Kind = CK_DerivedToBase; | ||||
872 | return; | ||||
873 | } | ||||
874 | |||||
875 | // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. | ||||
876 | const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); | ||||
877 | assert(SrcDecl && "Definition missing")((SrcDecl && "Definition missing") ? static_cast<void > (0) : __assert_fail ("SrcDecl && \"Definition missing\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 877, __PRETTY_FUNCTION__)); | ||||
878 | if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { | ||||
879 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) | ||||
880 | << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); | ||||
881 | SrcExpr = ExprError(); | ||||
882 | } | ||||
883 | |||||
884 | // dynamic_cast is not available with -fno-rtti. | ||||
885 | // As an exception, dynamic_cast to void* is available because it doesn't | ||||
886 | // use RTTI. | ||||
887 | if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { | ||||
888 | Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); | ||||
889 | SrcExpr = ExprError(); | ||||
890 | return; | ||||
891 | } | ||||
892 | |||||
893 | // Warns when dynamic_cast is used with RTTI data disabled. | ||||
894 | if (!Self.getLangOpts().RTTIData) { | ||||
895 | bool MicrosoftABI = | ||||
896 | Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft(); | ||||
897 | bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() == | ||||
898 | DiagnosticOptions::MSVC; | ||||
899 | if (MicrosoftABI || !DestPointee->isVoidType()) | ||||
900 | Self.Diag(OpRange.getBegin(), | ||||
901 | diag::warn_no_dynamic_cast_with_rtti_disabled) | ||||
902 | << isClangCL; | ||||
903 | } | ||||
904 | |||||
905 | // Done. Everything else is run-time checks. | ||||
906 | Kind = CK_Dynamic; | ||||
907 | } | ||||
908 | |||||
909 | /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. | ||||
910 | /// Refer to C++ 5.2.11 for details. const_cast is typically used in code | ||||
911 | /// like this: | ||||
912 | /// const char *str = "literal"; | ||||
913 | /// legacy_function(const_cast\<char*\>(str)); | ||||
914 | void CastOperation::CheckConstCast() { | ||||
915 | CheckNoDerefRAII NoderefCheck(*this); | ||||
916 | |||||
917 | if (ValueKind == VK_RValue) | ||||
918 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); | ||||
919 | else if (isPlaceholder()) | ||||
920 | SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); | ||||
921 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error | ||||
922 | return; | ||||
923 | |||||
924 | unsigned msg = diag::err_bad_cxx_cast_generic; | ||||
925 | auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg); | ||||
926 | if (TCR != TC_Success && msg != 0) { | ||||
927 | Self.Diag(OpRange.getBegin(), msg) << CT_Const | ||||
928 | << SrcExpr.get()->getType() << DestType << OpRange; | ||||
929 | } | ||||
930 | if (!isValidCast(TCR)) | ||||
931 | SrcExpr = ExprError(); | ||||
932 | } | ||||
933 | |||||
934 | void CastOperation::CheckAddrspaceCast() { | ||||
935 | unsigned msg = diag::err_bad_cxx_cast_generic; | ||||
936 | auto TCR = | ||||
937 | TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind); | ||||
938 | if (TCR != TC_Success && msg != 0) { | ||||
939 | Self.Diag(OpRange.getBegin(), msg) | ||||
940 | << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange; | ||||
941 | } | ||||
942 | if (!isValidCast(TCR)) | ||||
943 | SrcExpr = ExprError(); | ||||
944 | } | ||||
945 | |||||
946 | /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast | ||||
947 | /// or downcast between respective pointers or references. | ||||
948 | static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, | ||||
949 | QualType DestType, | ||||
950 | SourceRange OpRange) { | ||||
951 | QualType SrcType = SrcExpr->getType(); | ||||
952 | // When casting from pointer or reference, get pointee type; use original | ||||
953 | // type otherwise. | ||||
954 | const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); | ||||
955 | const CXXRecordDecl *SrcRD = | ||||
956 | SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); | ||||
957 | |||||
958 | // Examining subobjects for records is only possible if the complete and | ||||
959 | // valid definition is available. Also, template instantiation is not | ||||
960 | // allowed here. | ||||
961 | if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) | ||||
962 | return; | ||||
963 | |||||
964 | const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); | ||||
965 | |||||
966 | if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) | ||||
967 | return; | ||||
968 | |||||
969 | enum { | ||||
970 | ReinterpretUpcast, | ||||
971 | ReinterpretDowncast | ||||
972 | } ReinterpretKind; | ||||
973 | |||||
974 | CXXBasePaths BasePaths; | ||||
975 | |||||
976 | if (SrcRD->isDerivedFrom(DestRD, BasePaths)) | ||||
977 | ReinterpretKind = ReinterpretUpcast; | ||||
978 | else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) | ||||
979 | ReinterpretKind = ReinterpretDowncast; | ||||
980 | else | ||||
981 | return; | ||||
982 | |||||
983 | bool VirtualBase = true; | ||||
984 | bool NonZeroOffset = false; | ||||
985 | for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), | ||||
986 | E = BasePaths.end(); | ||||
987 | I != E; ++I) { | ||||
988 | const CXXBasePath &Path = *I; | ||||
989 | CharUnits Offset = CharUnits::Zero(); | ||||
990 | bool IsVirtual = false; | ||||
991 | for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); | ||||
992 | IElem != EElem; ++IElem) { | ||||
993 | IsVirtual = IElem->Base->isVirtual(); | ||||
994 | if (IsVirtual) | ||||
995 | break; | ||||
996 | const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); | ||||
997 | assert(BaseRD && "Base type should be a valid unqualified class type")((BaseRD && "Base type should be a valid unqualified class type" ) ? static_cast<void> (0) : __assert_fail ("BaseRD && \"Base type should be a valid unqualified class type\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 997, __PRETTY_FUNCTION__)); | ||||
998 | // Don't check if any base has invalid declaration or has no definition | ||||
999 | // since it has no layout info. | ||||
1000 | const CXXRecordDecl *Class = IElem->Class, | ||||
1001 | *ClassDefinition = Class->getDefinition(); | ||||
1002 | if (Class->isInvalidDecl() || !ClassDefinition || | ||||
1003 | !ClassDefinition->isCompleteDefinition()) | ||||
1004 | return; | ||||
1005 | |||||
1006 | const ASTRecordLayout &DerivedLayout = | ||||
1007 | Self.Context.getASTRecordLayout(Class); | ||||
1008 | Offset += DerivedLayout.getBaseClassOffset(BaseRD); | ||||
1009 | } | ||||
1010 | if (!IsVirtual) { | ||||
1011 | // Don't warn if any path is a non-virtually derived base at offset zero. | ||||
1012 | if (Offset.isZero()) | ||||
1013 | return; | ||||
1014 | // Offset makes sense only for non-virtual bases. | ||||
1015 | else | ||||
1016 | NonZeroOffset = true; | ||||
1017 | } | ||||
1018 | VirtualBase = VirtualBase && IsVirtual; | ||||
1019 | } | ||||
1020 | |||||
1021 | (void) NonZeroOffset; // Silence set but not used warning. | ||||
1022 | assert((VirtualBase || NonZeroOffset) &&(((VirtualBase || NonZeroOffset) && "Should have returned if has non-virtual base with zero offset" ) ? static_cast<void> (0) : __assert_fail ("(VirtualBase || NonZeroOffset) && \"Should have returned if has non-virtual base with zero offset\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 1023, __PRETTY_FUNCTION__)) | ||||
1023 | "Should have returned if has non-virtual base with zero offset")(((VirtualBase || NonZeroOffset) && "Should have returned if has non-virtual base with zero offset" ) ? static_cast<void> (0) : __assert_fail ("(VirtualBase || NonZeroOffset) && \"Should have returned if has non-virtual base with zero offset\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 1023, __PRETTY_FUNCTION__)); | ||||
1024 | |||||
1025 | QualType BaseType = | ||||
1026 | ReinterpretKind == ReinterpretUpcast? DestType : SrcType; | ||||
1027 | QualType DerivedType = | ||||
1028 | ReinterpretKind == ReinterpretUpcast? SrcType : DestType; | ||||
1029 | |||||
1030 | SourceLocation BeginLoc = OpRange.getBegin(); | ||||
1031 | Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) | ||||
1032 | << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) | ||||
1033 | << OpRange; | ||||
1034 | Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) | ||||
1035 | << int(ReinterpretKind) | ||||
1036 | << FixItHint::CreateReplacement(BeginLoc, "static_cast"); | ||||
1037 | } | ||||
1038 | |||||
1039 | static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType, | ||||
1040 | ASTContext &Context) { | ||||
1041 | if (SrcType->isPointerType() && DestType->isPointerType()) | ||||
1042 | return true; | ||||
1043 | |||||
1044 | // Allow integral type mismatch if their size are equal. | ||||
1045 | if (SrcType->isIntegralType(Context) && DestType->isIntegralType(Context)) | ||||
1046 | if (Context.getTypeInfoInChars(SrcType).Width == | ||||
1047 | Context.getTypeInfoInChars(DestType).Width) | ||||
1048 | return true; | ||||
1049 | |||||
1050 | return Context.hasSameUnqualifiedType(SrcType, DestType); | ||||
1051 | } | ||||
1052 | |||||
1053 | static bool checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr, | ||||
1054 | QualType DestType) { | ||||
1055 | if (Self.Diags.isIgnored(diag::warn_cast_function_type, | ||||
1056 | SrcExpr.get()->getExprLoc())) | ||||
1057 | return true; | ||||
1058 | |||||
1059 | QualType SrcType = SrcExpr.get()->getType(); | ||||
1060 | const FunctionType *SrcFTy = nullptr; | ||||
1061 | const FunctionType *DstFTy = nullptr; | ||||
1062 | if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) && | ||||
1063 | DestType->isFunctionPointerType()) || | ||||
1064 | (SrcType->isMemberFunctionPointerType() && | ||||
1065 | DestType->isMemberFunctionPointerType())) { | ||||
1066 | SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>(); | ||||
1067 | DstFTy = DestType->getPointeeType()->castAs<FunctionType>(); | ||||
1068 | } else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) { | ||||
1069 | SrcFTy = SrcType->castAs<FunctionType>(); | ||||
1070 | DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>(); | ||||
1071 | } else { | ||||
1072 | return true; | ||||
1073 | } | ||||
1074 | assert(SrcFTy && DstFTy)((SrcFTy && DstFTy) ? static_cast<void> (0) : __assert_fail ("SrcFTy && DstFTy", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 1074, __PRETTY_FUNCTION__)); | ||||
1075 | |||||
1076 | auto IsVoidVoid = [](const FunctionType *T) { | ||||
1077 | if (!T->getReturnType()->isVoidType()) | ||||
1078 | return false; | ||||
1079 | if (const auto *PT = T->getAs<FunctionProtoType>()) | ||||
1080 | return !PT->isVariadic() && PT->getNumParams() == 0; | ||||
1081 | return false; | ||||
1082 | }; | ||||
1083 | |||||
1084 | // Skip if either function type is void(*)(void) | ||||
1085 | if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy)) | ||||
1086 | return true; | ||||
1087 | |||||
1088 | // Check return type. | ||||
1089 | if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(), | ||||
1090 | Self.Context)) | ||||
1091 | return false; | ||||
1092 | |||||
1093 | // Check if either has unspecified number of parameters | ||||
1094 | if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType()) | ||||
1095 | return true; | ||||
1096 | |||||
1097 | // Check parameter types. | ||||
1098 | |||||
1099 | const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy); | ||||
1100 | const auto *DstFPTy = cast<FunctionProtoType>(DstFTy); | ||||
1101 | |||||
1102 | // In a cast involving function types with a variable argument list only the | ||||
1103 | // types of initial arguments that are provided are considered. | ||||
1104 | unsigned NumParams = SrcFPTy->getNumParams(); | ||||
1105 | unsigned DstNumParams = DstFPTy->getNumParams(); | ||||
1106 | if (NumParams > DstNumParams) { | ||||
1107 | if (!DstFPTy->isVariadic()) | ||||
1108 | return false; | ||||
1109 | NumParams = DstNumParams; | ||||
1110 | } else if (NumParams < DstNumParams) { | ||||
1111 | if (!SrcFPTy->isVariadic()) | ||||
1112 | return false; | ||||
1113 | } | ||||
1114 | |||||
1115 | for (unsigned i = 0; i < NumParams; ++i) | ||||
1116 | if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i), | ||||
1117 | DstFPTy->getParamType(i), Self.Context)) | ||||
1118 | return false; | ||||
1119 | |||||
1120 | return true; | ||||
1121 | } | ||||
1122 | |||||
1123 | /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is | ||||
1124 | /// valid. | ||||
1125 | /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code | ||||
1126 | /// like this: | ||||
1127 | /// char *bytes = reinterpret_cast\<char*\>(int_ptr); | ||||
1128 | void CastOperation::CheckReinterpretCast() { | ||||
1129 | if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) | ||||
1130 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); | ||||
1131 | else | ||||
1132 | checkNonOverloadPlaceholders(); | ||||
1133 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error | ||||
1134 | return; | ||||
1135 | |||||
1136 | unsigned msg = diag::err_bad_cxx_cast_generic; | ||||
1137 | TryCastResult tcr = | ||||
1138 | TryReinterpretCast(Self, SrcExpr, DestType, | ||||
1139 | /*CStyle*/false, OpRange, msg, Kind); | ||||
1140 | if (tcr != TC_Success && msg != 0) { | ||||
1141 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error | ||||
1142 | return; | ||||
1143 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { | ||||
1144 | //FIXME: &f<int>; is overloaded and resolvable | ||||
1145 | Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) | ||||
1146 | << OverloadExpr::find(SrcExpr.get()).Expression->getName() | ||||
1147 | << DestType << OpRange; | ||||
1148 | Self.NoteAllOverloadCandidates(SrcExpr.get()); | ||||
1149 | |||||
1150 | } else { | ||||
1151 | diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), | ||||
1152 | DestType, /*listInitialization=*/false); | ||||
1153 | } | ||||
1154 | } | ||||
1155 | |||||
1156 | if (isValidCast(tcr)) { | ||||
1157 | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) | ||||
1158 | checkObjCConversion(Sema::CCK_OtherCast); | ||||
1159 | DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); | ||||
1160 | |||||
1161 | if (!checkCastFunctionType(Self, SrcExpr, DestType)) | ||||
1162 | Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type) | ||||
1163 | << SrcExpr.get()->getType() << DestType << OpRange; | ||||
1164 | } else { | ||||
1165 | SrcExpr = ExprError(); | ||||
1166 | } | ||||
1167 | } | ||||
1168 | |||||
1169 | |||||
1170 | /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. | ||||
1171 | /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making | ||||
1172 | /// implicit conversions explicit and getting rid of data loss warnings. | ||||
1173 | void CastOperation::CheckStaticCast() { | ||||
1174 | CheckNoDerefRAII NoderefCheck(*this); | ||||
1175 | |||||
1176 | if (isPlaceholder()) { | ||||
1177 | checkNonOverloadPlaceholders(); | ||||
1178 | if (SrcExpr.isInvalid()) | ||||
1179 | return; | ||||
1180 | } | ||||
1181 | |||||
1182 | // This test is outside everything else because it's the only case where | ||||
1183 | // a non-lvalue-reference target type does not lead to decay. | ||||
1184 | // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". | ||||
1185 | if (DestType->isVoidType()) { | ||||
1186 | Kind = CK_ToVoid; | ||||
1187 | |||||
1188 | if (claimPlaceholder(BuiltinType::Overload)) { | ||||
1189 | Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, | ||||
1190 | false, // Decay Function to ptr | ||||
1191 | true, // Complain | ||||
1192 | OpRange, DestType, diag::err_bad_static_cast_overload); | ||||
1193 | if (SrcExpr.isInvalid()) | ||||
1194 | return; | ||||
1195 | } | ||||
1196 | |||||
1197 | SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); | ||||
1198 | return; | ||||
1199 | } | ||||
1200 | |||||
1201 | if (ValueKind == VK_RValue && !DestType->isRecordType() && | ||||
1202 | !isPlaceholder(BuiltinType::Overload)) { | ||||
1203 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); | ||||
1204 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error | ||||
1205 | return; | ||||
1206 | } | ||||
1207 | |||||
1208 | unsigned msg = diag::err_bad_cxx_cast_generic; | ||||
1209 | TryCastResult tcr | ||||
1210 | = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, | ||||
1211 | Kind, BasePath, /*ListInitialization=*/false); | ||||
1212 | if (tcr != TC_Success && msg != 0) { | ||||
1213 | if (SrcExpr.isInvalid()) | ||||
1214 | return; | ||||
1215 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { | ||||
1216 | OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; | ||||
1217 | Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) | ||||
1218 | << oe->getName() << DestType << OpRange | ||||
1219 | << oe->getQualifierLoc().getSourceRange(); | ||||
1220 | Self.NoteAllOverloadCandidates(SrcExpr.get()); | ||||
1221 | } else { | ||||
1222 | diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, | ||||
1223 | /*listInitialization=*/false); | ||||
1224 | } | ||||
1225 | } | ||||
1226 | |||||
1227 | if (isValidCast(tcr)) { | ||||
1228 | if (Kind == CK_BitCast) | ||||
1229 | checkCastAlign(); | ||||
1230 | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) | ||||
1231 | checkObjCConversion(Sema::CCK_OtherCast); | ||||
1232 | } else { | ||||
1233 | SrcExpr = ExprError(); | ||||
1234 | } | ||||
1235 | } | ||||
1236 | |||||
1237 | static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) { | ||||
1238 | auto *SrcPtrType = SrcType->getAs<PointerType>(); | ||||
1239 | if (!SrcPtrType) | ||||
1240 | return false; | ||||
1241 | auto *DestPtrType = DestType->getAs<PointerType>(); | ||||
1242 | if (!DestPtrType) | ||||
1243 | return false; | ||||
1244 | return SrcPtrType->getPointeeType().getAddressSpace() != | ||||
1245 | DestPtrType->getPointeeType().getAddressSpace(); | ||||
1246 | } | ||||
1247 | |||||
1248 | /// TryStaticCast - Check if a static cast can be performed, and do so if | ||||
1249 | /// possible. If @p CStyle, ignore access restrictions on hierarchy casting | ||||
1250 | /// and casting away constness. | ||||
1251 | static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, | ||||
1252 | QualType DestType, | ||||
1253 | Sema::CheckedConversionKind CCK, | ||||
1254 | SourceRange OpRange, unsigned &msg, | ||||
1255 | CastKind &Kind, CXXCastPath &BasePath, | ||||
1256 | bool ListInitialization) { | ||||
1257 | // Determine whether we have the semantics of a C-style cast. | ||||
1258 | bool CStyle | ||||
1259 | = (CCK
| ||||
1260 | |||||
1261 | // The order the tests is not entirely arbitrary. There is one conversion | ||||
1262 | // that can be handled in two different ways. Given: | ||||
1263 | // struct A {}; | ||||
1264 | // struct B : public A { | ||||
1265 | // B(); B(const A&); | ||||
1266 | // }; | ||||
1267 | // const A &a = B(); | ||||
1268 | // the cast static_cast<const B&>(a) could be seen as either a static | ||||
1269 | // reference downcast, or an explicit invocation of the user-defined | ||||
1270 | // conversion using B's conversion constructor. | ||||
1271 | // DR 427 specifies that the downcast is to be applied here. | ||||
1272 | |||||
1273 | // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". | ||||
1274 | // Done outside this function. | ||||
1275 | |||||
1276 | TryCastResult tcr; | ||||
1277 | |||||
1278 | // C++ 5.2.9p5, reference downcast. | ||||
1279 | // See the function for details. | ||||
1280 | // DR 427 specifies that this is to be applied before paragraph 2. | ||||
1281 | tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, | ||||
1282 | OpRange, msg, Kind, BasePath); | ||||
1283 | if (tcr
| ||||
1284 | return tcr; | ||||
1285 | |||||
1286 | // C++11 [expr.static.cast]p3: | ||||
1287 | // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 | ||||
1288 | // T2" if "cv2 T2" is reference-compatible with "cv1 T1". | ||||
1289 | tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, | ||||
1290 | BasePath, msg); | ||||
1291 | if (tcr
| ||||
1292 | return tcr; | ||||
1293 | |||||
1294 | // C++ 5.2.9p2: An expression e can be explicitly converted to a type T | ||||
1295 | // [...] if the declaration "T t(e);" is well-formed, [...]. | ||||
1296 | tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, | ||||
1297 | Kind, ListInitialization); | ||||
1298 | if (SrcExpr.isInvalid()) | ||||
1299 | return TC_Failed; | ||||
1300 | if (tcr
| ||||
1301 | return tcr; | ||||
1302 | |||||
1303 | // C++ 5.2.9p6: May apply the reverse of any standard conversion, except | ||||
1304 | // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean | ||||
1305 | // conversions, subject to further restrictions. | ||||
1306 | // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal | ||||
1307 | // of qualification conversions impossible. | ||||
1308 | // In the CStyle case, the earlier attempt to const_cast should have taken | ||||
1309 | // care of reverse qualification conversions. | ||||
1310 | |||||
1311 | QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); | ||||
1312 | |||||
1313 | // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly | ||||
1314 | // converted to an integral type. [...] A value of a scoped enumeration type | ||||
1315 | // can also be explicitly converted to a floating-point type [...]. | ||||
1316 | if (const EnumType *Enum
| ||||
1317 | if (Enum->getDecl()->isScoped()) { | ||||
1318 | if (DestType->isBooleanType()) { | ||||
1319 | Kind = CK_IntegralToBoolean; | ||||
1320 | return TC_Success; | ||||
1321 | } else if (DestType->isIntegralType(Self.Context)) { | ||||
1322 | Kind = CK_IntegralCast; | ||||
1323 | return TC_Success; | ||||
1324 | } else if (DestType->isRealFloatingType()) { | ||||
1325 | Kind = CK_IntegralToFloating; | ||||
1326 | return TC_Success; | ||||
1327 | } | ||||
1328 | } | ||||
1329 | } | ||||
1330 | |||||
1331 | // Reverse integral promotion/conversion. All such conversions are themselves | ||||
1332 | // again integral promotions or conversions and are thus already handled by | ||||
1333 | // p2 (TryDirectInitialization above). | ||||
1334 | // (Note: any data loss warnings should be suppressed.) | ||||
1335 | // The exception is the reverse of enum->integer, i.e. integer->enum (and | ||||
1336 | // enum->enum). See also C++ 5.2.9p7. | ||||
1337 | // The same goes for reverse floating point promotion/conversion and | ||||
1338 | // floating-integral conversions. Again, only floating->enum is relevant. | ||||
1339 | if (DestType->isEnumeralType()) { | ||||
1340 | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, | ||||
1341 | diag::err_bad_cast_incomplete)) { | ||||
1342 | SrcExpr = ExprError(); | ||||
1343 | return TC_Failed; | ||||
1344 | } | ||||
1345 | if (SrcType->isIntegralOrEnumerationType()) { | ||||
1346 | // [expr.static.cast]p10 If the enumeration type has a fixed underlying | ||||
1347 | // type, the value is first converted to that type by integral conversion | ||||
1348 | const EnumType *Enum = DestType->getAs<EnumType>(); | ||||
1349 | Kind = Enum->getDecl()->isFixed() && | ||||
| |||||
1350 | Enum->getDecl()->getIntegerType()->isBooleanType() | ||||
1351 | ? CK_IntegralToBoolean | ||||
1352 | : CK_IntegralCast; | ||||
1353 | return TC_Success; | ||||
1354 | } else if (SrcType->isRealFloatingType()) { | ||||
1355 | Kind = CK_FloatingToIntegral; | ||||
1356 | return TC_Success; | ||||
1357 | } | ||||
1358 | } | ||||
1359 | |||||
1360 | // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. | ||||
1361 | // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. | ||||
1362 | tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, | ||||
1363 | Kind, BasePath); | ||||
1364 | if (tcr != TC_NotApplicable) | ||||
1365 | return tcr; | ||||
1366 | |||||
1367 | // Reverse member pointer conversion. C++ 4.11 specifies member pointer | ||||
1368 | // conversion. C++ 5.2.9p9 has additional information. | ||||
1369 | // DR54's access restrictions apply here also. | ||||
1370 | tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, | ||||
1371 | OpRange, msg, Kind, BasePath); | ||||
1372 | if (tcr != TC_NotApplicable) | ||||
1373 | return tcr; | ||||
1374 | |||||
1375 | // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to | ||||
1376 | // void*. C++ 5.2.9p10 specifies additional restrictions, which really is | ||||
1377 | // just the usual constness stuff. | ||||
1378 | if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { | ||||
1379 | QualType SrcPointee = SrcPointer->getPointeeType(); | ||||
1380 | if (SrcPointee->isVoidType()) { | ||||
1381 | if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { | ||||
1382 | QualType DestPointee = DestPointer->getPointeeType(); | ||||
1383 | if (DestPointee->isIncompleteOrObjectType()) { | ||||
1384 | // This is definitely the intended conversion, but it might fail due | ||||
1385 | // to a qualifier violation. Note that we permit Objective-C lifetime | ||||
1386 | // and GC qualifier mismatches here. | ||||
1387 | if (!CStyle) { | ||||
1388 | Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); | ||||
1389 | Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); | ||||
1390 | DestPointeeQuals.removeObjCGCAttr(); | ||||
1391 | DestPointeeQuals.removeObjCLifetime(); | ||||
1392 | SrcPointeeQuals.removeObjCGCAttr(); | ||||
1393 | SrcPointeeQuals.removeObjCLifetime(); | ||||
1394 | if (DestPointeeQuals != SrcPointeeQuals && | ||||
1395 | !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { | ||||
1396 | msg = diag::err_bad_cxx_cast_qualifiers_away; | ||||
1397 | return TC_Failed; | ||||
1398 | } | ||||
1399 | } | ||||
1400 | Kind = IsAddressSpaceConversion(SrcType, DestType) | ||||
1401 | ? CK_AddressSpaceConversion | ||||
1402 | : CK_BitCast; | ||||
1403 | return TC_Success; | ||||
1404 | } | ||||
1405 | |||||
1406 | // Microsoft permits static_cast from 'pointer-to-void' to | ||||
1407 | // 'pointer-to-function'. | ||||
1408 | if (!CStyle && Self.getLangOpts().MSVCCompat && | ||||
1409 | DestPointee->isFunctionType()) { | ||||
1410 | Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; | ||||
1411 | Kind = CK_BitCast; | ||||
1412 | return TC_Success; | ||||
1413 | } | ||||
1414 | } | ||||
1415 | else if (DestType->isObjCObjectPointerType()) { | ||||
1416 | // allow both c-style cast and static_cast of objective-c pointers as | ||||
1417 | // they are pervasive. | ||||
1418 | Kind = CK_CPointerToObjCPointerCast; | ||||
1419 | return TC_Success; | ||||
1420 | } | ||||
1421 | else if (CStyle && DestType->isBlockPointerType()) { | ||||
1422 | // allow c-style cast of void * to block pointers. | ||||
1423 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
1424 | return TC_Success; | ||||
1425 | } | ||||
1426 | } | ||||
1427 | } | ||||
1428 | // Allow arbitrary objective-c pointer conversion with static casts. | ||||
1429 | if (SrcType->isObjCObjectPointerType() && | ||||
1430 | DestType->isObjCObjectPointerType()) { | ||||
1431 | Kind = CK_BitCast; | ||||
1432 | return TC_Success; | ||||
1433 | } | ||||
1434 | // Allow ns-pointer to cf-pointer conversion in either direction | ||||
1435 | // with static casts. | ||||
1436 | if (!CStyle && | ||||
1437 | Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) | ||||
1438 | return TC_Success; | ||||
1439 | |||||
1440 | // See if it looks like the user is trying to convert between | ||||
1441 | // related record types, and select a better diagnostic if so. | ||||
1442 | if (auto SrcPointer = SrcType->getAs<PointerType>()) | ||||
1443 | if (auto DestPointer = DestType->getAs<PointerType>()) | ||||
1444 | if (SrcPointer->getPointeeType()->getAs<RecordType>() && | ||||
1445 | DestPointer->getPointeeType()->getAs<RecordType>()) | ||||
1446 | msg = diag::err_bad_cxx_cast_unrelated_class; | ||||
1447 | |||||
1448 | // We tried everything. Everything! Nothing works! :-( | ||||
1449 | return TC_NotApplicable; | ||||
1450 | } | ||||
1451 | |||||
1452 | /// Tests whether a conversion according to N2844 is valid. | ||||
1453 | TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, | ||||
1454 | QualType DestType, bool CStyle, | ||||
1455 | CastKind &Kind, CXXCastPath &BasePath, | ||||
1456 | unsigned &msg) { | ||||
1457 | // C++11 [expr.static.cast]p3: | ||||
1458 | // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to | ||||
1459 | // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". | ||||
1460 | const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); | ||||
1461 | if (!R) | ||||
1462 | return TC_NotApplicable; | ||||
1463 | |||||
1464 | if (!SrcExpr->isGLValue()) | ||||
1465 | return TC_NotApplicable; | ||||
1466 | |||||
1467 | // Because we try the reference downcast before this function, from now on | ||||
1468 | // this is the only cast possibility, so we issue an error if we fail now. | ||||
1469 | // FIXME: Should allow casting away constness if CStyle. | ||||
1470 | QualType FromType = SrcExpr->getType(); | ||||
1471 | QualType ToType = R->getPointeeType(); | ||||
1472 | if (CStyle) { | ||||
1473 | FromType = FromType.getUnqualifiedType(); | ||||
1474 | ToType = ToType.getUnqualifiedType(); | ||||
1475 | } | ||||
1476 | |||||
1477 | Sema::ReferenceConversions RefConv; | ||||
1478 | Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship( | ||||
1479 | SrcExpr->getBeginLoc(), ToType, FromType, &RefConv); | ||||
1480 | if (RefResult != Sema::Ref_Compatible) { | ||||
1481 | if (CStyle || RefResult == Sema::Ref_Incompatible) | ||||
1482 | return TC_NotApplicable; | ||||
1483 | // Diagnose types which are reference-related but not compatible here since | ||||
1484 | // we can provide better diagnostics. In these cases forwarding to | ||||
1485 | // [expr.static.cast]p4 should never result in a well-formed cast. | ||||
1486 | msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast | ||||
1487 | : diag::err_bad_rvalue_to_rvalue_cast; | ||||
1488 | return TC_Failed; | ||||
1489 | } | ||||
1490 | |||||
1491 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) { | ||||
1492 | Kind = CK_DerivedToBase; | ||||
1493 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
1494 | /*DetectVirtual=*/true); | ||||
1495 | if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(), | ||||
1496 | R->getPointeeType(), Paths)) | ||||
1497 | return TC_NotApplicable; | ||||
1498 | |||||
1499 | Self.BuildBasePathArray(Paths, BasePath); | ||||
1500 | } else | ||||
1501 | Kind = CK_NoOp; | ||||
1502 | |||||
1503 | return TC_Success; | ||||
1504 | } | ||||
1505 | |||||
1506 | /// Tests whether a conversion according to C++ 5.2.9p5 is valid. | ||||
1507 | TryCastResult | ||||
1508 | TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, | ||||
1509 | bool CStyle, SourceRange OpRange, | ||||
1510 | unsigned &msg, CastKind &Kind, | ||||
1511 | CXXCastPath &BasePath) { | ||||
1512 | // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be | ||||
1513 | // cast to type "reference to cv2 D", where D is a class derived from B, | ||||
1514 | // if a valid standard conversion from "pointer to D" to "pointer to B" | ||||
1515 | // exists, cv2 >= cv1, and B is not a virtual base class of D. | ||||
1516 | // In addition, DR54 clarifies that the base must be accessible in the | ||||
1517 | // current context. Although the wording of DR54 only applies to the pointer | ||||
1518 | // variant of this rule, the intent is clearly for it to apply to the this | ||||
1519 | // conversion as well. | ||||
1520 | |||||
1521 | const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); | ||||
1522 | if (!DestReference) { | ||||
1523 | return TC_NotApplicable; | ||||
1524 | } | ||||
1525 | bool RValueRef = DestReference->isRValueReferenceType(); | ||||
1526 | if (!RValueRef && !SrcExpr->isLValue()) { | ||||
1527 | // We know the left side is an lvalue reference, so we can suggest a reason. | ||||
1528 | msg = diag::err_bad_cxx_cast_rvalue; | ||||
1529 | return TC_NotApplicable; | ||||
1530 | } | ||||
1531 | |||||
1532 | QualType DestPointee = DestReference->getPointeeType(); | ||||
1533 | |||||
1534 | // FIXME: If the source is a prvalue, we should issue a warning (because the | ||||
1535 | // cast always has undefined behavior), and for AST consistency, we should | ||||
1536 | // materialize a temporary. | ||||
1537 | return TryStaticDowncast(Self, | ||||
1538 | Self.Context.getCanonicalType(SrcExpr->getType()), | ||||
1539 | Self.Context.getCanonicalType(DestPointee), CStyle, | ||||
1540 | OpRange, SrcExpr->getType(), DestType, msg, Kind, | ||||
1541 | BasePath); | ||||
1542 | } | ||||
1543 | |||||
1544 | /// Tests whether a conversion according to C++ 5.2.9p8 is valid. | ||||
1545 | TryCastResult | ||||
1546 | TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, | ||||
1547 | bool CStyle, SourceRange OpRange, | ||||
1548 | unsigned &msg, CastKind &Kind, | ||||
1549 | CXXCastPath &BasePath) { | ||||
1550 | // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class | ||||
1551 | // type, can be converted to an rvalue of type "pointer to cv2 D", where D | ||||
1552 | // is a class derived from B, if a valid standard conversion from "pointer | ||||
1553 | // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base | ||||
1554 | // class of D. | ||||
1555 | // In addition, DR54 clarifies that the base must be accessible in the | ||||
1556 | // current context. | ||||
1557 | |||||
1558 | const PointerType *DestPointer = DestType->getAs<PointerType>(); | ||||
1559 | if (!DestPointer) { | ||||
1560 | return TC_NotApplicable; | ||||
1561 | } | ||||
1562 | |||||
1563 | const PointerType *SrcPointer = SrcType->getAs<PointerType>(); | ||||
1564 | if (!SrcPointer) { | ||||
1565 | msg = diag::err_bad_static_cast_pointer_nonpointer; | ||||
1566 | return TC_NotApplicable; | ||||
1567 | } | ||||
1568 | |||||
1569 | return TryStaticDowncast(Self, | ||||
1570 | Self.Context.getCanonicalType(SrcPointer->getPointeeType()), | ||||
1571 | Self.Context.getCanonicalType(DestPointer->getPointeeType()), | ||||
1572 | CStyle, OpRange, SrcType, DestType, msg, Kind, | ||||
1573 | BasePath); | ||||
1574 | } | ||||
1575 | |||||
1576 | /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and | ||||
1577 | /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to | ||||
1578 | /// DestType is possible and allowed. | ||||
1579 | TryCastResult | ||||
1580 | TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, | ||||
1581 | bool CStyle, SourceRange OpRange, QualType OrigSrcType, | ||||
1582 | QualType OrigDestType, unsigned &msg, | ||||
1583 | CastKind &Kind, CXXCastPath &BasePath) { | ||||
1584 | // We can only work with complete types. But don't complain if it doesn't work | ||||
1585 | if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || | ||||
1586 | !Self.isCompleteType(OpRange.getBegin(), DestType)) | ||||
1587 | return TC_NotApplicable; | ||||
1588 | |||||
1589 | // Downcast can only happen in class hierarchies, so we need classes. | ||||
1590 | if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { | ||||
1591 | return TC_NotApplicable; | ||||
1592 | } | ||||
1593 | |||||
1594 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
1595 | /*DetectVirtual=*/true); | ||||
1596 | if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { | ||||
1597 | return TC_NotApplicable; | ||||
1598 | } | ||||
1599 | |||||
1600 | // Target type does derive from source type. Now we're serious. If an error | ||||
1601 | // appears now, it's not ignored. | ||||
1602 | // This may not be entirely in line with the standard. Take for example: | ||||
1603 | // struct A {}; | ||||
1604 | // struct B : virtual A { | ||||
1605 | // B(A&); | ||||
1606 | // }; | ||||
1607 | // | ||||
1608 | // void f() | ||||
1609 | // { | ||||
1610 | // (void)static_cast<const B&>(*((A*)0)); | ||||
1611 | // } | ||||
1612 | // As far as the standard is concerned, p5 does not apply (A is virtual), so | ||||
1613 | // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. | ||||
1614 | // However, both GCC and Comeau reject this example, and accepting it would | ||||
1615 | // mean more complex code if we're to preserve the nice error message. | ||||
1616 | // FIXME: Being 100% compliant here would be nice to have. | ||||
1617 | |||||
1618 | // Must preserve cv, as always, unless we're in C-style mode. | ||||
1619 | if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { | ||||
1620 | msg = diag::err_bad_cxx_cast_qualifiers_away; | ||||
1621 | return TC_Failed; | ||||
1622 | } | ||||
1623 | |||||
1624 | if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { | ||||
1625 | // This code is analoguous to that in CheckDerivedToBaseConversion, except | ||||
1626 | // that it builds the paths in reverse order. | ||||
1627 | // To sum up: record all paths to the base and build a nice string from | ||||
1628 | // them. Use it to spice up the error message. | ||||
1629 | if (!Paths.isRecordingPaths()) { | ||||
1630 | Paths.clear(); | ||||
1631 | Paths.setRecordingPaths(true); | ||||
1632 | Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); | ||||
1633 | } | ||||
1634 | std::string PathDisplayStr; | ||||
1635 | std::set<unsigned> DisplayedPaths; | ||||
1636 | for (clang::CXXBasePath &Path : Paths) { | ||||
1637 | if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) { | ||||
1638 | // We haven't displayed a path to this particular base | ||||
1639 | // class subobject yet. | ||||
1640 | PathDisplayStr += "\n "; | ||||
1641 | for (CXXBasePathElement &PE : llvm::reverse(Path)) | ||||
1642 | PathDisplayStr += PE.Base->getType().getAsString() + " -> "; | ||||
1643 | PathDisplayStr += QualType(DestType).getAsString(); | ||||
1644 | } | ||||
1645 | } | ||||
1646 | |||||
1647 | Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) | ||||
1648 | << QualType(SrcType).getUnqualifiedType() | ||||
1649 | << QualType(DestType).getUnqualifiedType() | ||||
1650 | << PathDisplayStr << OpRange; | ||||
1651 | msg = 0; | ||||
1652 | return TC_Failed; | ||||
1653 | } | ||||
1654 | |||||
1655 | if (Paths.getDetectedVirtual() != nullptr) { | ||||
1656 | QualType VirtualBase(Paths.getDetectedVirtual(), 0); | ||||
1657 | Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) | ||||
1658 | << OrigSrcType << OrigDestType << VirtualBase << OpRange; | ||||
1659 | msg = 0; | ||||
1660 | return TC_Failed; | ||||
1661 | } | ||||
1662 | |||||
1663 | if (!CStyle) { | ||||
1664 | switch (Self.CheckBaseClassAccess(OpRange.getBegin(), | ||||
1665 | SrcType, DestType, | ||||
1666 | Paths.front(), | ||||
1667 | diag::err_downcast_from_inaccessible_base)) { | ||||
1668 | case Sema::AR_accessible: | ||||
1669 | case Sema::AR_delayed: // be optimistic | ||||
1670 | case Sema::AR_dependent: // be optimistic | ||||
1671 | break; | ||||
1672 | |||||
1673 | case Sema::AR_inaccessible: | ||||
1674 | msg = 0; | ||||
1675 | return TC_Failed; | ||||
1676 | } | ||||
1677 | } | ||||
1678 | |||||
1679 | Self.BuildBasePathArray(Paths, BasePath); | ||||
1680 | Kind = CK_BaseToDerived; | ||||
1681 | return TC_Success; | ||||
1682 | } | ||||
1683 | |||||
1684 | /// TryStaticMemberPointerUpcast - Tests whether a conversion according to | ||||
1685 | /// C++ 5.2.9p9 is valid: | ||||
1686 | /// | ||||
1687 | /// An rvalue of type "pointer to member of D of type cv1 T" can be | ||||
1688 | /// converted to an rvalue of type "pointer to member of B of type cv2 T", | ||||
1689 | /// where B is a base class of D [...]. | ||||
1690 | /// | ||||
1691 | TryCastResult | ||||
1692 | TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, | ||||
1693 | QualType DestType, bool CStyle, | ||||
1694 | SourceRange OpRange, | ||||
1695 | unsigned &msg, CastKind &Kind, | ||||
1696 | CXXCastPath &BasePath) { | ||||
1697 | const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); | ||||
1698 | if (!DestMemPtr) | ||||
1699 | return TC_NotApplicable; | ||||
1700 | |||||
1701 | bool WasOverloadedFunction = false; | ||||
1702 | DeclAccessPair FoundOverload; | ||||
1703 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { | ||||
1704 | if (FunctionDecl *Fn | ||||
1705 | = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, | ||||
1706 | FoundOverload)) { | ||||
1707 | CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); | ||||
1708 | SrcType = Self.Context.getMemberPointerType(Fn->getType(), | ||||
1709 | Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); | ||||
1710 | WasOverloadedFunction = true; | ||||
1711 | } | ||||
1712 | } | ||||
1713 | |||||
1714 | const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); | ||||
1715 | if (!SrcMemPtr) { | ||||
1716 | msg = diag::err_bad_static_cast_member_pointer_nonmp; | ||||
1717 | return TC_NotApplicable; | ||||
1718 | } | ||||
1719 | |||||
1720 | // Lock down the inheritance model right now in MS ABI, whether or not the | ||||
1721 | // pointee types are the same. | ||||
1722 | if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
1723 | (void)Self.isCompleteType(OpRange.getBegin(), SrcType); | ||||
1724 | (void)Self.isCompleteType(OpRange.getBegin(), DestType); | ||||
1725 | } | ||||
1726 | |||||
1727 | // T == T, modulo cv | ||||
1728 | if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), | ||||
1729 | DestMemPtr->getPointeeType())) | ||||
1730 | return TC_NotApplicable; | ||||
1731 | |||||
1732 | // B base of D | ||||
1733 | QualType SrcClass(SrcMemPtr->getClass(), 0); | ||||
1734 | QualType DestClass(DestMemPtr->getClass(), 0); | ||||
1735 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
1736 | /*DetectVirtual=*/true); | ||||
1737 | if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) | ||||
1738 | return TC_NotApplicable; | ||||
1739 | |||||
1740 | // B is a base of D. But is it an allowed base? If not, it's a hard error. | ||||
1741 | if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { | ||||
1742 | Paths.clear(); | ||||
1743 | Paths.setRecordingPaths(true); | ||||
1744 | bool StillOkay = | ||||
1745 | Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); | ||||
1746 | assert(StillOkay)((StillOkay) ? static_cast<void> (0) : __assert_fail ("StillOkay" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 1746, __PRETTY_FUNCTION__)); | ||||
1747 | (void)StillOkay; | ||||
1748 | std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); | ||||
1749 | Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) | ||||
1750 | << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; | ||||
1751 | msg = 0; | ||||
1752 | return TC_Failed; | ||||
1753 | } | ||||
1754 | |||||
1755 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { | ||||
1756 | Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) | ||||
1757 | << SrcClass << DestClass << QualType(VBase, 0) << OpRange; | ||||
1758 | msg = 0; | ||||
1759 | return TC_Failed; | ||||
1760 | } | ||||
1761 | |||||
1762 | if (!CStyle) { | ||||
1763 | switch (Self.CheckBaseClassAccess(OpRange.getBegin(), | ||||
1764 | DestClass, SrcClass, | ||||
1765 | Paths.front(), | ||||
1766 | diag::err_upcast_to_inaccessible_base)) { | ||||
1767 | case Sema::AR_accessible: | ||||
1768 | case Sema::AR_delayed: | ||||
1769 | case Sema::AR_dependent: | ||||
1770 | // Optimistically assume that the delayed and dependent cases | ||||
1771 | // will work out. | ||||
1772 | break; | ||||
1773 | |||||
1774 | case Sema::AR_inaccessible: | ||||
1775 | msg = 0; | ||||
1776 | return TC_Failed; | ||||
1777 | } | ||||
1778 | } | ||||
1779 | |||||
1780 | if (WasOverloadedFunction) { | ||||
1781 | // Resolve the address of the overloaded function again, this time | ||||
1782 | // allowing complaints if something goes wrong. | ||||
1783 | FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), | ||||
1784 | DestType, | ||||
1785 | true, | ||||
1786 | FoundOverload); | ||||
1787 | if (!Fn) { | ||||
1788 | msg = 0; | ||||
1789 | return TC_Failed; | ||||
1790 | } | ||||
1791 | |||||
1792 | SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); | ||||
1793 | if (!SrcExpr.isUsable()) { | ||||
1794 | msg = 0; | ||||
1795 | return TC_Failed; | ||||
1796 | } | ||||
1797 | } | ||||
1798 | |||||
1799 | Self.BuildBasePathArray(Paths, BasePath); | ||||
1800 | Kind = CK_DerivedToBaseMemberPointer; | ||||
1801 | return TC_Success; | ||||
1802 | } | ||||
1803 | |||||
1804 | /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 | ||||
1805 | /// is valid: | ||||
1806 | /// | ||||
1807 | /// An expression e can be explicitly converted to a type T using a | ||||
1808 | /// @c static_cast if the declaration "T t(e);" is well-formed [...]. | ||||
1809 | TryCastResult | ||||
1810 | TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, | ||||
1811 | Sema::CheckedConversionKind CCK, | ||||
1812 | SourceRange OpRange, unsigned &msg, | ||||
1813 | CastKind &Kind, bool ListInitialization) { | ||||
1814 | if (DestType->isRecordType()) { | ||||
1815 | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, | ||||
1816 | diag::err_bad_cast_incomplete) || | ||||
1817 | Self.RequireNonAbstractType(OpRange.getBegin(), DestType, | ||||
1818 | diag::err_allocation_of_abstract_type)) { | ||||
1819 | msg = 0; | ||||
1820 | return TC_Failed; | ||||
1821 | } | ||||
1822 | } | ||||
1823 | |||||
1824 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); | ||||
1825 | InitializationKind InitKind | ||||
1826 | = (CCK == Sema::CCK_CStyleCast) | ||||
1827 | ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, | ||||
1828 | ListInitialization) | ||||
1829 | : (CCK == Sema::CCK_FunctionalCast) | ||||
1830 | ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) | ||||
1831 | : InitializationKind::CreateCast(OpRange); | ||||
1832 | Expr *SrcExprRaw = SrcExpr.get(); | ||||
1833 | // FIXME: Per DR242, we should check for an implicit conversion sequence | ||||
1834 | // or for a constructor that could be invoked by direct-initialization | ||||
1835 | // here, not for an initialization sequence. | ||||
1836 | InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); | ||||
1837 | |||||
1838 | // At this point of CheckStaticCast, if the destination is a reference, | ||||
1839 | // or the expression is an overload expression this has to work. | ||||
1840 | // There is no other way that works. | ||||
1841 | // On the other hand, if we're checking a C-style cast, we've still got | ||||
1842 | // the reinterpret_cast way. | ||||
1843 | bool CStyle | ||||
1844 | = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); | ||||
1845 | if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) | ||||
1846 | return TC_NotApplicable; | ||||
1847 | |||||
1848 | ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); | ||||
1849 | if (Result.isInvalid()) { | ||||
1850 | msg = 0; | ||||
1851 | return TC_Failed; | ||||
1852 | } | ||||
1853 | |||||
1854 | if (InitSeq.isConstructorInitialization()) | ||||
1855 | Kind = CK_ConstructorConversion; | ||||
1856 | else | ||||
1857 | Kind = CK_NoOp; | ||||
1858 | |||||
1859 | SrcExpr = Result; | ||||
1860 | return TC_Success; | ||||
1861 | } | ||||
1862 | |||||
1863 | /// TryConstCast - See if a const_cast from source to destination is allowed, | ||||
1864 | /// and perform it if it is. | ||||
1865 | static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, | ||||
1866 | QualType DestType, bool CStyle, | ||||
1867 | unsigned &msg) { | ||||
1868 | DestType = Self.Context.getCanonicalType(DestType); | ||||
1869 | QualType SrcType = SrcExpr.get()->getType(); | ||||
1870 | bool NeedToMaterializeTemporary = false; | ||||
1871 | |||||
1872 | if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { | ||||
1873 | // C++11 5.2.11p4: | ||||
1874 | // if a pointer to T1 can be explicitly converted to the type "pointer to | ||||
1875 | // T2" using a const_cast, then the following conversions can also be | ||||
1876 | // made: | ||||
1877 | // -- an lvalue of type T1 can be explicitly converted to an lvalue of | ||||
1878 | // type T2 using the cast const_cast<T2&>; | ||||
1879 | // -- a glvalue of type T1 can be explicitly converted to an xvalue of | ||||
1880 | // type T2 using the cast const_cast<T2&&>; and | ||||
1881 | // -- if T1 is a class type, a prvalue of type T1 can be explicitly | ||||
1882 | // converted to an xvalue of type T2 using the cast const_cast<T2&&>. | ||||
1883 | |||||
1884 | if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { | ||||
1885 | // Cannot const_cast non-lvalue to lvalue reference type. But if this | ||||
1886 | // is C-style, static_cast might find a way, so we simply suggest a | ||||
1887 | // message and tell the parent to keep searching. | ||||
1888 | msg = diag::err_bad_cxx_cast_rvalue; | ||||
1889 | return TC_NotApplicable; | ||||
1890 | } | ||||
1891 | |||||
1892 | if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) { | ||||
1893 | if (!SrcType->isRecordType()) { | ||||
1894 | // Cannot const_cast non-class prvalue to rvalue reference type. But if | ||||
1895 | // this is C-style, static_cast can do this. | ||||
1896 | msg = diag::err_bad_cxx_cast_rvalue; | ||||
1897 | return TC_NotApplicable; | ||||
1898 | } | ||||
1899 | |||||
1900 | // Materialize the class prvalue so that the const_cast can bind a | ||||
1901 | // reference to it. | ||||
1902 | NeedToMaterializeTemporary = true; | ||||
1903 | } | ||||
1904 | |||||
1905 | // It's not completely clear under the standard whether we can | ||||
1906 | // const_cast bit-field gl-values. Doing so would not be | ||||
1907 | // intrinsically complicated, but for now, we say no for | ||||
1908 | // consistency with other compilers and await the word of the | ||||
1909 | // committee. | ||||
1910 | if (SrcExpr.get()->refersToBitField()) { | ||||
1911 | msg = diag::err_bad_cxx_cast_bitfield; | ||||
1912 | return TC_NotApplicable; | ||||
1913 | } | ||||
1914 | |||||
1915 | DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); | ||||
1916 | SrcType = Self.Context.getPointerType(SrcType); | ||||
1917 | } | ||||
1918 | |||||
1919 | // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] | ||||
1920 | // the rules for const_cast are the same as those used for pointers. | ||||
1921 | |||||
1922 | if (!DestType->isPointerType() && | ||||
1923 | !DestType->isMemberPointerType() && | ||||
1924 | !DestType->isObjCObjectPointerType()) { | ||||
1925 | // Cannot cast to non-pointer, non-reference type. Note that, if DestType | ||||
1926 | // was a reference type, we converted it to a pointer above. | ||||
1927 | // The status of rvalue references isn't entirely clear, but it looks like | ||||
1928 | // conversion to them is simply invalid. | ||||
1929 | // C++ 5.2.11p3: For two pointer types [...] | ||||
1930 | if (!CStyle) | ||||
1931 | msg = diag::err_bad_const_cast_dest; | ||||
1932 | return TC_NotApplicable; | ||||
1933 | } | ||||
1934 | if (DestType->isFunctionPointerType() || | ||||
1935 | DestType->isMemberFunctionPointerType()) { | ||||
1936 | // Cannot cast direct function pointers. | ||||
1937 | // C++ 5.2.11p2: [...] where T is any object type or the void type [...] | ||||
1938 | // T is the ultimate pointee of source and target type. | ||||
1939 | if (!CStyle) | ||||
1940 | msg = diag::err_bad_const_cast_dest; | ||||
1941 | return TC_NotApplicable; | ||||
1942 | } | ||||
1943 | |||||
1944 | // C++ [expr.const.cast]p3: | ||||
1945 | // "For two similar types T1 and T2, [...]" | ||||
1946 | // | ||||
1947 | // We only allow a const_cast to change cvr-qualifiers, not other kinds of | ||||
1948 | // type qualifiers. (Likewise, we ignore other changes when determining | ||||
1949 | // whether a cast casts away constness.) | ||||
1950 | if (!Self.Context.hasCvrSimilarType(SrcType, DestType)) | ||||
1951 | return TC_NotApplicable; | ||||
1952 | |||||
1953 | if (NeedToMaterializeTemporary) | ||||
1954 | // This is a const_cast from a class prvalue to an rvalue reference type. | ||||
1955 | // Materialize a temporary to store the result of the conversion. | ||||
1956 | SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(), | ||||
1957 | SrcExpr.get(), | ||||
1958 | /*IsLValueReference*/ false); | ||||
1959 | |||||
1960 | return TC_Success; | ||||
1961 | } | ||||
1962 | |||||
1963 | // Checks for undefined behavior in reinterpret_cast. | ||||
1964 | // The cases that is checked for is: | ||||
1965 | // *reinterpret_cast<T*>(&a) | ||||
1966 | // reinterpret_cast<T&>(a) | ||||
1967 | // where accessing 'a' as type 'T' will result in undefined behavior. | ||||
1968 | void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, | ||||
1969 | bool IsDereference, | ||||
1970 | SourceRange Range) { | ||||
1971 | unsigned DiagID = IsDereference ? | ||||
1972 | diag::warn_pointer_indirection_from_incompatible_type : | ||||
1973 | diag::warn_undefined_reinterpret_cast; | ||||
1974 | |||||
1975 | if (Diags.isIgnored(DiagID, Range.getBegin())) | ||||
1976 | return; | ||||
1977 | |||||
1978 | QualType SrcTy, DestTy; | ||||
1979 | if (IsDereference) { | ||||
1980 | if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { | ||||
1981 | return; | ||||
1982 | } | ||||
1983 | SrcTy = SrcType->getPointeeType(); | ||||
1984 | DestTy = DestType->getPointeeType(); | ||||
1985 | } else { | ||||
1986 | if (!DestType->getAs<ReferenceType>()) { | ||||
1987 | return; | ||||
1988 | } | ||||
1989 | SrcTy = SrcType; | ||||
1990 | DestTy = DestType->getPointeeType(); | ||||
1991 | } | ||||
1992 | |||||
1993 | // Cast is compatible if the types are the same. | ||||
1994 | if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { | ||||
1995 | return; | ||||
1996 | } | ||||
1997 | // or one of the types is a char or void type | ||||
1998 | if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || | ||||
1999 | SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { | ||||
2000 | return; | ||||
2001 | } | ||||
2002 | // or one of the types is a tag type. | ||||
2003 | if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { | ||||
2004 | return; | ||||
2005 | } | ||||
2006 | |||||
2007 | // FIXME: Scoped enums? | ||||
2008 | if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || | ||||
2009 | (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { | ||||
2010 | if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { | ||||
2011 | return; | ||||
2012 | } | ||||
2013 | } | ||||
2014 | |||||
2015 | Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; | ||||
2016 | } | ||||
2017 | |||||
2018 | static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, | ||||
2019 | QualType DestType) { | ||||
2020 | QualType SrcType = SrcExpr.get()->getType(); | ||||
2021 | if (Self.Context.hasSameType(SrcType, DestType)) | ||||
2022 | return; | ||||
2023 | if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) | ||||
2024 | if (SrcPtrTy->isObjCSelType()) { | ||||
2025 | QualType DT = DestType; | ||||
2026 | if (isa<PointerType>(DestType)) | ||||
2027 | DT = DestType->getPointeeType(); | ||||
2028 | if (!DT.getUnqualifiedType()->isVoidType()) | ||||
2029 | Self.Diag(SrcExpr.get()->getExprLoc(), | ||||
2030 | diag::warn_cast_pointer_from_sel) | ||||
2031 | << SrcType << DestType << SrcExpr.get()->getSourceRange(); | ||||
2032 | } | ||||
2033 | } | ||||
2034 | |||||
2035 | /// Diagnose casts that change the calling convention of a pointer to a function | ||||
2036 | /// defined in the current TU. | ||||
2037 | static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, | ||||
2038 | QualType DstType, SourceRange OpRange) { | ||||
2039 | // Check if this cast would change the calling convention of a function | ||||
2040 | // pointer type. | ||||
2041 | QualType SrcType = SrcExpr.get()->getType(); | ||||
2042 | if (Self.Context.hasSameType(SrcType, DstType) || | ||||
2043 | !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType()) | ||||
2044 | return; | ||||
2045 | const auto *SrcFTy = | ||||
2046 | SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); | ||||
2047 | const auto *DstFTy = | ||||
2048 | DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); | ||||
2049 | CallingConv SrcCC = SrcFTy->getCallConv(); | ||||
2050 | CallingConv DstCC = DstFTy->getCallConv(); | ||||
2051 | if (SrcCC == DstCC) | ||||
2052 | return; | ||||
2053 | |||||
2054 | // We have a calling convention cast. Check if the source is a pointer to a | ||||
2055 | // known, specific function that has already been defined. | ||||
2056 | Expr *Src = SrcExpr.get()->IgnoreParenImpCasts(); | ||||
2057 | if (auto *UO = dyn_cast<UnaryOperator>(Src)) | ||||
2058 | if (UO->getOpcode() == UO_AddrOf) | ||||
2059 | Src = UO->getSubExpr()->IgnoreParenImpCasts(); | ||||
2060 | auto *DRE = dyn_cast<DeclRefExpr>(Src); | ||||
2061 | if (!DRE) | ||||
2062 | return; | ||||
2063 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | ||||
2064 | if (!FD) | ||||
2065 | return; | ||||
2066 | |||||
2067 | // Only warn if we are casting from the default convention to a non-default | ||||
2068 | // convention. This can happen when the programmer forgot to apply the calling | ||||
2069 | // convention to the function declaration and then inserted this cast to | ||||
2070 | // satisfy the type system. | ||||
2071 | CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention( | ||||
2072 | FD->isVariadic(), FD->isCXXInstanceMember()); | ||||
2073 | if (DstCC == DefaultCC || SrcCC != DefaultCC) | ||||
2074 | return; | ||||
2075 | |||||
2076 | // Diagnose this cast, as it is probably bad. | ||||
2077 | StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC); | ||||
2078 | StringRef DstCCName = FunctionType::getNameForCallConv(DstCC); | ||||
2079 | Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv) | ||||
2080 | << SrcCCName << DstCCName << OpRange; | ||||
2081 | |||||
2082 | // The checks above are cheaper than checking if the diagnostic is enabled. | ||||
2083 | // However, it's worth checking if the warning is enabled before we construct | ||||
2084 | // a fixit. | ||||
2085 | if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin())) | ||||
2086 | return; | ||||
2087 | |||||
2088 | // Try to suggest a fixit to change the calling convention of the function | ||||
2089 | // whose address was taken. Try to use the latest macro for the convention. | ||||
2090 | // For example, users probably want to write "WINAPI" instead of "__stdcall" | ||||
2091 | // to match the Windows header declarations. | ||||
2092 | SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc(); | ||||
2093 | Preprocessor &PP = Self.getPreprocessor(); | ||||
2094 | SmallVector<TokenValue, 6> AttrTokens; | ||||
2095 | SmallString<64> CCAttrText; | ||||
2096 | llvm::raw_svector_ostream OS(CCAttrText); | ||||
2097 | if (Self.getLangOpts().MicrosoftExt) { | ||||
2098 | // __stdcall or __vectorcall | ||||
2099 | OS << "__" << DstCCName; | ||||
2100 | IdentifierInfo *II = PP.getIdentifierInfo(OS.str()); | ||||
2101 | AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) | ||||
2102 | ? TokenValue(II->getTokenID()) | ||||
2103 | : TokenValue(II)); | ||||
2104 | } else { | ||||
2105 | // __attribute__((stdcall)) or __attribute__((vectorcall)) | ||||
2106 | OS << "__attribute__((" << DstCCName << "))"; | ||||
2107 | AttrTokens.push_back(tok::kw___attribute); | ||||
2108 | AttrTokens.push_back(tok::l_paren); | ||||
2109 | AttrTokens.push_back(tok::l_paren); | ||||
2110 | IdentifierInfo *II = PP.getIdentifierInfo(DstCCName); | ||||
2111 | AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) | ||||
2112 | ? TokenValue(II->getTokenID()) | ||||
2113 | : TokenValue(II)); | ||||
2114 | AttrTokens.push_back(tok::r_paren); | ||||
2115 | AttrTokens.push_back(tok::r_paren); | ||||
2116 | } | ||||
2117 | StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens); | ||||
2118 | if (!AttrSpelling.empty()) | ||||
2119 | CCAttrText = AttrSpelling; | ||||
2120 | OS << ' '; | ||||
2121 | Self.Diag(NameLoc, diag::note_change_calling_conv_fixit) | ||||
2122 | << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText); | ||||
2123 | } | ||||
2124 | |||||
2125 | static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange, | ||||
2126 | const Expr *SrcExpr, QualType DestType, | ||||
2127 | Sema &Self) { | ||||
2128 | QualType SrcType = SrcExpr->getType(); | ||||
2129 | |||||
2130 | // Not warning on reinterpret_cast, boolean, constant expressions, etc | ||||
2131 | // are not explicit design choices, but consistent with GCC's behavior. | ||||
2132 | // Feel free to modify them if you've reason/evidence for an alternative. | ||||
2133 | if (CStyle && SrcType->isIntegralType(Self.Context) | ||||
2134 | && !SrcType->isBooleanType() | ||||
2135 | && !SrcType->isEnumeralType() | ||||
2136 | && !SrcExpr->isIntegerConstantExpr(Self.Context) | ||||
2137 | && Self.Context.getTypeSize(DestType) > | ||||
2138 | Self.Context.getTypeSize(SrcType)) { | ||||
2139 | // Separate between casts to void* and non-void* pointers. | ||||
2140 | // Some APIs use (abuse) void* for something like a user context, | ||||
2141 | // and often that value is an integer even if it isn't a pointer itself. | ||||
2142 | // Having a separate warning flag allows users to control the warning | ||||
2143 | // for their workflow. | ||||
2144 | unsigned Diag = DestType->isVoidPointerType() ? | ||||
2145 | diag::warn_int_to_void_pointer_cast | ||||
2146 | : diag::warn_int_to_pointer_cast; | ||||
2147 | Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; | ||||
2148 | } | ||||
2149 | } | ||||
2150 | |||||
2151 | static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, | ||||
2152 | ExprResult &Result) { | ||||
2153 | // We can only fix an overloaded reinterpret_cast if | ||||
2154 | // - it is a template with explicit arguments that resolves to an lvalue | ||||
2155 | // unambiguously, or | ||||
2156 | // - it is the only function in an overload set that may have its address | ||||
2157 | // taken. | ||||
2158 | |||||
2159 | Expr *E = Result.get(); | ||||
2160 | // TODO: what if this fails because of DiagnoseUseOfDecl or something | ||||
2161 | // like it? | ||||
2162 | if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( | ||||
2163 | Result, | ||||
2164 | Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr | ||||
2165 | ) && | ||||
2166 | Result.isUsable()) | ||||
2167 | return true; | ||||
2168 | |||||
2169 | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization | ||||
2170 | // preserves Result. | ||||
2171 | Result = E; | ||||
2172 | if (!Self.resolveAndFixAddressOfSingleOverloadCandidate( | ||||
2173 | Result, /*DoFunctionPointerConversion=*/true)) | ||||
2174 | return false; | ||||
2175 | return Result.isUsable(); | ||||
2176 | } | ||||
2177 | |||||
2178 | static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, | ||||
2179 | QualType DestType, bool CStyle, | ||||
2180 | SourceRange OpRange, | ||||
2181 | unsigned &msg, | ||||
2182 | CastKind &Kind) { | ||||
2183 | bool IsLValueCast = false; | ||||
2184 | |||||
2185 | DestType = Self.Context.getCanonicalType(DestType); | ||||
2186 | QualType SrcType = SrcExpr.get()->getType(); | ||||
2187 | |||||
2188 | // Is the source an overloaded name? (i.e. &foo) | ||||
2189 | // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) | ||||
2190 | if (SrcType == Self.Context.OverloadTy) { | ||||
2191 | ExprResult FixedExpr = SrcExpr; | ||||
2192 | if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) | ||||
2193 | return TC_NotApplicable; | ||||
2194 | |||||
2195 | assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr")((FixedExpr.isUsable() && "Invalid result fixing overloaded expr" ) ? static_cast<void> (0) : __assert_fail ("FixedExpr.isUsable() && \"Invalid result fixing overloaded expr\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2195, __PRETTY_FUNCTION__)); | ||||
2196 | SrcExpr = FixedExpr; | ||||
2197 | SrcType = SrcExpr.get()->getType(); | ||||
2198 | } | ||||
2199 | |||||
2200 | if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { | ||||
2201 | if (!SrcExpr.get()->isGLValue()) { | ||||
2202 | // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the | ||||
2203 | // similar comment in const_cast. | ||||
2204 | msg = diag::err_bad_cxx_cast_rvalue; | ||||
2205 | return TC_NotApplicable; | ||||
2206 | } | ||||
2207 | |||||
2208 | if (!CStyle) { | ||||
2209 | Self.CheckCompatibleReinterpretCast(SrcType, DestType, | ||||
2210 | /*IsDereference=*/false, OpRange); | ||||
2211 | } | ||||
2212 | |||||
2213 | // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the | ||||
2214 | // same effect as the conversion *reinterpret_cast<T*>(&x) with the | ||||
2215 | // built-in & and * operators. | ||||
2216 | |||||
2217 | const char *inappropriate = nullptr; | ||||
2218 | switch (SrcExpr.get()->getObjectKind()) { | ||||
2219 | case OK_Ordinary: | ||||
2220 | break; | ||||
2221 | case OK_BitField: | ||||
2222 | msg = diag::err_bad_cxx_cast_bitfield; | ||||
2223 | return TC_NotApplicable; | ||||
2224 | // FIXME: Use a specific diagnostic for the rest of these cases. | ||||
2225 | case OK_VectorComponent: inappropriate = "vector element"; break; | ||||
2226 | case OK_MatrixComponent: | ||||
2227 | inappropriate = "matrix element"; | ||||
2228 | break; | ||||
2229 | case OK_ObjCProperty: inappropriate = "property expression"; break; | ||||
2230 | case OK_ObjCSubscript: inappropriate = "container subscripting expression"; | ||||
2231 | break; | ||||
2232 | } | ||||
2233 | if (inappropriate) { | ||||
2234 | Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) | ||||
2235 | << inappropriate << DestType | ||||
2236 | << OpRange << SrcExpr.get()->getSourceRange(); | ||||
2237 | msg = 0; SrcExpr = ExprError(); | ||||
2238 | return TC_NotApplicable; | ||||
2239 | } | ||||
2240 | |||||
2241 | // This code does this transformation for the checked types. | ||||
2242 | DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); | ||||
2243 | SrcType = Self.Context.getPointerType(SrcType); | ||||
2244 | |||||
2245 | IsLValueCast = true; | ||||
2246 | } | ||||
2247 | |||||
2248 | // Canonicalize source for comparison. | ||||
2249 | SrcType = Self.Context.getCanonicalType(SrcType); | ||||
2250 | |||||
2251 | const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), | ||||
2252 | *SrcMemPtr = SrcType->getAs<MemberPointerType>(); | ||||
2253 | if (DestMemPtr && SrcMemPtr) { | ||||
2254 | // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" | ||||
2255 | // can be explicitly converted to an rvalue of type "pointer to member | ||||
2256 | // of Y of type T2" if T1 and T2 are both function types or both object | ||||
2257 | // types. | ||||
2258 | if (DestMemPtr->isMemberFunctionPointer() != | ||||
2259 | SrcMemPtr->isMemberFunctionPointer()) | ||||
2260 | return TC_NotApplicable; | ||||
2261 | |||||
2262 | if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
2263 | // We need to determine the inheritance model that the class will use if | ||||
2264 | // haven't yet. | ||||
2265 | (void)Self.isCompleteType(OpRange.getBegin(), SrcType); | ||||
2266 | (void)Self.isCompleteType(OpRange.getBegin(), DestType); | ||||
2267 | } | ||||
2268 | |||||
2269 | // Don't allow casting between member pointers of different sizes. | ||||
2270 | if (Self.Context.getTypeSize(DestMemPtr) != | ||||
2271 | Self.Context.getTypeSize(SrcMemPtr)) { | ||||
2272 | msg = diag::err_bad_cxx_cast_member_pointer_size; | ||||
2273 | return TC_Failed; | ||||
2274 | } | ||||
2275 | |||||
2276 | // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away | ||||
2277 | // constness. | ||||
2278 | // A reinterpret_cast followed by a const_cast can, though, so in C-style, | ||||
2279 | // we accept it. | ||||
2280 | if (auto CACK = | ||||
2281 | CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, | ||||
2282 | /*CheckObjCLifetime=*/CStyle)) | ||||
2283 | return getCastAwayConstnessCastKind(CACK, msg); | ||||
2284 | |||||
2285 | // A valid member pointer cast. | ||||
2286 | assert(!IsLValueCast)((!IsLValueCast) ? static_cast<void> (0) : __assert_fail ("!IsLValueCast", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2286, __PRETTY_FUNCTION__)); | ||||
2287 | Kind = CK_ReinterpretMemberPointer; | ||||
2288 | return TC_Success; | ||||
2289 | } | ||||
2290 | |||||
2291 | // See below for the enumeral issue. | ||||
2292 | if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { | ||||
2293 | // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral | ||||
2294 | // type large enough to hold it. A value of std::nullptr_t can be | ||||
2295 | // converted to an integral type; the conversion has the same meaning | ||||
2296 | // and validity as a conversion of (void*)0 to the integral type. | ||||
2297 | if (Self.Context.getTypeSize(SrcType) > | ||||
2298 | Self.Context.getTypeSize(DestType)) { | ||||
2299 | msg = diag::err_bad_reinterpret_cast_small_int; | ||||
2300 | return TC_Failed; | ||||
2301 | } | ||||
2302 | Kind = CK_PointerToIntegral; | ||||
2303 | return TC_Success; | ||||
2304 | } | ||||
2305 | |||||
2306 | // Allow reinterpret_casts between vectors of the same size and | ||||
2307 | // between vectors and integers of the same size. | ||||
2308 | bool destIsVector = DestType->isVectorType(); | ||||
2309 | bool srcIsVector = SrcType->isVectorType(); | ||||
2310 | if (srcIsVector || destIsVector) { | ||||
2311 | // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa. | ||||
2312 | if (Self.isValidSveBitcast(SrcType, DestType)) { | ||||
2313 | Kind = CK_BitCast; | ||||
2314 | return TC_Success; | ||||
2315 | } | ||||
2316 | |||||
2317 | // The non-vector type, if any, must have integral type. This is | ||||
2318 | // the same rule that C vector casts use; note, however, that enum | ||||
2319 | // types are not integral in C++. | ||||
2320 | if ((!destIsVector && !DestType->isIntegralType(Self.Context)) || | ||||
2321 | (!srcIsVector && !SrcType->isIntegralType(Self.Context))) | ||||
2322 | return TC_NotApplicable; | ||||
2323 | |||||
2324 | // The size we want to consider is eltCount * eltSize. | ||||
2325 | // That's exactly what the lax-conversion rules will check. | ||||
2326 | if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { | ||||
2327 | Kind = CK_BitCast; | ||||
2328 | return TC_Success; | ||||
2329 | } | ||||
2330 | |||||
2331 | // Otherwise, pick a reasonable diagnostic. | ||||
2332 | if (!destIsVector) | ||||
2333 | msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; | ||||
2334 | else if (!srcIsVector) | ||||
2335 | msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; | ||||
2336 | else | ||||
2337 | msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; | ||||
2338 | |||||
2339 | return TC_Failed; | ||||
2340 | } | ||||
2341 | |||||
2342 | if (SrcType == DestType) { | ||||
2343 | // C++ 5.2.10p2 has a note that mentions that, subject to all other | ||||
2344 | // restrictions, a cast to the same type is allowed so long as it does not | ||||
2345 | // cast away constness. In C++98, the intent was not entirely clear here, | ||||
2346 | // since all other paragraphs explicitly forbid casts to the same type. | ||||
2347 | // C++11 clarifies this case with p2. | ||||
2348 | // | ||||
2349 | // The only allowed types are: integral, enumeration, pointer, or | ||||
2350 | // pointer-to-member types. We also won't restrict Obj-C pointers either. | ||||
2351 | Kind = CK_NoOp; | ||||
2352 | TryCastResult Result = TC_NotApplicable; | ||||
2353 | if (SrcType->isIntegralOrEnumerationType() || | ||||
2354 | SrcType->isAnyPointerType() || | ||||
2355 | SrcType->isMemberPointerType() || | ||||
2356 | SrcType->isBlockPointerType()) { | ||||
2357 | Result = TC_Success; | ||||
2358 | } | ||||
2359 | return Result; | ||||
2360 | } | ||||
2361 | |||||
2362 | bool destIsPtr = DestType->isAnyPointerType() || | ||||
2363 | DestType->isBlockPointerType(); | ||||
2364 | bool srcIsPtr = SrcType->isAnyPointerType() || | ||||
2365 | SrcType->isBlockPointerType(); | ||||
2366 | if (!destIsPtr && !srcIsPtr) { | ||||
2367 | // Except for std::nullptr_t->integer and lvalue->reference, which are | ||||
2368 | // handled above, at least one of the two arguments must be a pointer. | ||||
2369 | return TC_NotApplicable; | ||||
2370 | } | ||||
2371 | |||||
2372 | if (DestType->isIntegralType(Self.Context)) { | ||||
2373 | assert(srcIsPtr && "One type must be a pointer")((srcIsPtr && "One type must be a pointer") ? static_cast <void> (0) : __assert_fail ("srcIsPtr && \"One type must be a pointer\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2373, __PRETTY_FUNCTION__)); | ||||
2374 | // C++ 5.2.10p4: A pointer can be explicitly converted to any integral | ||||
2375 | // type large enough to hold it; except in Microsoft mode, where the | ||||
2376 | // integral type size doesn't matter (except we don't allow bool). | ||||
2377 | if ((Self.Context.getTypeSize(SrcType) > | ||||
2378 | Self.Context.getTypeSize(DestType))) { | ||||
2379 | bool MicrosoftException = | ||||
2380 | Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType(); | ||||
2381 | if (MicrosoftException) { | ||||
2382 | unsigned Diag = SrcType->isVoidPointerType() | ||||
2383 | ? diag::warn_void_pointer_to_int_cast | ||||
2384 | : diag::warn_pointer_to_int_cast; | ||||
2385 | Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; | ||||
2386 | } else { | ||||
2387 | msg = diag::err_bad_reinterpret_cast_small_int; | ||||
2388 | return TC_Failed; | ||||
2389 | } | ||||
2390 | } | ||||
2391 | Kind = CK_PointerToIntegral; | ||||
2392 | return TC_Success; | ||||
2393 | } | ||||
2394 | |||||
2395 | if (SrcType->isIntegralOrEnumerationType()) { | ||||
2396 | assert(destIsPtr && "One type must be a pointer")((destIsPtr && "One type must be a pointer") ? static_cast <void> (0) : __assert_fail ("destIsPtr && \"One type must be a pointer\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2396, __PRETTY_FUNCTION__)); | ||||
2397 | checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self); | ||||
2398 | // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly | ||||
2399 | // converted to a pointer. | ||||
2400 | // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not | ||||
2401 | // necessarily converted to a null pointer value.] | ||||
2402 | Kind = CK_IntegralToPointer; | ||||
2403 | return TC_Success; | ||||
2404 | } | ||||
2405 | |||||
2406 | if (!destIsPtr || !srcIsPtr) { | ||||
2407 | // With the valid non-pointer conversions out of the way, we can be even | ||||
2408 | // more stringent. | ||||
2409 | return TC_NotApplicable; | ||||
2410 | } | ||||
2411 | |||||
2412 | // Cannot convert between block pointers and Objective-C object pointers. | ||||
2413 | if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || | ||||
2414 | (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) | ||||
2415 | return TC_NotApplicable; | ||||
2416 | |||||
2417 | // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. | ||||
2418 | // The C-style cast operator can. | ||||
2419 | TryCastResult SuccessResult = TC_Success; | ||||
2420 | if (auto CACK = | ||||
2421 | CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, | ||||
2422 | /*CheckObjCLifetime=*/CStyle)) | ||||
2423 | SuccessResult = getCastAwayConstnessCastKind(CACK, msg); | ||||
2424 | |||||
2425 | if (IsAddressSpaceConversion(SrcType, DestType)) { | ||||
2426 | Kind = CK_AddressSpaceConversion; | ||||
2427 | assert(SrcType->isPointerType() && DestType->isPointerType())((SrcType->isPointerType() && DestType->isPointerType ()) ? static_cast<void> (0) : __assert_fail ("SrcType->isPointerType() && DestType->isPointerType()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2427, __PRETTY_FUNCTION__)); | ||||
2428 | if (!CStyle && | ||||
2429 | !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf( | ||||
2430 | SrcType->getPointeeType().getQualifiers())) { | ||||
2431 | SuccessResult = TC_Failed; | ||||
2432 | } | ||||
2433 | } else if (IsLValueCast) { | ||||
2434 | Kind = CK_LValueBitCast; | ||||
2435 | } else if (DestType->isObjCObjectPointerType()) { | ||||
2436 | Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); | ||||
2437 | } else if (DestType->isBlockPointerType()) { | ||||
2438 | if (!SrcType->isBlockPointerType()) { | ||||
2439 | Kind = CK_AnyPointerToBlockPointerCast; | ||||
2440 | } else { | ||||
2441 | Kind = CK_BitCast; | ||||
2442 | } | ||||
2443 | } else { | ||||
2444 | Kind = CK_BitCast; | ||||
2445 | } | ||||
2446 | |||||
2447 | // Any pointer can be cast to an Objective-C pointer type with a C-style | ||||
2448 | // cast. | ||||
2449 | if (CStyle && DestType->isObjCObjectPointerType()) { | ||||
2450 | return SuccessResult; | ||||
2451 | } | ||||
2452 | if (CStyle) | ||||
2453 | DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); | ||||
2454 | |||||
2455 | DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); | ||||
2456 | |||||
2457 | // Not casting away constness, so the only remaining check is for compatible | ||||
2458 | // pointer categories. | ||||
2459 | |||||
2460 | if (SrcType->isFunctionPointerType()) { | ||||
2461 | if (DestType->isFunctionPointerType()) { | ||||
2462 | // C++ 5.2.10p6: A pointer to a function can be explicitly converted to | ||||
2463 | // a pointer to a function of a different type. | ||||
2464 | return SuccessResult; | ||||
2465 | } | ||||
2466 | |||||
2467 | // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to | ||||
2468 | // an object type or vice versa is conditionally-supported. | ||||
2469 | // Compilers support it in C++03 too, though, because it's necessary for | ||||
2470 | // casting the return value of dlsym() and GetProcAddress(). | ||||
2471 | // FIXME: Conditionally-supported behavior should be configurable in the | ||||
2472 | // TargetInfo or similar. | ||||
2473 | Self.Diag(OpRange.getBegin(), | ||||
2474 | Self.getLangOpts().CPlusPlus11 ? | ||||
2475 | diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) | ||||
2476 | << OpRange; | ||||
2477 | return SuccessResult; | ||||
2478 | } | ||||
2479 | |||||
2480 | if (DestType->isFunctionPointerType()) { | ||||
2481 | // See above. | ||||
2482 | Self.Diag(OpRange.getBegin(), | ||||
2483 | Self.getLangOpts().CPlusPlus11 ? | ||||
2484 | diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) | ||||
2485 | << OpRange; | ||||
2486 | return SuccessResult; | ||||
2487 | } | ||||
2488 | |||||
2489 | // Diagnose address space conversion in nested pointers. | ||||
2490 | QualType DestPtee = DestType->getPointeeType().isNull() | ||||
2491 | ? DestType->getPointeeType() | ||||
2492 | : DestType->getPointeeType()->getPointeeType(); | ||||
2493 | QualType SrcPtee = SrcType->getPointeeType().isNull() | ||||
2494 | ? SrcType->getPointeeType() | ||||
2495 | : SrcType->getPointeeType()->getPointeeType(); | ||||
2496 | while (!DestPtee.isNull() && !SrcPtee.isNull()) { | ||||
2497 | if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) { | ||||
2498 | Self.Diag(OpRange.getBegin(), | ||||
2499 | diag::warn_bad_cxx_cast_nested_pointer_addr_space) | ||||
2500 | << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange(); | ||||
2501 | break; | ||||
2502 | } | ||||
2503 | DestPtee = DestPtee->getPointeeType(); | ||||
2504 | SrcPtee = SrcPtee->getPointeeType(); | ||||
2505 | } | ||||
2506 | |||||
2507 | // C++ 5.2.10p7: A pointer to an object can be explicitly converted to | ||||
2508 | // a pointer to an object of different type. | ||||
2509 | // Void pointers are not specified, but supported by every compiler out there. | ||||
2510 | // So we finish by allowing everything that remains - it's got to be two | ||||
2511 | // object pointers. | ||||
2512 | return SuccessResult; | ||||
2513 | } | ||||
2514 | |||||
2515 | static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, | ||||
2516 | QualType DestType, bool CStyle, | ||||
2517 | unsigned &msg, CastKind &Kind) { | ||||
2518 | if (!Self.getLangOpts().OpenCL) | ||||
2519 | // FIXME: As compiler doesn't have any information about overlapping addr | ||||
2520 | // spaces at the moment we have to be permissive here. | ||||
2521 | return TC_NotApplicable; | ||||
2522 | // Even though the logic below is general enough and can be applied to | ||||
2523 | // non-OpenCL mode too, we fast-path above because no other languages | ||||
2524 | // define overlapping address spaces currently. | ||||
2525 | auto SrcType = SrcExpr.get()->getType(); | ||||
2526 | // FIXME: Should this be generalized to references? The reference parameter | ||||
2527 | // however becomes a reference pointee type here and therefore rejected. | ||||
2528 | // Perhaps this is the right behavior though according to C++. | ||||
2529 | auto SrcPtrType = SrcType->getAs<PointerType>(); | ||||
2530 | if (!SrcPtrType) | ||||
2531 | return TC_NotApplicable; | ||||
2532 | auto DestPtrType = DestType->getAs<PointerType>(); | ||||
2533 | if (!DestPtrType) | ||||
2534 | return TC_NotApplicable; | ||||
2535 | auto SrcPointeeType = SrcPtrType->getPointeeType(); | ||||
2536 | auto DestPointeeType = DestPtrType->getPointeeType(); | ||||
2537 | if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) { | ||||
2538 | msg = diag::err_bad_cxx_cast_addr_space_mismatch; | ||||
2539 | return TC_Failed; | ||||
2540 | } | ||||
2541 | auto SrcPointeeTypeWithoutAS = | ||||
2542 | Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType()); | ||||
2543 | auto DestPointeeTypeWithoutAS = | ||||
2544 | Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType()); | ||||
2545 | if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS, | ||||
2546 | DestPointeeTypeWithoutAS)) { | ||||
2547 | Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace() | ||||
2548 | ? CK_NoOp | ||||
2549 | : CK_AddressSpaceConversion; | ||||
2550 | return TC_Success; | ||||
2551 | } else { | ||||
2552 | return TC_NotApplicable; | ||||
2553 | } | ||||
2554 | } | ||||
2555 | |||||
2556 | void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) { | ||||
2557 | // In OpenCL only conversions between pointers to objects in overlapping | ||||
2558 | // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps | ||||
2559 | // with any named one, except for constant. | ||||
2560 | |||||
2561 | // Converting the top level pointee addrspace is permitted for compatible | ||||
2562 | // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but | ||||
2563 | // if any of the nested pointee addrspaces differ, we emit a warning | ||||
2564 | // regardless of addrspace compatibility. This makes | ||||
2565 | // local int ** p; | ||||
2566 | // return (generic int **) p; | ||||
2567 | // warn even though local -> generic is permitted. | ||||
2568 | if (Self.getLangOpts().OpenCL) { | ||||
2569 | const Type *DestPtr, *SrcPtr; | ||||
2570 | bool Nested = false; | ||||
2571 | unsigned DiagID = diag::err_typecheck_incompatible_address_space; | ||||
2572 | DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()), | ||||
2573 | SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr()); | ||||
2574 | |||||
2575 | while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) { | ||||
2576 | const PointerType *DestPPtr = cast<PointerType>(DestPtr); | ||||
2577 | const PointerType *SrcPPtr = cast<PointerType>(SrcPtr); | ||||
2578 | QualType DestPPointee = DestPPtr->getPointeeType(); | ||||
2579 | QualType SrcPPointee = SrcPPtr->getPointeeType(); | ||||
2580 | if (Nested | ||||
2581 | ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace() | ||||
2582 | : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) { | ||||
2583 | Self.Diag(OpRange.getBegin(), DiagID) | ||||
2584 | << SrcType << DestType << Sema::AA_Casting | ||||
2585 | << SrcExpr.get()->getSourceRange(); | ||||
2586 | if (!Nested) | ||||
2587 | SrcExpr = ExprError(); | ||||
2588 | return; | ||||
2589 | } | ||||
2590 | |||||
2591 | DestPtr = DestPPtr->getPointeeType().getTypePtr(); | ||||
2592 | SrcPtr = SrcPPtr->getPointeeType().getTypePtr(); | ||||
2593 | Nested = true; | ||||
2594 | DiagID = diag::ext_nested_pointer_qualifier_mismatch; | ||||
2595 | } | ||||
2596 | } | ||||
2597 | } | ||||
2598 | |||||
2599 | void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, | ||||
2600 | bool ListInitialization) { | ||||
2601 | assert(Self.getLangOpts().CPlusPlus)((Self.getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail ("Self.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2601, __PRETTY_FUNCTION__)); | ||||
2602 | |||||
2603 | // Handle placeholders. | ||||
2604 | if (isPlaceholder()) { | ||||
2605 | // C-style casts can resolve __unknown_any types. | ||||
2606 | if (claimPlaceholder(BuiltinType::UnknownAny)) { | ||||
2607 | SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, | ||||
2608 | SrcExpr.get(), Kind, | ||||
2609 | ValueKind, BasePath); | ||||
2610 | return; | ||||
2611 | } | ||||
2612 | |||||
2613 | checkNonOverloadPlaceholders(); | ||||
2614 | if (SrcExpr.isInvalid()) | ||||
2615 | return; | ||||
2616 | } | ||||
2617 | |||||
2618 | // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". | ||||
2619 | // This test is outside everything else because it's the only case where | ||||
2620 | // a non-lvalue-reference target type does not lead to decay. | ||||
2621 | if (DestType->isVoidType()) { | ||||
2622 | Kind = CK_ToVoid; | ||||
2623 | |||||
2624 | if (claimPlaceholder(BuiltinType::Overload)) { | ||||
2625 | Self.ResolveAndFixSingleFunctionTemplateSpecialization( | ||||
2626 | SrcExpr, /* Decay Function to ptr */ false, | ||||
2627 | /* Complain */ true, DestRange, DestType, | ||||
2628 | diag::err_bad_cstyle_cast_overload); | ||||
2629 | if (SrcExpr.isInvalid()) | ||||
2630 | return; | ||||
2631 | } | ||||
2632 | |||||
2633 | SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); | ||||
2634 | return; | ||||
2635 | } | ||||
2636 | |||||
2637 | // If the type is dependent, we won't do any other semantic analysis now. | ||||
2638 | if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || | ||||
2639 | SrcExpr.get()->isValueDependent()) { | ||||
2640 | assert(Kind == CK_Dependent)((Kind == CK_Dependent) ? static_cast<void> (0) : __assert_fail ("Kind == CK_Dependent", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2640, __PRETTY_FUNCTION__)); | ||||
2641 | return; | ||||
2642 | } | ||||
2643 | |||||
2644 | if (ValueKind == VK_RValue && !DestType->isRecordType() && | ||||
2645 | !isPlaceholder(BuiltinType::Overload)) { | ||||
2646 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); | ||||
2647 | if (SrcExpr.isInvalid()) | ||||
2648 | return; | ||||
2649 | } | ||||
2650 | |||||
2651 | // AltiVec vector initialization with a single literal. | ||||
2652 | if (const VectorType *vecTy = DestType->getAs<VectorType>()) | ||||
2653 | if (vecTy->getVectorKind() == VectorType::AltiVecVector | ||||
2654 | && (SrcExpr.get()->getType()->isIntegerType() | ||||
2655 | || SrcExpr.get()->getType()->isFloatingType())) { | ||||
2656 | Kind = CK_VectorSplat; | ||||
2657 | SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); | ||||
2658 | return; | ||||
2659 | } | ||||
2660 | |||||
2661 | // C++ [expr.cast]p5: The conversions performed by | ||||
2662 | // - a const_cast, | ||||
2663 | // - a static_cast, | ||||
2664 | // - a static_cast followed by a const_cast, | ||||
2665 | // - a reinterpret_cast, or | ||||
2666 | // - a reinterpret_cast followed by a const_cast, | ||||
2667 | // can be performed using the cast notation of explicit type conversion. | ||||
2668 | // [...] If a conversion can be interpreted in more than one of the ways | ||||
2669 | // listed above, the interpretation that appears first in the list is used, | ||||
2670 | // even if a cast resulting from that interpretation is ill-formed. | ||||
2671 | // In plain language, this means trying a const_cast ... | ||||
2672 | // Note that for address space we check compatibility after const_cast. | ||||
2673 | unsigned msg = diag::err_bad_cxx_cast_generic; | ||||
2674 | TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, | ||||
2675 | /*CStyle*/ true, msg); | ||||
2676 | if (SrcExpr.isInvalid()) | ||||
2677 | return; | ||||
2678 | if (isValidCast(tcr)) | ||||
2679 | Kind = CK_NoOp; | ||||
2680 | |||||
2681 | Sema::CheckedConversionKind CCK = | ||||
2682 | FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast; | ||||
2683 | if (tcr == TC_NotApplicable) { | ||||
2684 | tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg, | ||||
2685 | Kind); | ||||
2686 | if (SrcExpr.isInvalid()) | ||||
2687 | return; | ||||
2688 | |||||
2689 | if (tcr == TC_NotApplicable) { | ||||
2690 | // ... or if that is not possible, a static_cast, ignoring const and | ||||
2691 | // addr space, ... | ||||
2692 | tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind, | ||||
2693 | BasePath, ListInitialization); | ||||
2694 | if (SrcExpr.isInvalid()) | ||||
2695 | return; | ||||
2696 | |||||
2697 | if (tcr == TC_NotApplicable) { | ||||
2698 | // ... and finally a reinterpret_cast, ignoring const and addr space. | ||||
2699 | tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true, | ||||
2700 | OpRange, msg, Kind); | ||||
2701 | if (SrcExpr.isInvalid()) | ||||
2702 | return; | ||||
2703 | } | ||||
2704 | } | ||||
2705 | } | ||||
2706 | |||||
2707 | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | ||||
2708 | isValidCast(tcr)) | ||||
2709 | checkObjCConversion(CCK); | ||||
2710 | |||||
2711 | if (tcr != TC_Success && msg != 0) { | ||||
2712 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { | ||||
2713 | DeclAccessPair Found; | ||||
2714 | FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), | ||||
2715 | DestType, | ||||
2716 | /*Complain*/ true, | ||||
2717 | Found); | ||||
2718 | if (Fn) { | ||||
2719 | // If DestType is a function type (not to be confused with the function | ||||
2720 | // pointer type), it will be possible to resolve the function address, | ||||
2721 | // but the type cast should be considered as failure. | ||||
2722 | OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; | ||||
2723 | Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) | ||||
2724 | << OE->getName() << DestType << OpRange | ||||
2725 | << OE->getQualifierLoc().getSourceRange(); | ||||
2726 | Self.NoteAllOverloadCandidates(SrcExpr.get()); | ||||
2727 | } | ||||
2728 | } else { | ||||
2729 | diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), | ||||
2730 | OpRange, SrcExpr.get(), DestType, ListInitialization); | ||||
2731 | } | ||||
2732 | } | ||||
2733 | |||||
2734 | if (isValidCast(tcr)) { | ||||
2735 | if (Kind == CK_BitCast) | ||||
2736 | checkCastAlign(); | ||||
2737 | |||||
2738 | if (!checkCastFunctionType(Self, SrcExpr, DestType)) | ||||
2739 | Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type) | ||||
2740 | << SrcExpr.get()->getType() << DestType << OpRange; | ||||
2741 | |||||
2742 | } else { | ||||
2743 | SrcExpr = ExprError(); | ||||
2744 | } | ||||
2745 | } | ||||
2746 | |||||
2747 | /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a | ||||
2748 | /// non-matching type. Such as enum function call to int, int call to | ||||
2749 | /// pointer; etc. Cast to 'void' is an exception. | ||||
2750 | static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, | ||||
2751 | QualType DestType) { | ||||
2752 | if (Self.Diags.isIgnored(diag::warn_bad_function_cast, | ||||
2753 | SrcExpr.get()->getExprLoc())) | ||||
2754 | return; | ||||
2755 | |||||
2756 | if (!isa<CallExpr>(SrcExpr.get())) | ||||
2757 | return; | ||||
2758 | |||||
2759 | QualType SrcType = SrcExpr.get()->getType(); | ||||
2760 | if (DestType.getUnqualifiedType()->isVoidType()) | ||||
2761 | return; | ||||
2762 | if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) | ||||
2763 | && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) | ||||
2764 | return; | ||||
2765 | if (SrcType->isIntegerType() && DestType->isIntegerType() && | ||||
2766 | (SrcType->isBooleanType() == DestType->isBooleanType()) && | ||||
2767 | (SrcType->isEnumeralType() == DestType->isEnumeralType())) | ||||
2768 | return; | ||||
2769 | if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) | ||||
2770 | return; | ||||
2771 | if (SrcType->isEnumeralType() && DestType->isEnumeralType()) | ||||
2772 | return; | ||||
2773 | if (SrcType->isComplexType() && DestType->isComplexType()) | ||||
2774 | return; | ||||
2775 | if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) | ||||
2776 | return; | ||||
2777 | if (SrcType->isFixedPointType() && DestType->isFixedPointType()) | ||||
2778 | return; | ||||
2779 | |||||
2780 | Self.Diag(SrcExpr.get()->getExprLoc(), | ||||
2781 | diag::warn_bad_function_cast) | ||||
2782 | << SrcType << DestType << SrcExpr.get()->getSourceRange(); | ||||
2783 | } | ||||
2784 | |||||
2785 | /// Check the semantics of a C-style cast operation, in C. | ||||
2786 | void CastOperation::CheckCStyleCast() { | ||||
2787 | assert(!Self.getLangOpts().CPlusPlus)((!Self.getLangOpts().CPlusPlus) ? static_cast<void> (0 ) : __assert_fail ("!Self.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2787, __PRETTY_FUNCTION__)); | ||||
2788 | |||||
2789 | // C-style casts can resolve __unknown_any types. | ||||
2790 | if (claimPlaceholder(BuiltinType::UnknownAny)) { | ||||
2791 | SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, | ||||
2792 | SrcExpr.get(), Kind, | ||||
2793 | ValueKind, BasePath); | ||||
2794 | return; | ||||
2795 | } | ||||
2796 | |||||
2797 | // C99 6.5.4p2: the cast type needs to be void or scalar and the expression | ||||
2798 | // type needs to be scalar. | ||||
2799 | if (DestType->isVoidType()) { | ||||
2800 | // We don't necessarily do lvalue-to-rvalue conversions on this. | ||||
2801 | SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); | ||||
2802 | if (SrcExpr.isInvalid()) | ||||
2803 | return; | ||||
2804 | |||||
2805 | // Cast to void allows any expr type. | ||||
2806 | Kind = CK_ToVoid; | ||||
2807 | return; | ||||
2808 | } | ||||
2809 | |||||
2810 | // If the type is dependent, we won't do any other semantic analysis now. | ||||
2811 | if (Self.getASTContext().isDependenceAllowed() && | ||||
2812 | (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || | ||||
2813 | SrcExpr.get()->isValueDependent())) { | ||||
2814 | assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||(((DestType->containsErrors() || SrcExpr.get()->containsErrors () || SrcExpr.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(DestType->containsErrors() || SrcExpr.get()->containsErrors() || SrcExpr.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2816, __PRETTY_FUNCTION__)) | ||||
2815 | SrcExpr.get()->containsErrors()) &&(((DestType->containsErrors() || SrcExpr.get()->containsErrors () || SrcExpr.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(DestType->containsErrors() || SrcExpr.get()->containsErrors() || SrcExpr.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2816, __PRETTY_FUNCTION__)) | ||||
2816 | "should only occur in error-recovery path.")(((DestType->containsErrors() || SrcExpr.get()->containsErrors () || SrcExpr.get()->containsErrors()) && "should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("(DestType->containsErrors() || SrcExpr.get()->containsErrors() || SrcExpr.get()->containsErrors()) && \"should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2816, __PRETTY_FUNCTION__)); | ||||
2817 | assert(Kind == CK_Dependent)((Kind == CK_Dependent) ? static_cast<void> (0) : __assert_fail ("Kind == CK_Dependent", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2817, __PRETTY_FUNCTION__)); | ||||
2818 | return; | ||||
2819 | } | ||||
2820 | |||||
2821 | // Overloads are allowed with C extensions, so we need to support them. | ||||
2822 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { | ||||
2823 | DeclAccessPair DAP; | ||||
2824 | if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( | ||||
2825 | SrcExpr.get(), DestType, /*Complain=*/true, DAP)) | ||||
2826 | SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); | ||||
2827 | else | ||||
2828 | return; | ||||
2829 | assert(SrcExpr.isUsable())((SrcExpr.isUsable()) ? static_cast<void> (0) : __assert_fail ("SrcExpr.isUsable()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2829, __PRETTY_FUNCTION__)); | ||||
2830 | } | ||||
2831 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); | ||||
2832 | if (SrcExpr.isInvalid()) | ||||
2833 | return; | ||||
2834 | QualType SrcType = SrcExpr.get()->getType(); | ||||
2835 | |||||
2836 | assert(!SrcType->isPlaceholderType())((!SrcType->isPlaceholderType()) ? static_cast<void> (0) : __assert_fail ("!SrcType->isPlaceholderType()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 2836, __PRETTY_FUNCTION__)); | ||||
2837 | |||||
2838 | checkAddressSpaceCast(SrcType, DestType); | ||||
2839 | if (SrcExpr.isInvalid()) | ||||
2840 | return; | ||||
2841 | |||||
2842 | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, | ||||
2843 | diag::err_typecheck_cast_to_incomplete)) { | ||||
2844 | SrcExpr = ExprError(); | ||||
2845 | return; | ||||
2846 | } | ||||
2847 | |||||
2848 | // Allow casting a sizeless built-in type to itself. | ||||
2849 | if (DestType->isSizelessBuiltinType() && | ||||
2850 | Self.Context.hasSameUnqualifiedType(DestType, SrcType)) { | ||||
2851 | Kind = CK_NoOp; | ||||
2852 | return; | ||||
2853 | } | ||||
2854 | |||||
2855 | // Allow bitcasting between compatible SVE vector types. | ||||
2856 | if ((SrcType->isVectorType() || DestType->isVectorType()) && | ||||
2857 | Self.isValidSveBitcast(SrcType, DestType)) { | ||||
2858 | Kind = CK_BitCast; | ||||
2859 | return; | ||||
2860 | } | ||||
2861 | |||||
2862 | if (!DestType->isScalarType() && !DestType->isVectorType() && | ||||
2863 | !DestType->isMatrixType()) { | ||||
2864 | const RecordType *DestRecordTy = DestType->getAs<RecordType>(); | ||||
2865 | |||||
2866 | if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ | ||||
2867 | // GCC struct/union extension: allow cast to self. | ||||
2868 | Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) | ||||
2869 | << DestType << SrcExpr.get()->getSourceRange(); | ||||
2870 | Kind = CK_NoOp; | ||||
2871 | return; | ||||
2872 | } | ||||
2873 | |||||
2874 | // GCC's cast to union extension. | ||||
2875 | if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { | ||||
2876 | RecordDecl *RD = DestRecordTy->getDecl(); | ||||
2877 | if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) { | ||||
2878 | Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) | ||||
2879 | << SrcExpr.get()->getSourceRange(); | ||||
2880 | Kind = CK_ToUnion; | ||||
2881 | return; | ||||
2882 | } else { | ||||
2883 | Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) | ||||
2884 | << SrcType << SrcExpr.get()->getSourceRange(); | ||||
2885 | SrcExpr = ExprError(); | ||||
2886 | return; | ||||
2887 | } | ||||
2888 | } | ||||
2889 | |||||
2890 | // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type. | ||||
2891 | if (Self.getLangOpts().OpenCL && DestType->isEventT()) { | ||||
2892 | Expr::EvalResult Result; | ||||
2893 | if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) { | ||||
2894 | llvm::APSInt CastInt = Result.Val.getInt(); | ||||
2895 | if (0 == CastInt) { | ||||
2896 | Kind = CK_ZeroToOCLOpaqueType; | ||||
2897 | return; | ||||
2898 | } | ||||
2899 | Self.Diag(OpRange.getBegin(), | ||||
2900 | diag::err_opencl_cast_non_zero_to_event_t) | ||||
2901 | << CastInt.toString(10) << SrcExpr.get()->getSourceRange(); | ||||
2902 | SrcExpr = ExprError(); | ||||
2903 | return; | ||||
2904 | } | ||||
2905 | } | ||||
2906 | |||||
2907 | // Reject any other conversions to non-scalar types. | ||||
2908 | Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) | ||||
2909 | << DestType << SrcExpr.get()->getSourceRange(); | ||||
2910 | SrcExpr = ExprError(); | ||||
2911 | return; | ||||
2912 | } | ||||
2913 | |||||
2914 | // The type we're casting to is known to be a scalar, a vector, or a matrix. | ||||
2915 | |||||
2916 | // Require the operand to be a scalar, a vector, or a matrix. | ||||
2917 | if (!SrcType->isScalarType() && !SrcType->isVectorType() && | ||||
2918 | !SrcType->isMatrixType()) { | ||||
2919 | Self.Diag(SrcExpr.get()->getExprLoc(), | ||||
2920 | diag::err_typecheck_expect_scalar_operand) | ||||
2921 | << SrcType << SrcExpr.get()->getSourceRange(); | ||||
2922 | SrcExpr = ExprError(); | ||||
2923 | return; | ||||
2924 | } | ||||
2925 | |||||
2926 | if (DestType->isExtVectorType()) { | ||||
2927 | SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); | ||||
2928 | return; | ||||
2929 | } | ||||
2930 | |||||
2931 | if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) { | ||||
2932 | if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) | ||||
2933 | SrcExpr = ExprError(); | ||||
2934 | return; | ||||
2935 | } | ||||
2936 | |||||
2937 | if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { | ||||
2938 | if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && | ||||
2939 | (SrcType->isIntegerType() || SrcType->isFloatingType())) { | ||||
2940 | Kind = CK_VectorSplat; | ||||
2941 | SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); | ||||
2942 | } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { | ||||
2943 | SrcExpr = ExprError(); | ||||
2944 | } | ||||
2945 | return; | ||||
2946 | } | ||||
2947 | |||||
2948 | if (SrcType->isVectorType()) { | ||||
2949 | if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) | ||||
2950 | SrcExpr = ExprError(); | ||||
2951 | return; | ||||
2952 | } | ||||
2953 | |||||
2954 | // The source and target types are both scalars, i.e. | ||||
2955 | // - arithmetic types (fundamental, enum, and complex) | ||||
2956 | // - all kinds of pointers | ||||
2957 | // Note that member pointers were filtered out with C++, above. | ||||
2958 | |||||
2959 | if (isa<ObjCSelectorExpr>(SrcExpr.get())) { | ||||
2960 | Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); | ||||
2961 | SrcExpr = ExprError(); | ||||
2962 | return; | ||||
2963 | } | ||||
2964 | |||||
2965 | // Can't cast to or from bfloat | ||||
2966 | if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) { | ||||
2967 | Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16) | ||||
2968 | << SrcExpr.get()->getSourceRange(); | ||||
2969 | SrcExpr = ExprError(); | ||||
2970 | return; | ||||
2971 | } | ||||
2972 | if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) { | ||||
2973 | Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16) | ||||
2974 | << SrcExpr.get()->getSourceRange(); | ||||
2975 | SrcExpr = ExprError(); | ||||
2976 | return; | ||||
2977 | } | ||||
2978 | |||||
2979 | // If either type is a pointer, the other type has to be either an | ||||
2980 | // integer or a pointer. | ||||
2981 | if (!DestType->isArithmeticType()) { | ||||
2982 | if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { | ||||
2983 | Self.Diag(SrcExpr.get()->getExprLoc(), | ||||
2984 | diag::err_cast_pointer_from_non_pointer_int) | ||||
2985 | << SrcType << SrcExpr.get()->getSourceRange(); | ||||
2986 | SrcExpr = ExprError(); | ||||
2987 | return; | ||||
2988 | } | ||||
2989 | checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType, | ||||
2990 | Self); | ||||
2991 | } else if (!SrcType->isArithmeticType()) { | ||||
2992 | if (!DestType->isIntegralType(Self.Context) && | ||||
2993 | DestType->isArithmeticType()) { | ||||
2994 | Self.Diag(SrcExpr.get()->getBeginLoc(), | ||||
2995 | diag::err_cast_pointer_to_non_pointer_int) | ||||
2996 | << DestType << SrcExpr.get()->getSourceRange(); | ||||
2997 | SrcExpr = ExprError(); | ||||
2998 | return; | ||||
2999 | } | ||||
3000 | |||||
3001 | if ((Self.Context.getTypeSize(SrcType) > | ||||
3002 | Self.Context.getTypeSize(DestType)) && | ||||
3003 | !DestType->isBooleanType()) { | ||||
3004 | // C 6.3.2.3p6: Any pointer type may be converted to an integer type. | ||||
3005 | // Except as previously specified, the result is implementation-defined. | ||||
3006 | // If the result cannot be represented in the integer type, the behavior | ||||
3007 | // is undefined. The result need not be in the range of values of any | ||||
3008 | // integer type. | ||||
3009 | unsigned Diag; | ||||
3010 | if (SrcType->isVoidPointerType()) | ||||
3011 | Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast | ||||
3012 | : diag::warn_void_pointer_to_int_cast; | ||||
3013 | else if (DestType->isEnumeralType()) | ||||
3014 | Diag = diag::warn_pointer_to_enum_cast; | ||||
3015 | else | ||||
3016 | Diag = diag::warn_pointer_to_int_cast; | ||||
3017 | Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; | ||||
3018 | } | ||||
3019 | } | ||||
3020 | |||||
3021 | if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption( | ||||
3022 | "cl_khr_fp16", Self.getLangOpts())) { | ||||
3023 | if (DestType->isHalfType()) { | ||||
3024 | Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half) | ||||
3025 | << DestType << SrcExpr.get()->getSourceRange(); | ||||
3026 | SrcExpr = ExprError(); | ||||
3027 | return; | ||||
3028 | } | ||||
3029 | } | ||||
3030 | |||||
3031 | // ARC imposes extra restrictions on casts. | ||||
3032 | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) { | ||||
3033 | checkObjCConversion(Sema::CCK_CStyleCast); | ||||
3034 | if (SrcExpr.isInvalid()) | ||||
3035 | return; | ||||
3036 | |||||
3037 | const PointerType *CastPtr = DestType->getAs<PointerType>(); | ||||
3038 | if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) { | ||||
3039 | if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { | ||||
3040 | Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); | ||||
3041 | Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); | ||||
3042 | if (CastPtr->getPointeeType()->isObjCLifetimeType() && | ||||
3043 | ExprPtr->getPointeeType()->isObjCLifetimeType() && | ||||
3044 | !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { | ||||
3045 | Self.Diag(SrcExpr.get()->getBeginLoc(), | ||||
3046 | diag::err_typecheck_incompatible_ownership) | ||||
3047 | << SrcType << DestType << Sema::AA_Casting | ||||
3048 | << SrcExpr.get()->getSourceRange(); | ||||
3049 | return; | ||||
3050 | } | ||||
3051 | } | ||||
3052 | } | ||||
3053 | else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { | ||||
3054 | Self.Diag(SrcExpr.get()->getBeginLoc(), | ||||
3055 | diag::err_arc_convesion_of_weak_unavailable) | ||||
3056 | << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); | ||||
3057 | SrcExpr = ExprError(); | ||||
3058 | return; | ||||
3059 | } | ||||
3060 | } | ||||
3061 | |||||
3062 | if (!checkCastFunctionType(Self, SrcExpr, DestType)) | ||||
3063 | Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type) | ||||
3064 | << SrcType << DestType << OpRange; | ||||
3065 | |||||
3066 | DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); | ||||
3067 | DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); | ||||
3068 | DiagnoseBadFunctionCast(Self, SrcExpr, DestType); | ||||
3069 | Kind = Self.PrepareScalarCast(SrcExpr, DestType); | ||||
3070 | if (SrcExpr.isInvalid()) | ||||
3071 | return; | ||||
3072 | |||||
3073 | if (Kind == CK_BitCast) | ||||
3074 | checkCastAlign(); | ||||
3075 | } | ||||
3076 | |||||
3077 | void CastOperation::CheckBuiltinBitCast() { | ||||
3078 | QualType SrcType = SrcExpr.get()->getType(); | ||||
3079 | |||||
3080 | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, | ||||
3081 | diag::err_typecheck_cast_to_incomplete) || | ||||
3082 | Self.RequireCompleteType(OpRange.getBegin(), SrcType, | ||||
3083 | diag::err_incomplete_type)) { | ||||
3084 | SrcExpr = ExprError(); | ||||
3085 | return; | ||||
3086 | } | ||||
3087 | |||||
3088 | if (SrcExpr.get()->isRValue()) | ||||
3089 | SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(), | ||||
3090 | /*IsLValueReference=*/false); | ||||
3091 | |||||
3092 | CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType); | ||||
3093 | CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType); | ||||
3094 | if (DestSize != SourceSize) { | ||||
3095 | Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch) | ||||
3096 | << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity(); | ||||
3097 | SrcExpr = ExprError(); | ||||
3098 | return; | ||||
3099 | } | ||||
3100 | |||||
3101 | if (!DestType.isTriviallyCopyableType(Self.Context)) { | ||||
3102 | Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) | ||||
3103 | << 1; | ||||
3104 | SrcExpr = ExprError(); | ||||
3105 | return; | ||||
3106 | } | ||||
3107 | |||||
3108 | if (!SrcType.isTriviallyCopyableType(Self.Context)) { | ||||
3109 | Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) | ||||
3110 | << 0; | ||||
3111 | SrcExpr = ExprError(); | ||||
3112 | return; | ||||
3113 | } | ||||
3114 | |||||
3115 | Kind = CK_LValueToRValueBitCast; | ||||
3116 | } | ||||
3117 | |||||
3118 | /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either | ||||
3119 | /// const, volatile or both. | ||||
3120 | static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, | ||||
3121 | QualType DestType) { | ||||
3122 | if (SrcExpr.isInvalid()) | ||||
3123 | return; | ||||
3124 | |||||
3125 | QualType SrcType = SrcExpr.get()->getType(); | ||||
3126 | if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) || | ||||
3127 | DestType->isLValueReferenceType())) | ||||
3128 | return; | ||||
3129 | |||||
3130 | QualType TheOffendingSrcType, TheOffendingDestType; | ||||
3131 | Qualifiers CastAwayQualifiers; | ||||
3132 | if (CastsAwayConstness(Self, SrcType, DestType, true, false, | ||||
3133 | &TheOffendingSrcType, &TheOffendingDestType, | ||||
3134 | &CastAwayQualifiers) != | ||||
3135 | CastAwayConstnessKind::CACK_Similar) | ||||
3136 | return; | ||||
3137 | |||||
3138 | // FIXME: 'restrict' is not properly handled here. | ||||
3139 | int qualifiers = -1; | ||||
3140 | if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { | ||||
3141 | qualifiers = 0; | ||||
3142 | } else if (CastAwayQualifiers.hasConst()) { | ||||
3143 | qualifiers = 1; | ||||
3144 | } else if (CastAwayQualifiers.hasVolatile()) { | ||||
3145 | qualifiers = 2; | ||||
3146 | } | ||||
3147 | // This is a variant of int **x; const int **y = (const int **)x; | ||||
3148 | if (qualifiers == -1) | ||||
3149 | Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2) | ||||
3150 | << SrcType << DestType; | ||||
3151 | else | ||||
3152 | Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual) | ||||
3153 | << TheOffendingSrcType << TheOffendingDestType << qualifiers; | ||||
3154 | } | ||||
3155 | |||||
3156 | ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, | ||||
3157 | TypeSourceInfo *CastTypeInfo, | ||||
3158 | SourceLocation RPLoc, | ||||
3159 | Expr *CastExpr) { | ||||
3160 | CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); | ||||
3161 | Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); | ||||
3162 | Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc()); | ||||
3163 | |||||
3164 | if (getLangOpts().CPlusPlus) { | ||||
3165 | Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false, | ||||
3166 | isa<InitListExpr>(CastExpr)); | ||||
3167 | } else { | ||||
3168 | Op.CheckCStyleCast(); | ||||
3169 | } | ||||
3170 | |||||
3171 | if (Op.SrcExpr.isInvalid()) | ||||
3172 | return ExprError(); | ||||
3173 | |||||
3174 | // -Wcast-qual | ||||
3175 | DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType); | ||||
3176 | |||||
3177 | return Op.complete(CStyleCastExpr::Create( | ||||
3178 | Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), | ||||
3179 | &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc)); | ||||
3180 | } | ||||
3181 | |||||
3182 | ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, | ||||
3183 | QualType Type, | ||||
3184 | SourceLocation LPLoc, | ||||
3185 | Expr *CastExpr, | ||||
3186 | SourceLocation RPLoc) { | ||||
3187 | assert(LPLoc.isValid() && "List-initialization shouldn't get here.")((LPLoc.isValid() && "List-initialization shouldn't get here." ) ? static_cast<void> (0) : __assert_fail ("LPLoc.isValid() && \"List-initialization shouldn't get here.\"" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCast.cpp" , 3187, __PRETTY_FUNCTION__)); | ||||
3188 | CastOperation Op(*this, Type, CastExpr); | ||||
3189 | Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); | ||||
3190 | Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc()); | ||||
3191 | |||||
3192 | Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false); | ||||
3193 | if (Op.SrcExpr.isInvalid()) | ||||
3194 | return ExprError(); | ||||
3195 | |||||
3196 | auto *SubExpr = Op.SrcExpr.get(); | ||||
3197 | if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) | ||||
3198 | SubExpr = BindExpr->getSubExpr(); | ||||
3199 | if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) | ||||
3200 | ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); | ||||
3201 | |||||
3202 | return Op.complete(CXXFunctionalCastExpr::Create( | ||||
3203 | Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind, | ||||
3204 | Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc)); | ||||
3205 | } |
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/DependenceFlags.h" |
21 | #include "clang/AST/NestedNameSpecifier.h" |
22 | #include "clang/AST/TemplateName.h" |
23 | #include "clang/Basic/AddressSpaces.h" |
24 | #include "clang/Basic/AttrKinds.h" |
25 | #include "clang/Basic/Diagnostic.h" |
26 | #include "clang/Basic/ExceptionSpecificationType.h" |
27 | #include "clang/Basic/LLVM.h" |
28 | #include "clang/Basic/Linkage.h" |
29 | #include "clang/Basic/PartialDiagnostic.h" |
30 | #include "clang/Basic/SourceLocation.h" |
31 | #include "clang/Basic/Specifiers.h" |
32 | #include "clang/Basic/Visibility.h" |
33 | #include "llvm/ADT/APInt.h" |
34 | #include "llvm/ADT/APSInt.h" |
35 | #include "llvm/ADT/ArrayRef.h" |
36 | #include "llvm/ADT/FoldingSet.h" |
37 | #include "llvm/ADT/None.h" |
38 | #include "llvm/ADT/Optional.h" |
39 | #include "llvm/ADT/PointerIntPair.h" |
40 | #include "llvm/ADT/PointerUnion.h" |
41 | #include "llvm/ADT/StringRef.h" |
42 | #include "llvm/ADT/Twine.h" |
43 | #include "llvm/ADT/iterator_range.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/Compiler.h" |
46 | #include "llvm/Support/ErrorHandling.h" |
47 | #include "llvm/Support/PointerLikeTypeTraits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include "llvm/Support/type_traits.h" |
50 | #include <cassert> |
51 | #include <cstddef> |
52 | #include <cstdint> |
53 | #include <cstring> |
54 | #include <string> |
55 | #include <type_traits> |
56 | #include <utility> |
57 | |
58 | namespace clang { |
59 | |
60 | class ExtQuals; |
61 | class QualType; |
62 | class ConceptDecl; |
63 | class TagDecl; |
64 | class TemplateParameterList; |
65 | class Type; |
66 | |
67 | enum { |
68 | TypeAlignmentInBits = 4, |
69 | TypeAlignment = 1 << TypeAlignmentInBits |
70 | }; |
71 | |
72 | namespace serialization { |
73 | template <class T> class AbstractTypeReader; |
74 | template <class T> class AbstractTypeWriter; |
75 | } |
76 | |
77 | } // namespace clang |
78 | |
79 | namespace llvm { |
80 | |
81 | template <typename T> |
82 | struct PointerLikeTypeTraits; |
83 | template<> |
84 | struct PointerLikeTypeTraits< ::clang::Type*> { |
85 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
86 | |
87 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
88 | return static_cast< ::clang::Type*>(P); |
89 | } |
90 | |
91 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
92 | }; |
93 | |
94 | template<> |
95 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
96 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
97 | |
98 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
99 | return static_cast< ::clang::ExtQuals*>(P); |
100 | } |
101 | |
102 | static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; |
103 | }; |
104 | |
105 | } // namespace llvm |
106 | |
107 | namespace clang { |
108 | |
109 | class ASTContext; |
110 | template <typename> class CanQual; |
111 | class CXXRecordDecl; |
112 | class DeclContext; |
113 | class EnumDecl; |
114 | class Expr; |
115 | class ExtQualsTypeCommonBase; |
116 | class FunctionDecl; |
117 | class IdentifierInfo; |
118 | class NamedDecl; |
119 | class ObjCInterfaceDecl; |
120 | class ObjCProtocolDecl; |
121 | class ObjCTypeParamDecl; |
122 | struct PrintingPolicy; |
123 | class RecordDecl; |
124 | class Stmt; |
125 | class TagDecl; |
126 | class TemplateArgument; |
127 | class TemplateArgumentListInfo; |
128 | class TemplateArgumentLoc; |
129 | class TemplateTypeParmDecl; |
130 | class TypedefNameDecl; |
131 | class UnresolvedUsingTypenameDecl; |
132 | |
133 | using CanQualType = CanQual<Type>; |
134 | |
135 | // Provide forward declarations for all of the *Type classes. |
136 | #define TYPE(Class, Base) class Class##Type; |
137 | #include "clang/AST/TypeNodes.inc" |
138 | |
139 | /// The collection of all-type qualifiers we support. |
140 | /// Clang supports five independent qualifiers: |
141 | /// * C99: const, volatile, and restrict |
142 | /// * MS: __unaligned |
143 | /// * Embedded C (TR18037): address spaces |
144 | /// * Objective C: the GC attributes (none, weak, or strong) |
145 | class Qualifiers { |
146 | public: |
147 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
148 | Const = 0x1, |
149 | Restrict = 0x2, |
150 | Volatile = 0x4, |
151 | CVRMask = Const | Volatile | Restrict |
152 | }; |
153 | |
154 | enum GC { |
155 | GCNone = 0, |
156 | Weak, |
157 | Strong |
158 | }; |
159 | |
160 | enum ObjCLifetime { |
161 | /// There is no lifetime qualification on this type. |
162 | OCL_None, |
163 | |
164 | /// This object can be modified without requiring retains or |
165 | /// releases. |
166 | OCL_ExplicitNone, |
167 | |
168 | /// Assigning into this object requires the old value to be |
169 | /// released and the new value to be retained. The timing of the |
170 | /// release of the old value is inexact: it may be moved to |
171 | /// immediately after the last known point where the value is |
172 | /// live. |
173 | OCL_Strong, |
174 | |
175 | /// Reading or writing from this object requires a barrier call. |
176 | OCL_Weak, |
177 | |
178 | /// Assigning into this object requires a lifetime extension. |
179 | OCL_Autoreleasing |
180 | }; |
181 | |
182 | enum { |
183 | /// The maximum supported address space number. |
184 | /// 23 bits should be enough for anyone. |
185 | MaxAddressSpace = 0x7fffffu, |
186 | |
187 | /// The width of the "fast" qualifier mask. |
188 | FastWidth = 3, |
189 | |
190 | /// The fast qualifier mask. |
191 | FastMask = (1 << FastWidth) - 1 |
192 | }; |
193 | |
194 | /// Returns the common set of qualifiers while removing them from |
195 | /// the given sets. |
196 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
197 | // If both are only CVR-qualified, bit operations are sufficient. |
198 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
199 | Qualifiers Q; |
200 | Q.Mask = L.Mask & R.Mask; |
201 | L.Mask &= ~Q.Mask; |
202 | R.Mask &= ~Q.Mask; |
203 | return Q; |
204 | } |
205 | |
206 | Qualifiers Q; |
207 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
208 | Q.addCVRQualifiers(CommonCRV); |
209 | L.removeCVRQualifiers(CommonCRV); |
210 | R.removeCVRQualifiers(CommonCRV); |
211 | |
212 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
213 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
214 | L.removeObjCGCAttr(); |
215 | R.removeObjCGCAttr(); |
216 | } |
217 | |
218 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
219 | Q.setObjCLifetime(L.getObjCLifetime()); |
220 | L.removeObjCLifetime(); |
221 | R.removeObjCLifetime(); |
222 | } |
223 | |
224 | if (L.getAddressSpace() == R.getAddressSpace()) { |
225 | Q.setAddressSpace(L.getAddressSpace()); |
226 | L.removeAddressSpace(); |
227 | R.removeAddressSpace(); |
228 | } |
229 | return Q; |
230 | } |
231 | |
232 | static Qualifiers fromFastMask(unsigned Mask) { |
233 | Qualifiers Qs; |
234 | Qs.addFastQualifiers(Mask); |
235 | return Qs; |
236 | } |
237 | |
238 | static Qualifiers fromCVRMask(unsigned CVR) { |
239 | Qualifiers Qs; |
240 | Qs.addCVRQualifiers(CVR); |
241 | return Qs; |
242 | } |
243 | |
244 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
245 | Qualifiers Qs; |
246 | Qs.addCVRUQualifiers(CVRU); |
247 | return Qs; |
248 | } |
249 | |
250 | // Deserialize qualifiers from an opaque representation. |
251 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
252 | Qualifiers Qs; |
253 | Qs.Mask = opaque; |
254 | return Qs; |
255 | } |
256 | |
257 | // Serialize these qualifiers into an opaque representation. |
258 | unsigned getAsOpaqueValue() const { |
259 | return Mask; |
260 | } |
261 | |
262 | bool hasConst() const { return Mask & Const; } |
263 | bool hasOnlyConst() const { return Mask == Const; } |
264 | void removeConst() { Mask &= ~Const; } |
265 | void addConst() { Mask |= Const; } |
266 | |
267 | bool hasVolatile() const { return Mask & Volatile; } |
268 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
269 | void removeVolatile() { Mask &= ~Volatile; } |
270 | void addVolatile() { Mask |= Volatile; } |
271 | |
272 | bool hasRestrict() const { return Mask & Restrict; } |
273 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
274 | void removeRestrict() { Mask &= ~Restrict; } |
275 | void addRestrict() { Mask |= Restrict; } |
276 | |
277 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
278 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
279 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
280 | |
281 | void setCVRQualifiers(unsigned mask) { |
282 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 282, __PRETTY_FUNCTION__)); |
283 | Mask = (Mask & ~CVRMask) | mask; |
284 | } |
285 | void removeCVRQualifiers(unsigned mask) { |
286 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 286, __PRETTY_FUNCTION__)); |
287 | Mask &= ~mask; |
288 | } |
289 | void removeCVRQualifiers() { |
290 | removeCVRQualifiers(CVRMask); |
291 | } |
292 | void addCVRQualifiers(unsigned mask) { |
293 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 293, __PRETTY_FUNCTION__)); |
294 | Mask |= mask; |
295 | } |
296 | void addCVRUQualifiers(unsigned mask) { |
297 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 297, __PRETTY_FUNCTION__)); |
298 | Mask |= mask; |
299 | } |
300 | |
301 | bool hasUnaligned() const { return Mask & UMask; } |
302 | void setUnaligned(bool flag) { |
303 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
304 | } |
305 | void removeUnaligned() { Mask &= ~UMask; } |
306 | void addUnaligned() { Mask |= UMask; } |
307 | |
308 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
309 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
310 | void setObjCGCAttr(GC type) { |
311 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
312 | } |
313 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
314 | void addObjCGCAttr(GC type) { |
315 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 315, __PRETTY_FUNCTION__)); |
316 | setObjCGCAttr(type); |
317 | } |
318 | Qualifiers withoutObjCGCAttr() const { |
319 | Qualifiers qs = *this; |
320 | qs.removeObjCGCAttr(); |
321 | return qs; |
322 | } |
323 | Qualifiers withoutObjCLifetime() const { |
324 | Qualifiers qs = *this; |
325 | qs.removeObjCLifetime(); |
326 | return qs; |
327 | } |
328 | Qualifiers withoutAddressSpace() const { |
329 | Qualifiers qs = *this; |
330 | qs.removeAddressSpace(); |
331 | return qs; |
332 | } |
333 | |
334 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
335 | ObjCLifetime getObjCLifetime() const { |
336 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
337 | } |
338 | void setObjCLifetime(ObjCLifetime type) { |
339 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
340 | } |
341 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
342 | void addObjCLifetime(ObjCLifetime type) { |
343 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 343, __PRETTY_FUNCTION__)); |
344 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 344, __PRETTY_FUNCTION__)); |
345 | Mask |= (type << LifetimeShift); |
346 | } |
347 | |
348 | /// True if the lifetime is neither None or ExplicitNone. |
349 | bool hasNonTrivialObjCLifetime() const { |
350 | ObjCLifetime lifetime = getObjCLifetime(); |
351 | return (lifetime > OCL_ExplicitNone); |
352 | } |
353 | |
354 | /// True if the lifetime is either strong or weak. |
355 | bool hasStrongOrWeakObjCLifetime() const { |
356 | ObjCLifetime lifetime = getObjCLifetime(); |
357 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
358 | } |
359 | |
360 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
361 | LangAS getAddressSpace() const { |
362 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
363 | } |
364 | bool hasTargetSpecificAddressSpace() const { |
365 | return isTargetAddressSpace(getAddressSpace()); |
366 | } |
367 | /// Get the address space attribute value to be printed by diagnostics. |
368 | unsigned getAddressSpaceAttributePrintValue() const { |
369 | auto Addr = getAddressSpace(); |
370 | // This function is not supposed to be used with language specific |
371 | // address spaces. If that happens, the diagnostic message should consider |
372 | // printing the QualType instead of the address space value. |
373 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 373, __PRETTY_FUNCTION__)); |
374 | if (Addr != LangAS::Default) |
375 | return toTargetAddressSpace(Addr); |
376 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
377 | // since it cannot differentiate the situation where 0 denotes the default |
378 | // address space or user specified __attribute__((address_space(0))). |
379 | return 0; |
380 | } |
381 | void setAddressSpace(LangAS space) { |
382 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 382, __PRETTY_FUNCTION__)); |
383 | Mask = (Mask & ~AddressSpaceMask) |
384 | | (((uint32_t) space) << AddressSpaceShift); |
385 | } |
386 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
387 | void addAddressSpace(LangAS space) { |
388 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 388, __PRETTY_FUNCTION__)); |
389 | setAddressSpace(space); |
390 | } |
391 | |
392 | // Fast qualifiers are those that can be allocated directly |
393 | // on a QualType object. |
394 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
395 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
396 | void setFastQualifiers(unsigned mask) { |
397 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 397, __PRETTY_FUNCTION__)); |
398 | Mask = (Mask & ~FastMask) | mask; |
399 | } |
400 | void removeFastQualifiers(unsigned mask) { |
401 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 401, __PRETTY_FUNCTION__)); |
402 | Mask &= ~mask; |
403 | } |
404 | void removeFastQualifiers() { |
405 | removeFastQualifiers(FastMask); |
406 | } |
407 | void addFastQualifiers(unsigned mask) { |
408 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 408, __PRETTY_FUNCTION__)); |
409 | Mask |= mask; |
410 | } |
411 | |
412 | /// Return true if the set contains any qualifiers which require an ExtQuals |
413 | /// node to be allocated. |
414 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
415 | Qualifiers getNonFastQualifiers() const { |
416 | Qualifiers Quals = *this; |
417 | Quals.setFastQualifiers(0); |
418 | return Quals; |
419 | } |
420 | |
421 | /// Return true if the set contains any qualifiers. |
422 | bool hasQualifiers() const { return Mask; } |
423 | bool empty() const { return !Mask; } |
424 | |
425 | /// Add the qualifiers from the given set to this set. |
426 | void addQualifiers(Qualifiers Q) { |
427 | // If the other set doesn't have any non-boolean qualifiers, just |
428 | // bit-or it in. |
429 | if (!(Q.Mask & ~CVRMask)) |
430 | Mask |= Q.Mask; |
431 | else { |
432 | Mask |= (Q.Mask & CVRMask); |
433 | if (Q.hasAddressSpace()) |
434 | addAddressSpace(Q.getAddressSpace()); |
435 | if (Q.hasObjCGCAttr()) |
436 | addObjCGCAttr(Q.getObjCGCAttr()); |
437 | if (Q.hasObjCLifetime()) |
438 | addObjCLifetime(Q.getObjCLifetime()); |
439 | } |
440 | } |
441 | |
442 | /// Remove the qualifiers from the given set from this set. |
443 | void removeQualifiers(Qualifiers Q) { |
444 | // If the other set doesn't have any non-boolean qualifiers, just |
445 | // bit-and the inverse in. |
446 | if (!(Q.Mask & ~CVRMask)) |
447 | Mask &= ~Q.Mask; |
448 | else { |
449 | Mask &= ~(Q.Mask & CVRMask); |
450 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
451 | removeObjCGCAttr(); |
452 | if (getObjCLifetime() == Q.getObjCLifetime()) |
453 | removeObjCLifetime(); |
454 | if (getAddressSpace() == Q.getAddressSpace()) |
455 | removeAddressSpace(); |
456 | } |
457 | } |
458 | |
459 | /// Add the qualifiers from the given set to this set, given that |
460 | /// they don't conflict. |
461 | void addConsistentQualifiers(Qualifiers qs) { |
462 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)) |
463 | !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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 463, __PRETTY_FUNCTION__)); |
464 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)) |
465 | !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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 465, __PRETTY_FUNCTION__)); |
466 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)) |
467 | !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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 467, __PRETTY_FUNCTION__)); |
468 | Mask |= qs.Mask; |
469 | } |
470 | |
471 | /// Returns true if address space A is equal to or a superset of B. |
472 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
473 | /// overlapping address spaces. |
474 | /// CL1.1 or CL1.2: |
475 | /// every address space is a superset of itself. |
476 | /// CL2.0 adds: |
477 | /// __generic is a superset of any address space except for __constant. |
478 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
479 | // Address spaces must match exactly. |
480 | return A == B || |
481 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
482 | // for __constant can be used as __generic. |
483 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || |
484 | // We also define global_device and global_host address spaces, |
485 | // to distinguish global pointers allocated on host from pointers |
486 | // allocated on device, which are a subset of __global. |
487 | (A == LangAS::opencl_global && (B == LangAS::opencl_global_device || |
488 | B == LangAS::opencl_global_host)) || |
489 | // Consider pointer size address spaces to be equivalent to default. |
490 | ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && |
491 | (isPtrSizeAddressSpace(B) || B == LangAS::Default)); |
492 | } |
493 | |
494 | /// Returns true if the address space in these qualifiers is equal to or |
495 | /// a superset of the address space in the argument qualifiers. |
496 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
497 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
498 | } |
499 | |
500 | /// Determines if these qualifiers compatibly include another set. |
501 | /// Generally this answers the question of whether an object with the other |
502 | /// qualifiers can be safely used as an object with these qualifiers. |
503 | bool compatiblyIncludes(Qualifiers other) const { |
504 | return isAddressSpaceSupersetOf(other) && |
505 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
506 | // be changed. |
507 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
508 | !other.hasObjCGCAttr()) && |
509 | // ObjC lifetime qualifiers must match exactly. |
510 | getObjCLifetime() == other.getObjCLifetime() && |
511 | // CVR qualifiers may subset. |
512 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
513 | // U qualifier may superset. |
514 | (!other.hasUnaligned() || hasUnaligned()); |
515 | } |
516 | |
517 | /// Determines if these qualifiers compatibly include another set of |
518 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
519 | /// |
520 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
521 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
522 | /// including set also contains the 'const' qualifier, or both are non-__weak |
523 | /// and one is None (which can only happen in non-ARC modes). |
524 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
525 | if (getObjCLifetime() == other.getObjCLifetime()) |
526 | return true; |
527 | |
528 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
529 | return false; |
530 | |
531 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
532 | return true; |
533 | |
534 | return hasConst(); |
535 | } |
536 | |
537 | /// Determine whether this set of qualifiers is a strict superset of |
538 | /// another set of qualifiers, not considering qualifier compatibility. |
539 | bool isStrictSupersetOf(Qualifiers Other) const; |
540 | |
541 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
542 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
543 | |
544 | explicit operator bool() const { return hasQualifiers(); } |
545 | |
546 | Qualifiers &operator+=(Qualifiers R) { |
547 | addQualifiers(R); |
548 | return *this; |
549 | } |
550 | |
551 | // Union two qualifier sets. If an enumerated qualifier appears |
552 | // in both sets, use the one from the right. |
553 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
554 | L += R; |
555 | return L; |
556 | } |
557 | |
558 | Qualifiers &operator-=(Qualifiers R) { |
559 | removeQualifiers(R); |
560 | return *this; |
561 | } |
562 | |
563 | /// Compute the difference between two qualifier sets. |
564 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
565 | L -= R; |
566 | return L; |
567 | } |
568 | |
569 | std::string getAsString() const; |
570 | std::string getAsString(const PrintingPolicy &Policy) const; |
571 | |
572 | static std::string getAddrSpaceAsString(LangAS AS); |
573 | |
574 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
575 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
576 | bool appendSpaceIfNonEmpty = false) const; |
577 | |
578 | void Profile(llvm::FoldingSetNodeID &ID) const { |
579 | ID.AddInteger(Mask); |
580 | } |
581 | |
582 | private: |
583 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
584 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
585 | uint32_t Mask = 0; |
586 | |
587 | static const uint32_t UMask = 0x8; |
588 | static const uint32_t UShift = 3; |
589 | static const uint32_t GCAttrMask = 0x30; |
590 | static const uint32_t GCAttrShift = 4; |
591 | static const uint32_t LifetimeMask = 0x1C0; |
592 | static const uint32_t LifetimeShift = 6; |
593 | static const uint32_t AddressSpaceMask = |
594 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
595 | static const uint32_t AddressSpaceShift = 9; |
596 | }; |
597 | |
598 | /// A std::pair-like structure for storing a qualified type split |
599 | /// into its local qualifiers and its locally-unqualified type. |
600 | struct SplitQualType { |
601 | /// The locally-unqualified type. |
602 | const Type *Ty = nullptr; |
603 | |
604 | /// The local qualifiers. |
605 | Qualifiers Quals; |
606 | |
607 | SplitQualType() = default; |
608 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
609 | |
610 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
611 | |
612 | // Make std::tie work. |
613 | std::pair<const Type *,Qualifiers> asPair() const { |
614 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
615 | } |
616 | |
617 | friend bool operator==(SplitQualType a, SplitQualType b) { |
618 | return a.Ty == b.Ty && a.Quals == b.Quals; |
619 | } |
620 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
621 | return a.Ty != b.Ty || a.Quals != b.Quals; |
622 | } |
623 | }; |
624 | |
625 | /// The kind of type we are substituting Objective-C type arguments into. |
626 | /// |
627 | /// The kind of substitution affects the replacement of type parameters when |
628 | /// no concrete type information is provided, e.g., when dealing with an |
629 | /// unspecialized type. |
630 | enum class ObjCSubstitutionContext { |
631 | /// An ordinary type. |
632 | Ordinary, |
633 | |
634 | /// The result type of a method or function. |
635 | Result, |
636 | |
637 | /// The parameter type of a method or function. |
638 | Parameter, |
639 | |
640 | /// The type of a property. |
641 | Property, |
642 | |
643 | /// The superclass of a type. |
644 | Superclass, |
645 | }; |
646 | |
647 | /// A (possibly-)qualified type. |
648 | /// |
649 | /// For efficiency, we don't store CV-qualified types as nodes on their |
650 | /// own: instead each reference to a type stores the qualifiers. This |
651 | /// greatly reduces the number of nodes we need to allocate for types (for |
652 | /// example we only need one for 'int', 'const int', 'volatile int', |
653 | /// 'const volatile int', etc). |
654 | /// |
655 | /// As an added efficiency bonus, instead of making this a pair, we |
656 | /// just store the two bits we care about in the low bits of the |
657 | /// pointer. To handle the packing/unpacking, we make QualType be a |
658 | /// simple wrapper class that acts like a smart pointer. A third bit |
659 | /// indicates whether there are extended qualifiers present, in which |
660 | /// case the pointer points to a special structure. |
661 | class QualType { |
662 | friend class QualifierCollector; |
663 | |
664 | // Thankfully, these are efficiently composable. |
665 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
666 | Qualifiers::FastWidth> Value; |
667 | |
668 | const ExtQuals *getExtQualsUnsafe() const { |
669 | return Value.getPointer().get<const ExtQuals*>(); |
670 | } |
671 | |
672 | const Type *getTypePtrUnsafe() const { |
673 | return Value.getPointer().get<const Type*>(); |
674 | } |
675 | |
676 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
677 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 677, __PRETTY_FUNCTION__)); |
678 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
679 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
680 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
681 | } |
682 | |
683 | public: |
684 | QualType() = default; |
685 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
686 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
687 | |
688 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
689 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
690 | |
691 | /// Retrieves a pointer to the underlying (unqualified) type. |
692 | /// |
693 | /// This function requires that the type not be NULL. If the type might be |
694 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
695 | const Type *getTypePtr() const; |
696 | |
697 | const Type *getTypePtrOrNull() const; |
698 | |
699 | /// Retrieves a pointer to the name of the base type. |
700 | const IdentifierInfo *getBaseTypeIdentifier() const; |
701 | |
702 | /// Divides a QualType into its unqualified type and a set of local |
703 | /// qualifiers. |
704 | SplitQualType split() const; |
705 | |
706 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
707 | |
708 | static QualType getFromOpaquePtr(const void *Ptr) { |
709 | QualType T; |
710 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
711 | return T; |
712 | } |
713 | |
714 | const Type &operator*() const { |
715 | return *getTypePtr(); |
716 | } |
717 | |
718 | const Type *operator->() const { |
719 | return getTypePtr(); |
720 | } |
721 | |
722 | bool isCanonical() const; |
723 | bool isCanonicalAsParam() const; |
724 | |
725 | /// Return true if this QualType doesn't point to a type yet. |
726 | bool isNull() const { |
727 | return Value.getPointer().isNull(); |
728 | } |
729 | |
730 | /// Determine whether this particular QualType instance has the |
731 | /// "const" qualifier set, without looking through typedefs that may have |
732 | /// added "const" at a different level. |
733 | bool isLocalConstQualified() const { |
734 | return (getLocalFastQualifiers() & Qualifiers::Const); |
735 | } |
736 | |
737 | /// Determine whether this type is const-qualified. |
738 | bool isConstQualified() const; |
739 | |
740 | /// Determine whether this particular QualType instance has the |
741 | /// "restrict" qualifier set, without looking through typedefs that may have |
742 | /// added "restrict" at a different level. |
743 | bool isLocalRestrictQualified() const { |
744 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
745 | } |
746 | |
747 | /// Determine whether this type is restrict-qualified. |
748 | bool isRestrictQualified() const; |
749 | |
750 | /// Determine whether this particular QualType instance has the |
751 | /// "volatile" qualifier set, without looking through typedefs that may have |
752 | /// added "volatile" at a different level. |
753 | bool isLocalVolatileQualified() const { |
754 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
755 | } |
756 | |
757 | /// Determine whether this type is volatile-qualified. |
758 | bool isVolatileQualified() const; |
759 | |
760 | /// Determine whether this particular QualType instance has any |
761 | /// qualifiers, without looking through any typedefs that might add |
762 | /// qualifiers at a different level. |
763 | bool hasLocalQualifiers() const { |
764 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
765 | } |
766 | |
767 | /// Determine whether this type has any qualifiers. |
768 | bool hasQualifiers() const; |
769 | |
770 | /// Determine whether this particular QualType instance has any |
771 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
772 | /// instance. |
773 | bool hasLocalNonFastQualifiers() const { |
774 | return Value.getPointer().is<const ExtQuals*>(); |
775 | } |
776 | |
777 | /// Retrieve the set of qualifiers local to this particular QualType |
778 | /// instance, not including any qualifiers acquired through typedefs or |
779 | /// other sugar. |
780 | Qualifiers getLocalQualifiers() const; |
781 | |
782 | /// Retrieve the set of qualifiers applied to this type. |
783 | Qualifiers getQualifiers() const; |
784 | |
785 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
786 | /// local to this particular QualType instance, not including any qualifiers |
787 | /// acquired through typedefs or other sugar. |
788 | unsigned getLocalCVRQualifiers() const { |
789 | return getLocalFastQualifiers(); |
790 | } |
791 | |
792 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
793 | /// applied to this type. |
794 | unsigned getCVRQualifiers() const; |
795 | |
796 | bool isConstant(const ASTContext& Ctx) const { |
797 | return QualType::isConstant(*this, Ctx); |
798 | } |
799 | |
800 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
801 | bool isPODType(const ASTContext &Context) const; |
802 | |
803 | /// Return true if this is a POD type according to the rules of the C++98 |
804 | /// standard, regardless of the current compilation's language. |
805 | bool isCXX98PODType(const ASTContext &Context) const; |
806 | |
807 | /// Return true if this is a POD type according to the more relaxed rules |
808 | /// of the C++11 standard, regardless of the current compilation's language. |
809 | /// (C++0x [basic.types]p9). Note that, unlike |
810 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
811 | bool isCXX11PODType(const ASTContext &Context) const; |
812 | |
813 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
814 | bool isTrivialType(const ASTContext &Context) const; |
815 | |
816 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
817 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
818 | |
819 | |
820 | /// Returns true if it is a class and it might be dynamic. |
821 | bool mayBeDynamicClass() const; |
822 | |
823 | /// Returns true if it is not a class or if the class might not be dynamic. |
824 | bool mayBeNotDynamicClass() const; |
825 | |
826 | // Don't promise in the API that anything besides 'const' can be |
827 | // easily added. |
828 | |
829 | /// Add the `const` type qualifier to this QualType. |
830 | void addConst() { |
831 | addFastQualifiers(Qualifiers::Const); |
832 | } |
833 | QualType withConst() const { |
834 | return withFastQualifiers(Qualifiers::Const); |
835 | } |
836 | |
837 | /// Add the `volatile` type qualifier to this QualType. |
838 | void addVolatile() { |
839 | addFastQualifiers(Qualifiers::Volatile); |
840 | } |
841 | QualType withVolatile() const { |
842 | return withFastQualifiers(Qualifiers::Volatile); |
843 | } |
844 | |
845 | /// Add the `restrict` qualifier to this QualType. |
846 | void addRestrict() { |
847 | addFastQualifiers(Qualifiers::Restrict); |
848 | } |
849 | QualType withRestrict() const { |
850 | return withFastQualifiers(Qualifiers::Restrict); |
851 | } |
852 | |
853 | QualType withCVRQualifiers(unsigned CVR) const { |
854 | return withFastQualifiers(CVR); |
855 | } |
856 | |
857 | void addFastQualifiers(unsigned TQs) { |
858 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)) |
859 | && "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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 859, __PRETTY_FUNCTION__)); |
860 | Value.setInt(Value.getInt() | TQs); |
861 | } |
862 | |
863 | void removeLocalConst(); |
864 | void removeLocalVolatile(); |
865 | void removeLocalRestrict(); |
866 | void removeLocalCVRQualifiers(unsigned Mask); |
867 | |
868 | void removeLocalFastQualifiers() { Value.setInt(0); } |
869 | void removeLocalFastQualifiers(unsigned Mask) { |
870 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 870, __PRETTY_FUNCTION__)); |
871 | Value.setInt(Value.getInt() & ~Mask); |
872 | } |
873 | |
874 | // Creates a type with the given qualifiers in addition to any |
875 | // qualifiers already on this type. |
876 | QualType withFastQualifiers(unsigned TQs) const { |
877 | QualType T = *this; |
878 | T.addFastQualifiers(TQs); |
879 | return T; |
880 | } |
881 | |
882 | // Creates a type with exactly the given fast qualifiers, removing |
883 | // any existing fast qualifiers. |
884 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
885 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
886 | } |
887 | |
888 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
889 | QualType withoutLocalFastQualifiers() const { |
890 | QualType T = *this; |
891 | T.removeLocalFastQualifiers(); |
892 | return T; |
893 | } |
894 | |
895 | QualType getCanonicalType() const; |
896 | |
897 | /// Return this type with all of the instance-specific qualifiers |
898 | /// removed, but without removing any qualifiers that may have been applied |
899 | /// through typedefs. |
900 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
901 | |
902 | /// Retrieve the unqualified variant of the given type, |
903 | /// removing as little sugar as possible. |
904 | /// |
905 | /// This routine looks through various kinds of sugar to find the |
906 | /// least-desugared type that is unqualified. For example, given: |
907 | /// |
908 | /// \code |
909 | /// typedef int Integer; |
910 | /// typedef const Integer CInteger; |
911 | /// typedef CInteger DifferenceType; |
912 | /// \endcode |
913 | /// |
914 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
915 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
916 | /// |
917 | /// The resulting type might still be qualified if it's sugar for an array |
918 | /// type. To strip qualifiers even from within a sugared array type, use |
919 | /// ASTContext::getUnqualifiedArrayType. |
920 | inline QualType getUnqualifiedType() const; |
921 | |
922 | /// Retrieve the unqualified variant of the given type, removing as little |
923 | /// sugar as possible. |
924 | /// |
925 | /// Like getUnqualifiedType(), but also returns the set of |
926 | /// qualifiers that were built up. |
927 | /// |
928 | /// The resulting type might still be qualified if it's sugar for an array |
929 | /// type. To strip qualifiers even from within a sugared array type, use |
930 | /// ASTContext::getUnqualifiedArrayType. |
931 | inline SplitQualType getSplitUnqualifiedType() const; |
932 | |
933 | /// Determine whether this type is more qualified than the other |
934 | /// given type, requiring exact equality for non-CVR qualifiers. |
935 | bool isMoreQualifiedThan(QualType Other) const; |
936 | |
937 | /// Determine whether this type is at least as qualified as the other |
938 | /// given type, requiring exact equality for non-CVR qualifiers. |
939 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
940 | |
941 | QualType getNonReferenceType() const; |
942 | |
943 | /// Determine the type of a (typically non-lvalue) expression with the |
944 | /// specified result type. |
945 | /// |
946 | /// This routine should be used for expressions for which the return type is |
947 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
948 | /// an lvalue. It removes a top-level reference (since there are no |
949 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
950 | /// from non-class types (in C++) or all types (in C). |
951 | QualType getNonLValueExprType(const ASTContext &Context) const; |
952 | |
953 | /// Remove an outer pack expansion type (if any) from this type. Used as part |
954 | /// of converting the type of a declaration to the type of an expression that |
955 | /// references that expression. It's meaningless for an expression to have a |
956 | /// pack expansion type. |
957 | QualType getNonPackExpansionType() const; |
958 | |
959 | /// Return the specified type with any "sugar" removed from |
960 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
961 | /// the type is already concrete, it returns it unmodified. This is similar |
962 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
963 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
964 | /// concrete. |
965 | /// |
966 | /// Qualifiers are left in place. |
967 | QualType getDesugaredType(const ASTContext &Context) const { |
968 | return getDesugaredType(*this, Context); |
969 | } |
970 | |
971 | SplitQualType getSplitDesugaredType() const { |
972 | return getSplitDesugaredType(*this); |
973 | } |
974 | |
975 | /// Return the specified type with one level of "sugar" removed from |
976 | /// the type. |
977 | /// |
978 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
979 | /// of the type is already concrete, it returns it unmodified. |
980 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
981 | return getSingleStepDesugaredTypeImpl(*this, Context); |
982 | } |
983 | |
984 | /// Returns the specified type after dropping any |
985 | /// outer-level parentheses. |
986 | QualType IgnoreParens() const { |
987 | if (isa<ParenType>(*this)) |
988 | return QualType::IgnoreParens(*this); |
989 | return *this; |
990 | } |
991 | |
992 | /// Indicate whether the specified types and qualifiers are identical. |
993 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
994 | return LHS.Value == RHS.Value; |
995 | } |
996 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
997 | return LHS.Value != RHS.Value; |
998 | } |
999 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
1000 | return LHS.Value < RHS.Value; |
1001 | } |
1002 | |
1003 | static std::string getAsString(SplitQualType split, |
1004 | const PrintingPolicy &Policy) { |
1005 | return getAsString(split.Ty, split.Quals, Policy); |
1006 | } |
1007 | static std::string getAsString(const Type *ty, Qualifiers qs, |
1008 | const PrintingPolicy &Policy); |
1009 | |
1010 | std::string getAsString() const; |
1011 | std::string getAsString(const PrintingPolicy &Policy) const; |
1012 | |
1013 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
1014 | const Twine &PlaceHolder = Twine(), |
1015 | unsigned Indentation = 0) const; |
1016 | |
1017 | static void print(SplitQualType split, raw_ostream &OS, |
1018 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
1019 | unsigned Indentation = 0) { |
1020 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
1021 | } |
1022 | |
1023 | static void print(const Type *ty, Qualifiers qs, |
1024 | raw_ostream &OS, const PrintingPolicy &policy, |
1025 | const Twine &PlaceHolder, |
1026 | unsigned Indentation = 0); |
1027 | |
1028 | void getAsStringInternal(std::string &Str, |
1029 | const PrintingPolicy &Policy) const; |
1030 | |
1031 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1032 | const PrintingPolicy &policy) { |
1033 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1034 | } |
1035 | |
1036 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1037 | std::string &out, |
1038 | const PrintingPolicy &policy); |
1039 | |
1040 | class StreamedQualTypeHelper { |
1041 | const QualType &T; |
1042 | const PrintingPolicy &Policy; |
1043 | const Twine &PlaceHolder; |
1044 | unsigned Indentation; |
1045 | |
1046 | public: |
1047 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1048 | const Twine &PlaceHolder, unsigned Indentation) |
1049 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1050 | Indentation(Indentation) {} |
1051 | |
1052 | friend raw_ostream &operator<<(raw_ostream &OS, |
1053 | const StreamedQualTypeHelper &SQT) { |
1054 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1055 | return OS; |
1056 | } |
1057 | }; |
1058 | |
1059 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1060 | const Twine &PlaceHolder = Twine(), |
1061 | unsigned Indentation = 0) const { |
1062 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1063 | } |
1064 | |
1065 | void dump(const char *s) const; |
1066 | void dump() const; |
1067 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
1068 | |
1069 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1070 | ID.AddPointer(getAsOpaquePtr()); |
1071 | } |
1072 | |
1073 | /// Check if this type has any address space qualifier. |
1074 | inline bool hasAddressSpace() const; |
1075 | |
1076 | /// Return the address space of this type. |
1077 | inline LangAS getAddressSpace() const; |
1078 | |
1079 | /// Returns true if address space qualifiers overlap with T address space |
1080 | /// qualifiers. |
1081 | /// OpenCL C defines conversion rules for pointers to different address spaces |
1082 | /// and notion of overlapping address spaces. |
1083 | /// CL1.1 or CL1.2: |
1084 | /// address spaces overlap iff they are they same. |
1085 | /// OpenCL C v2.0 s6.5.5 adds: |
1086 | /// __generic overlaps with any address space except for __constant. |
1087 | bool isAddressSpaceOverlapping(QualType T) const { |
1088 | Qualifiers Q = getQualifiers(); |
1089 | Qualifiers TQ = T.getQualifiers(); |
1090 | // Address spaces overlap if at least one of them is a superset of another |
1091 | return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); |
1092 | } |
1093 | |
1094 | /// Returns gc attribute of this type. |
1095 | inline Qualifiers::GC getObjCGCAttr() const; |
1096 | |
1097 | /// true when Type is objc's weak. |
1098 | bool isObjCGCWeak() const { |
1099 | return getObjCGCAttr() == Qualifiers::Weak; |
1100 | } |
1101 | |
1102 | /// true when Type is objc's strong. |
1103 | bool isObjCGCStrong() const { |
1104 | return getObjCGCAttr() == Qualifiers::Strong; |
1105 | } |
1106 | |
1107 | /// Returns lifetime attribute of this type. |
1108 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1109 | return getQualifiers().getObjCLifetime(); |
1110 | } |
1111 | |
1112 | bool hasNonTrivialObjCLifetime() const { |
1113 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1114 | } |
1115 | |
1116 | bool hasStrongOrWeakObjCLifetime() const { |
1117 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1118 | } |
1119 | |
1120 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1121 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1122 | |
1123 | enum PrimitiveDefaultInitializeKind { |
1124 | /// The type does not fall into any of the following categories. Note that |
1125 | /// this case is zero-valued so that values of this enum can be used as a |
1126 | /// boolean condition for non-triviality. |
1127 | PDIK_Trivial, |
1128 | |
1129 | /// The type is an Objective-C retainable pointer type that is qualified |
1130 | /// with the ARC __strong qualifier. |
1131 | PDIK_ARCStrong, |
1132 | |
1133 | /// The type is an Objective-C retainable pointer type that is qualified |
1134 | /// with the ARC __weak qualifier. |
1135 | PDIK_ARCWeak, |
1136 | |
1137 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1138 | PDIK_Struct |
1139 | }; |
1140 | |
1141 | /// Functions to query basic properties of non-trivial C struct types. |
1142 | |
1143 | /// Check if this is a non-trivial type that would cause a C struct |
1144 | /// transitively containing this type to be non-trivial to default initialize |
1145 | /// and return the kind. |
1146 | PrimitiveDefaultInitializeKind |
1147 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1148 | |
1149 | enum PrimitiveCopyKind { |
1150 | /// The type does not fall into any of the following categories. Note that |
1151 | /// this case is zero-valued so that values of this enum can be used as a |
1152 | /// boolean condition for non-triviality. |
1153 | PCK_Trivial, |
1154 | |
1155 | /// The type would be trivial except that it is volatile-qualified. Types |
1156 | /// that fall into one of the other non-trivial cases may additionally be |
1157 | /// volatile-qualified. |
1158 | PCK_VolatileTrivial, |
1159 | |
1160 | /// The type is an Objective-C retainable pointer type that is qualified |
1161 | /// with the ARC __strong qualifier. |
1162 | PCK_ARCStrong, |
1163 | |
1164 | /// The type is an Objective-C retainable pointer type that is qualified |
1165 | /// with the ARC __weak qualifier. |
1166 | PCK_ARCWeak, |
1167 | |
1168 | /// The type is a struct containing a field whose type is neither |
1169 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1170 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1171 | /// semantics are too complex to express here, in part because they depend |
1172 | /// on the exact constructor or assignment operator that is chosen by |
1173 | /// overload resolution to do the copy. |
1174 | PCK_Struct |
1175 | }; |
1176 | |
1177 | /// Check if this is a non-trivial type that would cause a C struct |
1178 | /// transitively containing this type to be non-trivial to copy and return the |
1179 | /// kind. |
1180 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1181 | |
1182 | /// Check if this is a non-trivial type that would cause a C struct |
1183 | /// transitively containing this type to be non-trivial to destructively |
1184 | /// move and return the kind. Destructive move in this context is a C++-style |
1185 | /// move in which the source object is placed in a valid but unspecified state |
1186 | /// after it is moved, as opposed to a truly destructive move in which the |
1187 | /// source object is placed in an uninitialized state. |
1188 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1189 | |
1190 | enum DestructionKind { |
1191 | DK_none, |
1192 | DK_cxx_destructor, |
1193 | DK_objc_strong_lifetime, |
1194 | DK_objc_weak_lifetime, |
1195 | DK_nontrivial_c_struct |
1196 | }; |
1197 | |
1198 | /// Returns a nonzero value if objects of this type require |
1199 | /// non-trivial work to clean up after. Non-zero because it's |
1200 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1201 | /// something require destruction. |
1202 | DestructionKind isDestructedType() const { |
1203 | return isDestructedTypeImpl(*this); |
1204 | } |
1205 | |
1206 | /// Check if this is or contains a C union that is non-trivial to |
1207 | /// default-initialize, which is a union that has a member that is non-trivial |
1208 | /// to default-initialize. If this returns true, |
1209 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1210 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1211 | |
1212 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1213 | /// which is a union that has a member that is non-trivial to destruct. If |
1214 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1215 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1216 | |
1217 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1218 | /// is a union that has a member that is non-trivial to copy. If this returns |
1219 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1220 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1221 | |
1222 | /// Determine whether expressions of the given type are forbidden |
1223 | /// from being lvalues in C. |
1224 | /// |
1225 | /// The expression types that are forbidden to be lvalues are: |
1226 | /// - 'void', but not qualified void |
1227 | /// - function types |
1228 | /// |
1229 | /// The exact rule here is C99 6.3.2.1: |
1230 | /// An lvalue is an expression with an object type or an incomplete |
1231 | /// type other than void. |
1232 | bool isCForbiddenLValueType() const; |
1233 | |
1234 | /// Substitute type arguments for the Objective-C type parameters used in the |
1235 | /// subject type. |
1236 | /// |
1237 | /// \param ctx ASTContext in which the type exists. |
1238 | /// |
1239 | /// \param typeArgs The type arguments that will be substituted for the |
1240 | /// Objective-C type parameters in the subject type, which are generally |
1241 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1242 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1243 | /// for the context. |
1244 | /// |
1245 | /// \param context The context in which the subject type was written. |
1246 | /// |
1247 | /// \returns the resulting type. |
1248 | QualType substObjCTypeArgs(ASTContext &ctx, |
1249 | ArrayRef<QualType> typeArgs, |
1250 | ObjCSubstitutionContext context) const; |
1251 | |
1252 | /// Substitute type arguments from an object type for the Objective-C type |
1253 | /// parameters used in the subject type. |
1254 | /// |
1255 | /// This operation combines the computation of type arguments for |
1256 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1257 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1258 | /// callers that need to perform a single substitution in isolation. |
1259 | /// |
1260 | /// \param objectType The type of the object whose member type we're |
1261 | /// substituting into. For example, this might be the receiver of a message |
1262 | /// or the base of a property access. |
1263 | /// |
1264 | /// \param dc The declaration context from which the subject type was |
1265 | /// retrieved, which indicates (for example) which type parameters should |
1266 | /// be substituted. |
1267 | /// |
1268 | /// \param context The context in which the subject type was written. |
1269 | /// |
1270 | /// \returns the subject type after replacing all of the Objective-C type |
1271 | /// parameters with their corresponding arguments. |
1272 | QualType substObjCMemberType(QualType objectType, |
1273 | const DeclContext *dc, |
1274 | ObjCSubstitutionContext context) const; |
1275 | |
1276 | /// Strip Objective-C "__kindof" types from the given type. |
1277 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1278 | |
1279 | /// Remove all qualifiers including _Atomic. |
1280 | QualType getAtomicUnqualifiedType() const; |
1281 | |
1282 | private: |
1283 | // These methods are implemented in a separate translation unit; |
1284 | // "static"-ize them to avoid creating temporary QualTypes in the |
1285 | // caller. |
1286 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1287 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1288 | static SplitQualType getSplitDesugaredType(QualType T); |
1289 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1290 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1291 | const ASTContext &C); |
1292 | static QualType IgnoreParens(QualType T); |
1293 | static DestructionKind isDestructedTypeImpl(QualType type); |
1294 | |
1295 | /// Check if \param RD is or contains a non-trivial C union. |
1296 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1297 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1298 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1299 | }; |
1300 | |
1301 | } // namespace clang |
1302 | |
1303 | namespace llvm { |
1304 | |
1305 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1306 | /// to a specific Type class. |
1307 | template<> struct simplify_type< ::clang::QualType> { |
1308 | using SimpleType = const ::clang::Type *; |
1309 | |
1310 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1311 | return Val.getTypePtr(); |
1312 | } |
1313 | }; |
1314 | |
1315 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1316 | template<> |
1317 | struct PointerLikeTypeTraits<clang::QualType> { |
1318 | static inline void *getAsVoidPointer(clang::QualType P) { |
1319 | return P.getAsOpaquePtr(); |
1320 | } |
1321 | |
1322 | static inline clang::QualType getFromVoidPointer(void *P) { |
1323 | return clang::QualType::getFromOpaquePtr(P); |
1324 | } |
1325 | |
1326 | // Various qualifiers go in low bits. |
1327 | static constexpr int NumLowBitsAvailable = 0; |
1328 | }; |
1329 | |
1330 | } // namespace llvm |
1331 | |
1332 | namespace clang { |
1333 | |
1334 | /// Base class that is common to both the \c ExtQuals and \c Type |
1335 | /// classes, which allows \c QualType to access the common fields between the |
1336 | /// two. |
1337 | class ExtQualsTypeCommonBase { |
1338 | friend class ExtQuals; |
1339 | friend class QualType; |
1340 | friend class Type; |
1341 | |
1342 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1343 | /// a self-referential pointer (for \c Type). |
1344 | /// |
1345 | /// This pointer allows an efficient mapping from a QualType to its |
1346 | /// underlying type pointer. |
1347 | const Type *const BaseType; |
1348 | |
1349 | /// The canonical type of this type. A QualType. |
1350 | QualType CanonicalType; |
1351 | |
1352 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1353 | : BaseType(baseType), CanonicalType(canon) {} |
1354 | }; |
1355 | |
1356 | /// We can encode up to four bits in the low bits of a |
1357 | /// type pointer, but there are many more type qualifiers that we want |
1358 | /// to be able to apply to an arbitrary type. Therefore we have this |
1359 | /// struct, intended to be heap-allocated and used by QualType to |
1360 | /// store qualifiers. |
1361 | /// |
1362 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1363 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1364 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1365 | /// Objective-C GC attributes) are much more rare. |
1366 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1367 | // NOTE: changing the fast qualifiers should be straightforward as |
1368 | // long as you don't make 'const' non-fast. |
1369 | // 1. Qualifiers: |
1370 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1371 | // Fast qualifiers must occupy the low-order bits. |
1372 | // b) Update Qualifiers::FastWidth and FastMask. |
1373 | // 2. QualType: |
1374 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1375 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1376 | // this header. |
1377 | // 3. ASTContext: |
1378 | // a) Update get{Volatile,Restrict}Type. |
1379 | |
1380 | /// The immutable set of qualifiers applied by this node. Always contains |
1381 | /// extended qualifiers. |
1382 | Qualifiers Quals; |
1383 | |
1384 | ExtQuals *this_() { return this; } |
1385 | |
1386 | public: |
1387 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1388 | : ExtQualsTypeCommonBase(baseType, |
1389 | canon.isNull() ? QualType(this_(), 0) : canon), |
1390 | Quals(quals) { |
1391 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)) |
1392 | && "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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1392, __PRETTY_FUNCTION__)); |
1393 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)) |
1394 | && "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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1394, __PRETTY_FUNCTION__)); |
1395 | } |
1396 | |
1397 | Qualifiers getQualifiers() const { return Quals; } |
1398 | |
1399 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1400 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1401 | |
1402 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1403 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1404 | return Quals.getObjCLifetime(); |
1405 | } |
1406 | |
1407 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1408 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1409 | |
1410 | const Type *getBaseType() const { return BaseType; } |
1411 | |
1412 | public: |
1413 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1414 | Profile(ID, getBaseType(), Quals); |
1415 | } |
1416 | |
1417 | static void Profile(llvm::FoldingSetNodeID &ID, |
1418 | const Type *BaseType, |
1419 | Qualifiers Quals) { |
1420 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1420, __PRETTY_FUNCTION__)); |
1421 | ID.AddPointer(BaseType); |
1422 | Quals.Profile(ID); |
1423 | } |
1424 | }; |
1425 | |
1426 | /// The kind of C++11 ref-qualifier associated with a function type. |
1427 | /// This determines whether a member function's "this" object can be an |
1428 | /// lvalue, rvalue, or neither. |
1429 | enum RefQualifierKind { |
1430 | /// No ref-qualifier was provided. |
1431 | RQ_None = 0, |
1432 | |
1433 | /// An lvalue ref-qualifier was provided (\c &). |
1434 | RQ_LValue, |
1435 | |
1436 | /// An rvalue ref-qualifier was provided (\c &&). |
1437 | RQ_RValue |
1438 | }; |
1439 | |
1440 | /// Which keyword(s) were used to create an AutoType. |
1441 | enum class AutoTypeKeyword { |
1442 | /// auto |
1443 | Auto, |
1444 | |
1445 | /// decltype(auto) |
1446 | DecltypeAuto, |
1447 | |
1448 | /// __auto_type (GNU extension) |
1449 | GNUAutoType |
1450 | }; |
1451 | |
1452 | /// The base class of the type hierarchy. |
1453 | /// |
1454 | /// A central concept with types is that each type always has a canonical |
1455 | /// type. A canonical type is the type with any typedef names stripped out |
1456 | /// of it or the types it references. For example, consider: |
1457 | /// |
1458 | /// typedef int foo; |
1459 | /// typedef foo* bar; |
1460 | /// 'int *' 'foo *' 'bar' |
1461 | /// |
1462 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1463 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1464 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1465 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1466 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1467 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1468 | /// is also 'int*'. |
1469 | /// |
1470 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1471 | /// information about typedefs being used. Canonical types are useful for type |
1472 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1473 | /// about whether something has a particular form (e.g. is a function type), |
1474 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1475 | /// |
1476 | /// Types, once created, are immutable. |
1477 | /// |
1478 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1479 | public: |
1480 | enum TypeClass { |
1481 | #define TYPE(Class, Base) Class, |
1482 | #define LAST_TYPE(Class) TypeLast = Class |
1483 | #define ABSTRACT_TYPE(Class, Base) |
1484 | #include "clang/AST/TypeNodes.inc" |
1485 | }; |
1486 | |
1487 | private: |
1488 | /// Bitfields required by the Type class. |
1489 | class TypeBitfields { |
1490 | friend class Type; |
1491 | template <class T> friend class TypePropertyCache; |
1492 | |
1493 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1494 | unsigned TC : 8; |
1495 | |
1496 | /// Store information on the type dependency. |
1497 | unsigned Dependence : llvm::BitWidth<TypeDependence>; |
1498 | |
1499 | /// True if the cache (i.e. the bitfields here starting with |
1500 | /// 'Cache') is valid. |
1501 | mutable unsigned CacheValid : 1; |
1502 | |
1503 | /// Linkage of this type. |
1504 | mutable unsigned CachedLinkage : 3; |
1505 | |
1506 | /// Whether this type involves and local or unnamed types. |
1507 | mutable unsigned CachedLocalOrUnnamed : 1; |
1508 | |
1509 | /// Whether this type comes from an AST file. |
1510 | mutable unsigned FromAST : 1; |
1511 | |
1512 | bool isCacheValid() const { |
1513 | return CacheValid; |
1514 | } |
1515 | |
1516 | Linkage getLinkage() const { |
1517 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1517, __PRETTY_FUNCTION__)); |
1518 | return static_cast<Linkage>(CachedLinkage); |
1519 | } |
1520 | |
1521 | bool hasLocalOrUnnamedType() const { |
1522 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 1522, __PRETTY_FUNCTION__)); |
1523 | return CachedLocalOrUnnamed; |
1524 | } |
1525 | }; |
1526 | enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; |
1527 | |
1528 | protected: |
1529 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1530 | // into Type. |
1531 | |
1532 | class ArrayTypeBitfields { |
1533 | friend class ArrayType; |
1534 | |
1535 | unsigned : NumTypeBits; |
1536 | |
1537 | /// CVR qualifiers from declarations like |
1538 | /// 'int X[static restrict 4]'. For function parameters only. |
1539 | unsigned IndexTypeQuals : 3; |
1540 | |
1541 | /// Storage class qualifiers from declarations like |
1542 | /// 'int X[static restrict 4]'. For function parameters only. |
1543 | /// Actually an ArrayType::ArraySizeModifier. |
1544 | unsigned SizeModifier : 3; |
1545 | }; |
1546 | |
1547 | class ConstantArrayTypeBitfields { |
1548 | friend class ConstantArrayType; |
1549 | |
1550 | unsigned : NumTypeBits + 3 + 3; |
1551 | |
1552 | /// Whether we have a stored size expression. |
1553 | unsigned HasStoredSizeExpr : 1; |
1554 | }; |
1555 | |
1556 | class BuiltinTypeBitfields { |
1557 | friend class BuiltinType; |
1558 | |
1559 | unsigned : NumTypeBits; |
1560 | |
1561 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1562 | unsigned Kind : 8; |
1563 | }; |
1564 | |
1565 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1566 | /// Only common bits are stored here. Additional uncommon bits are stored |
1567 | /// in a trailing object after FunctionProtoType. |
1568 | class FunctionTypeBitfields { |
1569 | friend class FunctionProtoType; |
1570 | friend class FunctionType; |
1571 | |
1572 | unsigned : NumTypeBits; |
1573 | |
1574 | /// Extra information which affects how the function is called, like |
1575 | /// regparm and the calling convention. |
1576 | unsigned ExtInfo : 13; |
1577 | |
1578 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1579 | /// |
1580 | /// This is a value of type \c RefQualifierKind. |
1581 | unsigned RefQualifier : 2; |
1582 | |
1583 | /// Used only by FunctionProtoType, put here to pack with the |
1584 | /// other bitfields. |
1585 | /// The qualifiers are part of FunctionProtoType because... |
1586 | /// |
1587 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1588 | /// cv-qualifier-seq, [...], are part of the function type. |
1589 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1590 | /// Whether this function has extended Qualifiers. |
1591 | unsigned HasExtQuals : 1; |
1592 | |
1593 | /// The number of parameters this function has, not counting '...'. |
1594 | /// According to [implimits] 8 bits should be enough here but this is |
1595 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1596 | /// keep NumParams as wide as reasonably possible. |
1597 | unsigned NumParams : 16; |
1598 | |
1599 | /// The type of exception specification this function has. |
1600 | unsigned ExceptionSpecType : 4; |
1601 | |
1602 | /// Whether this function has extended parameter information. |
1603 | unsigned HasExtParameterInfos : 1; |
1604 | |
1605 | /// Whether the function is variadic. |
1606 | unsigned Variadic : 1; |
1607 | |
1608 | /// Whether this function has a trailing return type. |
1609 | unsigned HasTrailingReturn : 1; |
1610 | }; |
1611 | |
1612 | class ObjCObjectTypeBitfields { |
1613 | friend class ObjCObjectType; |
1614 | |
1615 | unsigned : NumTypeBits; |
1616 | |
1617 | /// The number of type arguments stored directly on this object type. |
1618 | unsigned NumTypeArgs : 7; |
1619 | |
1620 | /// The number of protocols stored directly on this object type. |
1621 | unsigned NumProtocols : 6; |
1622 | |
1623 | /// Whether this is a "kindof" type. |
1624 | unsigned IsKindOf : 1; |
1625 | }; |
1626 | |
1627 | class ReferenceTypeBitfields { |
1628 | friend class ReferenceType; |
1629 | |
1630 | unsigned : NumTypeBits; |
1631 | |
1632 | /// True if the type was originally spelled with an lvalue sigil. |
1633 | /// This is never true of rvalue references but can also be false |
1634 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1635 | /// as follows: |
1636 | /// |
1637 | /// typedef int &ref; // lvalue, spelled lvalue |
1638 | /// typedef int &&rvref; // rvalue |
1639 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1640 | /// ref &&a; // lvalue, inner ref |
1641 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1642 | /// rvref &&a; // rvalue, inner ref |
1643 | unsigned SpelledAsLValue : 1; |
1644 | |
1645 | /// True if the inner type is a reference type. This only happens |
1646 | /// in non-canonical forms. |
1647 | unsigned InnerRef : 1; |
1648 | }; |
1649 | |
1650 | class TypeWithKeywordBitfields { |
1651 | friend class TypeWithKeyword; |
1652 | |
1653 | unsigned : NumTypeBits; |
1654 | |
1655 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1656 | unsigned Keyword : 8; |
1657 | }; |
1658 | |
1659 | enum { NumTypeWithKeywordBits = 8 }; |
1660 | |
1661 | class ElaboratedTypeBitfields { |
1662 | friend class ElaboratedType; |
1663 | |
1664 | unsigned : NumTypeBits; |
1665 | unsigned : NumTypeWithKeywordBits; |
1666 | |
1667 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1668 | unsigned HasOwnedTagDecl : 1; |
1669 | }; |
1670 | |
1671 | class VectorTypeBitfields { |
1672 | friend class VectorType; |
1673 | friend class DependentVectorType; |
1674 | |
1675 | unsigned : NumTypeBits; |
1676 | |
1677 | /// The kind of vector, either a generic vector type or some |
1678 | /// target-specific vector type such as for AltiVec or Neon. |
1679 | unsigned VecKind : 3; |
1680 | /// The number of elements in the vector. |
1681 | uint32_t NumElements; |
1682 | }; |
1683 | |
1684 | class AttributedTypeBitfields { |
1685 | friend class AttributedType; |
1686 | |
1687 | unsigned : NumTypeBits; |
1688 | |
1689 | /// An AttributedType::Kind |
1690 | unsigned AttrKind : 32 - NumTypeBits; |
1691 | }; |
1692 | |
1693 | class AutoTypeBitfields { |
1694 | friend class AutoType; |
1695 | |
1696 | unsigned : NumTypeBits; |
1697 | |
1698 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1699 | /// or '__auto_type'? AutoTypeKeyword value. |
1700 | unsigned Keyword : 2; |
1701 | |
1702 | /// The number of template arguments in the type-constraints, which is |
1703 | /// expected to be able to hold at least 1024 according to [implimits]. |
1704 | /// However as this limit is somewhat easy to hit with template |
1705 | /// metaprogramming we'd prefer to keep it as large as possible. |
1706 | /// At the moment it has been left as a non-bitfield since this type |
1707 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1708 | /// introduce the performance impact of a bitfield. |
1709 | unsigned NumArgs; |
1710 | }; |
1711 | |
1712 | class SubstTemplateTypeParmPackTypeBitfields { |
1713 | friend class SubstTemplateTypeParmPackType; |
1714 | |
1715 | unsigned : NumTypeBits; |
1716 | |
1717 | /// The number of template arguments in \c Arguments, which is |
1718 | /// expected to be able to hold at least 1024 according to [implimits]. |
1719 | /// However as this limit is somewhat easy to hit with template |
1720 | /// metaprogramming we'd prefer to keep it as large as possible. |
1721 | /// At the moment it has been left as a non-bitfield since this type |
1722 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1723 | /// introduce the performance impact of a bitfield. |
1724 | unsigned NumArgs; |
1725 | }; |
1726 | |
1727 | class TemplateSpecializationTypeBitfields { |
1728 | friend class TemplateSpecializationType; |
1729 | |
1730 | unsigned : NumTypeBits; |
1731 | |
1732 | /// Whether this template specialization type is a substituted type alias. |
1733 | unsigned TypeAlias : 1; |
1734 | |
1735 | /// The number of template arguments named in this class template |
1736 | /// specialization, which is expected to be able to hold at least 1024 |
1737 | /// according to [implimits]. However, as this limit is somewhat easy to |
1738 | /// hit with template metaprogramming we'd prefer to keep it as large |
1739 | /// as possible. At the moment it has been left as a non-bitfield since |
1740 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1741 | /// to introduce the performance impact of a bitfield. |
1742 | unsigned NumArgs; |
1743 | }; |
1744 | |
1745 | class DependentTemplateSpecializationTypeBitfields { |
1746 | friend class DependentTemplateSpecializationType; |
1747 | |
1748 | unsigned : NumTypeBits; |
1749 | unsigned : NumTypeWithKeywordBits; |
1750 | |
1751 | /// The number of template arguments named in this class template |
1752 | /// specialization, which is expected to be able to hold at least 1024 |
1753 | /// according to [implimits]. However, as this limit is somewhat easy to |
1754 | /// hit with template metaprogramming we'd prefer to keep it as large |
1755 | /// as possible. At the moment it has been left as a non-bitfield since |
1756 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1757 | /// to introduce the performance impact of a bitfield. |
1758 | unsigned NumArgs; |
1759 | }; |
1760 | |
1761 | class PackExpansionTypeBitfields { |
1762 | friend class PackExpansionType; |
1763 | |
1764 | unsigned : NumTypeBits; |
1765 | |
1766 | /// The number of expansions that this pack expansion will |
1767 | /// generate when substituted (+1), which is expected to be able to |
1768 | /// hold at least 1024 according to [implimits]. However, as this limit |
1769 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1770 | /// keep it as large as possible. At the moment it has been left as a |
1771 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1772 | /// there is no reason to introduce the performance impact of a bitfield. |
1773 | /// |
1774 | /// This field will only have a non-zero value when some of the parameter |
1775 | /// packs that occur within the pattern have been substituted but others |
1776 | /// have not. |
1777 | unsigned NumExpansions; |
1778 | }; |
1779 | |
1780 | union { |
1781 | TypeBitfields TypeBits; |
1782 | ArrayTypeBitfields ArrayTypeBits; |
1783 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1784 | AttributedTypeBitfields AttributedTypeBits; |
1785 | AutoTypeBitfields AutoTypeBits; |
1786 | BuiltinTypeBitfields BuiltinTypeBits; |
1787 | FunctionTypeBitfields FunctionTypeBits; |
1788 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1789 | ReferenceTypeBitfields ReferenceTypeBits; |
1790 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1791 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1792 | VectorTypeBitfields VectorTypeBits; |
1793 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1794 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1795 | DependentTemplateSpecializationTypeBitfields |
1796 | DependentTemplateSpecializationTypeBits; |
1797 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1798 | }; |
1799 | |
1800 | private: |
1801 | template <class T> friend class TypePropertyCache; |
1802 | |
1803 | /// Set whether this type comes from an AST file. |
1804 | void setFromAST(bool V = true) const { |
1805 | TypeBits.FromAST = V; |
1806 | } |
1807 | |
1808 | protected: |
1809 | friend class ASTContext; |
1810 | |
1811 | Type(TypeClass tc, QualType canon, TypeDependence Dependence) |
1812 | : ExtQualsTypeCommonBase(this, |
1813 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1814 | static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), |
1815 | "changing bitfields changed sizeof(Type)!"); |
1816 | static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, |
1817 | "Insufficient alignment!"); |
1818 | TypeBits.TC = tc; |
1819 | TypeBits.Dependence = static_cast<unsigned>(Dependence); |
1820 | TypeBits.CacheValid = false; |
1821 | TypeBits.CachedLocalOrUnnamed = false; |
1822 | TypeBits.CachedLinkage = NoLinkage; |
1823 | TypeBits.FromAST = false; |
1824 | } |
1825 | |
1826 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1827 | Type *this_() { return this; } |
1828 | |
1829 | void setDependence(TypeDependence D) { |
1830 | TypeBits.Dependence = static_cast<unsigned>(D); |
1831 | } |
1832 | |
1833 | void addDependence(TypeDependence D) { setDependence(getDependence() | D); } |
1834 | |
1835 | public: |
1836 | friend class ASTReader; |
1837 | friend class ASTWriter; |
1838 | template <class T> friend class serialization::AbstractTypeReader; |
1839 | template <class T> friend class serialization::AbstractTypeWriter; |
1840 | |
1841 | Type(const Type &) = delete; |
1842 | Type(Type &&) = delete; |
1843 | Type &operator=(const Type &) = delete; |
1844 | Type &operator=(Type &&) = delete; |
1845 | |
1846 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1847 | |
1848 | /// Whether this type comes from an AST file. |
1849 | bool isFromAST() const { return TypeBits.FromAST; } |
1850 | |
1851 | /// Whether this type is or contains an unexpanded parameter |
1852 | /// pack, used to support C++0x variadic templates. |
1853 | /// |
1854 | /// A type that contains a parameter pack shall be expanded by the |
1855 | /// ellipsis operator at some point. For example, the typedef in the |
1856 | /// following example contains an unexpanded parameter pack 'T': |
1857 | /// |
1858 | /// \code |
1859 | /// template<typename ...T> |
1860 | /// struct X { |
1861 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1862 | /// }; |
1863 | /// \endcode |
1864 | /// |
1865 | /// Note that this routine does not specify which |
1866 | bool containsUnexpandedParameterPack() const { |
1867 | return getDependence() & TypeDependence::UnexpandedPack; |
1868 | } |
1869 | |
1870 | /// Determines if this type would be canonical if it had no further |
1871 | /// qualification. |
1872 | bool isCanonicalUnqualified() const { |
1873 | return CanonicalType == QualType(this, 0); |
1874 | } |
1875 | |
1876 | /// Pull a single level of sugar off of this locally-unqualified type. |
1877 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1878 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1879 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1880 | |
1881 | /// As an extension, we classify types as one of "sized" or "sizeless"; |
1882 | /// every type is one or the other. Standard types are all sized; |
1883 | /// sizeless types are purely an extension. |
1884 | /// |
1885 | /// Sizeless types contain data with no specified size, alignment, |
1886 | /// or layout. |
1887 | bool isSizelessType() const; |
1888 | bool isSizelessBuiltinType() const; |
1889 | |
1890 | /// Determines if this is a sizeless type supported by the |
1891 | /// 'arm_sve_vector_bits' type attribute, which can be applied to a single |
1892 | /// SVE vector or predicate, excluding tuple types such as svint32x4_t. |
1893 | bool isVLSTBuiltinType() const; |
1894 | |
1895 | /// Returns the representative type for the element of an SVE builtin type. |
1896 | /// This is used to represent fixed-length SVE vectors created with the |
1897 | /// 'arm_sve_vector_bits' type attribute as VectorType. |
1898 | QualType getSveEltType(const ASTContext &Ctx) const; |
1899 | |
1900 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1901 | /// object types, function types, and incomplete types. |
1902 | |
1903 | /// Return true if this is an incomplete type. |
1904 | /// A type that can describe objects, but which lacks information needed to |
1905 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1906 | /// routine will need to determine if the size is actually required. |
1907 | /// |
1908 | /// Def If non-null, and the type refers to some kind of declaration |
1909 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1910 | /// class), will be set to the declaration. |
1911 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1912 | |
1913 | /// Return true if this is an incomplete or object |
1914 | /// type, in other words, not a function type. |
1915 | bool isIncompleteOrObjectType() const { |
1916 | return !isFunctionType(); |
1917 | } |
1918 | |
1919 | /// Determine whether this type is an object type. |
1920 | bool isObjectType() const { |
1921 | // C++ [basic.types]p8: |
1922 | // An object type is a (possibly cv-qualified) type that is not a |
1923 | // function type, not a reference type, and not a void type. |
1924 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1925 | } |
1926 | |
1927 | /// Return true if this is a literal type |
1928 | /// (C++11 [basic.types]p10) |
1929 | bool isLiteralType(const ASTContext &Ctx) const; |
1930 | |
1931 | /// Determine if this type is a structural type, per C++20 [temp.param]p7. |
1932 | bool isStructuralType() const; |
1933 | |
1934 | /// Test if this type is a standard-layout type. |
1935 | /// (C++0x [basic.type]p9) |
1936 | bool isStandardLayoutType() const; |
1937 | |
1938 | /// Helper methods to distinguish type categories. All type predicates |
1939 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1940 | |
1941 | /// Returns true if the type is a builtin type. |
1942 | bool isBuiltinType() const; |
1943 | |
1944 | /// Test for a particular builtin type. |
1945 | bool isSpecificBuiltinType(unsigned K) const; |
1946 | |
1947 | /// Test for a type which does not represent an actual type-system type but |
1948 | /// is instead used as a placeholder for various convenient purposes within |
1949 | /// Clang. All such types are BuiltinTypes. |
1950 | bool isPlaceholderType() const; |
1951 | const BuiltinType *getAsPlaceholderType() const; |
1952 | |
1953 | /// Test for a specific placeholder type. |
1954 | bool isSpecificPlaceholderType(unsigned K) const; |
1955 | |
1956 | /// Test for a placeholder type other than Overload; see |
1957 | /// BuiltinType::isNonOverloadPlaceholderType. |
1958 | bool isNonOverloadPlaceholderType() const; |
1959 | |
1960 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1961 | /// isComplexIntegerType() can be used to test for complex integers. |
1962 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1963 | bool isEnumeralType() const; |
1964 | |
1965 | /// Determine whether this type is a scoped enumeration type. |
1966 | bool isScopedEnumeralType() const; |
1967 | bool isBooleanType() const; |
1968 | bool isCharType() const; |
1969 | bool isWideCharType() const; |
1970 | bool isChar8Type() const; |
1971 | bool isChar16Type() const; |
1972 | bool isChar32Type() const; |
1973 | bool isAnyCharacterType() const; |
1974 | bool isIntegralType(const ASTContext &Ctx) const; |
1975 | |
1976 | /// Determine whether this type is an integral or enumeration type. |
1977 | bool isIntegralOrEnumerationType() const; |
1978 | |
1979 | /// Determine whether this type is an integral or unscoped enumeration type. |
1980 | bool isIntegralOrUnscopedEnumerationType() const; |
1981 | bool isUnscopedEnumerationType() const; |
1982 | |
1983 | /// Floating point categories. |
1984 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1985 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1986 | /// isComplexIntegerType() can be used to test for complex integers. |
1987 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1988 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1989 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1990 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1991 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1992 | bool isBFloat16Type() const; |
1993 | bool isFloat128Type() const; |
1994 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1995 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1996 | bool isVoidType() const; // C99 6.2.5p19 |
1997 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1998 | bool isAggregateType() const; |
1999 | bool isFundamentalType() const; |
2000 | bool isCompoundType() const; |
2001 | |
2002 | // Type Predicates: Check to see if this type is structurally the specified |
2003 | // type, ignoring typedefs and qualifiers. |
2004 | bool isFunctionType() const; |
2005 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
2006 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
2007 | bool isPointerType() const; |
2008 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
2009 | bool isBlockPointerType() const; |
2010 | bool isVoidPointerType() const; |
2011 | bool isReferenceType() const; |
2012 | bool isLValueReferenceType() const; |
2013 | bool isRValueReferenceType() const; |
2014 | bool isObjectPointerType() const; |
2015 | bool isFunctionPointerType() const; |
2016 | bool isFunctionReferenceType() const; |
2017 | bool isMemberPointerType() const; |
2018 | bool isMemberFunctionPointerType() const; |
2019 | bool isMemberDataPointerType() const; |
2020 | bool isArrayType() const; |
2021 | bool isConstantArrayType() const; |
2022 | bool isIncompleteArrayType() const; |
2023 | bool isVariableArrayType() const; |
2024 | bool isDependentSizedArrayType() const; |
2025 | bool isRecordType() const; |
2026 | bool isClassType() const; |
2027 | bool isStructureType() const; |
2028 | bool isObjCBoxableRecordType() const; |
2029 | bool isInterfaceType() const; |
2030 | bool isStructureOrClassType() const; |
2031 | bool isUnionType() const; |
2032 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2033 | bool isVectorType() const; // GCC vector type. |
2034 | bool isExtVectorType() const; // Extended vector type. |
2035 | bool isMatrixType() const; // Matrix type. |
2036 | bool isConstantMatrixType() const; // Constant matrix type. |
2037 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2038 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2039 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2040 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2041 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2042 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2043 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2044 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2045 | // for the common case. |
2046 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2047 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2048 | bool isObjCQualifiedIdType() const; // id<foo> |
2049 | bool isObjCQualifiedClassType() const; // Class<foo> |
2050 | bool isObjCObjectOrInterfaceType() const; |
2051 | bool isObjCIdType() const; // id |
2052 | bool isDecltypeType() const; |
2053 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2054 | /// qualifier? |
2055 | /// |
2056 | /// This approximates the answer to the following question: if this |
2057 | /// translation unit were compiled in ARC, would this type be qualified |
2058 | /// with __unsafe_unretained? |
2059 | bool isObjCInertUnsafeUnretainedType() const { |
2060 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2061 | } |
2062 | |
2063 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2064 | /// object type, e.g., __kindof NSView * or __kindof id |
2065 | /// <NSCopying>. |
2066 | /// |
2067 | /// \param bound Will be set to the bound on non-id subtype types, |
2068 | /// which will be (possibly specialized) Objective-C class type, or |
2069 | /// null for 'id. |
2070 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2071 | const ObjCObjectType *&bound) const; |
2072 | |
2073 | bool isObjCClassType() const; // Class |
2074 | |
2075 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2076 | /// Class type, e.g., __kindof Class <NSCopying>. |
2077 | /// |
2078 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2079 | /// here because Objective-C's type system cannot express "a class |
2080 | /// object for a subclass of NSFoo". |
2081 | bool isObjCClassOrClassKindOfType() const; |
2082 | |
2083 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2084 | bool isObjCSelType() const; // Class |
2085 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2086 | bool isObjCARCBridgableType() const; |
2087 | bool isCARCBridgableType() const; |
2088 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2089 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2090 | bool isNothrowT() const; // C++ std::nothrow_t |
2091 | bool isAlignValT() const; // C++17 std::align_val_t |
2092 | bool isStdByteType() const; // C++17 std::byte |
2093 | bool isAtomicType() const; // C11 _Atomic() |
2094 | bool isUndeducedAutoType() const; // C++11 auto or |
2095 | // C++14 decltype(auto) |
2096 | bool isTypedefNameType() const; // typedef or alias template |
2097 | |
2098 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2099 | bool is##Id##Type() const; |
2100 | #include "clang/Basic/OpenCLImageTypes.def" |
2101 | |
2102 | bool isImageType() const; // Any OpenCL image type |
2103 | |
2104 | bool isSamplerT() const; // OpenCL sampler_t |
2105 | bool isEventT() const; // OpenCL event_t |
2106 | bool isClkEventT() const; // OpenCL clk_event_t |
2107 | bool isQueueT() const; // OpenCL queue_t |
2108 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2109 | |
2110 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2111 | bool is##Id##Type() const; |
2112 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2113 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2114 | bool isOCLIntelSubgroupAVCType() const; |
2115 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2116 | |
2117 | bool isPipeType() const; // OpenCL pipe type |
2118 | bool isExtIntType() const; // Extended Int Type |
2119 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2120 | |
2121 | /// Determines if this type, which must satisfy |
2122 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2123 | /// than implicitly __strong. |
2124 | bool isObjCARCImplicitlyUnretainedType() const; |
2125 | |
2126 | /// Check if the type is the CUDA device builtin surface type. |
2127 | bool isCUDADeviceBuiltinSurfaceType() const; |
2128 | /// Check if the type is the CUDA device builtin texture type. |
2129 | bool isCUDADeviceBuiltinTextureType() const; |
2130 | |
2131 | /// Return the implicit lifetime for this type, which must not be dependent. |
2132 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2133 | |
2134 | enum ScalarTypeKind { |
2135 | STK_CPointer, |
2136 | STK_BlockPointer, |
2137 | STK_ObjCObjectPointer, |
2138 | STK_MemberPointer, |
2139 | STK_Bool, |
2140 | STK_Integral, |
2141 | STK_Floating, |
2142 | STK_IntegralComplex, |
2143 | STK_FloatingComplex, |
2144 | STK_FixedPoint |
2145 | }; |
2146 | |
2147 | /// Given that this is a scalar type, classify it. |
2148 | ScalarTypeKind getScalarTypeKind() const; |
2149 | |
2150 | TypeDependence getDependence() const { |
2151 | return static_cast<TypeDependence>(TypeBits.Dependence); |
2152 | } |
2153 | |
2154 | /// Whether this type is an error type. |
2155 | bool containsErrors() const { |
2156 | return getDependence() & TypeDependence::Error; |
2157 | } |
2158 | |
2159 | /// Whether this type is a dependent type, meaning that its definition |
2160 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2161 | bool isDependentType() const { |
2162 | return getDependence() & TypeDependence::Dependent; |
2163 | } |
2164 | |
2165 | /// Determine whether this type is an instantiation-dependent type, |
2166 | /// meaning that the type involves a template parameter (even if the |
2167 | /// definition does not actually depend on the type substituted for that |
2168 | /// template parameter). |
2169 | bool isInstantiationDependentType() const { |
2170 | return getDependence() & TypeDependence::Instantiation; |
2171 | } |
2172 | |
2173 | /// Determine whether this type is an undeduced type, meaning that |
2174 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2175 | /// deduced. |
2176 | bool isUndeducedType() const; |
2177 | |
2178 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2179 | bool isVariablyModifiedType() const { |
2180 | return getDependence() & TypeDependence::VariablyModified; |
2181 | } |
2182 | |
2183 | /// Whether this type involves a variable-length array type |
2184 | /// with a definite size. |
2185 | bool hasSizedVLAType() const; |
2186 | |
2187 | /// Whether this type is or contains a local or unnamed type. |
2188 | bool hasUnnamedOrLocalType() const; |
2189 | |
2190 | bool isOverloadableType() const; |
2191 | |
2192 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2193 | bool isElaboratedTypeSpecifier() const; |
2194 | |
2195 | bool canDecayToPointerType() const; |
2196 | |
2197 | /// Whether this type is represented natively as a pointer. This includes |
2198 | /// pointers, references, block pointers, and Objective-C interface, |
2199 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2200 | bool hasPointerRepresentation() const; |
2201 | |
2202 | /// Whether this type can represent an objective pointer type for the |
2203 | /// purpose of GC'ability |
2204 | bool hasObjCPointerRepresentation() const; |
2205 | |
2206 | /// Determine whether this type has an integer representation |
2207 | /// of some sort, e.g., it is an integer type or a vector. |
2208 | bool hasIntegerRepresentation() const; |
2209 | |
2210 | /// Determine whether this type has an signed integer representation |
2211 | /// of some sort, e.g., it is an signed integer type or a vector. |
2212 | bool hasSignedIntegerRepresentation() const; |
2213 | |
2214 | /// Determine whether this type has an unsigned integer representation |
2215 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2216 | bool hasUnsignedIntegerRepresentation() const; |
2217 | |
2218 | /// Determine whether this type has a floating-point representation |
2219 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2220 | bool hasFloatingRepresentation() const; |
2221 | |
2222 | // Type Checking Functions: Check to see if this type is structurally the |
2223 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2224 | // the best type we can. |
2225 | const RecordType *getAsStructureType() const; |
2226 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2227 | const RecordType *getAsUnionType() const; |
2228 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2229 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2230 | |
2231 | // The following is a convenience method that returns an ObjCObjectPointerType |
2232 | // for object declared using an interface. |
2233 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2234 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2235 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2236 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2237 | |
2238 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2239 | /// because the type is a RecordType or because it is the injected-class-name |
2240 | /// type of a class template or class template partial specialization. |
2241 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2242 | |
2243 | /// Retrieves the RecordDecl this type refers to. |
2244 | RecordDecl *getAsRecordDecl() const; |
2245 | |
2246 | /// Retrieves the TagDecl that this type refers to, either |
2247 | /// because the type is a TagType or because it is the injected-class-name |
2248 | /// type of a class template or class template partial specialization. |
2249 | TagDecl *getAsTagDecl() const; |
2250 | |
2251 | /// If this is a pointer or reference to a RecordType, return the |
2252 | /// CXXRecordDecl that the type refers to. |
2253 | /// |
2254 | /// If this is not a pointer or reference, or the type being pointed to does |
2255 | /// not refer to a CXXRecordDecl, returns NULL. |
2256 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2257 | |
2258 | /// Get the DeducedType whose type will be deduced for a variable with |
2259 | /// an initializer of this type. This looks through declarators like pointer |
2260 | /// types, but not through decltype or typedefs. |
2261 | DeducedType *getContainedDeducedType() const; |
2262 | |
2263 | /// Get the AutoType whose type will be deduced for a variable with |
2264 | /// an initializer of this type. This looks through declarators like pointer |
2265 | /// types, but not through decltype or typedefs. |
2266 | AutoType *getContainedAutoType() const { |
2267 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2268 | } |
2269 | |
2270 | /// Determine whether this type was written with a leading 'auto' |
2271 | /// corresponding to a trailing return type (possibly for a nested |
2272 | /// function type within a pointer to function type or similar). |
2273 | bool hasAutoForTrailingReturnType() const; |
2274 | |
2275 | /// Member-template getAs<specific type>'. Look through sugar for |
2276 | /// an instance of \<specific type>. This scheme will eventually |
2277 | /// replace the specific getAsXXXX methods above. |
2278 | /// |
2279 | /// There are some specializations of this member template listed |
2280 | /// immediately following this class. |
2281 | template <typename T> const T *getAs() const; |
2282 | |
2283 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2284 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2285 | /// This is used when you need to walk over sugar nodes that represent some |
2286 | /// kind of type adjustment from a type that was written as a \<specific type> |
2287 | /// to another type that is still canonically a \<specific type>. |
2288 | template <typename T> const T *getAsAdjusted() const; |
2289 | |
2290 | /// A variant of getAs<> for array types which silently discards |
2291 | /// qualifiers from the outermost type. |
2292 | const ArrayType *getAsArrayTypeUnsafe() const; |
2293 | |
2294 | /// Member-template castAs<specific type>. Look through sugar for |
2295 | /// the underlying instance of \<specific type>. |
2296 | /// |
2297 | /// This method has the same relationship to getAs<T> as cast<T> has |
2298 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2299 | /// have the intended type, and this method will never return null. |
2300 | template <typename T> const T *castAs() const; |
2301 | |
2302 | /// A variant of castAs<> for array type which silently discards |
2303 | /// qualifiers from the outermost type. |
2304 | const ArrayType *castAsArrayTypeUnsafe() const; |
2305 | |
2306 | /// Determine whether this type had the specified attribute applied to it |
2307 | /// (looking through top-level type sugar). |
2308 | bool hasAttr(attr::Kind AK) const; |
2309 | |
2310 | /// Get the base element type of this type, potentially discarding type |
2311 | /// qualifiers. This should never be used when type qualifiers |
2312 | /// are meaningful. |
2313 | const Type *getBaseElementTypeUnsafe() const; |
2314 | |
2315 | /// If this is an array type, return the element type of the array, |
2316 | /// potentially with type qualifiers missing. |
2317 | /// This should never be used when type qualifiers are meaningful. |
2318 | const Type *getArrayElementTypeNoTypeQual() const; |
2319 | |
2320 | /// If this is a pointer type, return the pointee type. |
2321 | /// If this is an array type, return the array element type. |
2322 | /// This should never be used when type qualifiers are meaningful. |
2323 | const Type *getPointeeOrArrayElementType() const; |
2324 | |
2325 | /// If this is a pointer, ObjC object pointer, or block |
2326 | /// pointer, this returns the respective pointee. |
2327 | QualType getPointeeType() const; |
2328 | |
2329 | /// Return the specified type with any "sugar" removed from the type, |
2330 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2331 | const Type *getUnqualifiedDesugaredType() const; |
2332 | |
2333 | /// More type predicates useful for type checking/promotion |
2334 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2335 | |
2336 | /// Return true if this is an integer type that is |
2337 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2338 | /// or an enum decl which has a signed representation. |
2339 | bool isSignedIntegerType() const; |
2340 | |
2341 | /// Return true if this is an integer type that is |
2342 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2343 | /// or an enum decl which has an unsigned representation. |
2344 | bool isUnsignedIntegerType() const; |
2345 | |
2346 | /// Determines whether this is an integer type that is signed or an |
2347 | /// enumeration types whose underlying type is a signed integer type. |
2348 | bool isSignedIntegerOrEnumerationType() const; |
2349 | |
2350 | /// Determines whether this is an integer type that is unsigned or an |
2351 | /// enumeration types whose underlying type is a unsigned integer type. |
2352 | bool isUnsignedIntegerOrEnumerationType() const; |
2353 | |
2354 | /// Return true if this is a fixed point type according to |
2355 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2356 | bool isFixedPointType() const; |
2357 | |
2358 | /// Return true if this is a fixed point or integer type. |
2359 | bool isFixedPointOrIntegerType() const; |
2360 | |
2361 | /// Return true if this is a saturated fixed point type according to |
2362 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2363 | bool isSaturatedFixedPointType() const; |
2364 | |
2365 | /// Return true if this is a saturated fixed point type according to |
2366 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2367 | bool isUnsaturatedFixedPointType() const; |
2368 | |
2369 | /// Return true if this is a fixed point type that is signed according |
2370 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2371 | bool isSignedFixedPointType() const; |
2372 | |
2373 | /// Return true if this is a fixed point type that is unsigned according |
2374 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2375 | bool isUnsignedFixedPointType() const; |
2376 | |
2377 | /// Return true if this is not a variable sized type, |
2378 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2379 | /// incomplete types. |
2380 | bool isConstantSizeType() const; |
2381 | |
2382 | /// Returns true if this type can be represented by some |
2383 | /// set of type specifiers. |
2384 | bool isSpecifierType() const; |
2385 | |
2386 | /// Determine the linkage of this type. |
2387 | Linkage getLinkage() const; |
2388 | |
2389 | /// Determine the visibility of this type. |
2390 | Visibility getVisibility() const { |
2391 | return getLinkageAndVisibility().getVisibility(); |
2392 | } |
2393 | |
2394 | /// Return true if the visibility was explicitly set is the code. |
2395 | bool isVisibilityExplicit() const { |
2396 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2397 | } |
2398 | |
2399 | /// Determine the linkage and visibility of this type. |
2400 | LinkageInfo getLinkageAndVisibility() const; |
2401 | |
2402 | /// True if the computed linkage is valid. Used for consistency |
2403 | /// checking. Should always return true. |
2404 | bool isLinkageValid() const; |
2405 | |
2406 | /// Determine the nullability of the given type. |
2407 | /// |
2408 | /// Note that nullability is only captured as sugar within the type |
2409 | /// system, not as part of the canonical type, so nullability will |
2410 | /// be lost by canonicalization and desugaring. |
2411 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2412 | |
2413 | /// Determine whether the given type can have a nullability |
2414 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2415 | /// |
2416 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2417 | /// this type can have nullability because it is dependent. |
2418 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2419 | |
2420 | /// Retrieve the set of substitutions required when accessing a member |
2421 | /// of the Objective-C receiver type that is declared in the given context. |
2422 | /// |
2423 | /// \c *this is the type of the object we're operating on, e.g., the |
2424 | /// receiver for a message send or the base of a property access, and is |
2425 | /// expected to be of some object or object pointer type. |
2426 | /// |
2427 | /// \param dc The declaration context for which we are building up a |
2428 | /// substitution mapping, which should be an Objective-C class, extension, |
2429 | /// category, or method within. |
2430 | /// |
2431 | /// \returns an array of type arguments that can be substituted for |
2432 | /// the type parameters of the given declaration context in any type described |
2433 | /// within that context, or an empty optional to indicate that no |
2434 | /// substitution is required. |
2435 | Optional<ArrayRef<QualType>> |
2436 | getObjCSubstitutions(const DeclContext *dc) const; |
2437 | |
2438 | /// Determines if this is an ObjC interface type that may accept type |
2439 | /// parameters. |
2440 | bool acceptsObjCTypeParams() const; |
2441 | |
2442 | const char *getTypeClassName() const; |
2443 | |
2444 | QualType getCanonicalTypeInternal() const { |
2445 | return CanonicalType; |
2446 | } |
2447 | |
2448 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2449 | void dump() const; |
2450 | void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; |
2451 | }; |
2452 | |
2453 | /// This will check for a TypedefType by removing any existing sugar |
2454 | /// until it reaches a TypedefType or a non-sugared type. |
2455 | template <> const TypedefType *Type::getAs() const; |
2456 | |
2457 | /// This will check for a TemplateSpecializationType by removing any |
2458 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2459 | /// non-sugared type. |
2460 | template <> const TemplateSpecializationType *Type::getAs() const; |
2461 | |
2462 | /// This will check for an AttributedType by removing any existing sugar |
2463 | /// until it reaches an AttributedType or a non-sugared type. |
2464 | template <> const AttributedType *Type::getAs() const; |
2465 | |
2466 | // We can do canonical leaf types faster, because we don't have to |
2467 | // worry about preserving child type decoration. |
2468 | #define TYPE(Class, Base) |
2469 | #define LEAF_TYPE(Class) \ |
2470 | template <> inline const Class##Type *Type::getAs() const { \ |
2471 | return dyn_cast<Class##Type>(CanonicalType); \ |
2472 | } \ |
2473 | template <> inline const Class##Type *Type::castAs() const { \ |
2474 | return cast<Class##Type>(CanonicalType); \ |
2475 | } |
2476 | #include "clang/AST/TypeNodes.inc" |
2477 | |
2478 | /// This class is used for builtin types like 'int'. Builtin |
2479 | /// types are always canonical and have a literal name field. |
2480 | class BuiltinType : public Type { |
2481 | public: |
2482 | enum Kind { |
2483 | // OpenCL image types |
2484 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2485 | #include "clang/Basic/OpenCLImageTypes.def" |
2486 | // OpenCL extension types |
2487 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2488 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2489 | // SVE Types |
2490 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2491 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2492 | // PPC MMA Types |
2493 | #define PPC_VECTOR_TYPE(Name, Id, Size) Id, |
2494 | #include "clang/Basic/PPCTypes.def" |
2495 | // RVV Types |
2496 | #define RVV_TYPE(Name, Id, SingletonId) Id, |
2497 | #include "clang/Basic/RISCVVTypes.def" |
2498 | // All other builtin types |
2499 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2500 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2501 | #include "clang/AST/BuiltinTypes.def" |
2502 | }; |
2503 | |
2504 | private: |
2505 | friend class ASTContext; // ASTContext creates these. |
2506 | |
2507 | BuiltinType(Kind K) |
2508 | : Type(Builtin, QualType(), |
2509 | K == Dependent ? TypeDependence::DependentInstantiation |
2510 | : TypeDependence::None) { |
2511 | BuiltinTypeBits.Kind = K; |
2512 | } |
2513 | |
2514 | public: |
2515 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2516 | StringRef getName(const PrintingPolicy &Policy) const; |
2517 | |
2518 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2519 | // The StringRef is null-terminated. |
2520 | StringRef str = getName(Policy); |
2521 | 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-13~++20210413100635+64c24f493e5f/clang/include/clang/AST/Type.h" , 2521, __PRETTY_FUNCTION__)); |
2522 | return str.data(); |
2523 | } |
2524 | |
2525 | bool isSugared() const { return false; } |
2526 | QualType desugar() const { return QualType(this, 0); } |
2527 | |
2528 | bool isInteger() const { |
2529 | return getKind() >= Bool && getKind() <= Int128; |
2530 | } |
2531 | |
2532 | bool isSignedInteger() const { |
2533 | return getKind() >= Char_S && getKind() <= Int128; |
2534 | } |
2535 | |
2536 | bool isUnsignedInteger() const { |
2537 | return getKind() >= Bool && getKind() <= UInt128; |
2538 | } |
2539 | |
2540 | bool isFloatingPoint() const { |
2541 | return getKind() >= Half && getKind() <= Float128; |
2542 | } |
2543 | |
2544 | /// Determines whether the given kind corresponds to a placeholder type. |
2545 | static bool isPlaceholderTypeKind(Kind K) { |
2546 | return K >= Overload; |
2547 | } |
2548 | |
2549 | /// Determines whether this type is a placeholder type, i.e. a type |
2550 | /// which cannot appear in arbitrary positions in a fully-formed |
2551 | /// expression. |
2552 | bool isPlaceholderType() const { |
2553 | return isPlaceholderTypeKind(getKind()); |
2554 | } |
2555 | |
2556 | /// Determines whether this type is a placeholder type other than |
2557 | /// Overload. Most placeholder types require only syntactic |
2558 | /// information about their context in order to be resolved (e.g. |
2559 | /// whether it is a call expression), which means they can (and |
2560 | /// should) be resolved in an earlier "phase" of analysis. |
2561 | /// Overload expressions sometimes pick up further information |
2562 | /// from their context, like whether the context expects a |
2563 | /// specific function-pointer type, and so frequently need |
2564 | /// special treatment. |
2565 | bool isNonOverloadPlaceholderType() const { |
2566 | return getKind() > Overload; |
2567 | } |
2568 | |
2569 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2570 | }; |
2571 | |
2572 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2573 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2574 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2575 | friend class ASTContext; // ASTContext creates these. |
2576 | |
2577 | QualType ElementType; |
2578 | |
2579 | ComplexType(QualType Element, QualType CanonicalPtr) |
2580 | : Type(Complex, CanonicalPtr, Element->getDependence()), |
2581 | ElementType(Element) {} |
2582 | |
2583 | public: |
2584 | QualType getElementType() const { return ElementType; } |
2585 | |
2586 | bool isSugared() const { return false; } |
2587 | QualType desugar() const { return QualType(this, 0); } |
2588 | |
2589 | void Profile(llvm::FoldingSetNodeID &ID) { |
2590 | Profile(ID, getElementType()); |
2591 | } |
2592 | |
2593 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2594 | ID.AddPointer(Element.getAsOpaquePtr()); |
2595 | } |
2596 | |
2597 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2598 | }; |
2599 | |
2600 | /// Sugar for parentheses used when specifying types. |
2601 | class ParenType : public Type, public llvm::FoldingSetNode { |
2602 | friend class ASTContext; // ASTContext creates these. |
2603 | |
2604 | QualType Inner; |
2605 | |
2606 | ParenType(QualType InnerType, QualType CanonType) |
2607 | : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} |
2608 | |
2609 | public: |
2610 | QualType getInnerType() const { return Inner; } |
2611 | |
2612 | bool isSugared() const { return true; } |
2613 | QualType desugar() const { return getInnerType(); } |
2614 | |
2615 | void Profile(llvm::FoldingSetNodeID &ID) { |
2616 | Profile(ID, getInnerType()); |
2617 | } |
2618 | |
2619 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2620 | Inner.Profile(ID); |
2621 | } |
2622 | |
2623 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2624 | }; |
2625 | |
2626 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2627 | class PointerType : public Type, public llvm::FoldingSetNode { |
2628 | friend class ASTContext; // ASTContext creates these. |
2629 | |
2630 | QualType PointeeType; |
2631 | |
2632 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2633 | : Type(Pointer, CanonicalPtr, Pointee->getDependence()), |
2634 | PointeeType(Pointee) {} |
2635 | |
2636 | public: |
2637 | QualType getPointeeType() const { return PointeeType; } |
2638 | |
2639 | bool isSugared() const { return false; } |
2640 | QualType desugar() const { return QualType(this, 0); } |
2641 | |
2642 | void Profile(llvm::FoldingSetNodeID &ID) { |
2643 | Profile(ID, getPointeeType()); |
2644 | } |
2645 | |
2646 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2647 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2648 | } |
2649 | |
2650 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2651 | }; |
2652 | |
2653 | /// Represents a type which was implicitly adjusted by the semantic |
2654 | /// engine for arbitrary reasons. For example, array and function types can |
2655 | /// decay, and function types can have their calling conventions adjusted. |
2656 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2657 | QualType OriginalTy; |
2658 | QualType AdjustedTy; |
2659 | |
2660 | protected: |
2661 | friend class ASTContext; // ASTContext creates these. |
2662 | |
2663 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2664 | QualType CanonicalPtr) |
2665 | : Type(TC, CanonicalPtr, OriginalTy->getDependence()), |
2666 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2667 | |
2668 | public: |
2669 | QualType getOriginalType() const { return OriginalTy; } |
2670 | QualType getAdjustedType() const { return AdjustedTy; } |
2671 | |
2672 | bool isSugared() const { return true; } |
2673 | QualType desugar() const { return AdjustedTy; } |
2674 | |
2675 | void Profile(llvm::FoldingSetNodeID &ID) { |
2676 | Profile(ID, OriginalTy, AdjustedTy); |
2677 | } |
2678 | |
2679 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2680 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2681 | ID.AddPointer(New.getAsOpaquePtr()); |
2682 | } |
2683 | |