/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaCast.cpp
Line | Count | Source (jump to first uncovered line) |
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 | 1.37M | static bool isValidCast(TryCastResult TCR) { |
43 | 1.37M | return TCR == TC_Success || TCR == TC_Extension616k ; |
44 | 1.37M | } |
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 | 5.12M | Kind(CK_Dependent), IsARCUnbridgedCast(false) { |
63 | | |
64 | | // C++ [expr.type]/8.2.2: |
65 | | // If a pr-value initially has the type cv-T, where T is a |
66 | | // cv-unqualified non-class, non-array type, the type of the |
67 | | // expression is adjusted to T prior to any further analysis. |
68 | 5.12M | if (!S.Context.getLangOpts().ObjC && !DestType->isRecordType()4.73M && |
69 | 5.12M | !DestType->isArrayType()4.70M ) { |
70 | 4.70M | DestType = DestType.getUnqualifiedType(); |
71 | 4.70M | } |
72 | | |
73 | 5.12M | if (const BuiltinType *placeholder = |
74 | 5.12M | src.get()->getType()->getAsPlaceholderType()) { |
75 | 1.07k | PlaceholderKind = placeholder->getKind(); |
76 | 5.12M | } else { |
77 | 5.12M | PlaceholderKind = (BuiltinType::Kind) 0; |
78 | 5.12M | } |
79 | 5.12M | } |
80 | | |
81 | | Sema &Self; |
82 | | ExprResult SrcExpr; |
83 | | QualType DestType; |
84 | | QualType ResultType; |
85 | | ExprValueKind ValueKind; |
86 | | CastKind Kind; |
87 | | BuiltinType::Kind PlaceholderKind; |
88 | | CXXCastPath BasePath; |
89 | | bool IsARCUnbridgedCast; |
90 | | |
91 | | SourceRange OpRange; |
92 | | SourceRange DestRange; |
93 | | |
94 | | // Top-level semantics-checking routines. |
95 | | void CheckConstCast(); |
96 | | void CheckReinterpretCast(); |
97 | | void CheckStaticCast(); |
98 | | void CheckDynamicCast(); |
99 | | void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); |
100 | | void CheckCStyleCast(); |
101 | | void CheckBuiltinBitCast(); |
102 | | void CheckAddrspaceCast(); |
103 | | |
104 | 5.12M | void updatePartOfExplicitCastFlags(CastExpr *CE) { |
105 | | // Walk down from the CE to the OrigSrcExpr, and mark all immediate |
106 | | // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE |
107 | | // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched. |
108 | 8.03M | for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE2.91M ) |
109 | 2.91M | ICE->setIsPartOfExplicitCast(true); |
110 | 5.12M | } |
111 | | |
112 | | /// Complete an apparently-successful cast operation that yields |
113 | | /// the given expression. |
114 | 5.12M | ExprResult complete(CastExpr *castExpr) { |
115 | | // If this is an unbridged cast, wrap the result in an implicit |
116 | | // cast that yields the unbridged-cast placeholder type. |
117 | 5.12M | if (IsARCUnbridgedCast) { |
118 | 122 | castExpr = ImplicitCastExpr::Create( |
119 | 122 | Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent, |
120 | 122 | castExpr, nullptr, castExpr->getValueKind(), |
121 | 122 | Self.CurFPFeatureOverrides()); |
122 | 122 | } |
123 | 5.12M | updatePartOfExplicitCastFlags(castExpr); |
124 | 5.12M | return castExpr; |
125 | 5.12M | } |
126 | | |
127 | | // Internal convenience methods. |
128 | | |
129 | | /// Try to handle the given placeholder expression kind. Return |
130 | | /// true if the source expression has the appropriate placeholder |
131 | | /// kind. A placeholder can only be claimed once. |
132 | 4.13M | bool claimPlaceholder(BuiltinType::Kind K) { |
133 | 4.13M | if (PlaceholderKind != K) return false4.13M ; |
134 | | |
135 | 674 | PlaceholderKind = (BuiltinType::Kind) 0; |
136 | 674 | return true; |
137 | 4.13M | } |
138 | | |
139 | 890k | bool isPlaceholder() const { |
140 | 890k | return PlaceholderKind != 0; |
141 | 890k | } |
142 | 670k | bool isPlaceholder(BuiltinType::Kind K) const { |
143 | 670k | return PlaceholderKind == K; |
144 | 670k | } |
145 | | |
146 | | // Language specific cast restrictions for address spaces. |
147 | | void checkAddressSpaceCast(QualType SrcType, QualType DestType); |
148 | | |
149 | 171k | void checkCastAlign() { |
150 | 171k | Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); |
151 | 171k | } |
152 | | |
153 | 15.6k | void checkObjCConversion(Sema::CheckedConversionKind CCK) { |
154 | 15.6k | assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()); |
155 | | |
156 | 0 | Expr *src = SrcExpr.get(); |
157 | 15.6k | if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) == |
158 | 15.6k | Sema::ACR_unbridged) |
159 | 122 | IsARCUnbridgedCast = true; |
160 | 15.6k | SrcExpr = src; |
161 | 15.6k | } |
162 | | |
163 | | /// Check for and handle non-overload placeholder expressions. |
164 | 598 | void checkNonOverloadPlaceholders() { |
165 | 598 | if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)312 ) |
166 | 527 | return; |
167 | | |
168 | 71 | SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); |
169 | 71 | if (SrcExpr.isInvalid()) |
170 | 0 | return; |
171 | 71 | PlaceholderKind = (BuiltinType::Kind) 0; |
172 | 71 | } |
173 | | }; |
174 | | |
175 | | void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType, |
176 | 112k | SourceLocation OpLoc) { |
177 | 112k | if (const auto *PtrType = dyn_cast<PointerType>(FromType)) { |
178 | 8.24k | if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) { |
179 | 10 | if (const auto *DestType = dyn_cast<PointerType>(ToType)) { |
180 | 10 | if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) { |
181 | 10 | S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer); |
182 | 10 | } |
183 | 10 | } |
184 | 10 | } |
185 | 8.24k | } |
186 | 112k | } |
187 | | |
188 | | struct CheckNoDerefRAII { |
189 | 113k | CheckNoDerefRAII(CastOperation &Op) : Op(Op) {} |
190 | 113k | ~CheckNoDerefRAII() { |
191 | 113k | if (!Op.SrcExpr.isInvalid()) |
192 | 112k | CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType, |
193 | 112k | Op.OpRange.getBegin()); |
194 | 113k | } |
195 | | |
196 | | CastOperation &Op; |
197 | | }; |
198 | | } |
199 | | |
200 | | static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, |
201 | | QualType DestType); |
202 | | |
203 | | // The Try functions attempt a specific way of casting. If they succeed, they |
204 | | // return TC_Success. If their way of casting is not appropriate for the given |
205 | | // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic |
206 | | // to emit if no other way succeeds. If their way of casting is appropriate but |
207 | | // fails, they return TC_Failed and *must* set diag; they can set it to 0 if |
208 | | // they emit a specialized diagnostic. |
209 | | // All diagnostics returned by these functions must expect the same three |
210 | | // arguments: |
211 | | // %0: Cast Type (a value from the CastType enumeration) |
212 | | // %1: Source Type |
213 | | // %2: Destination Type |
214 | | static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, |
215 | | QualType DestType, bool CStyle, |
216 | | CastKind &Kind, |
217 | | CXXCastPath &BasePath, |
218 | | unsigned &msg); |
219 | | static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, |
220 | | QualType DestType, bool CStyle, |
221 | | SourceRange OpRange, |
222 | | unsigned &msg, |
223 | | CastKind &Kind, |
224 | | CXXCastPath &BasePath); |
225 | | static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, |
226 | | QualType DestType, bool CStyle, |
227 | | SourceRange OpRange, |
228 | | unsigned &msg, |
229 | | CastKind &Kind, |
230 | | CXXCastPath &BasePath); |
231 | | static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, |
232 | | CanQualType DestType, bool CStyle, |
233 | | SourceRange OpRange, |
234 | | QualType OrigSrcType, |
235 | | QualType OrigDestType, unsigned &msg, |
236 | | CastKind &Kind, |
237 | | CXXCastPath &BasePath); |
238 | | static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, |
239 | | QualType SrcType, |
240 | | QualType DestType,bool CStyle, |
241 | | SourceRange OpRange, |
242 | | unsigned &msg, |
243 | | CastKind &Kind, |
244 | | CXXCastPath &BasePath); |
245 | | |
246 | | static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, |
247 | | QualType DestType, |
248 | | Sema::CheckedConversionKind CCK, |
249 | | SourceRange OpRange, |
250 | | unsigned &msg, CastKind &Kind, |
251 | | bool ListInitialization); |
252 | | static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, |
253 | | QualType DestType, |
254 | | Sema::CheckedConversionKind CCK, |
255 | | SourceRange OpRange, |
256 | | unsigned &msg, CastKind &Kind, |
257 | | CXXCastPath &BasePath, |
258 | | bool ListInitialization); |
259 | | static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, |
260 | | QualType DestType, bool CStyle, |
261 | | unsigned &msg); |
262 | | static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, |
263 | | QualType DestType, bool CStyle, |
264 | | SourceRange OpRange, unsigned &msg, |
265 | | CastKind &Kind); |
266 | | static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, |
267 | | QualType DestType, bool CStyle, |
268 | | unsigned &msg, CastKind &Kind); |
269 | | |
270 | | /// ActOnCXXNamedCast - Parse |
271 | | /// {dynamic,static,reinterpret,const,addrspace}_cast's. |
272 | | ExprResult |
273 | | Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, |
274 | | SourceLocation LAngleBracketLoc, Declarator &D, |
275 | | SourceLocation RAngleBracketLoc, |
276 | | SourceLocation LParenLoc, Expr *E, |
277 | 214k | SourceLocation RParenLoc) { |
278 | | |
279 | 214k | assert(!D.isInvalidType()); |
280 | | |
281 | 0 | TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); |
282 | 214k | if (D.isInvalidType()) |
283 | 37 | return ExprError(); |
284 | | |
285 | 214k | if (getLangOpts().CPlusPlus) { |
286 | | // Check that there are no default arguments (C++ only). |
287 | 214k | CheckExtraCXXDefaultArguments(D); |
288 | 214k | } |
289 | | |
290 | 214k | return BuildCXXNamedCast(OpLoc, Kind, TInfo, E, |
291 | 214k | SourceRange(LAngleBracketLoc, RAngleBracketLoc), |
292 | 214k | SourceRange(LParenLoc, RParenLoc)); |
293 | 214k | } |
294 | | |
295 | | ExprResult |
296 | | Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, |
297 | | TypeSourceInfo *DestTInfo, Expr *E, |
298 | 286k | SourceRange AngleBrackets, SourceRange Parens) { |
299 | 286k | ExprResult Ex = E; |
300 | 286k | QualType DestType = DestTInfo->getType(); |
301 | | |
302 | | // If the type is dependent, we won't do the semantic analysis now. |
303 | 286k | bool TypeDependent = |
304 | 286k | DestType->isDependentType() || Ex.get()->isTypeDependent()183k ; |
305 | | |
306 | 286k | CastOperation Op(*this, DestType, E); |
307 | 286k | Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); |
308 | 286k | Op.DestRange = AngleBrackets; |
309 | | |
310 | 286k | switch (Kind) { |
311 | 0 | default: llvm_unreachable("Unknown C++ cast!"); |
312 | |
|
313 | 19 | case tok::kw_addrspace_cast: |
314 | 19 | if (!TypeDependent) { |
315 | 13 | Op.CheckAddrspaceCast(); |
316 | 13 | if (Op.SrcExpr.isInvalid()) |
317 | 9 | return ExprError(); |
318 | 13 | } |
319 | 10 | return Op.complete(CXXAddrspaceCastExpr::Create( |
320 | 10 | Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), |
321 | 10 | DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); |
322 | | |
323 | 7.61k | case tok::kw_const_cast: |
324 | 7.61k | if (!TypeDependent) { |
325 | 2.87k | Op.CheckConstCast(); |
326 | 2.87k | if (Op.SrcExpr.isInvalid()) |
327 | 116 | return ExprError(); |
328 | 2.76k | DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); |
329 | 2.76k | } |
330 | 7.50k | return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, |
331 | 7.50k | Op.ValueKind, Op.SrcExpr.get(), DestTInfo, |
332 | 7.50k | OpLoc, Parens.getEnd(), |
333 | 7.50k | AngleBrackets)); |
334 | | |
335 | 1.34k | case tok::kw_dynamic_cast: { |
336 | | // dynamic_cast is not supported in C++ for OpenCL. |
337 | 1.34k | if (getLangOpts().OpenCLCPlusPlus) { |
338 | 1 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) |
339 | 1 | << "dynamic_cast"); |
340 | 1 | } |
341 | | |
342 | 1.34k | if (!TypeDependent) { |
343 | 387 | Op.CheckDynamicCast(); |
344 | 387 | if (Op.SrcExpr.isInvalid()) |
345 | 53 | return ExprError(); |
346 | 387 | } |
347 | 1.28k | return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, |
348 | 1.28k | Op.ValueKind, Op.Kind, Op.SrcExpr.get(), |
349 | 1.28k | &Op.BasePath, DestTInfo, |
350 | 1.28k | OpLoc, Parens.getEnd(), |
351 | 1.28k | AngleBrackets)); |
352 | 1.34k | } |
353 | 9.18k | case tok::kw_reinterpret_cast: { |
354 | 9.18k | if (!TypeDependent) { |
355 | 3.45k | Op.CheckReinterpretCast(); |
356 | 3.45k | if (Op.SrcExpr.isInvalid()) |
357 | 126 | return ExprError(); |
358 | 3.32k | DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); |
359 | 3.32k | } |
360 | 9.06k | return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, |
361 | 9.06k | Op.ValueKind, Op.Kind, Op.SrcExpr.get(), |
362 | 9.06k | nullptr, DestTInfo, OpLoc, |
363 | 9.06k | Parens.getEnd(), |
364 | 9.06k | AngleBrackets)); |
365 | 9.18k | } |
366 | 267k | case tok::kw_static_cast: { |
367 | 267k | if (!TypeDependent) { |
368 | 110k | Op.CheckStaticCast(); |
369 | 110k | if (Op.SrcExpr.isInvalid()) |
370 | 202 | return ExprError(); |
371 | 109k | DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); |
372 | 109k | } |
373 | | |
374 | 267k | return Op.complete(CXXStaticCastExpr::Create( |
375 | 267k | Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), |
376 | 267k | &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc, |
377 | 267k | Parens.getEnd(), AngleBrackets)); |
378 | 267k | } |
379 | 286k | } |
380 | 286k | } |
381 | | |
382 | | ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D, |
383 | | ExprResult Operand, |
384 | 718 | SourceLocation RParenLoc) { |
385 | 718 | assert(!D.isInvalidType()); |
386 | | |
387 | 0 | TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType()); |
388 | 718 | if (D.isInvalidType()) |
389 | 0 | return ExprError(); |
390 | | |
391 | 718 | return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc); |
392 | 718 | } |
393 | | |
394 | | ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc, |
395 | | TypeSourceInfo *TSI, Expr *Operand, |
396 | 803 | SourceLocation RParenLoc) { |
397 | 803 | CastOperation Op(*this, TSI->getType(), Operand); |
398 | 803 | Op.OpRange = SourceRange(KWLoc, RParenLoc); |
399 | 803 | TypeLoc TL = TSI->getTypeLoc(); |
400 | 803 | Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); |
401 | | |
402 | 803 | if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()792 ) { |
403 | 792 | Op.CheckBuiltinBitCast(); |
404 | 792 | if (Op.SrcExpr.isInvalid()) |
405 | 6 | return ExprError(); |
406 | 792 | } |
407 | | |
408 | 797 | BuiltinBitCastExpr *BCE = |
409 | 797 | new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind, |
410 | 797 | Op.SrcExpr.get(), TSI, KWLoc, RParenLoc); |
411 | 797 | return Op.complete(BCE); |
412 | 803 | } |
413 | | |
414 | | /// Try to diagnose a failed overloaded cast. Returns true if |
415 | | /// diagnostics were emitted. |
416 | | static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, |
417 | | SourceRange range, Expr *src, |
418 | | QualType destType, |
419 | 384 | bool listInitialization) { |
420 | 384 | switch (CT) { |
421 | | // These cast kinds don't consider user-defined conversions. |
422 | 0 | case CT_Const: |
423 | 29 | case CT_Reinterpret: |
424 | 29 | case CT_Dynamic: |
425 | 29 | case CT_Addrspace: |
426 | 29 | return false; |
427 | | |
428 | | // These do. |
429 | 81 | case CT_Static: |
430 | 127 | case CT_CStyle: |
431 | 355 | case CT_Functional: |
432 | 355 | break; |
433 | 384 | } |
434 | | |
435 | 355 | QualType srcType = src->getType(); |
436 | 355 | if (!destType->isRecordType() && !srcType->isRecordType()209 ) |
437 | 113 | return false; |
438 | | |
439 | 242 | InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); |
440 | 242 | InitializationKind initKind |
441 | 242 | = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), |
442 | 10 | range, listInitialization) |
443 | 242 | : (CT == CT_Functional)232 ? InitializationKind::CreateFunctionalCast(range, |
444 | 221 | listInitialization) |
445 | 232 | : InitializationKind::CreateCast(/*type range?*/ range)11 ; |
446 | 242 | InitializationSequence sequence(S, entity, initKind, src); |
447 | | |
448 | 242 | assert(sequence.Failed() && "initialization succeeded on second try?"); |
449 | 0 | switch (sequence.getFailureKind()) { |
450 | 0 | default: return false; |
451 | | |
452 | 146 | case InitializationSequence::FK_ConstructorOverloadFailed: |
453 | 242 | case InitializationSequence::FK_UserConversionOverloadFailed: |
454 | 242 | break; |
455 | 242 | } |
456 | | |
457 | 242 | OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); |
458 | | |
459 | 242 | unsigned msg = 0; |
460 | 242 | OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; |
461 | | |
462 | 242 | switch (sequence.getFailedOverloadResult()) { |
463 | 0 | case OR_Success: llvm_unreachable("successful failed overload"); |
464 | 229 | case OR_No_Viable_Function: |
465 | 229 | if (candidates.empty()) |
466 | 95 | msg = diag::err_ovl_no_conversion_in_cast; |
467 | 134 | else |
468 | 134 | msg = diag::err_ovl_no_viable_conversion_in_cast; |
469 | 229 | howManyCandidates = OCD_AllCandidates; |
470 | 229 | break; |
471 | | |
472 | 2 | case OR_Ambiguous: |
473 | 2 | msg = diag::err_ovl_ambiguous_conversion_in_cast; |
474 | 2 | howManyCandidates = OCD_AmbiguousCandidates; |
475 | 2 | break; |
476 | | |
477 | 11 | case OR_Deleted: |
478 | 11 | msg = diag::err_ovl_deleted_conversion_in_cast; |
479 | 11 | howManyCandidates = OCD_ViableCandidates; |
480 | 11 | break; |
481 | 242 | } |
482 | | |
483 | 242 | candidates.NoteCandidates( |
484 | 242 | PartialDiagnosticAt(range.getBegin(), |
485 | 242 | S.PDiag(msg) << CT << srcType << destType << range |
486 | 242 | << src->getSourceRange()), |
487 | 242 | S, howManyCandidates, src); |
488 | | |
489 | 242 | return true; |
490 | 242 | } |
491 | | |
492 | | /// Diagnose a failed cast. |
493 | | static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, |
494 | | SourceRange opRange, Expr *src, QualType destType, |
495 | 642 | bool listInitialization) { |
496 | 642 | if (msg == diag::err_bad_cxx_cast_generic && |
497 | 642 | tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, |
498 | 384 | listInitialization)) |
499 | 242 | return; |
500 | | |
501 | 400 | S.Diag(opRange.getBegin(), msg) << castType |
502 | 400 | << src->getType() << destType << opRange << src->getSourceRange(); |
503 | | |
504 | | // Detect if both types are (ptr to) class, and note any incompleteness. |
505 | 400 | int DifferentPtrness = 0; |
506 | 400 | QualType From = destType; |
507 | 400 | if (auto Ptr = From->getAs<PointerType>()) { |
508 | 242 | From = Ptr->getPointeeType(); |
509 | 242 | DifferentPtrness++; |
510 | 242 | } |
511 | 400 | QualType To = src->getType(); |
512 | 400 | if (auto Ptr = To->getAs<PointerType>()) { |
513 | 258 | To = Ptr->getPointeeType(); |
514 | 258 | DifferentPtrness--; |
515 | 258 | } |
516 | 400 | if (!DifferentPtrness) { |
517 | 368 | auto RecFrom = From->getAs<RecordType>(); |
518 | 368 | auto RecTo = To->getAs<RecordType>(); |
519 | 368 | if (RecFrom && RecTo40 ) { |
520 | 28 | auto DeclFrom = RecFrom->getAsCXXRecordDecl(); |
521 | 28 | if (!DeclFrom->isCompleteDefinition()) |
522 | 2 | S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom; |
523 | 28 | auto DeclTo = RecTo->getAsCXXRecordDecl(); |
524 | 28 | if (!DeclTo->isCompleteDefinition()) |
525 | 1 | S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo; |
526 | 28 | } |
527 | 368 | } |
528 | 400 | } |
529 | | |
530 | | namespace { |
531 | | /// The kind of unwrapping we did when determining whether a conversion casts |
532 | | /// away constness. |
533 | | enum CastAwayConstnessKind { |
534 | | /// The conversion does not cast away constness. |
535 | | CACK_None = 0, |
536 | | /// We unwrapped similar types. |
537 | | CACK_Similar = 1, |
538 | | /// We unwrapped dissimilar types with similar representations (eg, a pointer |
539 | | /// versus an Objective-C object pointer). |
540 | | CACK_SimilarKind = 2, |
541 | | /// We unwrapped representationally-unrelated types, such as a pointer versus |
542 | | /// a pointer-to-member. |
543 | | CACK_Incoherent = 3, |
544 | | }; |
545 | | } |
546 | | |
547 | | /// Unwrap one level of types for CastsAwayConstness. |
548 | | /// |
549 | | /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from |
550 | | /// both types, provided that they're both pointer-like or array-like. Unlike |
551 | | /// the Sema function, doesn't care if the unwrapped pieces are related. |
552 | | /// |
553 | | /// This function may remove additional levels as necessary for correctness: |
554 | | /// the resulting T1 is unwrapped sufficiently that it is never an array type, |
555 | | /// so that its qualifiers can be directly compared to those of T2 (which will |
556 | | /// have the combined set of qualifiers from all indermediate levels of T2), |
557 | | /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers |
558 | | /// with those from T2. |
559 | | static CastAwayConstnessKind |
560 | 454k | unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) { |
561 | 454k | enum { None, Ptr, MemPtr, BlockPtr, Array }; |
562 | 482k | auto Classify = [](QualType T) { |
563 | 482k | if (T->isAnyPointerType()) return Ptr27.9k ; |
564 | 454k | if (T->isMemberPointerType()) return MemPtr83 ; |
565 | 454k | if (T->isBlockPointerType()) return BlockPtr78 ; |
566 | | // We somewhat-arbitrarily don't look through VLA types here. This is at |
567 | | // least consistent with the behavior of UnwrapSimilarTypes. |
568 | 454k | if (T->isConstantArrayType() || T->isIncompleteArrayType()452k ) return Array1.65k ; |
569 | 452k | return None; |
570 | 454k | }; |
571 | | |
572 | 454k | auto Unwrap = [&](QualType T) { |
573 | 25.3k | if (auto *AT = Context.getAsArrayType(T)) |
574 | 181 | return AT->getElementType(); |
575 | 25.1k | return T->getPointeeType(); |
576 | 25.3k | }; |
577 | | |
578 | 454k | CastAwayConstnessKind Kind; |
579 | | |
580 | 454k | if (T2->isReferenceType()) { |
581 | | // Special case: if the destination type is a reference type, unwrap it as |
582 | | // the first level. (The source will have been an lvalue expression in this |
583 | | // case, so there is no corresponding "reference to" in T1 to remove.) This |
584 | | // simulates removing a "pointer to" from both sides. |
585 | 507 | T2 = T2->getPointeeType(); |
586 | 507 | Kind = CastAwayConstnessKind::CACK_Similar; |
587 | 454k | } else if (Context.UnwrapSimilarTypes(T1, T2)) { |
588 | 219k | Kind = CastAwayConstnessKind::CACK_Similar; |
589 | 234k | } else { |
590 | | // Try unwrapping mismatching levels. |
591 | 234k | int T1Class = Classify(T1); |
592 | 234k | if (T1Class == None) |
593 | 220k | return CastAwayConstnessKind::CACK_None; |
594 | | |
595 | 14.5k | int T2Class = Classify(T2); |
596 | 14.5k | if (T2Class == None) |
597 | 1.97k | return CastAwayConstnessKind::CACK_None; |
598 | | |
599 | 12.5k | T1 = Unwrap(T1); |
600 | 12.5k | T2 = Unwrap(T2); |
601 | 12.5k | Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind12.4k |
602 | 12.5k | : CastAwayConstnessKind::CACK_Incoherent48 ; |
603 | 12.5k | } |
604 | | |
605 | | // We've unwrapped at least one level. If the resulting T1 is a (possibly |
606 | | // multidimensional) array type, any qualifier on any matching layer of |
607 | | // T2 is considered to correspond to T1. Decompose down to the element |
608 | | // type of T1 so that we can compare properly. |
609 | 232k | while (232k true) { |
610 | 232k | Context.UnwrapSimilarArrayTypes(T1, T2); |
611 | | |
612 | 232k | if (Classify(T1) != Array) |
613 | 231k | break; |
614 | | |
615 | 871 | auto T2Class = Classify(T2); |
616 | 871 | if (T2Class == None) |
617 | 738 | break; |
618 | | |
619 | 133 | if (T2Class != Array) |
620 | 85 | Kind = CastAwayConstnessKind::CACK_Incoherent; |
621 | 48 | else if (Kind != CastAwayConstnessKind::CACK_Incoherent) |
622 | 42 | Kind = CastAwayConstnessKind::CACK_SimilarKind; |
623 | | |
624 | 133 | T1 = Unwrap(T1); |
625 | 133 | T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers()); |
626 | 133 | } |
627 | | |
628 | 232k | return Kind; |
629 | 454k | } |
630 | | |
631 | | /// Check if the pointer conversion from SrcType to DestType casts away |
632 | | /// constness as defined in C++ [expr.const.cast]. This is used by the cast |
633 | | /// checkers. Both arguments must denote pointer (possibly to member) types. |
634 | | /// |
635 | | /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. |
636 | | /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. |
637 | | static CastAwayConstnessKind |
638 | | CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, |
639 | | bool CheckCVR, bool CheckObjCLifetime, |
640 | | QualType *TheOffendingSrcType = nullptr, |
641 | | QualType *TheOffendingDestType = nullptr, |
642 | 239k | Qualifiers *CastAwayQualifiers = nullptr) { |
643 | | // If the only checking we care about is for Objective-C lifetime qualifiers, |
644 | | // and we're not in ObjC mode, there's nothing to check. |
645 | 239k | if (!CheckCVR && CheckObjCLifetime33.2k && !Self.Context.getLangOpts().ObjC33.2k ) |
646 | 7.37k | return CastAwayConstnessKind::CACK_None; |
647 | | |
648 | 232k | if (!DestType->isReferenceType()) { |
649 | 231k | assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || |
650 | 231k | SrcType->isBlockPointerType()) && |
651 | 231k | "Source type is not pointer or pointer to member."); |
652 | 0 | assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || |
653 | 231k | DestType->isBlockPointerType()) && |
654 | 231k | "Destination type is not pointer or pointer to member."); |
655 | 231k | } |
656 | | |
657 | 0 | QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), |
658 | 232k | UnwrappedDestType = Self.Context.getCanonicalType(DestType); |
659 | | |
660 | | // Find the qualifiers. We only care about cvr-qualifiers for the |
661 | | // purpose of this check, because other qualifiers (address spaces, |
662 | | // Objective-C GC, etc.) are part of the type's identity. |
663 | 232k | QualType PrevUnwrappedSrcType = UnwrappedSrcType; |
664 | 232k | QualType PrevUnwrappedDestType = UnwrappedDestType; |
665 | 232k | auto WorstKind = CastAwayConstnessKind::CACK_Similar; |
666 | 232k | bool AllConstSoFar = true; |
667 | 454k | while (auto Kind = unwrapCastAwayConstnessLevel( |
668 | 232k | Self.Context, UnwrappedSrcType, UnwrappedDestType)) { |
669 | | // Track the worst kind of unwrap we needed to do before we found a |
670 | | // problem. |
671 | 232k | if (Kind > WorstKind) |
672 | 12.6k | WorstKind = Kind; |
673 | | |
674 | | // Determine the relevant qualifiers at this level. |
675 | 232k | Qualifiers SrcQuals, DestQuals; |
676 | 232k | Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); |
677 | 232k | Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); |
678 | | |
679 | | // We do not meaningfully track object const-ness of Objective-C object |
680 | | // types. Remove const from the source type if either the source or |
681 | | // the destination is an Objective-C object type. |
682 | 232k | if (UnwrappedSrcType->isObjCObjectType() || |
683 | 232k | UnwrappedDestType->isObjCObjectType()231k ) |
684 | 12.8k | SrcQuals.removeConst(); |
685 | | |
686 | 232k | if (CheckCVR) { |
687 | 206k | Qualifiers SrcCvrQuals = |
688 | 206k | Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()); |
689 | 206k | Qualifiers DestCvrQuals = |
690 | 206k | Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()); |
691 | | |
692 | 206k | if (SrcCvrQuals != DestCvrQuals) { |
693 | 15.6k | if (CastAwayQualifiers) |
694 | 15.3k | *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals; |
695 | | |
696 | | // If we removed a cvr-qualifier, this is casting away 'constness'. |
697 | 15.6k | if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) { |
698 | 9.94k | if (TheOffendingSrcType) |
699 | 9.88k | *TheOffendingSrcType = PrevUnwrappedSrcType; |
700 | 9.94k | if (TheOffendingDestType) |
701 | 9.88k | *TheOffendingDestType = PrevUnwrappedDestType; |
702 | 9.94k | return WorstKind; |
703 | 9.94k | } |
704 | | |
705 | | // If any prior level was not 'const', this is also casting away |
706 | | // 'constness'. We noted the outermost type missing a 'const' already. |
707 | 5.70k | if (!AllConstSoFar) |
708 | 28 | return WorstKind; |
709 | 5.70k | } |
710 | 206k | } |
711 | | |
712 | 222k | if (CheckObjCLifetime && |
713 | 222k | !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)25.8k ) |
714 | 25 | return WorstKind; |
715 | | |
716 | | // If we found our first non-const-qualified type, this may be the place |
717 | | // where things start to go wrong. |
718 | 222k | if (AllConstSoFar && !DestQuals.hasConst()222k ) { |
719 | 140k | AllConstSoFar = false; |
720 | 140k | if (TheOffendingSrcType) |
721 | 124k | *TheOffendingSrcType = PrevUnwrappedSrcType; |
722 | 140k | if (TheOffendingDestType) |
723 | 124k | *TheOffendingDestType = PrevUnwrappedDestType; |
724 | 140k | } |
725 | | |
726 | 222k | PrevUnwrappedSrcType = UnwrappedSrcType; |
727 | 222k | PrevUnwrappedDestType = UnwrappedDestType; |
728 | 222k | } |
729 | | |
730 | 222k | return CastAwayConstnessKind::CACK_None; |
731 | 232k | } |
732 | | |
733 | | static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK, |
734 | 88 | unsigned &DiagID) { |
735 | 88 | switch (CACK) { |
736 | 0 | case CastAwayConstnessKind::CACK_None: |
737 | 0 | llvm_unreachable("did not cast away constness"); |
738 | |
|
739 | 61 | case CastAwayConstnessKind::CACK_Similar: |
740 | | // FIXME: Accept these as an extension too? |
741 | 70 | case CastAwayConstnessKind::CACK_SimilarKind: |
742 | 70 | DiagID = diag::err_bad_cxx_cast_qualifiers_away; |
743 | 70 | return TC_Failed; |
744 | | |
745 | 18 | case CastAwayConstnessKind::CACK_Incoherent: |
746 | 18 | DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent; |
747 | 18 | return TC_Extension; |
748 | 88 | } |
749 | | |
750 | 0 | llvm_unreachable("unexpected cast away constness kind"); |
751 | 0 | } |
752 | | |
753 | | /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. |
754 | | /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- |
755 | | /// checked downcasts in class hierarchies. |
756 | 387 | void CastOperation::CheckDynamicCast() { |
757 | 387 | CheckNoDerefRAII NoderefCheck(*this); |
758 | | |
759 | 387 | if (ValueKind == VK_PRValue) |
760 | 310 | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); |
761 | 77 | else if (isPlaceholder()) |
762 | 1 | SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); |
763 | 387 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error |
764 | 0 | return; |
765 | | |
766 | 387 | QualType OrigSrcType = SrcExpr.get()->getType(); |
767 | 387 | QualType DestType = Self.Context.getCanonicalType(this->DestType); |
768 | | |
769 | | // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, |
770 | | // or "pointer to cv void". |
771 | | |
772 | 387 | QualType DestPointee; |
773 | 387 | const PointerType *DestPointer = DestType->getAs<PointerType>(); |
774 | 387 | const ReferenceType *DestReference = nullptr; |
775 | 387 | if (DestPointer) { |
776 | 306 | DestPointee = DestPointer->getPointeeType(); |
777 | 306 | } else if (81 (DestReference = DestType->getAs<ReferenceType>())81 ) { |
778 | 77 | DestPointee = DestReference->getPointeeType(); |
779 | 77 | } else { |
780 | 4 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) |
781 | 4 | << this->DestType << DestRange; |
782 | 4 | SrcExpr = ExprError(); |
783 | 4 | return; |
784 | 4 | } |
785 | | |
786 | 383 | const RecordType *DestRecord = DestPointee->getAs<RecordType>(); |
787 | 383 | if (DestPointee->isVoidType()) { |
788 | 13 | assert(DestPointer && "Reference to void is not possible"); |
789 | 370 | } else if (DestRecord) { |
790 | 368 | if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, |
791 | 368 | diag::err_bad_cast_incomplete, |
792 | 368 | DestRange)) { |
793 | 10 | SrcExpr = ExprError(); |
794 | 10 | return; |
795 | 10 | } |
796 | 368 | } else { |
797 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) |
798 | 2 | << DestPointee.getUnqualifiedType() << DestRange; |
799 | 2 | SrcExpr = ExprError(); |
800 | 2 | return; |
801 | 2 | } |
802 | | |
803 | | // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to |
804 | | // complete class type, [...]. If T is an lvalue reference type, v shall be |
805 | | // an lvalue of a complete class type, [...]. If T is an rvalue reference |
806 | | // type, v shall be an expression having a complete class type, [...] |
807 | 371 | QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); |
808 | 371 | QualType SrcPointee; |
809 | 371 | if (DestPointer) { |
810 | 295 | if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { |
811 | 294 | SrcPointee = SrcPointer->getPointeeType(); |
812 | 294 | } else { |
813 | 1 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) |
814 | 1 | << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange(); |
815 | 1 | SrcExpr = ExprError(); |
816 | 1 | return; |
817 | 1 | } |
818 | 295 | } else if (76 DestReference->isLValueReferenceType()76 ) { |
819 | 60 | if (!SrcExpr.get()->isLValue()) { |
820 | 1 | Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) |
821 | 1 | << CT_Dynamic << OrigSrcType << this->DestType << OpRange; |
822 | 1 | } |
823 | 60 | SrcPointee = SrcType; |
824 | 60 | } else { |
825 | | // If we're dynamic_casting from a prvalue to an rvalue reference, we need |
826 | | // to materialize the prvalue before we bind the reference to it. |
827 | 16 | if (SrcExpr.get()->isPRValue()) |
828 | 9 | SrcExpr = Self.CreateMaterializeTemporaryExpr( |
829 | 9 | SrcType, SrcExpr.get(), /*IsLValueReference*/ false); |
830 | 16 | SrcPointee = SrcType; |
831 | 16 | } |
832 | | |
833 | 370 | const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); |
834 | 370 | if (SrcRecord) { |
835 | 368 | if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, |
836 | 368 | diag::err_bad_cast_incomplete, |
837 | 368 | SrcExpr.get())) { |
838 | 2 | SrcExpr = ExprError(); |
839 | 2 | return; |
840 | 2 | } |
841 | 368 | } else { |
842 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) |
843 | 2 | << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); |
844 | 2 | SrcExpr = ExprError(); |
845 | 2 | return; |
846 | 2 | } |
847 | | |
848 | 366 | assert((DestPointer || DestReference) && |
849 | 366 | "Bad destination non-ptr/ref slipped through."); |
850 | 0 | assert((DestRecord || DestPointee->isVoidType()) && |
851 | 366 | "Bad destination pointee slipped through."); |
852 | 0 | assert(SrcRecord && "Bad source pointee slipped through."); |
853 | | |
854 | | // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. |
855 | 366 | if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { |
856 | 12 | Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) |
857 | 12 | << CT_Dynamic << OrigSrcType << this->DestType << OpRange; |
858 | 12 | SrcExpr = ExprError(); |
859 | 12 | return; |
860 | 12 | } |
861 | | |
862 | | // C++ 5.2.7p3: If the type of v is the same as the required result type, |
863 | | // [except for cv]. |
864 | 354 | if (DestRecord == SrcRecord) { |
865 | 45 | Kind = CK_NoOp; |
866 | 45 | return; |
867 | 45 | } |
868 | | |
869 | | // C++ 5.2.7p5 |
870 | | // Upcasts are resolved statically. |
871 | 309 | if (DestRecord && |
872 | 309 | Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)296 ) { |
873 | 78 | if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, |
874 | 78 | OpRange.getBegin(), OpRange, |
875 | 78 | &BasePath)) { |
876 | 17 | SrcExpr = ExprError(); |
877 | 17 | return; |
878 | 17 | } |
879 | | |
880 | 61 | Kind = CK_DerivedToBase; |
881 | 61 | return; |
882 | 78 | } |
883 | | |
884 | | // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. |
885 | 231 | const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); |
886 | 231 | assert(SrcDecl && "Definition missing"); |
887 | 231 | if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { |
888 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) |
889 | 2 | << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); |
890 | 2 | SrcExpr = ExprError(); |
891 | 2 | } |
892 | | |
893 | | // dynamic_cast is not available with -fno-rtti. |
894 | | // As an exception, dynamic_cast to void* is available because it doesn't |
895 | | // use RTTI. |
896 | 231 | if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()2 ) { |
897 | 1 | Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); |
898 | 1 | SrcExpr = ExprError(); |
899 | 1 | return; |
900 | 1 | } |
901 | | |
902 | | // Warns when dynamic_cast is used with RTTI data disabled. |
903 | 230 | if (!Self.getLangOpts().RTTIData) { |
904 | 7 | bool MicrosoftABI = |
905 | 7 | Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft(); |
906 | 7 | bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() == |
907 | 7 | DiagnosticOptions::MSVC; |
908 | 7 | if (MicrosoftABI || !DestPointee->isVoidType()4 ) |
909 | 5 | Self.Diag(OpRange.getBegin(), |
910 | 5 | diag::warn_no_dynamic_cast_with_rtti_disabled) |
911 | 5 | << isClangCL; |
912 | 7 | } |
913 | | |
914 | | // Done. Everything else is run-time checks. |
915 | 230 | Kind = CK_Dynamic; |
916 | 230 | } |
917 | | |
918 | | /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. |
919 | | /// Refer to C++ 5.2.11 for details. const_cast is typically used in code |
920 | | /// like this: |
921 | | /// const char *str = "literal"; |
922 | | /// legacy_function(const_cast\<char*\>(str)); |
923 | 2.87k | void CastOperation::CheckConstCast() { |
924 | 2.87k | CheckNoDerefRAII NoderefCheck(*this); |
925 | | |
926 | 2.87k | if (ValueKind == VK_PRValue) |
927 | 2.59k | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); |
928 | 285 | else if (isPlaceholder()) |
929 | 1 | SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); |
930 | 2.87k | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error |
931 | 0 | return; |
932 | | |
933 | 2.87k | unsigned msg = diag::err_bad_cxx_cast_generic; |
934 | 2.87k | auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg); |
935 | 2.87k | if (TCR != TC_Success && msg != 0116 ) { |
936 | 116 | Self.Diag(OpRange.getBegin(), msg) << CT_Const |
937 | 116 | << SrcExpr.get()->getType() << DestType << OpRange; |
938 | 116 | } |
939 | 2.87k | if (!isValidCast(TCR)) |
940 | 116 | SrcExpr = ExprError(); |
941 | 2.87k | } |
942 | | |
943 | 13 | void CastOperation::CheckAddrspaceCast() { |
944 | 13 | unsigned msg = diag::err_bad_cxx_cast_generic; |
945 | 13 | auto TCR = |
946 | 13 | TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind); |
947 | 13 | if (TCR != TC_Success && msg != 09 ) { |
948 | 9 | Self.Diag(OpRange.getBegin(), msg) |
949 | 9 | << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange; |
950 | 9 | } |
951 | 13 | if (!isValidCast(TCR)) |
952 | 9 | SrcExpr = ExprError(); |
953 | 13 | } |
954 | | |
955 | | /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast |
956 | | /// or downcast between respective pointers or references. |
957 | | static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, |
958 | | QualType DestType, |
959 | 3.32k | SourceRange OpRange) { |
960 | 3.32k | QualType SrcType = SrcExpr->getType(); |
961 | | // When casting from pointer or reference, get pointee type; use original |
962 | | // type otherwise. |
963 | 3.32k | const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); |
964 | 3.32k | const CXXRecordDecl *SrcRD = |
965 | 3.32k | SrcPointeeRD ? SrcPointeeRD478 : SrcType->getAsCXXRecordDecl()2.84k ; |
966 | | |
967 | | // Examining subobjects for records is only possible if the complete and |
968 | | // valid definition is available. Also, template instantiation is not |
969 | | // allowed here. |
970 | 3.32k | if (!SrcRD || !SrcRD->isCompleteDefinition()648 || SrcRD->isInvalidDecl()619 ) |
971 | 2.72k | return; |
972 | | |
973 | 599 | const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); |
974 | | |
975 | 599 | if (!DestRD || !DestRD->isCompleteDefinition()581 || DestRD->isInvalidDecl()567 ) |
976 | 32 | return; |
977 | | |
978 | 567 | enum { |
979 | 567 | ReinterpretUpcast, |
980 | 567 | ReinterpretDowncast |
981 | 567 | } ReinterpretKind; |
982 | | |
983 | 567 | CXXBasePaths BasePaths; |
984 | | |
985 | 567 | if (SrcRD->isDerivedFrom(DestRD, BasePaths)) |
986 | 239 | ReinterpretKind = ReinterpretUpcast; |
987 | 328 | else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) |
988 | 166 | ReinterpretKind = ReinterpretDowncast; |
989 | 162 | else |
990 | 162 | return; |
991 | | |
992 | 405 | bool VirtualBase = true; |
993 | 405 | bool NonZeroOffset = false; |
994 | 405 | for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), |
995 | 405 | E = BasePaths.end(); |
996 | 525 | I != E; ++I120 ) { |
997 | 421 | const CXXBasePath &Path = *I; |
998 | 421 | CharUnits Offset = CharUnits::Zero(); |
999 | 421 | bool IsVirtual = false; |
1000 | 421 | for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); |
1001 | 770 | IElem != EElem; ++IElem349 ) { |
1002 | 445 | IsVirtual = IElem->Base->isVirtual(); |
1003 | 445 | if (IsVirtual) |
1004 | 96 | break; |
1005 | 349 | const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); |
1006 | 349 | assert(BaseRD && "Base type should be a valid unqualified class type"); |
1007 | | // Don't check if any base has invalid declaration or has no definition |
1008 | | // since it has no layout info. |
1009 | 0 | const CXXRecordDecl *Class = IElem->Class, |
1010 | 349 | *ClassDefinition = Class->getDefinition(); |
1011 | 349 | if (Class->isInvalidDecl() || !ClassDefinition || |
1012 | 349 | !ClassDefinition->isCompleteDefinition()) |
1013 | 0 | return; |
1014 | | |
1015 | 349 | const ASTRecordLayout &DerivedLayout = |
1016 | 349 | Self.Context.getASTRecordLayout(Class); |
1017 | 349 | Offset += DerivedLayout.getBaseClassOffset(BaseRD); |
1018 | 349 | } |
1019 | 421 | if (!IsVirtual) { |
1020 | | // Don't warn if any path is a non-virtually derived base at offset zero. |
1021 | 325 | if (Offset.isZero()) |
1022 | 301 | return; |
1023 | | // Offset makes sense only for non-virtual bases. |
1024 | 24 | else |
1025 | 24 | NonZeroOffset = true; |
1026 | 325 | } |
1027 | 120 | VirtualBase = VirtualBase && IsVirtual; |
1028 | 120 | } |
1029 | | |
1030 | 104 | (void) NonZeroOffset; // Silence set but not used warning. |
1031 | 104 | assert((VirtualBase || NonZeroOffset) && |
1032 | 104 | "Should have returned if has non-virtual base with zero offset"); |
1033 | | |
1034 | 0 | QualType BaseType = |
1035 | 104 | ReinterpretKind == ReinterpretUpcast? DestType58 : SrcType46 ; |
1036 | 104 | QualType DerivedType = |
1037 | 104 | ReinterpretKind == ReinterpretUpcast? SrcType58 : DestType46 ; |
1038 | | |
1039 | 104 | SourceLocation BeginLoc = OpRange.getBegin(); |
1040 | 104 | Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) |
1041 | 104 | << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) |
1042 | 104 | << OpRange; |
1043 | 104 | Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) |
1044 | 104 | << int(ReinterpretKind) |
1045 | 104 | << FixItHint::CreateReplacement(BeginLoc, "static_cast"); |
1046 | 104 | } |
1047 | | |
1048 | | static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType, |
1049 | 24 | ASTContext &Context) { |
1050 | 24 | if (SrcType->isPointerType() && DestType->isPointerType()1 ) |
1051 | 0 | return true; |
1052 | | |
1053 | | // Allow integral type mismatch if their size are equal. |
1054 | 24 | if (SrcType->isIntegralType(Context) && DestType->isIntegralType(Context)22 ) |
1055 | 17 | if (Context.getTypeInfoInChars(SrcType).Width == |
1056 | 17 | Context.getTypeInfoInChars(DestType).Width) |
1057 | 17 | return true; |
1058 | | |
1059 | 7 | return Context.hasSameUnqualifiedType(SrcType, DestType); |
1060 | 24 | } |
1061 | | |
1062 | | static bool checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr, |
1063 | 1.40M | QualType DestType) { |
1064 | 1.40M | if (Self.Diags.isIgnored(diag::warn_cast_function_type, |
1065 | 1.40M | SrcExpr.get()->getExprLoc())) |
1066 | 1.40M | return true; |
1067 | | |
1068 | 22 | QualType SrcType = SrcExpr.get()->getType(); |
1069 | 22 | const FunctionType *SrcFTy = nullptr; |
1070 | 22 | const FunctionType *DstFTy = nullptr; |
1071 | 22 | if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()21 ) && |
1072 | 22 | DestType->isFunctionPointerType()16 ) || |
1073 | 22 | (6 SrcType->isMemberFunctionPointerType()6 && |
1074 | 17 | DestType->isMemberFunctionPointerType()1 )) { |
1075 | 17 | SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>(); |
1076 | 17 | DstFTy = DestType->getPointeeType()->castAs<FunctionType>(); |
1077 | 17 | } else if (5 SrcType->isFunctionType()5 && DestType->isFunctionReferenceType()1 ) { |
1078 | 1 | SrcFTy = SrcType->castAs<FunctionType>(); |
1079 | 1 | DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>(); |
1080 | 4 | } else { |
1081 | 4 | return true; |
1082 | 4 | } |
1083 | 18 | assert(SrcFTy && DstFTy); |
1084 | | |
1085 | 36 | auto IsVoidVoid = [](const FunctionType *T) { |
1086 | 36 | if (!T->getReturnType()->isVoidType()) |
1087 | 30 | return false; |
1088 | 6 | if (const auto *PT = T->getAs<FunctionProtoType>()) |
1089 | 5 | return !PT->isVariadic() && PT->getNumParams() == 04 ; |
1090 | 1 | return false; |
1091 | 6 | }; |
1092 | | |
1093 | | // Skip if either function type is void(*)(void) |
1094 | 18 | if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy)) |
1095 | 2 | return true; |
1096 | | |
1097 | | // Check return type. |
1098 | 16 | if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(), |
1099 | 16 | Self.Context)) |
1100 | 2 | return false; |
1101 | | |
1102 | | // Check if either has unspecified number of parameters |
1103 | 14 | if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType()) |
1104 | 1 | return true; |
1105 | | |
1106 | | // Check parameter types. |
1107 | | |
1108 | 13 | const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy); |
1109 | 13 | const auto *DstFPTy = cast<FunctionProtoType>(DstFTy); |
1110 | | |
1111 | | // In a cast involving function types with a variable argument list only the |
1112 | | // types of initial arguments that are provided are considered. |
1113 | 13 | unsigned NumParams = SrcFPTy->getNumParams(); |
1114 | 13 | unsigned DstNumParams = DstFPTy->getNumParams(); |
1115 | 13 | if (NumParams > DstNumParams) { |
1116 | 1 | if (!DstFPTy->isVariadic()) |
1117 | 0 | return false; |
1118 | 1 | NumParams = DstNumParams; |
1119 | 12 | } else if (NumParams < DstNumParams) { |
1120 | 4 | if (!SrcFPTy->isVariadic()) |
1121 | 4 | return false; |
1122 | 4 | } |
1123 | | |
1124 | 13 | for (unsigned i = 0; 9 i < NumParams; ++i4 ) |
1125 | 8 | if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i), |
1126 | 8 | DstFPTy->getParamType(i), Self.Context)) |
1127 | 4 | return false; |
1128 | | |
1129 | 5 | return true; |
1130 | 9 | } |
1131 | | |
1132 | | /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is |
1133 | | /// valid. |
1134 | | /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code |
1135 | | /// like this: |
1136 | | /// char *bytes = reinterpret_cast\<char*\>(int_ptr); |
1137 | 3.45k | void CastOperation::CheckReinterpretCast() { |
1138 | 3.45k | if (ValueKind == VK_PRValue && !isPlaceholder(BuiltinType::Overload)3.16k ) |
1139 | 3.09k | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); |
1140 | 353 | else |
1141 | 353 | checkNonOverloadPlaceholders(); |
1142 | 3.45k | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error |
1143 | 0 | return; |
1144 | | |
1145 | 3.45k | unsigned msg = diag::err_bad_cxx_cast_generic; |
1146 | 3.45k | TryCastResult tcr = |
1147 | 3.45k | TryReinterpretCast(Self, SrcExpr, DestType, |
1148 | 3.45k | /*CStyle*/false, OpRange, msg, Kind); |
1149 | 3.45k | if (tcr != TC_Success && msg != 0144 ) { |
1150 | 142 | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error |
1151 | 0 | return; |
1152 | 142 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { |
1153 | | //FIXME: &f<int>; is overloaded and resolvable |
1154 | 24 | Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) |
1155 | 24 | << OverloadExpr::find(SrcExpr.get()).Expression->getName() |
1156 | 24 | << DestType << OpRange; |
1157 | 24 | Self.NoteAllOverloadCandidates(SrcExpr.get()); |
1158 | | |
1159 | 118 | } else { |
1160 | 118 | diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), |
1161 | 118 | DestType, /*listInitialization=*/false); |
1162 | 118 | } |
1163 | 142 | } |
1164 | | |
1165 | 3.45k | if (isValidCast(tcr)) { |
1166 | 3.32k | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) |
1167 | 26 | checkObjCConversion(Sema::CCK_OtherCast); |
1168 | 3.32k | DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); |
1169 | | |
1170 | 3.32k | if (!checkCastFunctionType(Self, SrcExpr, DestType)) |
1171 | 1 | Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type) |
1172 | 1 | << SrcExpr.get()->getType() << DestType << OpRange; |
1173 | 3.32k | } else { |
1174 | 126 | SrcExpr = ExprError(); |
1175 | 126 | } |
1176 | 3.45k | } |
1177 | | |
1178 | | |
1179 | | /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. |
1180 | | /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making |
1181 | | /// implicit conversions explicit and getting rid of data loss warnings. |
1182 | 110k | void CastOperation::CheckStaticCast() { |
1183 | 110k | CheckNoDerefRAII NoderefCheck(*this); |
1184 | | |
1185 | 110k | if (isPlaceholder()) { |
1186 | 25 | checkNonOverloadPlaceholders(); |
1187 | 25 | if (SrcExpr.isInvalid()) |
1188 | 0 | return; |
1189 | 25 | } |
1190 | | |
1191 | | // This test is outside everything else because it's the only case where |
1192 | | // a non-lvalue-reference target type does not lead to decay. |
1193 | | // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". |
1194 | 110k | if (DestType->isVoidType()) { |
1195 | 15 | Kind = CK_ToVoid; |
1196 | | |
1197 | 15 | if (claimPlaceholder(BuiltinType::Overload)) { |
1198 | 4 | Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, |
1199 | 4 | false, // Decay Function to ptr |
1200 | 4 | true, // Complain |
1201 | 4 | OpRange, DestType, diag::err_bad_static_cast_overload); |
1202 | 4 | if (SrcExpr.isInvalid()) |
1203 | 2 | return; |
1204 | 4 | } |
1205 | | |
1206 | 13 | SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); |
1207 | 13 | return; |
1208 | 15 | } |
1209 | | |
1210 | 110k | if (ValueKind == VK_PRValue && !DestType->isRecordType()68.9k && |
1211 | 110k | !isPlaceholder(BuiltinType::Overload)68.5k ) { |
1212 | 68.5k | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); |
1213 | 68.5k | if (SrcExpr.isInvalid()) // if conversion failed, don't report another error |
1214 | 0 | return; |
1215 | 68.5k | } |
1216 | | |
1217 | 110k | unsigned msg = diag::err_bad_cxx_cast_generic; |
1218 | 110k | TryCastResult tcr |
1219 | 110k | = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, |
1220 | 110k | Kind, BasePath, /*ListInitialization=*/false); |
1221 | 110k | if (tcr != TC_Success && msg != 0200 ) { |
1222 | 140 | if (SrcExpr.isInvalid()) |
1223 | 2 | return; |
1224 | 138 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { |
1225 | 4 | OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; |
1226 | 4 | Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) |
1227 | 4 | << oe->getName() << DestType << OpRange |
1228 | 4 | << oe->getQualifierLoc().getSourceRange(); |
1229 | 4 | Self.NoteAllOverloadCandidates(SrcExpr.get()); |
1230 | 134 | } else { |
1231 | 134 | diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, |
1232 | 134 | /*listInitialization=*/false); |
1233 | 134 | } |
1234 | 138 | } |
1235 | | |
1236 | 110k | if (isValidCast(tcr)) { |
1237 | 109k | if (Kind == CK_BitCast) |
1238 | 3.93k | checkCastAlign(); |
1239 | 109k | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) |
1240 | 271 | checkObjCConversion(Sema::CCK_OtherCast); |
1241 | 109k | } else { |
1242 | 198 | SrcExpr = ExprError(); |
1243 | 198 | } |
1244 | 110k | } |
1245 | | |
1246 | 59.2k | static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) { |
1247 | 59.2k | auto *SrcPtrType = SrcType->getAs<PointerType>(); |
1248 | 59.2k | if (!SrcPtrType) |
1249 | 80 | return false; |
1250 | 59.1k | auto *DestPtrType = DestType->getAs<PointerType>(); |
1251 | 59.1k | if (!DestPtrType) |
1252 | 4.98k | return false; |
1253 | 54.1k | return SrcPtrType->getPointeeType().getAddressSpace() != |
1254 | 54.1k | DestPtrType->getPointeeType().getAddressSpace(); |
1255 | 59.1k | } |
1256 | | |
1257 | | /// TryStaticCast - Check if a static cast can be performed, and do so if |
1258 | | /// possible. If @p CStyle, ignore access restrictions on hierarchy casting |
1259 | | /// and casting away constness. |
1260 | | static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, |
1261 | | QualType DestType, |
1262 | | Sema::CheckedConversionKind CCK, |
1263 | | SourceRange OpRange, unsigned &msg, |
1264 | | CastKind &Kind, CXXCastPath &BasePath, |
1265 | 725k | bool ListInitialization) { |
1266 | | // Determine whether we have the semantics of a C-style cast. |
1267 | 725k | bool CStyle |
1268 | 725k | = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast178k ); |
1269 | | |
1270 | | // The order the tests is not entirely arbitrary. There is one conversion |
1271 | | // that can be handled in two different ways. Given: |
1272 | | // struct A {}; |
1273 | | // struct B : public A { |
1274 | | // B(); B(const A&); |
1275 | | // }; |
1276 | | // const A &a = B(); |
1277 | | // the cast static_cast<const B&>(a) could be seen as either a static |
1278 | | // reference downcast, or an explicit invocation of the user-defined |
1279 | | // conversion using B's conversion constructor. |
1280 | | // DR 427 specifies that the downcast is to be applied here. |
1281 | | |
1282 | | // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". |
1283 | | // Done outside this function. |
1284 | | |
1285 | 725k | TryCastResult tcr; |
1286 | | |
1287 | | // C++ 5.2.9p5, reference downcast. |
1288 | | // See the function for details. |
1289 | | // DR 427 specifies that this is to be applied before paragraph 2. |
1290 | 725k | tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, |
1291 | 725k | OpRange, msg, Kind, BasePath); |
1292 | 725k | if (tcr != TC_NotApplicable) |
1293 | 174 | return tcr; |
1294 | | |
1295 | | // C++11 [expr.static.cast]p3: |
1296 | | // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 |
1297 | | // T2" if "cv2 T2" is reference-compatible with "cv1 T1". |
1298 | 725k | tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, |
1299 | 725k | BasePath, msg); |
1300 | 725k | if (tcr != TC_NotApplicable) |
1301 | 32.0k | return tcr; |
1302 | | |
1303 | | // C++ 5.2.9p2: An expression e can be explicitly converted to a type T |
1304 | | // [...] if the declaration "T t(e);" is well-formed, [...]. |
1305 | 693k | tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, |
1306 | 693k | Kind, ListInitialization); |
1307 | 693k | if (SrcExpr.isInvalid()) |
1308 | 0 | return TC_Failed; |
1309 | 693k | if (tcr != TC_NotApplicable) |
1310 | 612k | return tcr; |
1311 | | |
1312 | | // C++ 5.2.9p6: May apply the reverse of any standard conversion, except |
1313 | | // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean |
1314 | | // conversions, subject to further restrictions. |
1315 | | // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal |
1316 | | // of qualification conversions impossible. (In C++20, adding an array bound |
1317 | | // would be the reverse of a qualification conversion, but adding permission |
1318 | | // to add an array bound in a static_cast is a wording oversight.) |
1319 | | // In the CStyle case, the earlier attempt to const_cast should have taken |
1320 | | // care of reverse qualification conversions. |
1321 | | |
1322 | 80.6k | QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); |
1323 | | |
1324 | | // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly |
1325 | | // converted to an integral type. [...] A value of a scoped enumeration type |
1326 | | // can also be explicitly converted to a floating-point type [...]. |
1327 | 80.6k | if (const EnumType *Enum = SrcType->getAs<EnumType>()) { |
1328 | 2.84k | if (Enum->getDecl()->isScoped()) { |
1329 | 2.83k | if (DestType->isBooleanType()) { |
1330 | 2 | Kind = CK_IntegralToBoolean; |
1331 | 2 | return TC_Success; |
1332 | 2.82k | } else if (DestType->isIntegralType(Self.Context)) { |
1333 | 2.82k | Kind = CK_IntegralCast; |
1334 | 2.82k | return TC_Success; |
1335 | 2.82k | } else if (4 DestType->isRealFloatingType()4 ) { |
1336 | 4 | Kind = CK_IntegralToFloating; |
1337 | 4 | return TC_Success; |
1338 | 4 | } |
1339 | 2.83k | } |
1340 | 2.84k | } |
1341 | | |
1342 | | // Reverse integral promotion/conversion. All such conversions are themselves |
1343 | | // again integral promotions or conversions and are thus already handled by |
1344 | | // p2 (TryDirectInitialization above). |
1345 | | // (Note: any data loss warnings should be suppressed.) |
1346 | | // The exception is the reverse of enum->integer, i.e. integer->enum (and |
1347 | | // enum->enum). See also C++ 5.2.9p7. |
1348 | | // The same goes for reverse floating point promotion/conversion and |
1349 | | // floating-integral conversions. Again, only floating->enum is relevant. |
1350 | 77.8k | if (DestType->isEnumeralType()) { |
1351 | 1.94k | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, |
1352 | 1.94k | diag::err_bad_cast_incomplete)) { |
1353 | 5 | SrcExpr = ExprError(); |
1354 | 5 | return TC_Failed; |
1355 | 5 | } |
1356 | 1.94k | if (SrcType->isIntegralOrEnumerationType()) { |
1357 | | // [expr.static.cast]p10 If the enumeration type has a fixed underlying |
1358 | | // type, the value is first converted to that type by integral conversion |
1359 | 1.93k | const EnumType *Enum = DestType->castAs<EnumType>(); |
1360 | 1.93k | Kind = Enum->getDecl()->isFixed() && |
1361 | 1.93k | Enum->getDecl()->getIntegerType()->isBooleanType()1.64k |
1362 | 1.93k | ? CK_IntegralToBoolean14 |
1363 | 1.93k | : CK_IntegralCast1.91k ; |
1364 | 1.93k | return TC_Success; |
1365 | 1.93k | } else if (8 SrcType->isRealFloatingType()8 ) { |
1366 | 4 | Kind = CK_FloatingToIntegral; |
1367 | 4 | return TC_Success; |
1368 | 4 | } |
1369 | 1.94k | } |
1370 | | |
1371 | | // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. |
1372 | | // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. |
1373 | 75.9k | tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, |
1374 | 75.9k | Kind, BasePath); |
1375 | 75.9k | if (tcr != TC_NotApplicable) |
1376 | 924 | return tcr; |
1377 | | |
1378 | | // Reverse member pointer conversion. C++ 4.11 specifies member pointer |
1379 | | // conversion. C++ 5.2.9p9 has additional information. |
1380 | | // DR54's access restrictions apply here also. |
1381 | 74.9k | tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, |
1382 | 74.9k | OpRange, msg, Kind, BasePath); |
1383 | 74.9k | if (tcr != TC_NotApplicable) |
1384 | 119 | return tcr; |
1385 | | |
1386 | | // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to |
1387 | | // void*. C++ 5.2.9p10 specifies additional restrictions, which really is |
1388 | | // just the usual constness stuff. |
1389 | 74.8k | if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { |
1390 | 59.7k | QualType SrcPointee = SrcPointer->getPointeeType(); |
1391 | 59.7k | if (SrcPointee->isVoidType()) { |
1392 | 26.3k | if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { |
1393 | 25.1k | QualType DestPointee = DestPointer->getPointeeType(); |
1394 | 25.1k | if (DestPointee->isIncompleteOrObjectType()) { |
1395 | | // This is definitely the intended conversion, but it might fail due |
1396 | | // to a qualifier violation. Note that we permit Objective-C lifetime |
1397 | | // and GC qualifier mismatches here. |
1398 | 24.7k | if (!CStyle) { |
1399 | 3.94k | Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); |
1400 | 3.94k | Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); |
1401 | 3.94k | DestPointeeQuals.removeObjCGCAttr(); |
1402 | 3.94k | DestPointeeQuals.removeObjCLifetime(); |
1403 | 3.94k | SrcPointeeQuals.removeObjCGCAttr(); |
1404 | 3.94k | SrcPointeeQuals.removeObjCLifetime(); |
1405 | 3.94k | if (DestPointeeQuals != SrcPointeeQuals && |
1406 | 3.94k | !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)48 ) { |
1407 | 27 | msg = diag::err_bad_cxx_cast_qualifiers_away; |
1408 | 27 | return TC_Failed; |
1409 | 27 | } |
1410 | 3.94k | } |
1411 | 24.7k | Kind = IsAddressSpaceConversion(SrcType, DestType) |
1412 | 24.7k | ? CK_AddressSpaceConversion15 |
1413 | 24.7k | : CK_BitCast24.7k ; |
1414 | 24.7k | return TC_Success; |
1415 | 24.7k | } |
1416 | | |
1417 | | // Microsoft permits static_cast from 'pointer-to-void' to |
1418 | | // 'pointer-to-function'. |
1419 | 335 | if (!CStyle && Self.getLangOpts().MSVCCompat6 && |
1420 | 335 | DestPointee->isFunctionType()5 ) { |
1421 | 5 | Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; |
1422 | 5 | Kind = CK_BitCast; |
1423 | 5 | return TC_Success; |
1424 | 5 | } |
1425 | 335 | } |
1426 | 1.21k | else if (DestType->isObjCObjectPointerType()) { |
1427 | | // allow both c-style cast and static_cast of objective-c pointers as |
1428 | | // they are pervasive. |
1429 | 655 | Kind = CK_CPointerToObjCPointerCast; |
1430 | 655 | return TC_Success; |
1431 | 655 | } |
1432 | 560 | else if (CStyle && DestType->isBlockPointerType()) { |
1433 | | // allow c-style cast of void * to block pointers. |
1434 | 11 | Kind = CK_AnyPointerToBlockPointerCast; |
1435 | 11 | return TC_Success; |
1436 | 11 | } |
1437 | 26.3k | } |
1438 | 59.7k | } |
1439 | | // Allow arbitrary objective-c pointer conversion with static casts. |
1440 | 49.4k | if (SrcType->isObjCObjectPointerType() && |
1441 | 49.4k | DestType->isObjCObjectPointerType()88 ) { |
1442 | 3 | Kind = CK_BitCast; |
1443 | 3 | return TC_Success; |
1444 | 3 | } |
1445 | | // Allow ns-pointer to cf-pointer conversion in either direction |
1446 | | // with static casts. |
1447 | 49.4k | if (!CStyle && |
1448 | 49.4k | Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)143 ) |
1449 | 22 | return TC_Success; |
1450 | | |
1451 | | // See if it looks like the user is trying to convert between |
1452 | | // related record types, and select a better diagnostic if so. |
1453 | 49.4k | if (auto SrcPointer = SrcType->getAs<PointerType>()) |
1454 | 34.3k | if (auto DestPointer = DestType->getAs<PointerType>()) |
1455 | 27.8k | if (SrcPointer->getPointeeType()->getAs<RecordType>() && |
1456 | 27.8k | DestPointer->getPointeeType()->getAs<RecordType>()9.32k ) |
1457 | 537 | msg = diag::err_bad_cxx_cast_unrelated_class; |
1458 | | |
1459 | 49.4k | if (SrcType->isMatrixType() && DestType->isMatrixType()52 ) { |
1460 | 44 | if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) { |
1461 | 4 | SrcExpr = ExprError(); |
1462 | 4 | return TC_Failed; |
1463 | 4 | } |
1464 | 40 | return TC_Success; |
1465 | 44 | } |
1466 | | |
1467 | | // We tried everything. Everything! Nothing works! :-( |
1468 | 49.3k | return TC_NotApplicable; |
1469 | 49.4k | } |
1470 | | |
1471 | | /// Tests whether a conversion according to N2844 is valid. |
1472 | | TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, |
1473 | | QualType DestType, bool CStyle, |
1474 | | CastKind &Kind, CXXCastPath &BasePath, |
1475 | 725k | unsigned &msg) { |
1476 | | // C++11 [expr.static.cast]p3: |
1477 | | // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to |
1478 | | // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". |
1479 | 725k | const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); |
1480 | 725k | if (!R) |
1481 | 693k | return TC_NotApplicable; |
1482 | | |
1483 | 32.1k | if (!SrcExpr->isGLValue()) |
1484 | 50 | return TC_NotApplicable; |
1485 | | |
1486 | | // Because we try the reference downcast before this function, from now on |
1487 | | // this is the only cast possibility, so we issue an error if we fail now. |
1488 | | // FIXME: Should allow casting away constness if CStyle. |
1489 | 32.1k | QualType FromType = SrcExpr->getType(); |
1490 | 32.1k | QualType ToType = R->getPointeeType(); |
1491 | 32.1k | if (CStyle) { |
1492 | 6 | FromType = FromType.getUnqualifiedType(); |
1493 | 6 | ToType = ToType.getUnqualifiedType(); |
1494 | 6 | } |
1495 | | |
1496 | 32.1k | Sema::ReferenceConversions RefConv; |
1497 | 32.1k | Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship( |
1498 | 32.1k | SrcExpr->getBeginLoc(), ToType, FromType, &RefConv); |
1499 | 32.1k | if (RefResult != Sema::Ref_Compatible) { |
1500 | 15 | if (CStyle || RefResult == Sema::Ref_Incompatible13 ) |
1501 | 11 | return TC_NotApplicable; |
1502 | | // Diagnose types which are reference-related but not compatible here since |
1503 | | // we can provide better diagnostics. In these cases forwarding to |
1504 | | // [expr.static.cast]p4 should never result in a well-formed cast. |
1505 | 4 | msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast2 |
1506 | 4 | : diag::err_bad_rvalue_to_rvalue_cast2 ; |
1507 | 4 | return TC_Failed; |
1508 | 15 | } |
1509 | | |
1510 | 32.0k | if (RefConv & Sema::ReferenceConversions::DerivedToBase) { |
1511 | 25 | Kind = CK_DerivedToBase; |
1512 | 25 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
1513 | 25 | /*DetectVirtual=*/true); |
1514 | 25 | if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(), |
1515 | 25 | R->getPointeeType(), Paths)) |
1516 | 0 | return TC_NotApplicable; |
1517 | | |
1518 | 25 | Self.BuildBasePathArray(Paths, BasePath); |
1519 | 25 | } else |
1520 | 32.0k | Kind = CK_NoOp; |
1521 | | |
1522 | 32.0k | return TC_Success; |
1523 | 32.0k | } |
1524 | | |
1525 | | /// Tests whether a conversion according to C++ 5.2.9p5 is valid. |
1526 | | TryCastResult |
1527 | | TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, |
1528 | | bool CStyle, SourceRange OpRange, |
1529 | | unsigned &msg, CastKind &Kind, |
1530 | 725k | CXXCastPath &BasePath) { |
1531 | | // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be |
1532 | | // cast to type "reference to cv2 D", where D is a class derived from B, |
1533 | | // if a valid standard conversion from "pointer to D" to "pointer to B" |
1534 | | // exists, cv2 >= cv1, and B is not a virtual base class of D. |
1535 | | // In addition, DR54 clarifies that the base must be accessible in the |
1536 | | // current context. Although the wording of DR54 only applies to the pointer |
1537 | | // variant of this rule, the intent is clearly for it to apply to the this |
1538 | | // conversion as well. |
1539 | | |
1540 | 725k | const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); |
1541 | 725k | if (!DestReference) { |
1542 | 683k | return TC_NotApplicable; |
1543 | 683k | } |
1544 | 41.5k | bool RValueRef = DestReference->isRValueReferenceType(); |
1545 | 41.5k | if (!RValueRef && !SrcExpr->isLValue()9.37k ) { |
1546 | | // We know the left side is an lvalue reference, so we can suggest a reason. |
1547 | 115 | msg = diag::err_bad_cxx_cast_rvalue; |
1548 | 115 | return TC_NotApplicable; |
1549 | 115 | } |
1550 | | |
1551 | 41.4k | QualType DestPointee = DestReference->getPointeeType(); |
1552 | | |
1553 | | // FIXME: If the source is a prvalue, we should issue a warning (because the |
1554 | | // cast always has undefined behavior), and for AST consistency, we should |
1555 | | // materialize a temporary. |
1556 | 41.4k | return TryStaticDowncast(Self, |
1557 | 41.4k | Self.Context.getCanonicalType(SrcExpr->getType()), |
1558 | 41.4k | Self.Context.getCanonicalType(DestPointee), CStyle, |
1559 | 41.4k | OpRange, SrcExpr->getType(), DestType, msg, Kind, |
1560 | 41.4k | BasePath); |
1561 | 41.5k | } |
1562 | | |
1563 | | /// Tests whether a conversion according to C++ 5.2.9p8 is valid. |
1564 | | TryCastResult |
1565 | | TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, |
1566 | | bool CStyle, SourceRange OpRange, |
1567 | | unsigned &msg, CastKind &Kind, |
1568 | 75.9k | CXXCastPath &BasePath) { |
1569 | | // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class |
1570 | | // type, can be converted to an rvalue of type "pointer to cv2 D", where D |
1571 | | // is a class derived from B, if a valid standard conversion from "pointer |
1572 | | // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base |
1573 | | // class of D. |
1574 | | // In addition, DR54 clarifies that the base must be accessible in the |
1575 | | // current context. |
1576 | | |
1577 | 75.9k | const PointerType *DestPointer = DestType->getAs<PointerType>(); |
1578 | 75.9k | if (!DestPointer) { |
1579 | 20.7k | return TC_NotApplicable; |
1580 | 20.7k | } |
1581 | | |
1582 | 55.1k | const PointerType *SrcPointer = SrcType->getAs<PointerType>(); |
1583 | 55.1k | if (!SrcPointer) { |
1584 | 1.57k | msg = diag::err_bad_static_cast_pointer_nonpointer; |
1585 | 1.57k | return TC_NotApplicable; |
1586 | 1.57k | } |
1587 | | |
1588 | 53.5k | return TryStaticDowncast(Self, |
1589 | 53.5k | Self.Context.getCanonicalType(SrcPointer->getPointeeType()), |
1590 | 53.5k | Self.Context.getCanonicalType(DestPointer->getPointeeType()), |
1591 | 53.5k | CStyle, OpRange, SrcType, DestType, msg, Kind, |
1592 | 53.5k | BasePath); |
1593 | 55.1k | } |
1594 | | |
1595 | | /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and |
1596 | | /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to |
1597 | | /// DestType is possible and allowed. |
1598 | | TryCastResult |
1599 | | TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, |
1600 | | bool CStyle, SourceRange OpRange, QualType OrigSrcType, |
1601 | | QualType OrigDestType, unsigned &msg, |
1602 | 95.0k | CastKind &Kind, CXXCastPath &BasePath) { |
1603 | | // We can only work with complete types. But don't complain if it doesn't work |
1604 | 95.0k | if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || |
1605 | 95.0k | !Self.isCompleteType(OpRange.getBegin(), DestType)69.6k ) |
1606 | 26.8k | return TC_NotApplicable; |
1607 | | |
1608 | | // Downcast can only happen in class hierarchies, so we need classes. |
1609 | 68.1k | if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()51.2k ) { |
1610 | 27.0k | return TC_NotApplicable; |
1611 | 27.0k | } |
1612 | | |
1613 | 41.1k | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
1614 | 41.1k | /*DetectVirtual=*/true); |
1615 | 41.1k | if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { |
1616 | 40.0k | return TC_NotApplicable; |
1617 | 40.0k | } |
1618 | | |
1619 | | // Target type does derive from source type. Now we're serious. If an error |
1620 | | // appears now, it's not ignored. |
1621 | | // This may not be entirely in line with the standard. Take for example: |
1622 | | // struct A {}; |
1623 | | // struct B : virtual A { |
1624 | | // B(A&); |
1625 | | // }; |
1626 | | // |
1627 | | // void f() |
1628 | | // { |
1629 | | // (void)static_cast<const B&>(*((A*)0)); |
1630 | | // } |
1631 | | // As far as the standard is concerned, p5 does not apply (A is virtual), so |
1632 | | // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. |
1633 | | // However, both GCC and Comeau reject this example, and accepting it would |
1634 | | // mean more complex code if we're to preserve the nice error message. |
1635 | | // FIXME: Being 100% compliant here would be nice to have. |
1636 | | |
1637 | | // Must preserve cv, as always, unless we're in C-style mode. |
1638 | 1.09k | if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)945 ) { |
1639 | 8 | msg = diag::err_bad_cxx_cast_qualifiers_away; |
1640 | 8 | return TC_Failed; |
1641 | 8 | } |
1642 | | |
1643 | 1.09k | if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { |
1644 | | // This code is analoguous to that in CheckDerivedToBaseConversion, except |
1645 | | // that it builds the paths in reverse order. |
1646 | | // To sum up: record all paths to the base and build a nice string from |
1647 | | // them. Use it to spice up the error message. |
1648 | 6 | if (!Paths.isRecordingPaths()) { |
1649 | 0 | Paths.clear(); |
1650 | 0 | Paths.setRecordingPaths(true); |
1651 | 0 | Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); |
1652 | 0 | } |
1653 | 6 | std::string PathDisplayStr; |
1654 | 6 | std::set<unsigned> DisplayedPaths; |
1655 | 12 | for (clang::CXXBasePath &Path : Paths) { |
1656 | 12 | if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) { |
1657 | | // We haven't displayed a path to this particular base |
1658 | | // class subobject yet. |
1659 | 12 | PathDisplayStr += "\n "; |
1660 | 12 | for (CXXBasePathElement &PE : llvm::reverse(Path)) |
1661 | 36 | PathDisplayStr += PE.Base->getType().getAsString() + " -> "; |
1662 | 12 | PathDisplayStr += QualType(DestType).getAsString(); |
1663 | 12 | } |
1664 | 12 | } |
1665 | | |
1666 | 6 | Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) |
1667 | 6 | << QualType(SrcType).getUnqualifiedType() |
1668 | 6 | << QualType(DestType).getUnqualifiedType() |
1669 | 6 | << PathDisplayStr << OpRange; |
1670 | 6 | msg = 0; |
1671 | 6 | return TC_Failed; |
1672 | 6 | } |
1673 | | |
1674 | 1.08k | if (Paths.getDetectedVirtual() != nullptr) { |
1675 | 36 | QualType VirtualBase(Paths.getDetectedVirtual(), 0); |
1676 | 36 | Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) |
1677 | 36 | << OrigSrcType << OrigDestType << VirtualBase << OpRange; |
1678 | 36 | msg = 0; |
1679 | 36 | return TC_Failed; |
1680 | 36 | } |
1681 | | |
1682 | 1.04k | if (!CStyle) { |
1683 | 915 | switch (Self.CheckBaseClassAccess(OpRange.getBegin(), |
1684 | 915 | SrcType, DestType, |
1685 | 915 | Paths.front(), |
1686 | 915 | diag::err_downcast_from_inaccessible_base)) { |
1687 | 901 | case Sema::AR_accessible: |
1688 | 913 | case Sema::AR_delayed: // be optimistic |
1689 | 913 | case Sema::AR_dependent: // be optimistic |
1690 | 913 | break; |
1691 | | |
1692 | 2 | case Sema::AR_inaccessible: |
1693 | 2 | msg = 0; |
1694 | 2 | return TC_Failed; |
1695 | 915 | } |
1696 | 915 | } |
1697 | | |
1698 | 1.04k | Self.BuildBasePathArray(Paths, BasePath); |
1699 | 1.04k | Kind = CK_BaseToDerived; |
1700 | 1.04k | return TC_Success; |
1701 | 1.04k | } |
1702 | | |
1703 | | /// TryStaticMemberPointerUpcast - Tests whether a conversion according to |
1704 | | /// C++ 5.2.9p9 is valid: |
1705 | | /// |
1706 | | /// An rvalue of type "pointer to member of D of type cv1 T" can be |
1707 | | /// converted to an rvalue of type "pointer to member of B of type cv2 T", |
1708 | | /// where B is a base class of D [...]. |
1709 | | /// |
1710 | | TryCastResult |
1711 | | TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, |
1712 | | QualType DestType, bool CStyle, |
1713 | | SourceRange OpRange, |
1714 | | unsigned &msg, CastKind &Kind, |
1715 | 74.9k | CXXCastPath &BasePath) { |
1716 | 74.9k | const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); |
1717 | 74.9k | if (!DestMemPtr) |
1718 | 74.8k | return TC_NotApplicable; |
1719 | | |
1720 | 169 | bool WasOverloadedFunction = false; |
1721 | 169 | DeclAccessPair FoundOverload; |
1722 | 169 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { |
1723 | 11 | if (FunctionDecl *Fn |
1724 | 11 | = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, |
1725 | 11 | FoundOverload)) { |
1726 | 11 | CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); |
1727 | 11 | SrcType = Self.Context.getMemberPointerType(Fn->getType(), |
1728 | 11 | Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); |
1729 | 11 | WasOverloadedFunction = true; |
1730 | 11 | } |
1731 | 11 | } |
1732 | | |
1733 | 169 | const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); |
1734 | 169 | if (!SrcMemPtr) { |
1735 | 1 | msg = diag::err_bad_static_cast_member_pointer_nonmp; |
1736 | 1 | return TC_NotApplicable; |
1737 | 1 | } |
1738 | | |
1739 | | // Lock down the inheritance model right now in MS ABI, whether or not the |
1740 | | // pointee types are the same. |
1741 | 168 | if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
1742 | 19 | (void)Self.isCompleteType(OpRange.getBegin(), SrcType); |
1743 | 19 | (void)Self.isCompleteType(OpRange.getBegin(), DestType); |
1744 | 19 | } |
1745 | | |
1746 | | // T == T, modulo cv |
1747 | 168 | if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), |
1748 | 168 | DestMemPtr->getPointeeType())) |
1749 | 33 | return TC_NotApplicable; |
1750 | | |
1751 | | // B base of D |
1752 | 135 | QualType SrcClass(SrcMemPtr->getClass(), 0); |
1753 | 135 | QualType DestClass(DestMemPtr->getClass(), 0); |
1754 | 135 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
1755 | 135 | /*DetectVirtual=*/true); |
1756 | 135 | if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) |
1757 | 16 | return TC_NotApplicable; |
1758 | | |
1759 | | // B is a base of D. But is it an allowed base? If not, it's a hard error. |
1760 | 119 | if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { |
1761 | 3 | Paths.clear(); |
1762 | 3 | Paths.setRecordingPaths(true); |
1763 | 3 | bool StillOkay = |
1764 | 3 | Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); |
1765 | 3 | assert(StillOkay); |
1766 | 0 | (void)StillOkay; |
1767 | 3 | std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); |
1768 | 3 | Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) |
1769 | 3 | << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; |
1770 | 3 | msg = 0; |
1771 | 3 | return TC_Failed; |
1772 | 3 | } |
1773 | | |
1774 | 116 | if (const RecordType *VBase = Paths.getDetectedVirtual()) { |
1775 | 15 | Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) |
1776 | 15 | << SrcClass << DestClass << QualType(VBase, 0) << OpRange; |
1777 | 15 | msg = 0; |
1778 | 15 | return TC_Failed; |
1779 | 15 | } |
1780 | | |
1781 | 101 | if (!CStyle) { |
1782 | 26 | switch (Self.CheckBaseClassAccess(OpRange.getBegin(), |
1783 | 26 | DestClass, SrcClass, |
1784 | 26 | Paths.front(), |
1785 | 26 | diag::err_upcast_to_inaccessible_base)) { |
1786 | 21 | case Sema::AR_accessible: |
1787 | 25 | case Sema::AR_delayed: |
1788 | 25 | case Sema::AR_dependent: |
1789 | | // Optimistically assume that the delayed and dependent cases |
1790 | | // will work out. |
1791 | 25 | break; |
1792 | | |
1793 | 1 | case Sema::AR_inaccessible: |
1794 | 1 | msg = 0; |
1795 | 1 | return TC_Failed; |
1796 | 26 | } |
1797 | 26 | } |
1798 | | |
1799 | 100 | if (WasOverloadedFunction) { |
1800 | | // Resolve the address of the overloaded function again, this time |
1801 | | // allowing complaints if something goes wrong. |
1802 | 10 | FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), |
1803 | 10 | DestType, |
1804 | 10 | true, |
1805 | 10 | FoundOverload); |
1806 | 10 | if (!Fn) { |
1807 | 0 | msg = 0; |
1808 | 0 | return TC_Failed; |
1809 | 0 | } |
1810 | | |
1811 | 10 | SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); |
1812 | 10 | if (!SrcExpr.isUsable()) { |
1813 | 0 | msg = 0; |
1814 | 0 | return TC_Failed; |
1815 | 0 | } |
1816 | 10 | } |
1817 | | |
1818 | 100 | Self.BuildBasePathArray(Paths, BasePath); |
1819 | 100 | Kind = CK_DerivedToBaseMemberPointer; |
1820 | 100 | return TC_Success; |
1821 | 100 | } |
1822 | | |
1823 | | /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 |
1824 | | /// is valid: |
1825 | | /// |
1826 | | /// An expression e can be explicitly converted to a type T using a |
1827 | | /// @c static_cast if the declaration "T t(e);" is well-formed [...]. |
1828 | | TryCastResult |
1829 | | TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, |
1830 | | Sema::CheckedConversionKind CCK, |
1831 | | SourceRange OpRange, unsigned &msg, |
1832 | 693k | CastKind &Kind, bool ListInitialization) { |
1833 | 693k | if (DestType->isRecordType()) { |
1834 | 26.5k | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, |
1835 | 26.5k | diag::err_bad_cast_incomplete) || |
1836 | 26.5k | Self.RequireNonAbstractType(OpRange.getBegin(), DestType, |
1837 | 26.5k | diag::err_allocation_of_abstract_type)) { |
1838 | 22 | msg = 0; |
1839 | 22 | return TC_Failed; |
1840 | 22 | } |
1841 | 26.5k | } |
1842 | | |
1843 | 693k | InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); |
1844 | 693k | InitializationKind InitKind |
1845 | 693k | = (CCK == Sema::CCK_CStyleCast) |
1846 | 693k | ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, |
1847 | 546k | ListInitialization) |
1848 | 693k | : (CCK == Sema::CCK_FunctionalCast)146k |
1849 | 146k | ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)68.4k |
1850 | 146k | : InitializationKind::CreateCast(OpRange)77.8k ; |
1851 | 693k | Expr *SrcExprRaw = SrcExpr.get(); |
1852 | | // FIXME: Per DR242, we should check for an implicit conversion sequence |
1853 | | // or for a constructor that could be invoked by direct-initialization |
1854 | | // here, not for an initialization sequence. |
1855 | 693k | InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); |
1856 | | |
1857 | | // At this point of CheckStaticCast, if the destination is a reference, |
1858 | | // or the expression is an overload expression this has to work. |
1859 | | // There is no other way that works. |
1860 | | // On the other hand, if we're checking a C-style cast, we've still got |
1861 | | // the reinterpret_cast way. |
1862 | 693k | bool CStyle |
1863 | 693k | = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast146k ); |
1864 | 693k | if (InitSeq.Failed() && (80.6k CStyle80.6k || !DestType->isReferenceType()8.85k )) |
1865 | 80.6k | return TC_NotApplicable; |
1866 | | |
1867 | 612k | ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); |
1868 | 612k | if (Result.isInvalid()) { |
1869 | 29 | msg = 0; |
1870 | 29 | return TC_Failed; |
1871 | 29 | } |
1872 | | |
1873 | 612k | if (InitSeq.isConstructorInitialization()) |
1874 | 26.2k | Kind = CK_ConstructorConversion; |
1875 | 586k | else |
1876 | 586k | Kind = CK_NoOp; |
1877 | | |
1878 | 612k | SrcExpr = Result; |
1879 | 612k | return TC_Success; |
1880 | 612k | } |
1881 | | |
1882 | | /// TryConstCast - See if a const_cast from source to destination is allowed, |
1883 | | /// and perform it if it is. |
1884 | | static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, |
1885 | | QualType DestType, bool CStyle, |
1886 | 627k | unsigned &msg) { |
1887 | 627k | DestType = Self.Context.getCanonicalType(DestType); |
1888 | 627k | QualType SrcType = SrcExpr.get()->getType(); |
1889 | 627k | bool NeedToMaterializeTemporary = false; |
1890 | | |
1891 | 627k | if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { |
1892 | | // C++11 5.2.11p4: |
1893 | | // if a pointer to T1 can be explicitly converted to the type "pointer to |
1894 | | // T2" using a const_cast, then the following conversions can also be |
1895 | | // made: |
1896 | | // -- an lvalue of type T1 can be explicitly converted to an lvalue of |
1897 | | // type T2 using the cast const_cast<T2&>; |
1898 | | // -- a glvalue of type T1 can be explicitly converted to an xvalue of |
1899 | | // type T2 using the cast const_cast<T2&&>; and |
1900 | | // -- if T1 is a class type, a prvalue of type T1 can be explicitly |
1901 | | // converted to an xvalue of type T2 using the cast const_cast<T2&&>. |
1902 | | |
1903 | 915 | if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()814 ) { |
1904 | | // Cannot const_cast non-lvalue to lvalue reference type. But if this |
1905 | | // is C-style, static_cast might find a way, so we simply suggest a |
1906 | | // message and tell the parent to keep searching. |
1907 | 62 | msg = diag::err_bad_cxx_cast_rvalue; |
1908 | 62 | return TC_NotApplicable; |
1909 | 62 | } |
1910 | | |
1911 | 853 | if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isPRValue()101 ) { |
1912 | 48 | if (!SrcType->isRecordType()) { |
1913 | | // Cannot const_cast non-class prvalue to rvalue reference type. But if |
1914 | | // this is C-style, static_cast can do this. |
1915 | 11 | msg = diag::err_bad_cxx_cast_rvalue; |
1916 | 11 | return TC_NotApplicable; |
1917 | 11 | } |
1918 | | |
1919 | | // Materialize the class prvalue so that the const_cast can bind a |
1920 | | // reference to it. |
1921 | 37 | NeedToMaterializeTemporary = true; |
1922 | 37 | } |
1923 | | |
1924 | | // It's not completely clear under the standard whether we can |
1925 | | // const_cast bit-field gl-values. Doing so would not be |
1926 | | // intrinsically complicated, but for now, we say no for |
1927 | | // consistency with other compilers and await the word of the |
1928 | | // committee. |
1929 | 842 | if (SrcExpr.get()->refersToBitField()) { |
1930 | 6 | msg = diag::err_bad_cxx_cast_bitfield; |
1931 | 6 | return TC_NotApplicable; |
1932 | 6 | } |
1933 | | |
1934 | 836 | DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); |
1935 | 836 | SrcType = Self.Context.getPointerType(SrcType); |
1936 | 836 | } |
1937 | | |
1938 | | // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] |
1939 | | // the rules for const_cast are the same as those used for pointers. |
1940 | | |
1941 | 627k | if (!DestType->isPointerType() && |
1942 | 627k | !DestType->isMemberPointerType()556k && |
1943 | 627k | !DestType->isObjCObjectPointerType()556k ) { |
1944 | | // Cannot cast to non-pointer, non-reference type. Note that, if DestType |
1945 | | // was a reference type, we converted it to a pointer above. |
1946 | | // The status of rvalue references isn't entirely clear, but it looks like |
1947 | | // conversion to them is simply invalid. |
1948 | | // C++ 5.2.11p3: For two pointer types [...] |
1949 | 550k | if (!CStyle) |
1950 | 3 | msg = diag::err_bad_const_cast_dest; |
1951 | 550k | return TC_NotApplicable; |
1952 | 550k | } |
1953 | 76.7k | if (DestType->isFunctionPointerType() || |
1954 | 76.7k | DestType->isMemberFunctionPointerType()75.7k ) { |
1955 | | // Cannot cast direct function pointers. |
1956 | | // C++ 5.2.11p2: [...] where T is any object type or the void type [...] |
1957 | | // T is the ultimate pointee of source and target type. |
1958 | 1.14k | if (!CStyle) |
1959 | 6 | msg = diag::err_bad_const_cast_dest; |
1960 | 1.14k | return TC_NotApplicable; |
1961 | 1.14k | } |
1962 | | |
1963 | | // C++ [expr.const.cast]p3: |
1964 | | // "For two similar types T1 and T2, [...]" |
1965 | | // |
1966 | | // We only allow a const_cast to change cvr-qualifiers, not other kinds of |
1967 | | // type qualifiers. (Likewise, we ignore other changes when determining |
1968 | | // whether a cast casts away constness.) |
1969 | 75.6k | if (!Self.Context.hasCvrSimilarType(SrcType, DestType)) |
1970 | 63.9k | return TC_NotApplicable; |
1971 | | |
1972 | 11.7k | if (NeedToMaterializeTemporary) |
1973 | | // This is a const_cast from a class prvalue to an rvalue reference type. |
1974 | | // Materialize a temporary to store the result of the conversion. |
1975 | 30 | SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(), |
1976 | 30 | SrcExpr.get(), |
1977 | 30 | /*IsLValueReference*/ false); |
1978 | | |
1979 | 11.7k | return TC_Success; |
1980 | 75.6k | } |
1981 | | |
1982 | | // Checks for undefined behavior in reinterpret_cast. |
1983 | | // The cases that is checked for is: |
1984 | | // *reinterpret_cast<T*>(&a) |
1985 | | // reinterpret_cast<T&>(a) |
1986 | | // where accessing 'a' as type 'T' will result in undefined behavior. |
1987 | | void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, |
1988 | | bool IsDereference, |
1989 | 492 | SourceRange Range) { |
1990 | 492 | unsigned DiagID = IsDereference ? |
1991 | 208 | diag::warn_pointer_indirection_from_incompatible_type : |
1992 | 492 | diag::warn_undefined_reinterpret_cast284 ; |
1993 | | |
1994 | 492 | if (Diags.isIgnored(DiagID, Range.getBegin())) |
1995 | 383 | return; |
1996 | | |
1997 | 109 | QualType SrcTy, DestTy; |
1998 | 109 | if (IsDereference) { |
1999 | 58 | if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { |
2000 | 0 | return; |
2001 | 0 | } |
2002 | 58 | SrcTy = SrcType->getPointeeType(); |
2003 | 58 | DestTy = DestType->getPointeeType(); |
2004 | 58 | } else { |
2005 | 51 | if (!DestType->getAs<ReferenceType>()) { |
2006 | 0 | return; |
2007 | 0 | } |
2008 | 51 | SrcTy = SrcType; |
2009 | 51 | DestTy = DestType->getPointeeType(); |
2010 | 51 | } |
2011 | | |
2012 | | // Cast is compatible if the types are the same. |
2013 | 109 | if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { |
2014 | 44 | return; |
2015 | 44 | } |
2016 | | // or one of the types is a char or void type |
2017 | 65 | if (DestTy->isAnyCharacterType() || DestTy->isVoidType()50 || |
2018 | 65 | SrcTy->isAnyCharacterType()45 || SrcTy->isVoidType()37 ) { |
2019 | 33 | return; |
2020 | 33 | } |
2021 | | // or one of the types is a tag type. |
2022 | 32 | if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()24 ) { |
2023 | 8 | return; |
2024 | 8 | } |
2025 | | |
2026 | | // FIXME: Scoped enums? |
2027 | 24 | if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()8 ) || |
2028 | 24 | (16 SrcTy->isSignedIntegerType()16 && DestTy->isUnsignedIntegerType()12 )) { |
2029 | 16 | if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { |
2030 | 16 | return; |
2031 | 16 | } |
2032 | 16 | } |
2033 | | |
2034 | 8 | Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; |
2035 | 8 | } |
2036 | | |
2037 | | static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, |
2038 | 809k | QualType DestType) { |
2039 | 809k | QualType SrcType = SrcExpr.get()->getType(); |
2040 | 809k | if (Self.Context.hasSameType(SrcType, DestType)) |
2041 | 552k | return; |
2042 | 256k | if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) |
2043 | 137k | if (SrcPtrTy->isObjCSelType()) { |
2044 | 8 | QualType DT = DestType; |
2045 | 8 | if (isa<PointerType>(DestType)) |
2046 | 8 | DT = DestType->getPointeeType(); |
2047 | 8 | if (!DT.getUnqualifiedType()->isVoidType()) |
2048 | 4 | Self.Diag(SrcExpr.get()->getExprLoc(), |
2049 | 4 | diag::warn_cast_pointer_from_sel) |
2050 | 4 | << SrcType << DestType << SrcExpr.get()->getSourceRange(); |
2051 | 8 | } |
2052 | 256k | } |
2053 | | |
2054 | | /// Diagnose casts that change the calling convention of a pointer to a function |
2055 | | /// defined in the current TU. |
2056 | | static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, |
2057 | 810k | QualType DstType, SourceRange OpRange) { |
2058 | | // Check if this cast would change the calling convention of a function |
2059 | | // pointer type. |
2060 | 810k | QualType SrcType = SrcExpr.get()->getType(); |
2061 | 810k | if (Self.Context.hasSameType(SrcType, DstType) || |
2062 | 810k | !SrcType->isFunctionPointerType()257k || !DstType->isFunctionPointerType()2.33k ) |
2063 | 810k | return; |
2064 | 144 | const auto *SrcFTy = |
2065 | 144 | SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); |
2066 | 144 | const auto *DstFTy = |
2067 | 144 | DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); |
2068 | 144 | CallingConv SrcCC = SrcFTy->getCallConv(); |
2069 | 144 | CallingConv DstCC = DstFTy->getCallConv(); |
2070 | 144 | if (SrcCC == DstCC) |
2071 | 112 | return; |
2072 | | |
2073 | | // We have a calling convention cast. Check if the source is a pointer to a |
2074 | | // known, specific function that has already been defined. |
2075 | 32 | Expr *Src = SrcExpr.get()->IgnoreParenImpCasts(); |
2076 | 32 | if (auto *UO = dyn_cast<UnaryOperator>(Src)) |
2077 | 8 | if (UO->getOpcode() == UO_AddrOf) |
2078 | 8 | Src = UO->getSubExpr()->IgnoreParenImpCasts(); |
2079 | 32 | auto *DRE = dyn_cast<DeclRefExpr>(Src); |
2080 | 32 | if (!DRE) |
2081 | 0 | return; |
2082 | 32 | auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); |
2083 | 32 | if (!FD) |
2084 | 4 | return; |
2085 | | |
2086 | | // Only warn if we are casting from the default convention to a non-default |
2087 | | // convention. This can happen when the programmer forgot to apply the calling |
2088 | | // convention to the function declaration and then inserted this cast to |
2089 | | // satisfy the type system. |
2090 | 28 | CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention( |
2091 | 28 | FD->isVariadic(), FD->isCXXInstanceMember()); |
2092 | 28 | if (DstCC == DefaultCC || SrcCC != DefaultCC24 ) |
2093 | 4 | return; |
2094 | | |
2095 | | // Diagnose this cast, as it is probably bad. |
2096 | 24 | StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC); |
2097 | 24 | StringRef DstCCName = FunctionType::getNameForCallConv(DstCC); |
2098 | 24 | Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv) |
2099 | 24 | << SrcCCName << DstCCName << OpRange; |
2100 | | |
2101 | | // The checks above are cheaper than checking if the diagnostic is enabled. |
2102 | | // However, it's worth checking if the warning is enabled before we construct |
2103 | | // a fixit. |
2104 | 24 | if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin())) |
2105 | 0 | return; |
2106 | | |
2107 | | // Try to suggest a fixit to change the calling convention of the function |
2108 | | // whose address was taken. Try to use the latest macro for the convention. |
2109 | | // For example, users probably want to write "WINAPI" instead of "__stdcall" |
2110 | | // to match the Windows header declarations. |
2111 | 24 | SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc(); |
2112 | 24 | Preprocessor &PP = Self.getPreprocessor(); |
2113 | 24 | SmallVector<TokenValue, 6> AttrTokens; |
2114 | 24 | SmallString<64> CCAttrText; |
2115 | 24 | llvm::raw_svector_ostream OS(CCAttrText); |
2116 | 24 | if (Self.getLangOpts().MicrosoftExt) { |
2117 | | // __stdcall or __vectorcall |
2118 | 18 | OS << "__" << DstCCName; |
2119 | 18 | IdentifierInfo *II = PP.getIdentifierInfo(OS.str()); |
2120 | 18 | AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) |
2121 | 18 | ? TokenValue(II->getTokenID()) |
2122 | 18 | : TokenValue(II)0 ); |
2123 | 18 | } else { |
2124 | | // __attribute__((stdcall)) or __attribute__((vectorcall)) |
2125 | 6 | OS << "__attribute__((" << DstCCName << "))"; |
2126 | 6 | AttrTokens.push_back(tok::kw___attribute); |
2127 | 6 | AttrTokens.push_back(tok::l_paren); |
2128 | 6 | AttrTokens.push_back(tok::l_paren); |
2129 | 6 | IdentifierInfo *II = PP.getIdentifierInfo(DstCCName); |
2130 | 6 | AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) |
2131 | 6 | ? TokenValue(II->getTokenID())0 |
2132 | 6 | : TokenValue(II)); |
2133 | 6 | AttrTokens.push_back(tok::r_paren); |
2134 | 6 | AttrTokens.push_back(tok::r_paren); |
2135 | 6 | } |
2136 | 24 | StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens); |
2137 | 24 | if (!AttrSpelling.empty()) |
2138 | 20 | CCAttrText = AttrSpelling; |
2139 | 24 | OS << ' '; |
2140 | 24 | Self.Diag(NameLoc, diag::note_change_calling_conv_fixit) |
2141 | 24 | << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText); |
2142 | 24 | } |
2143 | | |
2144 | | static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange, |
2145 | | const Expr *SrcExpr, QualType DestType, |
2146 | 124k | Sema &Self) { |
2147 | 124k | QualType SrcType = SrcExpr->getType(); |
2148 | | |
2149 | | // Not warning on reinterpret_cast, boolean, constant expressions, etc |
2150 | | // are not explicit design choices, but consistent with GCC's behavior. |
2151 | | // Feel free to modify them if you've reason/evidence for an alternative. |
2152 | 124k | if (CStyle && SrcType->isIntegralType(Self.Context)123k |
2153 | 124k | && !SrcType->isBooleanType()9.31k |
2154 | 124k | && !SrcType->isEnumeralType()9.30k |
2155 | 124k | && !SrcExpr->isIntegerConstantExpr(Self.Context)9.30k |
2156 | 124k | && Self.Context.getTypeSize(DestType) > |
2157 | 3.40k | Self.Context.getTypeSize(SrcType)) { |
2158 | | // Separate between casts to void* and non-void* pointers. |
2159 | | // Some APIs use (abuse) void* for something like a user context, |
2160 | | // and often that value is an integer even if it isn't a pointer itself. |
2161 | | // Having a separate warning flag allows users to control the warning |
2162 | | // for their workflow. |
2163 | 55 | unsigned Diag = DestType->isVoidPointerType() ? |
2164 | 8 | diag::warn_int_to_void_pointer_cast |
2165 | 55 | : diag::warn_int_to_pointer_cast47 ; |
2166 | 55 | Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; |
2167 | 55 | } |
2168 | 124k | } |
2169 | | |
2170 | | static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, |
2171 | 114 | ExprResult &Result) { |
2172 | | // We can only fix an overloaded reinterpret_cast if |
2173 | | // - it is a template with explicit arguments that resolves to an lvalue |
2174 | | // unambiguously, or |
2175 | | // - it is the only function in an overload set that may have its address |
2176 | | // taken. |
2177 | | |
2178 | 114 | Expr *E = Result.get(); |
2179 | | // TODO: what if this fails because of DiagnoseUseOfDecl or something |
2180 | | // like it? |
2181 | 114 | if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( |
2182 | 114 | Result, |
2183 | 114 | Expr::getValueKindForType(DestType) == |
2184 | 114 | VK_PRValue // Convert Fun to Ptr |
2185 | 114 | ) && |
2186 | 114 | Result.isUsable()44 ) |
2187 | 44 | return true; |
2188 | | |
2189 | | // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization |
2190 | | // preserves Result. |
2191 | 70 | Result = E; |
2192 | 70 | if (!Self.resolveAndFixAddressOfSingleOverloadCandidate( |
2193 | 70 | Result, /*DoFunctionPointerConversion=*/true)) |
2194 | 33 | return false; |
2195 | 37 | return Result.isUsable(); |
2196 | 70 | } |
2197 | | |
2198 | | static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, |
2199 | | QualType DestType, bool CStyle, |
2200 | | SourceRange OpRange, |
2201 | | unsigned &msg, |
2202 | 52.7k | CastKind &Kind) { |
2203 | 52.7k | bool IsLValueCast = false; |
2204 | | |
2205 | 52.7k | DestType = Self.Context.getCanonicalType(DestType); |
2206 | 52.7k | QualType SrcType = SrcExpr.get()->getType(); |
2207 | | |
2208 | | // Is the source an overloaded name? (i.e. &foo) |
2209 | | // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) |
2210 | 52.7k | if (SrcType == Self.Context.OverloadTy) { |
2211 | 114 | ExprResult FixedExpr = SrcExpr; |
2212 | 114 | if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) |
2213 | 33 | return TC_NotApplicable; |
2214 | | |
2215 | 81 | assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr"); |
2216 | 0 | SrcExpr = FixedExpr; |
2217 | 81 | SrcType = SrcExpr.get()->getType(); |
2218 | 81 | } |
2219 | | |
2220 | 52.6k | if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { |
2221 | 542 | if (!SrcExpr.get()->isGLValue()) { |
2222 | | // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the |
2223 | | // similar comment in const_cast. |
2224 | 5 | msg = diag::err_bad_cxx_cast_rvalue; |
2225 | 5 | return TC_NotApplicable; |
2226 | 5 | } |
2227 | | |
2228 | 537 | if (!CStyle) { |
2229 | 284 | Self.CheckCompatibleReinterpretCast(SrcType, DestType, |
2230 | 284 | /*IsDereference=*/false, OpRange); |
2231 | 284 | } |
2232 | | |
2233 | | // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the |
2234 | | // same effect as the conversion *reinterpret_cast<T*>(&x) with the |
2235 | | // built-in & and * operators. |
2236 | | |
2237 | 537 | const char *inappropriate = nullptr; |
2238 | 537 | switch (SrcExpr.get()->getObjectKind()) { |
2239 | 533 | case OK_Ordinary: |
2240 | 533 | break; |
2241 | 2 | case OK_BitField: |
2242 | 2 | msg = diag::err_bad_cxx_cast_bitfield; |
2243 | 2 | return TC_NotApplicable; |
2244 | | // FIXME: Use a specific diagnostic for the rest of these cases. |
2245 | 1 | case OK_VectorComponent: inappropriate = "vector element"; break; |
2246 | 1 | case OK_MatrixComponent: |
2247 | 1 | inappropriate = "matrix element"; |
2248 | 1 | break; |
2249 | 0 | case OK_ObjCProperty: inappropriate = "property expression"; break; |
2250 | 0 | case OK_ObjCSubscript: inappropriate = "container subscripting expression"; |
2251 | 0 | break; |
2252 | 537 | } |
2253 | 535 | if (inappropriate) { |
2254 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) |
2255 | 2 | << inappropriate << DestType |
2256 | 2 | << OpRange << SrcExpr.get()->getSourceRange(); |
2257 | 2 | msg = 0; SrcExpr = ExprError(); |
2258 | 2 | return TC_NotApplicable; |
2259 | 2 | } |
2260 | | |
2261 | | // This code does this transformation for the checked types. |
2262 | 533 | DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); |
2263 | 533 | SrcType = Self.Context.getPointerType(SrcType); |
2264 | | |
2265 | 533 | IsLValueCast = true; |
2266 | 533 | } |
2267 | | |
2268 | | // Canonicalize source for comparison. |
2269 | 52.6k | SrcType = Self.Context.getCanonicalType(SrcType); |
2270 | | |
2271 | 52.6k | const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), |
2272 | 52.6k | *SrcMemPtr = SrcType->getAs<MemberPointerType>(); |
2273 | 52.6k | if (DestMemPtr && SrcMemPtr72 ) { |
2274 | | // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" |
2275 | | // can be explicitly converted to an rvalue of type "pointer to member |
2276 | | // of Y of type T2" if T1 and T2 are both function types or both object |
2277 | | // types. |
2278 | 69 | if (DestMemPtr->isMemberFunctionPointer() != |
2279 | 69 | SrcMemPtr->isMemberFunctionPointer()) |
2280 | 6 | return TC_NotApplicable; |
2281 | | |
2282 | 63 | if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
2283 | | // We need to determine the inheritance model that the class will use if |
2284 | | // haven't yet. |
2285 | 19 | (void)Self.isCompleteType(OpRange.getBegin(), SrcType); |
2286 | 19 | (void)Self.isCompleteType(OpRange.getBegin(), DestType); |
2287 | 19 | } |
2288 | | |
2289 | | // Don't allow casting between member pointers of different sizes. |
2290 | 63 | if (Self.Context.getTypeSize(DestMemPtr) != |
2291 | 63 | Self.Context.getTypeSize(SrcMemPtr)) { |
2292 | 2 | msg = diag::err_bad_cxx_cast_member_pointer_size; |
2293 | 2 | return TC_Failed; |
2294 | 2 | } |
2295 | | |
2296 | | // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away |
2297 | | // constness. |
2298 | | // A reinterpret_cast followed by a const_cast can, though, so in C-style, |
2299 | | // we accept it. |
2300 | 61 | if (auto CACK = |
2301 | 61 | CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, |
2302 | 61 | /*CheckObjCLifetime=*/CStyle)) |
2303 | 1 | return getCastAwayConstnessCastKind(CACK, msg); |
2304 | | |
2305 | | // A valid member pointer cast. |
2306 | 60 | assert(!IsLValueCast); |
2307 | 0 | Kind = CK_ReinterpretMemberPointer; |
2308 | 60 | return TC_Success; |
2309 | 61 | } |
2310 | | |
2311 | | // See below for the enumeral issue. |
2312 | 52.6k | if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)26 ) { |
2313 | | // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral |
2314 | | // type large enough to hold it. A value of std::nullptr_t can be |
2315 | | // converted to an integral type; the conversion has the same meaning |
2316 | | // and validity as a conversion of (void*)0 to the integral type. |
2317 | 26 | if (Self.Context.getTypeSize(SrcType) > |
2318 | 26 | Self.Context.getTypeSize(DestType)) { |
2319 | 1 | msg = diag::err_bad_reinterpret_cast_small_int; |
2320 | 1 | return TC_Failed; |
2321 | 1 | } |
2322 | 25 | Kind = CK_PointerToIntegral; |
2323 | 25 | return TC_Success; |
2324 | 26 | } |
2325 | | |
2326 | | // Allow reinterpret_casts between vectors of the same size and |
2327 | | // between vectors and integers of the same size. |
2328 | 52.5k | bool destIsVector = DestType->isVectorType(); |
2329 | 52.5k | bool srcIsVector = SrcType->isVectorType(); |
2330 | 52.5k | if (srcIsVector || destIsVector40.1k ) { |
2331 | | // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa. |
2332 | 12.8k | if (Self.isValidSveBitcast(SrcType, DestType)) { |
2333 | 120 | Kind = CK_BitCast; |
2334 | 120 | return TC_Success; |
2335 | 120 | } |
2336 | | |
2337 | | // The non-vector type, if any, must have integral type. This is |
2338 | | // the same rule that C vector casts use; note, however, that enum |
2339 | | // types are not integral in C++. |
2340 | 12.7k | if ((!destIsVector && !DestType->isIntegralType(Self.Context)554 ) || |
2341 | 12.7k | (12.7k !srcIsVector12.7k && !SrcType->isIntegralType(Self.Context)405 )) |
2342 | 10 | return TC_NotApplicable; |
2343 | | |
2344 | | // The size we want to consider is eltCount * eltSize. |
2345 | | // That's exactly what the lax-conversion rules will check. |
2346 | 12.7k | if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { |
2347 | 12.7k | Kind = CK_BitCast; |
2348 | 12.7k | return TC_Success; |
2349 | 12.7k | } |
2350 | | |
2351 | 27 | if (Self.LangOpts.OpenCL && !CStyle5 ) { |
2352 | 5 | if (DestType->isExtVectorType() || SrcType->isExtVectorType()3 ) { |
2353 | | // FIXME: Allow for reinterpret cast between 3 and 4 element vectors |
2354 | 5 | if (Self.areVectorTypesSameSize(SrcType, DestType)) { |
2355 | 4 | Kind = CK_BitCast; |
2356 | 4 | return TC_Success; |
2357 | 4 | } |
2358 | 5 | } |
2359 | 5 | } |
2360 | | |
2361 | | // Otherwise, pick a reasonable diagnostic. |
2362 | 23 | if (!destIsVector) |
2363 | 5 | msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; |
2364 | 18 | else if (!srcIsVector) |
2365 | 1 | msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; |
2366 | 17 | else |
2367 | 17 | msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; |
2368 | | |
2369 | 23 | return TC_Failed; |
2370 | 27 | } |
2371 | | |
2372 | 39.7k | if (SrcType == DestType) { |
2373 | | // C++ 5.2.10p2 has a note that mentions that, subject to all other |
2374 | | // restrictions, a cast to the same type is allowed so long as it does not |
2375 | | // cast away constness. In C++98, the intent was not entirely clear here, |
2376 | | // since all other paragraphs explicitly forbid casts to the same type. |
2377 | | // C++11 clarifies this case with p2. |
2378 | | // |
2379 | | // The only allowed types are: integral, enumeration, pointer, or |
2380 | | // pointer-to-member types. We also won't restrict Obj-C pointers either. |
2381 | 88 | Kind = CK_NoOp; |
2382 | 88 | TryCastResult Result = TC_NotApplicable; |
2383 | 88 | if (SrcType->isIntegralOrEnumerationType() || |
2384 | 88 | SrcType->isAnyPointerType()74 || |
2385 | 88 | SrcType->isMemberPointerType()7 || |
2386 | 88 | SrcType->isBlockPointerType()7 ) { |
2387 | 81 | Result = TC_Success; |
2388 | 81 | } |
2389 | 88 | return Result; |
2390 | 88 | } |
2391 | | |
2392 | 39.6k | bool destIsPtr = DestType->isAnyPointerType() || |
2393 | 39.6k | DestType->isBlockPointerType()3.10k ; |
2394 | 39.6k | bool srcIsPtr = SrcType->isAnyPointerType() || |
2395 | 39.6k | SrcType->isBlockPointerType()2.28k ; |
2396 | 39.6k | if (!destIsPtr && !srcIsPtr3.10k ) { |
2397 | | // Except for std::nullptr_t->integer and lvalue->reference, which are |
2398 | | // handled above, at least one of the two arguments must be a pointer. |
2399 | 259 | return TC_NotApplicable; |
2400 | 259 | } |
2401 | | |
2402 | 39.3k | if (DestType->isIntegralType(Self.Context)) { |
2403 | 2.84k | assert(srcIsPtr && "One type must be a pointer"); |
2404 | | // C++ 5.2.10p4: A pointer can be explicitly converted to any integral |
2405 | | // type large enough to hold it; except in Microsoft mode, where the |
2406 | | // integral type size doesn't matter (except we don't allow bool). |
2407 | 2.84k | if ((Self.Context.getTypeSize(SrcType) > |
2408 | 2.84k | Self.Context.getTypeSize(DestType))) { |
2409 | 38 | bool MicrosoftException = |
2410 | 38 | Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType()30 ; |
2411 | 38 | if (MicrosoftException) { |
2412 | 24 | unsigned Diag = SrcType->isVoidPointerType() |
2413 | 24 | ? diag::warn_void_pointer_to_int_cast12 |
2414 | 24 | : diag::warn_pointer_to_int_cast12 ; |
2415 | 24 | Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; |
2416 | 24 | } else { |
2417 | 14 | msg = diag::err_bad_reinterpret_cast_small_int; |
2418 | 14 | return TC_Failed; |
2419 | 14 | } |
2420 | 38 | } |
2421 | 2.82k | Kind = CK_PointerToIntegral; |
2422 | 2.82k | return TC_Success; |
2423 | 2.84k | } |
2424 | | |
2425 | 36.5k | if (SrcType->isIntegralOrEnumerationType()) { |
2426 | 2.02k | assert(destIsPtr && "One type must be a pointer"); |
2427 | 0 | checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self); |
2428 | | // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly |
2429 | | // converted to a pointer. |
2430 | | // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not |
2431 | | // necessarily converted to a null pointer value.] |
2432 | 2.02k | Kind = CK_IntegralToPointer; |
2433 | 2.02k | return TC_Success; |
2434 | 2.02k | } |
2435 | | |
2436 | 34.4k | if (!destIsPtr || !srcIsPtr34.4k ) { |
2437 | | // With the valid non-pointer conversions out of the way, we can be even |
2438 | | // more stringent. |
2439 | 9 | return TC_NotApplicable; |
2440 | 9 | } |
2441 | | |
2442 | | // Cannot convert between block pointers and Objective-C object pointers. |
2443 | 34.4k | if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()3 ) || |
2444 | 34.4k | (34.4k DestType->isBlockPointerType()34.4k && SrcType->isObjCObjectPointerType()3 )) |
2445 | 2 | return TC_NotApplicable; |
2446 | | |
2447 | | // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. |
2448 | | // The C-style cast operator can. |
2449 | 34.4k | TryCastResult SuccessResult = TC_Success; |
2450 | 34.4k | if (auto CACK = |
2451 | 34.4k | CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, |
2452 | 34.4k | /*CheckObjCLifetime=*/CStyle)) |
2453 | 87 | SuccessResult = getCastAwayConstnessCastKind(CACK, msg); |
2454 | | |
2455 | 34.4k | if (IsAddressSpaceConversion(SrcType, DestType)) { |
2456 | 149 | Kind = CK_AddressSpaceConversion; |
2457 | 149 | assert(SrcType->isPointerType() && DestType->isPointerType()); |
2458 | 149 | if (!CStyle && |
2459 | 149 | !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf( |
2460 | 16 | SrcType->getPointeeType().getQualifiers())) { |
2461 | 14 | SuccessResult = TC_Failed; |
2462 | 14 | } |
2463 | 34.3k | } else if (IsLValueCast) { |
2464 | 505 | Kind = CK_LValueBitCast; |
2465 | 33.8k | } else if (DestType->isObjCObjectPointerType()) { |
2466 | 4.98k | Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); |
2467 | 28.8k | } else if (DestType->isBlockPointerType()) { |
2468 | 2 | if (!SrcType->isBlockPointerType()) { |
2469 | 2 | Kind = CK_AnyPointerToBlockPointerCast; |
2470 | 2 | } else { |
2471 | 0 | Kind = CK_BitCast; |
2472 | 0 | } |
2473 | 28.8k | } else { |
2474 | 28.8k | Kind = CK_BitCast; |
2475 | 28.8k | } |
2476 | | |
2477 | | // Any pointer can be cast to an Objective-C pointer type with a C-style |
2478 | | // cast. |
2479 | 34.4k | if (CStyle && DestType->isObjCObjectPointerType()33.1k ) { |
2480 | 4.97k | return SuccessResult; |
2481 | 4.97k | } |
2482 | 29.5k | if (CStyle) |
2483 | 28.1k | DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); |
2484 | | |
2485 | 29.5k | DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); |
2486 | | |
2487 | | // Not casting away constness, so the only remaining check is for compatible |
2488 | | // pointer categories. |
2489 | | |
2490 | 29.5k | if (SrcType->isFunctionPointerType()) { |
2491 | 1.38k | if (DestType->isFunctionPointerType()) { |
2492 | | // C++ 5.2.10p6: A pointer to a function can be explicitly converted to |
2493 | | // a pointer to a function of a different type. |
2494 | 95 | return SuccessResult; |
2495 | 95 | } |
2496 | | |
2497 | | // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to |
2498 | | // an object type or vice versa is conditionally-supported. |
2499 | | // Compilers support it in C++03 too, though, because it's necessary for |
2500 | | // casting the return value of dlsym() and GetProcAddress(). |
2501 | | // FIXME: Conditionally-supported behavior should be configurable in the |
2502 | | // TargetInfo or similar. |
2503 | 1.29k | Self.Diag(OpRange.getBegin(), |
2504 | 1.29k | Self.getLangOpts().CPlusPlus11 ? |
2505 | 961 | diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj330 ) |
2506 | 1.29k | << OpRange; |
2507 | 1.29k | return SuccessResult; |
2508 | 1.38k | } |
2509 | | |
2510 | 28.1k | if (DestType->isFunctionPointerType()) { |
2511 | | // See above. |
2512 | 466 | Self.Diag(OpRange.getBegin(), |
2513 | 466 | Self.getLangOpts().CPlusPlus11 ? |
2514 | 331 | diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj135 ) |
2515 | 466 | << OpRange; |
2516 | 466 | return SuccessResult; |
2517 | 466 | } |
2518 | | |
2519 | | // Diagnose address space conversion in nested pointers. |
2520 | 27.6k | QualType DestPtee = DestType->getPointeeType().isNull() |
2521 | 27.6k | ? DestType->getPointeeType()0 |
2522 | 27.6k | : DestType->getPointeeType()->getPointeeType(); |
2523 | 27.6k | QualType SrcPtee = SrcType->getPointeeType().isNull() |
2524 | 27.6k | ? SrcType->getPointeeType()0 |
2525 | 27.6k | : SrcType->getPointeeType()->getPointeeType(); |
2526 | 27.7k | while (!DestPtee.isNull() && !SrcPtee.isNull()240 ) { |
2527 | 115 | if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) { |
2528 | 12 | Self.Diag(OpRange.getBegin(), |
2529 | 12 | diag::warn_bad_cxx_cast_nested_pointer_addr_space) |
2530 | 12 | << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange(); |
2531 | 12 | break; |
2532 | 12 | } |
2533 | 103 | DestPtee = DestPtee->getPointeeType(); |
2534 | 103 | SrcPtee = SrcPtee->getPointeeType(); |
2535 | 103 | } |
2536 | | |
2537 | | // C++ 5.2.10p7: A pointer to an object can be explicitly converted to |
2538 | | // a pointer to an object of different type. |
2539 | | // Void pointers are not specified, but supported by every compiler out there. |
2540 | | // So we finish by allowing everything that remains - it's got to be two |
2541 | | // object pointers. |
2542 | 27.6k | return SuccessResult; |
2543 | 28.1k | } |
2544 | | |
2545 | | static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, |
2546 | | QualType DestType, bool CStyle, |
2547 | 615k | unsigned &msg, CastKind &Kind) { |
2548 | 615k | if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice615k ) |
2549 | | // FIXME: As compiler doesn't have any information about overlapping addr |
2550 | | // spaces at the moment we have to be permissive here. |
2551 | 615k | return TC_NotApplicable; |
2552 | | // Even though the logic below is general enough and can be applied to |
2553 | | // non-OpenCL mode too, we fast-path above because no other languages |
2554 | | // define overlapping address spaces currently. |
2555 | 173 | auto SrcType = SrcExpr.get()->getType(); |
2556 | | // FIXME: Should this be generalized to references? The reference parameter |
2557 | | // however becomes a reference pointee type here and therefore rejected. |
2558 | | // Perhaps this is the right behavior though according to C++. |
2559 | 173 | auto SrcPtrType = SrcType->getAs<PointerType>(); |
2560 | 173 | if (!SrcPtrType) |
2561 | 28 | return TC_NotApplicable; |
2562 | 145 | auto DestPtrType = DestType->getAs<PointerType>(); |
2563 | 145 | if (!DestPtrType) |
2564 | 2 | return TC_NotApplicable; |
2565 | 143 | auto SrcPointeeType = SrcPtrType->getPointeeType(); |
2566 | 143 | auto DestPointeeType = DestPtrType->getPointeeType(); |
2567 | 143 | if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) { |
2568 | 70 | msg = diag::err_bad_cxx_cast_addr_space_mismatch; |
2569 | 70 | return TC_Failed; |
2570 | 70 | } |
2571 | 73 | auto SrcPointeeTypeWithoutAS = |
2572 | 73 | Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType()); |
2573 | 73 | auto DestPointeeTypeWithoutAS = |
2574 | 73 | Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType()); |
2575 | 73 | if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS, |
2576 | 73 | DestPointeeTypeWithoutAS)) { |
2577 | 29 | Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace() |
2578 | 29 | ? CK_NoOp1 |
2579 | 29 | : CK_AddressSpaceConversion28 ; |
2580 | 29 | return TC_Success; |
2581 | 44 | } else { |
2582 | 44 | return TC_NotApplicable; |
2583 | 44 | } |
2584 | 73 | } |
2585 | | |
2586 | 4.04M | void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) { |
2587 | | // In OpenCL only conversions between pointers to objects in overlapping |
2588 | | // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps |
2589 | | // with any named one, except for constant. |
2590 | | |
2591 | | // Converting the top level pointee addrspace is permitted for compatible |
2592 | | // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but |
2593 | | // if any of the nested pointee addrspaces differ, we emit a warning |
2594 | | // regardless of addrspace compatibility. This makes |
2595 | | // local int ** p; |
2596 | | // return (generic int **) p; |
2597 | | // warn even though local -> generic is permitted. |
2598 | 4.04M | if (Self.getLangOpts().OpenCL) { |
2599 | 1.34k | const Type *DestPtr, *SrcPtr; |
2600 | 1.34k | bool Nested = false; |
2601 | 1.34k | unsigned DiagID = diag::err_typecheck_incompatible_address_space; |
2602 | 1.34k | DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()), |
2603 | 1.34k | SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr()); |
2604 | | |
2605 | 1.74k | while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)1.10k ) { |
2606 | 491 | const PointerType *DestPPtr = cast<PointerType>(DestPtr); |
2607 | 491 | const PointerType *SrcPPtr = cast<PointerType>(SrcPtr); |
2608 | 491 | QualType DestPPointee = DestPPtr->getPointeeType(); |
2609 | 491 | QualType SrcPPointee = SrcPPtr->getPointeeType(); |
2610 | 491 | if (Nested |
2611 | 491 | ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()21 |
2612 | 491 | : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)470 ) { |
2613 | 96 | Self.Diag(OpRange.getBegin(), DiagID) |
2614 | 96 | << SrcType << DestType << Sema::AA_Casting |
2615 | 96 | << SrcExpr.get()->getSourceRange(); |
2616 | 96 | if (!Nested) |
2617 | 85 | SrcExpr = ExprError(); |
2618 | 96 | return; |
2619 | 96 | } |
2620 | | |
2621 | 395 | DestPtr = DestPPtr->getPointeeType().getTypePtr(); |
2622 | 395 | SrcPtr = SrcPPtr->getPointeeType().getTypePtr(); |
2623 | 395 | Nested = true; |
2624 | 395 | DiagID = diag::ext_nested_pointer_qualifier_mismatch; |
2625 | 395 | } |
2626 | 1.34k | } |
2627 | 4.04M | } |
2628 | | |
2629 | 3.62M | bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) { |
2630 | 3.62M | bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() == |
2631 | 3.62M | LangOptions::AltivecSrcCompatKind::XL; |
2632 | 3.62M | VectorType::VectorKind VKind = VecTy->getVectorKind(); |
2633 | | |
2634 | 3.62M | if ((VKind == VectorType::AltiVecVector) || |
2635 | 3.62M | (3.59M SrcCompatXL3.59M && (108 (VKind == VectorType::AltiVecBool)108 || |
2636 | 28.4k | (VKind == VectorType::AltiVecPixel)12 ))) { |
2637 | 28.4k | return true; |
2638 | 28.4k | } |
2639 | 3.59M | return false; |
2640 | 3.62M | } |
2641 | | |
2642 | | bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, |
2643 | 3.62M | QualType SrcTy) { |
2644 | 3.62M | bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() == |
2645 | 3.62M | LangOptions::AltivecSrcCompatKind::GCC; |
2646 | 3.62M | if (this->getLangOpts().AltiVec && SrcCompatGCC30.8k ) { |
2647 | 72 | this->Diag(R.getBegin(), |
2648 | 72 | diag::err_invalid_conversion_between_vector_and_integer) |
2649 | 72 | << VecTy << SrcTy << R; |
2650 | 72 | return true; |
2651 | 72 | } |
2652 | 3.62M | return false; |
2653 | 3.62M | } |
2654 | | |
2655 | | void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, |
2656 | 779k | bool ListInitialization) { |
2657 | 779k | assert(Self.getLangOpts().CPlusPlus); |
2658 | | |
2659 | | // Handle placeholders. |
2660 | 779k | if (isPlaceholder()) { |
2661 | | // C-style casts can resolve __unknown_any types. |
2662 | 842 | if (claimPlaceholder(BuiltinType::UnknownAny)) { |
2663 | 622 | SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, |
2664 | 622 | SrcExpr.get(), Kind, |
2665 | 622 | ValueKind, BasePath); |
2666 | 622 | return; |
2667 | 622 | } |
2668 | | |
2669 | 220 | checkNonOverloadPlaceholders(); |
2670 | 220 | if (SrcExpr.isInvalid()) |
2671 | 0 | return; |
2672 | 220 | } |
2673 | | |
2674 | | // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". |
2675 | | // This test is outside everything else because it's the only case where |
2676 | | // a non-lvalue-reference target type does not lead to decay. |
2677 | 778k | if (DestType->isVoidType()) { |
2678 | 75.9k | Kind = CK_ToVoid; |
2679 | | |
2680 | 75.9k | if (claimPlaceholder(BuiltinType::Overload)) { |
2681 | 43 | Self.ResolveAndFixSingleFunctionTemplateSpecialization( |
2682 | 43 | SrcExpr, /* Decay Function to ptr */ false, |
2683 | 43 | /* Complain */ true, DestRange, DestType, |
2684 | 43 | diag::err_bad_cstyle_cast_overload); |
2685 | 43 | if (SrcExpr.isInvalid()) |
2686 | 13 | return; |
2687 | 43 | } |
2688 | | |
2689 | 75.9k | SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); |
2690 | 75.9k | return; |
2691 | 75.9k | } |
2692 | | |
2693 | | // If the type is dependent, we won't do any other semantic analysis now. |
2694 | 702k | if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()672k || |
2695 | 702k | SrcExpr.get()->isValueDependent()627k ) { |
2696 | 76.9k | assert(Kind == CK_Dependent); |
2697 | 0 | return; |
2698 | 76.9k | } |
2699 | | |
2700 | 625k | if (ValueKind == VK_PRValue && !DestType->isRecordType()625k && |
2701 | 625k | !isPlaceholder(BuiltinType::Overload)598k ) { |
2702 | 598k | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); |
2703 | 598k | if (SrcExpr.isInvalid()) |
2704 | 2 | return; |
2705 | 598k | } |
2706 | | |
2707 | | // AltiVec vector initialization with a single literal. |
2708 | 625k | if (const VectorType *vecTy = DestType->getAs<VectorType>()) { |
2709 | 358k | if (Self.CheckAltivecInitFromScalar(OpRange, DestType, |
2710 | 358k | SrcExpr.get()->getType())) { |
2711 | 0 | SrcExpr = ExprError(); |
2712 | 0 | return; |
2713 | 0 | } |
2714 | 358k | if (Self.ShouldSplatAltivecScalarInCast(vecTy) && |
2715 | 358k | (20.3k SrcExpr.get()->getType()->isIntegerType()20.3k || |
2716 | 20.3k | SrcExpr.get()->getType()->isFloatingType()19.2k )) { |
2717 | 1.20k | Kind = CK_VectorSplat; |
2718 | 1.20k | SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); |
2719 | 1.20k | return; |
2720 | 1.20k | } |
2721 | 358k | } |
2722 | | |
2723 | | // C++ [expr.cast]p5: The conversions performed by |
2724 | | // - a const_cast, |
2725 | | // - a static_cast, |
2726 | | // - a static_cast followed by a const_cast, |
2727 | | // - a reinterpret_cast, or |
2728 | | // - a reinterpret_cast followed by a const_cast, |
2729 | | // can be performed using the cast notation of explicit type conversion. |
2730 | | // [...] If a conversion can be interpreted in more than one of the ways |
2731 | | // listed above, the interpretation that appears first in the list is used, |
2732 | | // even if a cast resulting from that interpretation is ill-formed. |
2733 | | // In plain language, this means trying a const_cast ... |
2734 | | // Note that for address space we check compatibility after const_cast. |
2735 | 624k | unsigned msg = diag::err_bad_cxx_cast_generic; |
2736 | 624k | TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, |
2737 | 624k | /*CStyle*/ true, msg); |
2738 | 624k | if (SrcExpr.isInvalid()) |
2739 | 0 | return; |
2740 | 624k | if (isValidCast(tcr)) |
2741 | 8.94k | Kind = CK_NoOp; |
2742 | | |
2743 | 624k | Sema::CheckedConversionKind CCK = |
2744 | 624k | FunctionalStyle ? Sema::CCK_FunctionalCast68.6k : Sema::CCK_CStyleCast555k ; |
2745 | 624k | if (tcr == TC_NotApplicable) { |
2746 | 615k | tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg, |
2747 | 615k | Kind); |
2748 | 615k | if (SrcExpr.isInvalid()) |
2749 | 0 | return; |
2750 | | |
2751 | 615k | if (tcr == TC_NotApplicable) { |
2752 | | // ... or if that is not possible, a static_cast, ignoring const and |
2753 | | // addr space, ... |
2754 | 615k | tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind, |
2755 | 615k | BasePath, ListInitialization); |
2756 | 615k | if (SrcExpr.isInvalid()) |
2757 | 7 | return; |
2758 | | |
2759 | 615k | if (tcr == TC_NotApplicable) { |
2760 | | // ... and finally a reinterpret_cast, ignoring const and addr space. |
2761 | 49.2k | tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true, |
2762 | 49.2k | OpRange, msg, Kind); |
2763 | 49.2k | if (SrcExpr.isInvalid()) |
2764 | 0 | return; |
2765 | 49.2k | } |
2766 | 615k | } |
2767 | 615k | } |
2768 | | |
2769 | 624k | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
2770 | 624k | isValidCast(tcr)14.2k ) |
2771 | 14.2k | checkObjCConversion(CCK); |
2772 | | |
2773 | 624k | if (tcr != TC_Success && msg != 0453 ) { |
2774 | 399 | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { |
2775 | 9 | DeclAccessPair Found; |
2776 | 9 | FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), |
2777 | 9 | DestType, |
2778 | 9 | /*Complain*/ true, |
2779 | 9 | Found); |
2780 | 9 | if (Fn) { |
2781 | | // If DestType is a function type (not to be confused with the function |
2782 | | // pointer type), it will be possible to resolve the function address, |
2783 | | // but the type cast should be considered as failure. |
2784 | 1 | OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; |
2785 | 1 | Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) |
2786 | 1 | << OE->getName() << DestType << OpRange |
2787 | 1 | << OE->getQualifierLoc().getSourceRange(); |
2788 | 1 | Self.NoteAllOverloadCandidates(SrcExpr.get()); |
2789 | 1 | } |
2790 | 390 | } else { |
2791 | 390 | diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional238 : CT_CStyle152 ), |
2792 | 390 | OpRange, SrcExpr.get(), DestType, ListInitialization); |
2793 | 390 | } |
2794 | 399 | } |
2795 | | |
2796 | 624k | if (isValidCast(tcr)) { |
2797 | 624k | if (Kind == CK_BitCast) |
2798 | 61.4k | checkCastAlign(); |
2799 | | |
2800 | 624k | if (!checkCastFunctionType(Self, SrcExpr, DestType)) |
2801 | 6 | Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type) |
2802 | 6 | << SrcExpr.get()->getType() << DestType << OpRange; |
2803 | | |
2804 | 624k | } else { |
2805 | 453 | SrcExpr = ExprError(); |
2806 | 453 | } |
2807 | 624k | } |
2808 | | |
2809 | | /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a |
2810 | | /// non-matching type. Such as enum function call to int, int call to |
2811 | | /// pointer; etc. Cast to 'void' is an exception. |
2812 | | static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, |
2813 | 780k | QualType DestType) { |
2814 | 780k | if (Self.Diags.isIgnored(diag::warn_bad_function_cast, |
2815 | 780k | SrcExpr.get()->getExprLoc())) |
2816 | 780k | return; |
2817 | | |
2818 | 27 | if (!isa<CallExpr>(SrcExpr.get())) |
2819 | 4 | return; |
2820 | | |
2821 | 23 | QualType SrcType = SrcExpr.get()->getType(); |
2822 | 23 | if (DestType.getUnqualifiedType()->isVoidType()) |
2823 | 0 | return; |
2824 | 23 | if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()19 ) |
2825 | 23 | && (4 DestType->isAnyPointerType()4 || DestType->isBlockPointerType()2 )) |
2826 | 2 | return; |
2827 | 21 | if (SrcType->isIntegerType() && DestType->isIntegerType()11 && |
2828 | 21 | (SrcType->isBooleanType() == DestType->isBooleanType())8 && |
2829 | 21 | (SrcType->isEnumeralType() == DestType->isEnumeralType())6 ) |
2830 | 5 | return; |
2831 | 16 | if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()4 ) |
2832 | 2 | return; |
2833 | 14 | if (SrcType->isEnumeralType() && DestType->isEnumeralType()1 ) |
2834 | 0 | return; |
2835 | 14 | if (SrcType->isComplexType() && DestType->isComplexType()2 ) |
2836 | 1 | return; |
2837 | 13 | if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()0 ) |
2838 | 0 | return; |
2839 | 13 | if (SrcType->isFixedPointType() && DestType->isFixedPointType()2 ) |
2840 | 1 | return; |
2841 | | |
2842 | 12 | Self.Diag(SrcExpr.get()->getExprLoc(), |
2843 | 12 | diag::warn_bad_function_cast) |
2844 | 12 | << SrcType << DestType << SrcExpr.get()->getSourceRange(); |
2845 | 12 | } |
2846 | | |
2847 | | /// Check the semantics of a C-style cast operation, in C. |
2848 | 4.05M | void CastOperation::CheckCStyleCast() { |
2849 | 4.05M | assert(!Self.getLangOpts().CPlusPlus); |
2850 | | |
2851 | | // C-style casts can resolve __unknown_any types. |
2852 | 4.05M | if (claimPlaceholder(BuiltinType::UnknownAny)) { |
2853 | 5 | SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, |
2854 | 5 | SrcExpr.get(), Kind, |
2855 | 5 | ValueKind, BasePath); |
2856 | 5 | return; |
2857 | 5 | } |
2858 | | |
2859 | | // C99 6.5.4p2: the cast type needs to be void or scalar and the expression |
2860 | | // type needs to be scalar. |
2861 | 4.05M | if (DestType->isVoidType()) { |
2862 | | // We don't necessarily do lvalue-to-rvalue conversions on this. |
2863 | 7.90k | SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); |
2864 | 7.90k | if (SrcExpr.isInvalid()) |
2865 | 0 | return; |
2866 | | |
2867 | | // Cast to void allows any expr type. |
2868 | 7.90k | Kind = CK_ToVoid; |
2869 | 7.90k | return; |
2870 | 7.90k | } |
2871 | | |
2872 | | // If the type is dependent, we won't do any other semantic analysis now. |
2873 | 4.04M | if (Self.getASTContext().isDependenceAllowed() && |
2874 | 4.04M | (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || |
2875 | 4.04M | SrcExpr.get()->isValueDependent()4.04M )) { |
2876 | 282 | assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() || |
2877 | 282 | SrcExpr.get()->containsErrors()) && |
2878 | 282 | "should only occur in error-recovery path."); |
2879 | 0 | assert(Kind == CK_Dependent); |
2880 | 0 | return; |
2881 | 282 | } |
2882 | | |
2883 | | // Overloads are allowed with C extensions, so we need to support them. |
2884 | 4.04M | if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { |
2885 | 20 | DeclAccessPair DAP; |
2886 | 20 | if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( |
2887 | 20 | SrcExpr.get(), DestType, /*Complain=*/true, DAP)) |
2888 | 16 | SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); |
2889 | 4 | else |
2890 | 4 | return; |
2891 | 16 | assert(SrcExpr.isUsable()); |
2892 | 16 | } |
2893 | 4.04M | SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); |
2894 | 4.04M | if (SrcExpr.isInvalid()) |
2895 | 2 | return; |
2896 | 4.04M | QualType SrcType = SrcExpr.get()->getType(); |
2897 | | |
2898 | 4.04M | assert(!SrcType->isPlaceholderType()); |
2899 | | |
2900 | 0 | checkAddressSpaceCast(SrcType, DestType); |
2901 | 4.04M | if (SrcExpr.isInvalid()) |
2902 | 85 | return; |
2903 | | |
2904 | 4.04M | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, |
2905 | 4.04M | diag::err_typecheck_cast_to_incomplete)) { |
2906 | 4 | SrcExpr = ExprError(); |
2907 | 4 | return; |
2908 | 4 | } |
2909 | | |
2910 | | // Allow casting a sizeless built-in type to itself. |
2911 | 4.04M | if (DestType->isSizelessBuiltinType() && |
2912 | 4.04M | Self.Context.hasSameUnqualifiedType(DestType, SrcType)92 ) { |
2913 | 6 | Kind = CK_NoOp; |
2914 | 6 | return; |
2915 | 6 | } |
2916 | | |
2917 | | // Allow bitcasting between compatible SVE vector types. |
2918 | 4.04M | if ((SrcType->isVectorType() || DestType->isVectorType()784k ) && |
2919 | 4.04M | Self.isValidSveBitcast(SrcType, DestType)3.26M ) { |
2920 | 160 | Kind = CK_BitCast; |
2921 | 160 | return; |
2922 | 160 | } |
2923 | | |
2924 | 4.04M | if (!DestType->isScalarType() && !DestType->isVectorType()3.26M && |
2925 | 4.04M | !DestType->isMatrixType()79 ) { |
2926 | 50 | const RecordType *DestRecordTy = DestType->getAs<RecordType>(); |
2927 | | |
2928 | 50 | if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)33 ){ |
2929 | | // GCC struct/union extension: allow cast to self. |
2930 | 7 | Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) |
2931 | 7 | << DestType << SrcExpr.get()->getSourceRange(); |
2932 | 7 | Kind = CK_NoOp; |
2933 | 7 | return; |
2934 | 7 | } |
2935 | | |
2936 | | // GCC's cast to union extension. |
2937 | 43 | if (DestRecordTy && DestRecordTy->getDecl()->isUnion()26 ) { |
2938 | 25 | RecordDecl *RD = DestRecordTy->getDecl(); |
2939 | 25 | if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) { |
2940 | 22 | Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) |
2941 | 22 | << SrcExpr.get()->getSourceRange(); |
2942 | 22 | Kind = CK_ToUnion; |
2943 | 22 | return; |
2944 | 22 | } else { |
2945 | 3 | Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) |
2946 | 3 | << SrcType << SrcExpr.get()->getSourceRange(); |
2947 | 3 | SrcExpr = ExprError(); |
2948 | 3 | return; |
2949 | 3 | } |
2950 | 25 | } |
2951 | | |
2952 | | // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type. |
2953 | 18 | if (Self.getLangOpts().OpenCL && DestType->isEventT()2 ) { |
2954 | 2 | Expr::EvalResult Result; |
2955 | 2 | if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) { |
2956 | 2 | llvm::APSInt CastInt = Result.Val.getInt(); |
2957 | 2 | if (0 == CastInt) { |
2958 | 1 | Kind = CK_ZeroToOCLOpaqueType; |
2959 | 1 | return; |
2960 | 1 | } |
2961 | 1 | Self.Diag(OpRange.getBegin(), |
2962 | 1 | diag::err_opencl_cast_non_zero_to_event_t) |
2963 | 1 | << toString(CastInt, 10) << SrcExpr.get()->getSourceRange(); |
2964 | 1 | SrcExpr = ExprError(); |
2965 | 1 | return; |
2966 | 2 | } |
2967 | 2 | } |
2968 | | |
2969 | | // Reject any other conversions to non-scalar types. |
2970 | 16 | Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) |
2971 | 16 | << DestType << SrcExpr.get()->getSourceRange(); |
2972 | 16 | SrcExpr = ExprError(); |
2973 | 16 | return; |
2974 | 18 | } |
2975 | | |
2976 | | // The type we're casting to is known to be a scalar, a vector, or a matrix. |
2977 | | |
2978 | | // Require the operand to be a scalar, a vector, or a matrix. |
2979 | 4.04M | if (!SrcType->isScalarType() && !SrcType->isVectorType()3.26M && |
2980 | 4.04M | !SrcType->isMatrixType()56 ) { |
2981 | 27 | Self.Diag(SrcExpr.get()->getExprLoc(), |
2982 | 27 | diag::err_typecheck_expect_scalar_operand) |
2983 | 27 | << SrcType << SrcExpr.get()->getSourceRange(); |
2984 | 27 | SrcExpr = ExprError(); |
2985 | 27 | return; |
2986 | 27 | } |
2987 | | |
2988 | 4.04M | if (DestType->isExtVectorType()) { |
2989 | 82 | SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); |
2990 | 82 | return; |
2991 | 82 | } |
2992 | | |
2993 | 4.04M | if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()4.04M ) { |
2994 | 33 | if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) |
2995 | 11 | SrcExpr = ExprError(); |
2996 | 33 | return; |
2997 | 33 | } |
2998 | | |
2999 | 4.04M | if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { |
3000 | 3.26M | if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) { |
3001 | 36 | SrcExpr = ExprError(); |
3002 | 36 | return; |
3003 | 36 | } |
3004 | 3.26M | if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) && |
3005 | 3.26M | (5.00k SrcType->isIntegerType()5.00k || SrcType->isFloatingType()4.64k )) { |
3006 | 412 | Kind = CK_VectorSplat; |
3007 | 412 | SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); |
3008 | 3.26M | } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { |
3009 | 132 | SrcExpr = ExprError(); |
3010 | 132 | } |
3011 | 3.26M | return; |
3012 | 3.26M | } |
3013 | | |
3014 | 784k | if (SrcType->isVectorType()) { |
3015 | 3.77k | if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) |
3016 | 3 | SrcExpr = ExprError(); |
3017 | 3.77k | return; |
3018 | 3.77k | } |
3019 | | |
3020 | | // The source and target types are both scalars, i.e. |
3021 | | // - arithmetic types (fundamental, enum, and complex) |
3022 | | // - all kinds of pointers |
3023 | | // Note that member pointers were filtered out with C++, above. |
3024 | | |
3025 | 780k | if (isa<ObjCSelectorExpr>(SrcExpr.get())) { |
3026 | 2 | Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); |
3027 | 2 | SrcExpr = ExprError(); |
3028 | 2 | return; |
3029 | 2 | } |
3030 | | |
3031 | | // Can't cast to or from bfloat |
3032 | 780k | if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()174 ) { |
3033 | 4 | Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16) |
3034 | 4 | << SrcExpr.get()->getSourceRange(); |
3035 | 4 | SrcExpr = ExprError(); |
3036 | 4 | return; |
3037 | 4 | } |
3038 | 780k | if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()172 ) { |
3039 | 2 | Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16) |
3040 | 2 | << SrcExpr.get()->getSourceRange(); |
3041 | 2 | SrcExpr = ExprError(); |
3042 | 2 | return; |
3043 | 2 | } |
3044 | | |
3045 | | // If either type is a pointer, the other type has to be either an |
3046 | | // integer or a pointer. |
3047 | 780k | if (!DestType->isArithmeticType()) { |
3048 | 122k | if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()114k ) { |
3049 | 1 | Self.Diag(SrcExpr.get()->getExprLoc(), |
3050 | 1 | diag::err_cast_pointer_from_non_pointer_int) |
3051 | 1 | << SrcType << SrcExpr.get()->getSourceRange(); |
3052 | 1 | SrcExpr = ExprError(); |
3053 | 1 | return; |
3054 | 1 | } |
3055 | 122k | checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType, |
3056 | 122k | Self); |
3057 | 658k | } else if (!SrcType->isArithmeticType()) { |
3058 | 3.18k | if (!DestType->isIntegralType(Self.Context) && |
3059 | 3.18k | DestType->isArithmeticType()1 ) { |
3060 | 1 | Self.Diag(SrcExpr.get()->getBeginLoc(), |
3061 | 1 | diag::err_cast_pointer_to_non_pointer_int) |
3062 | 1 | << DestType << SrcExpr.get()->getSourceRange(); |
3063 | 1 | SrcExpr = ExprError(); |
3064 | 1 | return; |
3065 | 1 | } |
3066 | | |
3067 | 3.18k | if ((Self.Context.getTypeSize(SrcType) > |
3068 | 3.18k | Self.Context.getTypeSize(DestType)) && |
3069 | 3.18k | !DestType->isBooleanType()101 ) { |
3070 | | // C 6.3.2.3p6: Any pointer type may be converted to an integer type. |
3071 | | // Except as previously specified, the result is implementation-defined. |
3072 | | // If the result cannot be represented in the integer type, the behavior |
3073 | | // is undefined. The result need not be in the range of values of any |
3074 | | // integer type. |
3075 | 84 | unsigned Diag; |
3076 | 84 | if (SrcType->isVoidPointerType()) |
3077 | 29 | Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast2 |
3078 | 29 | : diag::warn_void_pointer_to_int_cast27 ; |
3079 | 55 | else if (DestType->isEnumeralType()) |
3080 | 2 | Diag = diag::warn_pointer_to_enum_cast; |
3081 | 53 | else |
3082 | 53 | Diag = diag::warn_pointer_to_int_cast; |
3083 | 84 | Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; |
3084 | 84 | } |
3085 | 3.18k | } |
3086 | | |
3087 | 780k | if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption( |
3088 | 1.19k | "cl_khr_fp16", Self.getLangOpts())) { |
3089 | 1.10k | if (DestType->isHalfType()) { |
3090 | 2 | Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half) |
3091 | 2 | << DestType << SrcExpr.get()->getSourceRange(); |
3092 | 2 | SrcExpr = ExprError(); |
3093 | 2 | return; |
3094 | 2 | } |
3095 | 1.10k | } |
3096 | | |
3097 | | // ARC imposes extra restrictions on casts. |
3098 | 780k | if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) { |
3099 | 1.15k | checkObjCConversion(Sema::CCK_CStyleCast); |
3100 | 1.15k | if (SrcExpr.isInvalid()) |
3101 | 0 | return; |
3102 | | |
3103 | 1.15k | const PointerType *CastPtr = DestType->getAs<PointerType>(); |
3104 | 1.15k | if (Self.getLangOpts().ObjCAutoRefCount && CastPtr1.14k ) { |
3105 | 410 | if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { |
3106 | 196 | Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); |
3107 | 196 | Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); |
3108 | 196 | if (CastPtr->getPointeeType()->isObjCLifetimeType() && |
3109 | 196 | ExprPtr->getPointeeType()->isObjCLifetimeType()43 && |
3110 | 196 | !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)33 ) { |
3111 | 14 | Self.Diag(SrcExpr.get()->getBeginLoc(), |
3112 | 14 | diag::err_typecheck_incompatible_ownership) |
3113 | 14 | << SrcType << DestType << Sema::AA_Casting |
3114 | 14 | << SrcExpr.get()->getSourceRange(); |
3115 | 14 | return; |
3116 | 14 | } |
3117 | 196 | } |
3118 | 410 | } |
3119 | 746 | else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { |
3120 | 4 | Self.Diag(SrcExpr.get()->getBeginLoc(), |
3121 | 4 | diag::err_arc_convesion_of_weak_unavailable) |
3122 | 4 | << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); |
3123 | 4 | SrcExpr = ExprError(); |
3124 | 4 | return; |
3125 | 4 | } |
3126 | 1.15k | } |
3127 | | |
3128 | 780k | if (!checkCastFunctionType(Self, SrcExpr, DestType)) |
3129 | 3 | Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type) |
3130 | 3 | << SrcType << DestType << OpRange; |
3131 | | |
3132 | 780k | if (isa<PointerType>(SrcType) && isa<PointerType>(DestType)113k ) { |
3133 | 109k | QualType SrcTy = cast<PointerType>(SrcType)->getPointeeType(); |
3134 | 109k | QualType DestTy = cast<PointerType>(DestType)->getPointeeType(); |
3135 | | |
3136 | 109k | const RecordDecl *SrcRD = SrcTy->getAsRecordDecl(); |
3137 | 109k | const RecordDecl *DestRD = DestTy->getAsRecordDecl(); |
3138 | | |
3139 | 109k | if (SrcRD && DestRD2.60k && SrcRD->hasAttr<RandomizeLayoutAttr>()1.56k && |
3140 | 109k | SrcRD != DestRD0 ) { |
3141 | | // The struct we are casting the pointer from was randomized. |
3142 | 0 | Self.Diag(OpRange.getBegin(), diag::err_cast_from_randomized_struct) |
3143 | 0 | << SrcType << DestType; |
3144 | 0 | SrcExpr = ExprError(); |
3145 | 0 | return; |
3146 | 0 | } |
3147 | 109k | } |
3148 | | |
3149 | 780k | DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); |
3150 | 780k | DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); |
3151 | 780k | DiagnoseBadFunctionCast(Self, SrcExpr, DestType); |
3152 | 780k | Kind = Self.PrepareScalarCast(SrcExpr, DestType); |
3153 | 780k | if (SrcExpr.isInvalid()) |
3154 | 0 | return; |
3155 | | |
3156 | 780k | if (Kind == CK_BitCast) |
3157 | 105k | checkCastAlign(); |
3158 | 780k | } |
3159 | | |
3160 | 792 | void CastOperation::CheckBuiltinBitCast() { |
3161 | 792 | QualType SrcType = SrcExpr.get()->getType(); |
3162 | | |
3163 | 792 | if (Self.RequireCompleteType(OpRange.getBegin(), DestType, |
3164 | 792 | diag::err_typecheck_cast_to_incomplete) || |
3165 | 792 | Self.RequireCompleteType(OpRange.getBegin(), SrcType, |
3166 | 792 | diag::err_incomplete_type)) { |
3167 | 0 | SrcExpr = ExprError(); |
3168 | 0 | return; |
3169 | 0 | } |
3170 | | |
3171 | 792 | if (SrcExpr.get()->isPRValue()) |
3172 | 79 | SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(), |
3173 | 79 | /*IsLValueReference=*/false); |
3174 | | |
3175 | 792 | CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType); |
3176 | 792 | CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType); |
3177 | 792 | if (DestSize != SourceSize) { |
3178 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch) |
3179 | 2 | << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity(); |
3180 | 2 | SrcExpr = ExprError(); |
3181 | 2 | return; |
3182 | 2 | } |
3183 | | |
3184 | 790 | if (!DestType.isTriviallyCopyableType(Self.Context)) { |
3185 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) |
3186 | 2 | << 1; |
3187 | 2 | SrcExpr = ExprError(); |
3188 | 2 | return; |
3189 | 2 | } |
3190 | | |
3191 | 788 | if (!SrcType.isTriviallyCopyableType(Self.Context)) { |
3192 | 2 | Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) |
3193 | 2 | << 0; |
3194 | 2 | SrcExpr = ExprError(); |
3195 | 2 | return; |
3196 | 2 | } |
3197 | | |
3198 | 786 | Kind = CK_LValueToRValueBitCast; |
3199 | 786 | } |
3200 | | |
3201 | | /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either |
3202 | | /// const, volatile or both. |
3203 | | static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, |
3204 | 4.76M | QualType DestType) { |
3205 | 4.76M | if (SrcExpr.isInvalid()) |
3206 | 0 | return; |
3207 | | |
3208 | 4.76M | QualType SrcType = SrcExpr.get()->getType(); |
3209 | 4.76M | if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()220k ) || |
3210 | 4.76M | DestType->isLValueReferenceType()4.56M )) |
3211 | 4.56M | return; |
3212 | | |
3213 | 204k | QualType TheOffendingSrcType, TheOffendingDestType; |
3214 | 204k | Qualifiers CastAwayQualifiers; |
3215 | 204k | if (CastsAwayConstness(Self, SrcType, DestType, true, false, |
3216 | 204k | &TheOffendingSrcType, &TheOffendingDestType, |
3217 | 204k | &CastAwayQualifiers) != |
3218 | 204k | CastAwayConstnessKind::CACK_Similar) |
3219 | 195k | return; |
3220 | | |
3221 | | // FIXME: 'restrict' is not properly handled here. |
3222 | 9.91k | int qualifiers = -1; |
3223 | 9.91k | if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()9.75k ) { |
3224 | 14 | qualifiers = 0; |
3225 | 9.89k | } else if (CastAwayQualifiers.hasConst()) { |
3226 | 9.73k | qualifiers = 1; |
3227 | 9.73k | } else if (158 CastAwayQualifiers.hasVolatile()158 ) { |
3228 | 136 | qualifiers = 2; |
3229 | 136 | } |
3230 | | // This is a variant of int **x; const int **y = (const int **)x; |
3231 | 9.91k | if (qualifiers == -1) |
3232 | 22 | Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2) |
3233 | 22 | << SrcType << DestType; |
3234 | 9.88k | else |
3235 | 9.88k | Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual) |
3236 | 9.88k | << TheOffendingSrcType << TheOffendingDestType << qualifiers; |
3237 | 9.91k | } |
3238 | | |
3239 | | ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, |
3240 | | TypeSourceInfo *CastTypeInfo, |
3241 | | SourceLocation RPLoc, |
3242 | 4.76M | Expr *CastExpr) { |
3243 | 4.76M | CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); |
3244 | 4.76M | Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); |
3245 | 4.76M | Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc()); |
3246 | | |
3247 | 4.76M | if (getLangOpts().CPlusPlus) { |
3248 | 709k | Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false, |
3249 | 709k | isa<InitListExpr>(CastExpr)); |
3250 | 4.05M | } else { |
3251 | 4.05M | Op.CheckCStyleCast(); |
3252 | 4.05M | } |
3253 | | |
3254 | 4.76M | if (Op.SrcExpr.isInvalid()) |
3255 | 554 | return ExprError(); |
3256 | | |
3257 | | // -Wcast-qual |
3258 | 4.76M | DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType); |
3259 | | |
3260 | 4.76M | return Op.complete(CStyleCastExpr::Create( |
3261 | 4.76M | Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), |
3262 | 4.76M | &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc)); |
3263 | 4.76M | } |
3264 | | |
3265 | | ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, |
3266 | | QualType Type, |
3267 | | SourceLocation LPLoc, |
3268 | | Expr *CastExpr, |
3269 | 69.8k | SourceLocation RPLoc) { |
3270 | 69.8k | assert(LPLoc.isValid() && "List-initialization shouldn't get here."); |
3271 | 0 | CastOperation Op(*this, Type, CastExpr); |
3272 | 69.8k | Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); |
3273 | 69.8k | Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc()); |
3274 | | |
3275 | 69.8k | Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false); |
3276 | 69.8k | if (Op.SrcExpr.isInvalid()) |
3277 | 266 | return ExprError(); |
3278 | | |
3279 | 69.5k | auto *SubExpr = Op.SrcExpr.get(); |
3280 | 69.5k | if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) |
3281 | 6.43k | SubExpr = BindExpr->getSubExpr(); |
3282 | 69.5k | if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) |
3283 | 25.8k | ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); |
3284 | | |
3285 | 69.5k | return Op.complete(CXXFunctionalCastExpr::Create( |
3286 | 69.5k | Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind, |
3287 | 69.5k | Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc)); |
3288 | 69.8k | } |