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