1 //===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ named casts.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/Basic/PartialDiagnostic.h"
20 #include "llvm/ADT/SmallVector.h"
22 using namespace clang
;
25 static void NoteAllOverloadCandidates(Expr
* const Expr
, Sema
& sema
);
28 TC_NotApplicable
, ///< The cast method is not applicable.
29 TC_Success
, ///< The cast method is appropriate and successful.
30 TC_Failed
///< The cast method is appropriate, but failed. A
31 ///< diagnostic has been emitted.
35 CT_Const
, ///< const_cast
36 CT_Static
, ///< static_cast
37 CT_Reinterpret
, ///< reinterpret_cast
38 CT_Dynamic
, ///< dynamic_cast
39 CT_CStyle
, ///< (Type)expr
40 CT_Functional
///< Type(expr)
46 static void CheckConstCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
48 const SourceRange
&OpRange
,
49 const SourceRange
&DestRange
);
50 static void CheckReinterpretCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
52 const SourceRange
&OpRange
,
53 const SourceRange
&DestRange
,
55 static void CheckStaticCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
57 const SourceRange
&OpRange
,
59 CXXCastPath
&BasePath
);
60 static void CheckDynamicCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
62 const SourceRange
&OpRange
,
63 const SourceRange
&DestRange
,
65 CXXCastPath
&BasePath
);
67 static bool CastsAwayConstness(Sema
&Self
, QualType SrcType
, QualType DestType
);
69 // The Try functions attempt a specific way of casting. If they succeed, they
70 // return TC_Success. If their way of casting is not appropriate for the given
71 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
72 // to emit if no other way succeeds. If their way of casting is appropriate but
73 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
74 // they emit a specialized diagnostic.
75 // All diagnostics returned by these functions must expect the same three
77 // %0: Cast Type (a value from the CastType enumeration)
79 // %2: Destination Type
80 static TryCastResult
TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
,
81 QualType DestType
, unsigned &msg
);
82 static TryCastResult
TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
,
83 QualType DestType
, bool CStyle
,
84 const SourceRange
&OpRange
,
87 CXXCastPath
&BasePath
);
88 static TryCastResult
TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
,
89 QualType DestType
, bool CStyle
,
90 const SourceRange
&OpRange
,
93 CXXCastPath
&BasePath
);
94 static TryCastResult
TryStaticDowncast(Sema
&Self
, CanQualType SrcType
,
95 CanQualType DestType
, bool CStyle
,
96 const SourceRange
&OpRange
,
98 QualType OrigDestType
, unsigned &msg
,
100 CXXCastPath
&BasePath
);
101 static TryCastResult
TryStaticMemberPointerUpcast(Sema
&Self
, Expr
*&SrcExpr
,
103 QualType DestType
,bool CStyle
,
104 const SourceRange
&OpRange
,
107 CXXCastPath
&BasePath
);
109 static TryCastResult
TryStaticImplicitCast(Sema
&Self
, Expr
*&SrcExpr
,
110 QualType DestType
, bool CStyle
,
111 const SourceRange
&OpRange
,
114 static TryCastResult
TryStaticCast(Sema
&Self
, Expr
*&SrcExpr
,
115 QualType DestType
, bool CStyle
,
116 const SourceRange
&OpRange
,
119 CXXCastPath
&BasePath
);
120 static TryCastResult
TryConstCast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
121 bool CStyle
, unsigned &msg
);
122 static TryCastResult
TryReinterpretCast(Sema
&Self
, Expr
*SrcExpr
,
123 QualType DestType
, bool CStyle
,
124 const SourceRange
&OpRange
,
128 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
130 Sema::ActOnCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
131 SourceLocation LAngleBracketLoc
, ParsedType Ty
,
132 SourceLocation RAngleBracketLoc
,
133 SourceLocation LParenLoc
, Expr
*E
,
134 SourceLocation RParenLoc
) {
136 TypeSourceInfo
*DestTInfo
;
137 QualType DestType
= GetTypeFromParser(Ty
, &DestTInfo
);
139 DestTInfo
= Context
.getTrivialTypeSourceInfo(DestType
, SourceLocation());
141 return BuildCXXNamedCast(OpLoc
, Kind
, DestTInfo
, move(E
),
142 SourceRange(LAngleBracketLoc
, RAngleBracketLoc
),
143 SourceRange(LParenLoc
, RParenLoc
));
147 Sema::BuildCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
148 TypeSourceInfo
*DestTInfo
, Expr
*Ex
,
149 SourceRange AngleBrackets
, SourceRange Parens
) {
150 QualType DestType
= DestTInfo
->getType();
152 SourceRange
OpRange(OpLoc
, Parens
.getEnd());
153 SourceRange DestRange
= AngleBrackets
;
155 // If the type is dependent, we won't do the semantic analysis now.
156 // FIXME: should we check this in a more fine-grained manner?
157 bool TypeDependent
= DestType
->isDependentType() || Ex
->isTypeDependent();
159 if (Ex
->isBoundMemberFunction(Context
))
160 Diag(Ex
->getLocStart(), diag::err_invalid_use_of_bound_member_func
)
161 << Ex
->getSourceRange();
163 ExprValueKind VK
= VK_RValue
;
165 VK
= Expr::getValueKindForType(DestType
);
168 default: llvm_unreachable("Unknown C++ cast!");
170 case tok::kw_const_cast
:
172 CheckConstCast(*this, Ex
, DestType
, VK
, OpRange
, DestRange
);
173 return Owned(CXXConstCastExpr::Create(Context
,
174 DestType
.getNonLValueExprType(Context
),
175 VK
, Ex
, DestTInfo
, OpLoc
));
177 case tok::kw_dynamic_cast
: {
178 CastKind Kind
= CK_Dependent
;
179 CXXCastPath BasePath
;
181 CheckDynamicCast(*this, Ex
, DestType
, VK
, OpRange
, DestRange
,
183 return Owned(CXXDynamicCastExpr::Create(Context
,
184 DestType
.getNonLValueExprType(Context
),
185 VK
, Kind
, Ex
, &BasePath
, DestTInfo
,
188 case tok::kw_reinterpret_cast
: {
189 CastKind Kind
= CK_Dependent
;
191 CheckReinterpretCast(*this, Ex
, DestType
, VK
, OpRange
, DestRange
, Kind
);
192 return Owned(CXXReinterpretCastExpr::Create(Context
,
193 DestType
.getNonLValueExprType(Context
),
197 case tok::kw_static_cast
: {
198 CastKind Kind
= CK_Dependent
;
199 CXXCastPath BasePath
;
201 CheckStaticCast(*this, Ex
, DestType
, VK
, OpRange
, Kind
, BasePath
);
203 return Owned(CXXStaticCastExpr::Create(Context
,
204 DestType
.getNonLValueExprType(Context
),
205 VK
, Kind
, Ex
, &BasePath
,
213 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
214 /// this removes one level of indirection from both types, provided that they're
215 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
216 /// this one doesn't care if the two pointers-to-member don't point into the
217 /// same class. This is because CastsAwayConstness doesn't care.
218 static bool UnwrapDissimilarPointerTypes(QualType
& T1
, QualType
& T2
) {
219 const PointerType
*T1PtrType
= T1
->getAs
<PointerType
>(),
220 *T2PtrType
= T2
->getAs
<PointerType
>();
221 if (T1PtrType
&& T2PtrType
) {
222 T1
= T1PtrType
->getPointeeType();
223 T2
= T2PtrType
->getPointeeType();
226 const ObjCObjectPointerType
*T1ObjCPtrType
=
227 T1
->getAs
<ObjCObjectPointerType
>(),
229 T2
->getAs
<ObjCObjectPointerType
>();
232 T1
= T1ObjCPtrType
->getPointeeType();
233 T2
= T2ObjCPtrType
->getPointeeType();
236 else if (T2PtrType
) {
237 T1
= T1ObjCPtrType
->getPointeeType();
238 T2
= T2PtrType
->getPointeeType();
242 else if (T2ObjCPtrType
) {
244 T2
= T2ObjCPtrType
->getPointeeType();
245 T1
= T1PtrType
->getPointeeType();
250 const MemberPointerType
*T1MPType
= T1
->getAs
<MemberPointerType
>(),
251 *T2MPType
= T2
->getAs
<MemberPointerType
>();
252 if (T1MPType
&& T2MPType
) {
253 T1
= T1MPType
->getPointeeType();
254 T2
= T2MPType
->getPointeeType();
258 const BlockPointerType
*T1BPType
= T1
->getAs
<BlockPointerType
>(),
259 *T2BPType
= T2
->getAs
<BlockPointerType
>();
260 if (T1BPType
&& T2BPType
) {
261 T1
= T1BPType
->getPointeeType();
262 T2
= T2BPType
->getPointeeType();
269 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
270 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
271 /// the cast checkers. Both arguments must denote pointer (possibly to member)
274 CastsAwayConstness(Sema
&Self
, QualType SrcType
, QualType DestType
) {
275 // Casting away constness is defined in C++ 5.2.11p8 with reference to
276 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
277 // the rules are non-trivial. So first we construct Tcv *...cv* as described
279 assert((SrcType
->isAnyPointerType() || SrcType
->isMemberPointerType() ||
280 SrcType
->isBlockPointerType()) &&
281 "Source type is not pointer or pointer to member.");
282 assert((DestType
->isAnyPointerType() || DestType
->isMemberPointerType() ||
283 DestType
->isBlockPointerType()) &&
284 "Destination type is not pointer or pointer to member.");
286 QualType UnwrappedSrcType
= Self
.Context
.getCanonicalType(SrcType
),
287 UnwrappedDestType
= Self
.Context
.getCanonicalType(DestType
);
288 llvm::SmallVector
<Qualifiers
, 8> cv1
, cv2
;
290 // Find the qualifications.
291 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType
, UnwrappedDestType
)) {
293 Self
.Context
.getUnqualifiedArrayType(UnwrappedSrcType
, SrcQuals
);
294 cv1
.push_back(SrcQuals
);
296 Qualifiers DestQuals
;
297 Self
.Context
.getUnqualifiedArrayType(UnwrappedDestType
, DestQuals
);
298 cv2
.push_back(DestQuals
);
303 // Construct void pointers with those qualifiers (in reverse order of
304 // unwrapping, of course).
305 QualType SrcConstruct
= Self
.Context
.VoidTy
;
306 QualType DestConstruct
= Self
.Context
.VoidTy
;
307 ASTContext
&Context
= Self
.Context
;
308 for (llvm::SmallVector
<Qualifiers
, 8>::reverse_iterator i1
= cv1
.rbegin(),
310 i1
!= cv1
.rend(); ++i1
, ++i2
) {
312 = Context
.getPointerType(Context
.getQualifiedType(SrcConstruct
, *i1
));
314 = Context
.getPointerType(Context
.getQualifiedType(DestConstruct
, *i2
));
317 // Test if they're compatible.
318 return SrcConstruct
!= DestConstruct
&&
319 !Self
.IsQualificationConversion(SrcConstruct
, DestConstruct
);
322 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
323 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
324 /// checked downcasts in class hierarchies.
326 CheckDynamicCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
327 ExprValueKind
&VK
, const SourceRange
&OpRange
,
328 const SourceRange
&DestRange
, CastKind
&Kind
,
329 CXXCastPath
&BasePath
) {
330 QualType OrigDestType
= DestType
, OrigSrcType
= SrcExpr
->getType();
331 DestType
= Self
.Context
.getCanonicalType(DestType
);
333 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
334 // or "pointer to cv void".
336 QualType DestPointee
;
337 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
338 const ReferenceType
*DestReference
= 0;
340 DestPointee
= DestPointer
->getPointeeType();
341 } else if ((DestReference
= DestType
->getAs
<ReferenceType
>())) {
342 DestPointee
= DestReference
->getPointeeType();
343 VK
= isa
<LValueReferenceType
>(DestReference
) ? VK_LValue
: VK_RValue
;
345 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr
)
346 << OrigDestType
<< DestRange
;
350 const RecordType
*DestRecord
= DestPointee
->getAs
<RecordType
>();
351 if (DestPointee
->isVoidType()) {
352 assert(DestPointer
&& "Reference to void is not possible");
353 } else if (DestRecord
) {
354 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestPointee
,
355 Self
.PDiag(diag::err_bad_dynamic_cast_incomplete
)
359 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
360 << DestPointee
.getUnqualifiedType() << DestRange
;
364 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
365 // complete class type, [...]. If T is an lvalue reference type, v shall be
366 // an lvalue of a complete class type, [...]. If T is an rvalue reference
367 // type, v shall be an expression having a complete effective class type,
370 QualType SrcType
= Self
.Context
.getCanonicalType(OrigSrcType
);
373 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
374 SrcPointee
= SrcPointer
->getPointeeType();
376 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ptr
)
377 << OrigSrcType
<< SrcExpr
->getSourceRange();
380 } else if (DestReference
->isLValueReferenceType()) {
381 if (!SrcExpr
->isLValue()) {
382 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_rvalue
)
383 << CT_Dynamic
<< OrigSrcType
<< OrigDestType
<< OpRange
;
385 SrcPointee
= SrcType
;
387 SrcPointee
= SrcType
;
390 const RecordType
*SrcRecord
= SrcPointee
->getAs
<RecordType
>();
392 if (Self
.RequireCompleteType(OpRange
.getBegin(), SrcPointee
,
393 Self
.PDiag(diag::err_bad_dynamic_cast_incomplete
)
394 << SrcExpr
->getSourceRange()))
397 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
398 << SrcPointee
.getUnqualifiedType() << SrcExpr
->getSourceRange();
402 assert((DestPointer
|| DestReference
) &&
403 "Bad destination non-ptr/ref slipped through.");
404 assert((DestRecord
|| DestPointee
->isVoidType()) &&
405 "Bad destination pointee slipped through.");
406 assert(SrcRecord
&& "Bad source pointee slipped through.");
408 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
409 if (!DestPointee
.isAtLeastAsQualifiedAs(SrcPointee
)) {
410 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_const_away
)
411 << CT_Dynamic
<< OrigSrcType
<< OrigDestType
<< OpRange
;
415 // C++ 5.2.7p3: If the type of v is the same as the required result type,
417 if (DestRecord
== SrcRecord
) {
423 // Upcasts are resolved statically.
424 if (DestRecord
&& Self
.IsDerivedFrom(SrcPointee
, DestPointee
)) {
425 if (Self
.CheckDerivedToBaseConversion(SrcPointee
, DestPointee
,
426 OpRange
.getBegin(), OpRange
,
430 Kind
= CK_DerivedToBase
;
432 // If we are casting to or through a virtual base class, we need a
434 if (Self
.BasePathInvolvesVirtualBase(BasePath
))
435 Self
.MarkVTableUsed(OpRange
.getBegin(),
436 cast
<CXXRecordDecl
>(SrcRecord
->getDecl()));
440 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
441 const RecordDecl
*SrcDecl
= SrcRecord
->getDecl()->getDefinition();
442 assert(SrcDecl
&& "Definition missing");
443 if (!cast
<CXXRecordDecl
>(SrcDecl
)->isPolymorphic()) {
444 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic
)
445 << SrcPointee
.getUnqualifiedType() << SrcExpr
->getSourceRange();
447 Self
.MarkVTableUsed(OpRange
.getBegin(),
448 cast
<CXXRecordDecl
>(SrcRecord
->getDecl()));
450 // Done. Everything else is run-time checks.
454 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
455 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
457 /// const char *str = "literal";
458 /// legacy_function(const_cast\<char*\>(str));
460 CheckConstCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
, ExprValueKind
&VK
,
461 const SourceRange
&OpRange
, const SourceRange
&DestRange
) {
462 VK
= Expr::getValueKindForType(DestType
);
464 Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
);
466 unsigned msg
= diag::err_bad_cxx_cast_generic
;
467 if (TryConstCast(Self
, SrcExpr
, DestType
, /*CStyle*/false, msg
) != TC_Success
469 Self
.Diag(OpRange
.getBegin(), msg
) << CT_Const
470 << SrcExpr
->getType() << DestType
<< OpRange
;
473 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
475 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
477 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
479 CheckReinterpretCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
480 ExprValueKind
&VK
, const SourceRange
&OpRange
,
481 const SourceRange
&DestRange
, CastKind
&Kind
) {
482 VK
= Expr::getValueKindForType(DestType
);
484 Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
);
486 unsigned msg
= diag::err_bad_cxx_cast_generic
;
487 if (TryReinterpretCast(Self
, SrcExpr
, DestType
, /*CStyle*/false, OpRange
,
489 != TC_Success
&& msg
!= 0)
491 if (SrcExpr
->getType() == Self
.Context
.OverloadTy
)
493 //FIXME: &f<int>; is overloaded and resolvable
494 Self
.Diag(OpRange
.getBegin(), diag::err_bad_reinterpret_cast_overload
)
495 << OverloadExpr::find(SrcExpr
).Expression
->getName()
496 << DestType
<< OpRange
;
497 NoteAllOverloadCandidates(SrcExpr
, Self
);
501 Self
.Diag(OpRange
.getBegin(), msg
) << CT_Reinterpret
502 << SrcExpr
->getType() << DestType
<< OpRange
;
508 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
509 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
510 /// implicit conversions explicit and getting rid of data loss warnings.
512 CheckStaticCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
513 ExprValueKind
&VK
, const SourceRange
&OpRange
,
514 CastKind
&Kind
, CXXCastPath
&BasePath
) {
515 // This test is outside everything else because it's the only case where
516 // a non-lvalue-reference target type does not lead to decay.
517 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
518 if (DestType
->isVoidType()) {
519 Self
.IgnoredValueConversions(SrcExpr
);
524 VK
= Expr::getValueKindForType(DestType
);
525 if (VK
== VK_RValue
&& !DestType
->isRecordType())
526 Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
);
528 unsigned msg
= diag::err_bad_cxx_cast_generic
;
529 if (TryStaticCast(Self
, SrcExpr
, DestType
, /*CStyle*/false, OpRange
, msg
,
530 Kind
, BasePath
) != TC_Success
&& msg
!= 0)
532 if (SrcExpr
->getType() == Self
.Context
.OverloadTy
)
534 OverloadExpr
* oe
= OverloadExpr::find(SrcExpr
).Expression
;
535 Self
.Diag(OpRange
.getBegin(), diag::err_bad_static_cast_overload
)
536 << oe
->getName() << DestType
<< OpRange
<< oe
->getQualifierRange();
537 NoteAllOverloadCandidates(SrcExpr
, Self
);
540 Self
.Diag(OpRange
.getBegin(), msg
) << CT_Static
541 << SrcExpr
->getType() << DestType
<< OpRange
;
543 else if (Kind
== CK_BitCast
)
544 Self
.CheckCastAlign(SrcExpr
, DestType
, OpRange
);
547 /// TryStaticCast - Check if a static cast can be performed, and do so if
548 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
549 /// and casting away constness.
550 static TryCastResult
TryStaticCast(Sema
&Self
, Expr
*&SrcExpr
,
551 QualType DestType
, bool CStyle
,
552 const SourceRange
&OpRange
, unsigned &msg
,
554 CXXCastPath
&BasePath
) {
555 // The order the tests is not entirely arbitrary. There is one conversion
556 // that can be handled in two different ways. Given:
558 // struct B : public A {
562 // the cast static_cast<const B&>(a) could be seen as either a static
563 // reference downcast, or an explicit invocation of the user-defined
564 // conversion using B's conversion constructor.
565 // DR 427 specifies that the downcast is to be applied here.
567 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
568 // Done outside this function.
572 // C++ 5.2.9p5, reference downcast.
573 // See the function for details.
574 // DR 427 specifies that this is to be applied before paragraph 2.
575 tcr
= TryStaticReferenceDowncast(Self
, SrcExpr
, DestType
, CStyle
, OpRange
,
576 msg
, Kind
, BasePath
);
577 if (tcr
!= TC_NotApplicable
)
580 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
581 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
582 tcr
= TryLValueToRValueCast(Self
, SrcExpr
, DestType
, msg
);
583 if (tcr
!= TC_NotApplicable
) {
588 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
589 // [...] if the declaration "T t(e);" is well-formed, [...].
590 tcr
= TryStaticImplicitCast(Self
, SrcExpr
, DestType
, CStyle
, OpRange
, msg
,
592 if (tcr
!= TC_NotApplicable
)
595 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
596 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
597 // conversions, subject to further restrictions.
598 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
599 // of qualification conversions impossible.
600 // In the CStyle case, the earlier attempt to const_cast should have taken
601 // care of reverse qualification conversions.
603 QualType OrigSrcType
= SrcExpr
->getType();
605 QualType SrcType
= Self
.Context
.getCanonicalType(SrcExpr
->getType());
607 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
608 // converted to an integral type.
609 if (Self
.getLangOptions().CPlusPlus0x
&& SrcType
->isEnumeralType()) {
610 assert(SrcType
->getAs
<EnumType
>()->getDecl()->isScoped());
611 if (DestType
->isBooleanType()) {
612 Kind
= CK_IntegralToBoolean
;
614 } else if (DestType
->isIntegralType(Self
.Context
)) {
615 Kind
= CK_IntegralCast
;
620 // Reverse integral promotion/conversion. All such conversions are themselves
621 // again integral promotions or conversions and are thus already handled by
622 // p2 (TryDirectInitialization above).
623 // (Note: any data loss warnings should be suppressed.)
624 // The exception is the reverse of enum->integer, i.e. integer->enum (and
625 // enum->enum). See also C++ 5.2.9p7.
626 // The same goes for reverse floating point promotion/conversion and
627 // floating-integral conversions. Again, only floating->enum is relevant.
628 if (DestType
->isEnumeralType()) {
629 if (SrcType
->isComplexType() || SrcType
->isVectorType()) {
630 // Fall through - these cannot be converted.
631 } else if (SrcType
->isArithmeticType() || SrcType
->isEnumeralType()) {
632 Kind
= CK_IntegralCast
;
637 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
638 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
639 tcr
= TryStaticPointerDowncast(Self
, SrcType
, DestType
, CStyle
, OpRange
, msg
,
641 if (tcr
!= TC_NotApplicable
)
644 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
645 // conversion. C++ 5.2.9p9 has additional information.
646 // DR54's access restrictions apply here also.
647 tcr
= TryStaticMemberPointerUpcast(Self
, SrcExpr
, SrcType
, DestType
, CStyle
,
648 OpRange
, msg
, Kind
, BasePath
);
649 if (tcr
!= TC_NotApplicable
)
652 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
653 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
654 // just the usual constness stuff.
655 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
656 QualType SrcPointee
= SrcPointer
->getPointeeType();
657 if (SrcPointee
->isVoidType()) {
658 if (const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>()) {
659 QualType DestPointee
= DestPointer
->getPointeeType();
660 if (DestPointee
->isIncompleteOrObjectType()) {
661 // This is definitely the intended conversion, but it might fail due
662 // to a const violation.
663 if (!CStyle
&& !DestPointee
.isAtLeastAsQualifiedAs(SrcPointee
)) {
664 msg
= diag::err_bad_cxx_cast_const_away
;
671 else if (DestType
->isObjCObjectPointerType()) {
672 // allow both c-style cast and static_cast of objective-c pointers as
673 // they are pervasive.
674 Kind
= CK_AnyPointerToObjCPointerCast
;
677 else if (CStyle
&& DestType
->isBlockPointerType()) {
678 // allow c-style cast of void * to block pointers.
679 Kind
= CK_AnyPointerToBlockPointerCast
;
684 // Allow arbitray objective-c pointer conversion with static casts.
685 if (SrcType
->isObjCObjectPointerType() &&
686 DestType
->isObjCObjectPointerType()) {
691 // We tried everything. Everything! Nothing works! :-(
692 return TC_NotApplicable
;
695 /// Tests whether a conversion according to N2844 is valid.
697 TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
699 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
700 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
701 const RValueReferenceType
*R
= DestType
->getAs
<RValueReferenceType
>();
703 return TC_NotApplicable
;
705 if (!SrcExpr
->isLValue())
706 return TC_NotApplicable
;
708 // Because we try the reference downcast before this function, from now on
709 // this is the only cast possibility, so we issue an error if we fail now.
710 // FIXME: Should allow casting away constness if CStyle.
713 if (Self
.CompareReferenceRelationship(SrcExpr
->getLocStart(),
714 SrcExpr
->getType(), R
->getPointeeType(),
715 DerivedToBase
, ObjCConversion
) <
716 Sema::Ref_Compatible_With_Added_Qualification
) {
717 msg
= diag::err_bad_lvalue_to_rvalue_cast
;
721 // FIXME: We should probably have an AST node for lvalue-to-rvalue
726 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
728 TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
729 bool CStyle
, const SourceRange
&OpRange
,
730 unsigned &msg
, CastKind
&Kind
,
731 CXXCastPath
&BasePath
) {
732 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
733 // cast to type "reference to cv2 D", where D is a class derived from B,
734 // if a valid standard conversion from "pointer to D" to "pointer to B"
735 // exists, cv2 >= cv1, and B is not a virtual base class of D.
736 // In addition, DR54 clarifies that the base must be accessible in the
737 // current context. Although the wording of DR54 only applies to the pointer
738 // variant of this rule, the intent is clearly for it to apply to the this
739 // conversion as well.
741 const ReferenceType
*DestReference
= DestType
->getAs
<ReferenceType
>();
742 if (!DestReference
) {
743 return TC_NotApplicable
;
745 bool RValueRef
= DestReference
->isRValueReferenceType();
746 if (!RValueRef
&& !SrcExpr
->isLValue()) {
747 // We know the left side is an lvalue reference, so we can suggest a reason.
748 msg
= diag::err_bad_cxx_cast_rvalue
;
749 return TC_NotApplicable
;
752 QualType DestPointee
= DestReference
->getPointeeType();
754 return TryStaticDowncast(Self
,
755 Self
.Context
.getCanonicalType(SrcExpr
->getType()),
756 Self
.Context
.getCanonicalType(DestPointee
), CStyle
,
757 OpRange
, SrcExpr
->getType(), DestType
, msg
, Kind
,
761 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
763 TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
, QualType DestType
,
764 bool CStyle
, const SourceRange
&OpRange
,
765 unsigned &msg
, CastKind
&Kind
,
766 CXXCastPath
&BasePath
) {
767 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
768 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
769 // is a class derived from B, if a valid standard conversion from "pointer
770 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
772 // In addition, DR54 clarifies that the base must be accessible in the
775 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
777 return TC_NotApplicable
;
780 const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>();
782 msg
= diag::err_bad_static_cast_pointer_nonpointer
;
783 return TC_NotApplicable
;
786 return TryStaticDowncast(Self
,
787 Self
.Context
.getCanonicalType(SrcPointer
->getPointeeType()),
788 Self
.Context
.getCanonicalType(DestPointer
->getPointeeType()),
789 CStyle
, OpRange
, SrcType
, DestType
, msg
, Kind
,
793 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
794 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
795 /// DestType is possible and allowed.
797 TryStaticDowncast(Sema
&Self
, CanQualType SrcType
, CanQualType DestType
,
798 bool CStyle
, const SourceRange
&OpRange
, QualType OrigSrcType
,
799 QualType OrigDestType
, unsigned &msg
,
800 CastKind
&Kind
, CXXCastPath
&BasePath
) {
801 // We can only work with complete types. But don't complain if it doesn't work
802 if (Self
.RequireCompleteType(OpRange
.getBegin(), SrcType
, Self
.PDiag(0)) ||
803 Self
.RequireCompleteType(OpRange
.getBegin(), DestType
, Self
.PDiag(0)))
804 return TC_NotApplicable
;
806 // Downcast can only happen in class hierarchies, so we need classes.
807 if (!DestType
->getAs
<RecordType
>() || !SrcType
->getAs
<RecordType
>()) {
808 return TC_NotApplicable
;
811 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
812 /*DetectVirtual=*/true);
813 if (!Self
.IsDerivedFrom(DestType
, SrcType
, Paths
)) {
814 return TC_NotApplicable
;
817 // Target type does derive from source type. Now we're serious. If an error
818 // appears now, it's not ignored.
819 // This may not be entirely in line with the standard. Take for example:
821 // struct B : virtual A {
827 // (void)static_cast<const B&>(*((A*)0));
829 // As far as the standard is concerned, p5 does not apply (A is virtual), so
830 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
831 // However, both GCC and Comeau reject this example, and accepting it would
832 // mean more complex code if we're to preserve the nice error message.
833 // FIXME: Being 100% compliant here would be nice to have.
835 // Must preserve cv, as always, unless we're in C-style mode.
836 if (!CStyle
&& !DestType
.isAtLeastAsQualifiedAs(SrcType
)) {
837 msg
= diag::err_bad_cxx_cast_const_away
;
841 if (Paths
.isAmbiguous(SrcType
.getUnqualifiedType())) {
842 // This code is analoguous to that in CheckDerivedToBaseConversion, except
843 // that it builds the paths in reverse order.
844 // To sum up: record all paths to the base and build a nice string from
845 // them. Use it to spice up the error message.
846 if (!Paths
.isRecordingPaths()) {
848 Paths
.setRecordingPaths(true);
849 Self
.IsDerivedFrom(DestType
, SrcType
, Paths
);
851 std::string PathDisplayStr
;
852 std::set
<unsigned> DisplayedPaths
;
853 for (CXXBasePaths::paths_iterator PI
= Paths
.begin(), PE
= Paths
.end();
855 if (DisplayedPaths
.insert(PI
->back().SubobjectNumber
).second
) {
856 // We haven't displayed a path to this particular base
857 // class subobject yet.
858 PathDisplayStr
+= "\n ";
859 for (CXXBasePath::const_reverse_iterator EI
= PI
->rbegin(),
862 PathDisplayStr
+= EI
->Base
->getType().getAsString() + " -> ";
863 PathDisplayStr
+= QualType(DestType
).getAsString();
867 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_base_to_derived_cast
)
868 << QualType(SrcType
).getUnqualifiedType()
869 << QualType(DestType
).getUnqualifiedType()
870 << PathDisplayStr
<< OpRange
;
875 if (Paths
.getDetectedVirtual() != 0) {
876 QualType
VirtualBase(Paths
.getDetectedVirtual(), 0);
877 Self
.Diag(OpRange
.getBegin(), diag::err_static_downcast_via_virtual
)
878 << OrigSrcType
<< OrigDestType
<< VirtualBase
<< OpRange
;
883 if (!CStyle
&& Self
.CheckBaseClassAccess(OpRange
.getBegin(),
886 diag::err_downcast_from_inaccessible_base
)) {
891 Self
.BuildBasePathArray(Paths
, BasePath
);
892 Kind
= CK_BaseToDerived
;
896 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
897 /// C++ 5.2.9p9 is valid:
899 /// An rvalue of type "pointer to member of D of type cv1 T" can be
900 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
901 /// where B is a base class of D [...].
904 TryStaticMemberPointerUpcast(Sema
&Self
, Expr
*&SrcExpr
, QualType SrcType
,
905 QualType DestType
, bool CStyle
,
906 const SourceRange
&OpRange
,
907 unsigned &msg
, CastKind
&Kind
,
908 CXXCastPath
&BasePath
) {
909 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>();
911 return TC_NotApplicable
;
913 bool WasOverloadedFunction
= false;
914 DeclAccessPair FoundOverload
;
915 if (SrcExpr
->getType() == Self
.Context
.OverloadTy
) {
917 = Self
.ResolveAddressOfOverloadedFunction(SrcExpr
, DestType
, false,
919 CXXMethodDecl
*M
= cast
<CXXMethodDecl
>(Fn
);
920 SrcType
= Self
.Context
.getMemberPointerType(Fn
->getType(),
921 Self
.Context
.getTypeDeclType(M
->getParent()).getTypePtr());
922 WasOverloadedFunction
= true;
926 const MemberPointerType
*SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
928 msg
= diag::err_bad_static_cast_member_pointer_nonmp
;
929 return TC_NotApplicable
;
933 if (!Self
.Context
.hasSameUnqualifiedType(SrcMemPtr
->getPointeeType(),
934 DestMemPtr
->getPointeeType()))
935 return TC_NotApplicable
;
938 QualType
SrcClass(SrcMemPtr
->getClass(), 0);
939 QualType
DestClass(DestMemPtr
->getClass(), 0);
940 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
941 /*DetectVirtual=*/true);
942 if (!Self
.IsDerivedFrom(SrcClass
, DestClass
, Paths
)) {
943 return TC_NotApplicable
;
946 // B is a base of D. But is it an allowed base? If not, it's a hard error.
947 if (Paths
.isAmbiguous(Self
.Context
.getCanonicalType(DestClass
))) {
949 Paths
.setRecordingPaths(true);
950 bool StillOkay
= Self
.IsDerivedFrom(SrcClass
, DestClass
, Paths
);
952 StillOkay
= StillOkay
;
953 std::string PathDisplayStr
= Self
.getAmbiguousPathsDisplayString(Paths
);
954 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_memptr_conv
)
955 << 1 << SrcClass
<< DestClass
<< PathDisplayStr
<< OpRange
;
960 if (const RecordType
*VBase
= Paths
.getDetectedVirtual()) {
961 Self
.Diag(OpRange
.getBegin(), diag::err_memptr_conv_via_virtual
)
962 << SrcClass
<< DestClass
<< QualType(VBase
, 0) << OpRange
;
967 if (!CStyle
&& Self
.CheckBaseClassAccess(OpRange
.getBegin(),
970 diag::err_upcast_to_inaccessible_base
)) {
975 if (WasOverloadedFunction
) {
976 // Resolve the address of the overloaded function again, this time
977 // allowing complaints if something goes wrong.
978 FunctionDecl
*Fn
= Self
.ResolveAddressOfOverloadedFunction(SrcExpr
,
987 SrcExpr
= Self
.FixOverloadedFunctionReference(SrcExpr
, FoundOverload
, Fn
);
994 Self
.BuildBasePathArray(Paths
, BasePath
);
995 Kind
= CK_DerivedToBaseMemberPointer
;
999 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1002 /// An expression e can be explicitly converted to a type T using a
1003 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1005 TryStaticImplicitCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
1006 bool CStyle
, const SourceRange
&OpRange
, unsigned &msg
,
1008 if (DestType
->isRecordType()) {
1009 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
1010 diag::err_bad_dynamic_cast_incomplete
)) {
1016 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(DestType
);
1017 InitializationKind InitKind
1018 = InitializationKind::CreateCast(/*FIXME:*/OpRange
,
1020 InitializationSequence
InitSeq(Self
, Entity
, InitKind
, &SrcExpr
, 1);
1022 // At this point of CheckStaticCast, if the destination is a reference,
1023 // or the expression is an overload expression this has to work.
1024 // There is no other way that works.
1025 // On the other hand, if we're checking a C-style cast, we've still got
1026 // the reinterpret_cast way.
1028 if (InitSeq
.getKind() == InitializationSequence::FailedSequence
&&
1029 (CStyle
|| !DestType
->isReferenceType()))
1030 return TC_NotApplicable
;
1033 = InitSeq
.Perform(Self
, Entity
, InitKind
, MultiExprArg(Self
, &SrcExpr
, 1));
1034 if (Result
.isInvalid()) {
1039 if (InitSeq
.isConstructorInitialization())
1040 Kind
= CK_ConstructorConversion
;
1044 SrcExpr
= Result
.takeAs
<Expr
>();
1048 /// TryConstCast - See if a const_cast from source to destination is allowed,
1049 /// and perform it if it is.
1050 static TryCastResult
TryConstCast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
1051 bool CStyle
, unsigned &msg
) {
1052 DestType
= Self
.Context
.getCanonicalType(DestType
);
1053 QualType SrcType
= SrcExpr
->getType();
1054 if (const LValueReferenceType
*DestTypeTmp
=
1055 DestType
->getAs
<LValueReferenceType
>()) {
1056 if (!SrcExpr
->isLValue()) {
1057 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1058 // is C-style, static_cast might find a way, so we simply suggest a
1059 // message and tell the parent to keep searching.
1060 msg
= diag::err_bad_cxx_cast_rvalue
;
1061 return TC_NotApplicable
;
1064 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1065 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1066 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
1067 SrcType
= Self
.Context
.getPointerType(SrcType
);
1070 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1071 // the rules for const_cast are the same as those used for pointers.
1073 if (!DestType
->isPointerType() &&
1074 !DestType
->isMemberPointerType() &&
1075 !DestType
->isObjCObjectPointerType()) {
1076 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1077 // was a reference type, we converted it to a pointer above.
1078 // The status of rvalue references isn't entirely clear, but it looks like
1079 // conversion to them is simply invalid.
1080 // C++ 5.2.11p3: For two pointer types [...]
1082 msg
= diag::err_bad_const_cast_dest
;
1083 return TC_NotApplicable
;
1085 if (DestType
->isFunctionPointerType() ||
1086 DestType
->isMemberFunctionPointerType()) {
1087 // Cannot cast direct function pointers.
1088 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1089 // T is the ultimate pointee of source and target type.
1091 msg
= diag::err_bad_const_cast_dest
;
1092 return TC_NotApplicable
;
1094 SrcType
= Self
.Context
.getCanonicalType(SrcType
);
1096 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1097 // completely equal.
1098 // FIXME: const_cast should probably not be able to convert between pointers
1099 // to different address spaces.
1100 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1101 // in multi-level pointers may change, but the level count must be the same,
1102 // as must be the final pointee type.
1103 while (SrcType
!= DestType
&&
1104 Self
.Context
.UnwrapSimilarPointerTypes(SrcType
, DestType
)) {
1106 SrcType
= Self
.Context
.getUnqualifiedArrayType(SrcType
, Quals
);
1107 DestType
= Self
.Context
.getUnqualifiedArrayType(DestType
, Quals
);
1110 // Since we're dealing in canonical types, the remainder must be the same.
1111 if (SrcType
!= DestType
)
1112 return TC_NotApplicable
;
1118 static void NoteAllOverloadCandidates(Expr
* const Expr
, Sema
& sema
)
1121 assert(Expr
->getType() == sema
.Context
.OverloadTy
);
1123 OverloadExpr::FindResult Ovl
= OverloadExpr::find(Expr
);
1124 OverloadExpr
*const OvlExpr
= Ovl
.Expression
;
1126 for (UnresolvedSetIterator it
= OvlExpr
->decls_begin(),
1127 end
= OvlExpr
->decls_end(); it
!= end
; ++it
) {
1128 if ( FunctionTemplateDecl
*ftd
=
1129 dyn_cast
<FunctionTemplateDecl
>((*it
)->getUnderlyingDecl()) )
1131 sema
.NoteOverloadCandidate(ftd
->getTemplatedDecl());
1133 else if ( FunctionDecl
*f
=
1134 dyn_cast
<FunctionDecl
>((*it
)->getUnderlyingDecl()) )
1136 sema
.NoteOverloadCandidate(f
);
1142 static TryCastResult
TryReinterpretCast(Sema
&Self
, Expr
*SrcExpr
,
1143 QualType DestType
, bool CStyle
,
1144 const SourceRange
&OpRange
,
1147 bool IsLValueCast
= false;
1149 DestType
= Self
.Context
.getCanonicalType(DestType
);
1150 QualType SrcType
= SrcExpr
->getType();
1152 // Is the source an overloaded name? (i.e. &foo)
1153 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
1154 if (SrcType
== Self
.Context
.OverloadTy
)
1155 return TC_NotApplicable
;
1157 if (const ReferenceType
*DestTypeTmp
= DestType
->getAs
<ReferenceType
>()) {
1158 bool LValue
= DestTypeTmp
->isLValueReferenceType();
1159 if (LValue
&& !SrcExpr
->isLValue()) {
1160 // Cannot cast non-lvalue to reference type. See the similar comment in
1162 msg
= diag::err_bad_cxx_cast_rvalue
;
1163 return TC_NotApplicable
;
1166 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1167 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1168 // built-in & and * operators.
1169 // This code does this transformation for the checked types.
1170 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
1171 SrcType
= Self
.Context
.getPointerType(SrcType
);
1173 IsLValueCast
= true;
1176 // Canonicalize source for comparison.
1177 SrcType
= Self
.Context
.getCanonicalType(SrcType
);
1179 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>(),
1180 *SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
1181 if (DestMemPtr
&& SrcMemPtr
) {
1182 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1183 // can be explicitly converted to an rvalue of type "pointer to member
1184 // of Y of type T2" if T1 and T2 are both function types or both object
1186 if (DestMemPtr
->getPointeeType()->isFunctionType() !=
1187 SrcMemPtr
->getPointeeType()->isFunctionType())
1188 return TC_NotApplicable
;
1190 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1192 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1194 if (!CStyle
&& CastsAwayConstness(Self
, SrcType
, DestType
)) {
1195 msg
= diag::err_bad_cxx_cast_const_away
;
1199 // Don't allow casting between member pointers of different sizes.
1200 if (Self
.Context
.getTypeSize(DestMemPtr
) !=
1201 Self
.Context
.getTypeSize(SrcMemPtr
)) {
1202 msg
= diag::err_bad_cxx_cast_member_pointer_size
;
1206 // A valid member pointer cast.
1207 Kind
= IsLValueCast
? CK_LValueBitCast
: CK_BitCast
;
1211 // See below for the enumeral issue.
1212 if (SrcType
->isNullPtrType() && DestType
->isIntegralType(Self
.Context
)) {
1213 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1214 // type large enough to hold it. A value of std::nullptr_t can be
1215 // converted to an integral type; the conversion has the same meaning
1216 // and validity as a conversion of (void*)0 to the integral type.
1217 if (Self
.Context
.getTypeSize(SrcType
) >
1218 Self
.Context
.getTypeSize(DestType
)) {
1219 msg
= diag::err_bad_reinterpret_cast_small_int
;
1222 Kind
= CK_PointerToIntegral
;
1226 bool destIsVector
= DestType
->isVectorType();
1227 bool srcIsVector
= SrcType
->isVectorType();
1228 if (srcIsVector
|| destIsVector
) {
1229 // FIXME: Should this also apply to floating point types?
1230 bool srcIsScalar
= SrcType
->isIntegralType(Self
.Context
);
1231 bool destIsScalar
= DestType
->isIntegralType(Self
.Context
);
1233 // Check if this is a cast between a vector and something else.
1234 if (!(srcIsScalar
&& destIsVector
) && !(srcIsVector
&& destIsScalar
) &&
1235 !(srcIsVector
&& destIsVector
))
1236 return TC_NotApplicable
;
1238 // If both types have the same size, we can successfully cast.
1239 if (Self
.Context
.getTypeSize(SrcType
)
1240 == Self
.Context
.getTypeSize(DestType
)) {
1246 msg
= diag::err_bad_cxx_cast_vector_to_scalar_different_size
;
1247 else if (srcIsScalar
)
1248 msg
= diag::err_bad_cxx_cast_scalar_to_vector_different_size
;
1250 msg
= diag::err_bad_cxx_cast_vector_to_vector_different_size
;
1255 bool destIsPtr
= DestType
->isAnyPointerType() ||
1256 DestType
->isBlockPointerType();
1257 bool srcIsPtr
= SrcType
->isAnyPointerType() ||
1258 SrcType
->isBlockPointerType();
1259 if (!destIsPtr
&& !srcIsPtr
) {
1260 // Except for std::nullptr_t->integer and lvalue->reference, which are
1261 // handled above, at least one of the two arguments must be a pointer.
1262 return TC_NotApplicable
;
1265 if (SrcType
== DestType
) {
1266 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1267 // restrictions, a cast to the same type is allowed. The intent is not
1268 // entirely clear here, since all other paragraphs explicitly forbid casts
1269 // to the same type. However, the behavior of compilers is pretty consistent
1270 // on this point: allow same-type conversion if the involved types are
1271 // pointers, disallow otherwise.
1276 if (DestType
->isIntegralType(Self
.Context
)) {
1277 assert(srcIsPtr
&& "One type must be a pointer");
1278 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1279 // type large enough to hold it.
1280 if (Self
.Context
.getTypeSize(SrcType
) >
1281 Self
.Context
.getTypeSize(DestType
)) {
1282 msg
= diag::err_bad_reinterpret_cast_small_int
;
1285 Kind
= CK_PointerToIntegral
;
1289 if (SrcType
->isIntegralOrEnumerationType()) {
1290 assert(destIsPtr
&& "One type must be a pointer");
1291 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1292 // converted to a pointer.
1293 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1294 // necessarily converted to a null pointer value.]
1295 Kind
= CK_IntegralToPointer
;
1299 if (!destIsPtr
|| !srcIsPtr
) {
1300 // With the valid non-pointer conversions out of the way, we can be even
1302 return TC_NotApplicable
;
1305 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1306 // The C-style cast operator can.
1307 if (!CStyle
&& CastsAwayConstness(Self
, SrcType
, DestType
)) {
1308 msg
= diag::err_bad_cxx_cast_const_away
;
1312 // Cannot convert between block pointers and Objective-C object pointers.
1313 if ((SrcType
->isBlockPointerType() && DestType
->isObjCObjectPointerType()) ||
1314 (DestType
->isBlockPointerType() && SrcType
->isObjCObjectPointerType()))
1315 return TC_NotApplicable
;
1317 // Any pointer can be cast to an Objective-C pointer type with a C-style
1319 if (CStyle
&& DestType
->isObjCObjectPointerType()) {
1320 Kind
= CK_AnyPointerToObjCPointerCast
;
1324 // Not casting away constness, so the only remaining check is for compatible
1325 // pointer categories.
1326 Kind
= IsLValueCast
? CK_LValueBitCast
: CK_BitCast
;
1328 if (SrcType
->isFunctionPointerType()) {
1329 if (DestType
->isFunctionPointerType()) {
1330 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1331 // a pointer to a function of a different type.
1335 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1336 // an object type or vice versa is conditionally-supported.
1337 // Compilers support it in C++03 too, though, because it's necessary for
1338 // casting the return value of dlsym() and GetProcAddress().
1339 // FIXME: Conditionally-supported behavior should be configurable in the
1340 // TargetInfo or similar.
1341 if (!Self
.getLangOptions().CPlusPlus0x
)
1342 Self
.Diag(OpRange
.getBegin(), diag::ext_cast_fn_obj
) << OpRange
;
1346 if (DestType
->isFunctionPointerType()) {
1348 if (!Self
.getLangOptions().CPlusPlus0x
)
1349 Self
.Diag(OpRange
.getBegin(), diag::ext_cast_fn_obj
) << OpRange
;
1353 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1354 // a pointer to an object of different type.
1355 // Void pointers are not specified, but supported by every compiler out there.
1356 // So we finish by allowing everything that remains - it's got to be two
1362 Sema::CXXCheckCStyleCast(SourceRange R
, QualType CastTy
, ExprValueKind
&VK
,
1363 Expr
*&CastExpr
, CastKind
&Kind
,
1364 CXXCastPath
&BasePath
,
1365 bool FunctionalStyle
) {
1366 if (CastExpr
->isBoundMemberFunction(Context
))
1367 return Diag(CastExpr
->getLocStart(),
1368 diag::err_invalid_use_of_bound_member_func
)
1369 << CastExpr
->getSourceRange();
1371 // This test is outside everything else because it's the only case where
1372 // a non-lvalue-reference target type does not lead to decay.
1373 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1374 if (CastTy
->isVoidType()) {
1375 IgnoredValueConversions(CastExpr
);
1380 // Make sure we determine the value kind before we bail out for
1382 VK
= Expr::getValueKindForType(CastTy
);
1384 // If the type is dependent, we won't do any other semantic analysis now.
1385 if (CastTy
->isDependentType() || CastExpr
->isTypeDependent()) {
1386 Kind
= CK_Dependent
;
1390 if (VK
== VK_RValue
&& !CastTy
->isRecordType())
1391 DefaultFunctionArrayLvalueConversion(CastExpr
);
1393 // C++ [expr.cast]p5: The conversions performed by
1396 // - a static_cast followed by a const_cast,
1397 // - a reinterpret_cast, or
1398 // - a reinterpret_cast followed by a const_cast,
1399 // can be performed using the cast notation of explicit type conversion.
1400 // [...] If a conversion can be interpreted in more than one of the ways
1401 // listed above, the interpretation that appears first in the list is used,
1402 // even if a cast resulting from that interpretation is ill-formed.
1403 // In plain language, this means trying a const_cast ...
1404 unsigned msg
= diag::err_bad_cxx_cast_generic
;
1405 TryCastResult tcr
= TryConstCast(*this, CastExpr
, CastTy
, /*CStyle*/true,
1407 if (tcr
== TC_Success
)
1410 if (tcr
== TC_NotApplicable
) {
1411 // ... or if that is not possible, a static_cast, ignoring const, ...
1412 tcr
= TryStaticCast(*this, CastExpr
, CastTy
, /*CStyle*/true, R
, msg
, Kind
,
1414 if (tcr
== TC_NotApplicable
) {
1415 // ... and finally a reinterpret_cast, ignoring const.
1416 tcr
= TryReinterpretCast(*this, CastExpr
, CastTy
, /*CStyle*/true, R
, msg
,
1421 if (tcr
!= TC_Success
&& msg
!= 0) {
1422 if (CastExpr
->getType() == Context
.OverloadTy
) {
1423 DeclAccessPair Found
;
1424 FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(CastExpr
,
1426 /* Complain */ true,
1428 assert(!Fn
&& "cast failed but able to resolve overload expression!!");
1431 Diag(R
.getBegin(), msg
) << (FunctionalStyle
? CT_Functional
: CT_CStyle
)
1432 << CastExpr
->getType() << CastTy
<< R
;
1435 else if (Kind
== CK_BitCast
)
1436 CheckCastAlign(CastExpr
, CastTy
, R
);
1438 return tcr
!= TC_Success
;