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
, bool CStyle
,
83 CXXCastPath
&BasePath
,
85 static TryCastResult
TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
,
86 QualType DestType
, bool CStyle
,
87 const SourceRange
&OpRange
,
90 CXXCastPath
&BasePath
);
91 static TryCastResult
TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
,
92 QualType DestType
, bool CStyle
,
93 const SourceRange
&OpRange
,
96 CXXCastPath
&BasePath
);
97 static TryCastResult
TryStaticDowncast(Sema
&Self
, CanQualType SrcType
,
98 CanQualType DestType
, bool CStyle
,
99 const SourceRange
&OpRange
,
100 QualType OrigSrcType
,
101 QualType OrigDestType
, unsigned &msg
,
103 CXXCastPath
&BasePath
);
104 static TryCastResult
TryStaticMemberPointerUpcast(Sema
&Self
, Expr
*&SrcExpr
,
106 QualType DestType
,bool CStyle
,
107 const SourceRange
&OpRange
,
110 CXXCastPath
&BasePath
);
112 static TryCastResult
TryStaticImplicitCast(Sema
&Self
, Expr
*&SrcExpr
,
113 QualType DestType
, bool CStyle
,
114 const SourceRange
&OpRange
,
117 static TryCastResult
TryStaticCast(Sema
&Self
, Expr
*&SrcExpr
,
118 QualType DestType
, bool CStyle
,
119 const SourceRange
&OpRange
,
122 CXXCastPath
&BasePath
);
123 static TryCastResult
TryConstCast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
124 bool CStyle
, unsigned &msg
);
125 static TryCastResult
TryReinterpretCast(Sema
&Self
, Expr
*SrcExpr
,
126 QualType DestType
, bool CStyle
,
127 const SourceRange
&OpRange
,
131 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
133 Sema::ActOnCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
134 SourceLocation LAngleBracketLoc
, ParsedType Ty
,
135 SourceLocation RAngleBracketLoc
,
136 SourceLocation LParenLoc
, Expr
*E
,
137 SourceLocation RParenLoc
) {
139 TypeSourceInfo
*DestTInfo
;
140 QualType DestType
= GetTypeFromParser(Ty
, &DestTInfo
);
142 DestTInfo
= Context
.getTrivialTypeSourceInfo(DestType
, SourceLocation());
144 return BuildCXXNamedCast(OpLoc
, Kind
, DestTInfo
, move(E
),
145 SourceRange(LAngleBracketLoc
, RAngleBracketLoc
),
146 SourceRange(LParenLoc
, RParenLoc
));
150 Sema::BuildCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
151 TypeSourceInfo
*DestTInfo
, Expr
*Ex
,
152 SourceRange AngleBrackets
, SourceRange Parens
) {
153 QualType DestType
= DestTInfo
->getType();
155 SourceRange
OpRange(OpLoc
, Parens
.getEnd());
156 SourceRange DestRange
= AngleBrackets
;
158 // If the type is dependent, we won't do the semantic analysis now.
159 // FIXME: should we check this in a more fine-grained manner?
160 bool TypeDependent
= DestType
->isDependentType() || Ex
->isTypeDependent();
162 if (Ex
->isBoundMemberFunction(Context
))
163 Diag(Ex
->getLocStart(), diag::err_invalid_use_of_bound_member_func
)
164 << Ex
->getSourceRange();
166 ExprValueKind VK
= VK_RValue
;
168 VK
= Expr::getValueKindForType(DestType
);
171 default: llvm_unreachable("Unknown C++ cast!");
173 case tok::kw_const_cast
:
175 CheckConstCast(*this, Ex
, DestType
, VK
, OpRange
, DestRange
);
176 return Owned(CXXConstCastExpr::Create(Context
,
177 DestType
.getNonLValueExprType(Context
),
178 VK
, Ex
, DestTInfo
, OpLoc
,
181 case tok::kw_dynamic_cast
: {
182 CastKind Kind
= CK_Dependent
;
183 CXXCastPath BasePath
;
185 CheckDynamicCast(*this, Ex
, DestType
, VK
, OpRange
, DestRange
,
187 return Owned(CXXDynamicCastExpr::Create(Context
,
188 DestType
.getNonLValueExprType(Context
),
189 VK
, Kind
, Ex
, &BasePath
, DestTInfo
,
190 OpLoc
, Parens
.getEnd()));
192 case tok::kw_reinterpret_cast
: {
193 CastKind Kind
= CK_Dependent
;
195 CheckReinterpretCast(*this, Ex
, DestType
, VK
, OpRange
, DestRange
, Kind
);
196 return Owned(CXXReinterpretCastExpr::Create(Context
,
197 DestType
.getNonLValueExprType(Context
),
199 DestTInfo
, OpLoc
, Parens
.getEnd()));
201 case tok::kw_static_cast
: {
202 CastKind Kind
= CK_Dependent
;
203 CXXCastPath BasePath
;
205 CheckStaticCast(*this, Ex
, DestType
, VK
, OpRange
, Kind
, BasePath
);
207 return Owned(CXXStaticCastExpr::Create(Context
,
208 DestType
.getNonLValueExprType(Context
),
209 VK
, Kind
, Ex
, &BasePath
,
210 DestTInfo
, OpLoc
, Parens
.getEnd()));
217 /// Try to diagnose a failed overloaded cast. Returns true if
218 /// diagnostics were emitted.
219 static bool tryDiagnoseOverloadedCast(Sema
&S
, CastType CT
,
220 SourceRange range
, Expr
*src
,
223 // These cast kinds don't consider user-defined conversions.
236 QualType srcType
= src
->getType();
237 if (!destType
->isRecordType() && !srcType
->isRecordType())
240 InitializedEntity entity
= InitializedEntity::InitializeTemporary(destType
);
241 InitializationKind initKind
242 = InitializationKind::CreateCast(/*type range?*/ range
,
243 (CT
== CT_CStyle
|| CT
== CT_Functional
));
244 InitializationSequence
sequence(S
, entity
, initKind
, &src
, 1);
246 assert(sequence
.getKind() == InitializationSequence::FailedSequence
&&
247 "initialization succeeded on second try?");
248 switch (sequence
.getFailureKind()) {
249 default: return false;
251 case InitializationSequence::FK_ConstructorOverloadFailed
:
252 case InitializationSequence::FK_UserConversionOverloadFailed
:
256 OverloadCandidateSet
&candidates
= sequence
.getFailedCandidateSet();
259 OverloadCandidateDisplayKind howManyCandidates
= OCD_AllCandidates
;
261 switch (sequence
.getFailedOverloadResult()) {
262 case OR_Success
: llvm_unreachable("successful failed overload");
264 case OR_No_Viable_Function
:
265 if (candidates
.empty())
266 msg
= diag::err_ovl_no_conversion_in_cast
;
268 msg
= diag::err_ovl_no_viable_conversion_in_cast
;
269 howManyCandidates
= OCD_AllCandidates
;
273 msg
= diag::err_ovl_ambiguous_conversion_in_cast
;
274 howManyCandidates
= OCD_ViableCandidates
;
278 msg
= diag::err_ovl_deleted_conversion_in_cast
;
279 howManyCandidates
= OCD_ViableCandidates
;
283 S
.Diag(range
.getBegin(), msg
)
284 << CT
<< srcType
<< destType
285 << range
<< src
->getSourceRange();
287 candidates
.NoteCandidates(S
, howManyCandidates
, &src
, 1);
292 /// Diagnose a failed cast.
293 static void diagnoseBadCast(Sema
&S
, unsigned msg
, CastType castType
,
294 SourceRange opRange
, Expr
*src
, QualType destType
) {
295 if (msg
== diag::err_bad_cxx_cast_generic
&&
296 tryDiagnoseOverloadedCast(S
, castType
, opRange
, src
, destType
))
299 S
.Diag(opRange
.getBegin(), msg
) << castType
300 << src
->getType() << destType
<< opRange
<< src
->getSourceRange();
303 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
304 /// this removes one level of indirection from both types, provided that they're
305 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
306 /// this one doesn't care if the two pointers-to-member don't point into the
307 /// same class. This is because CastsAwayConstness doesn't care.
308 static bool UnwrapDissimilarPointerTypes(QualType
& T1
, QualType
& T2
) {
309 const PointerType
*T1PtrType
= T1
->getAs
<PointerType
>(),
310 *T2PtrType
= T2
->getAs
<PointerType
>();
311 if (T1PtrType
&& T2PtrType
) {
312 T1
= T1PtrType
->getPointeeType();
313 T2
= T2PtrType
->getPointeeType();
316 const ObjCObjectPointerType
*T1ObjCPtrType
=
317 T1
->getAs
<ObjCObjectPointerType
>(),
319 T2
->getAs
<ObjCObjectPointerType
>();
322 T1
= T1ObjCPtrType
->getPointeeType();
323 T2
= T2ObjCPtrType
->getPointeeType();
326 else if (T2PtrType
) {
327 T1
= T1ObjCPtrType
->getPointeeType();
328 T2
= T2PtrType
->getPointeeType();
332 else if (T2ObjCPtrType
) {
334 T2
= T2ObjCPtrType
->getPointeeType();
335 T1
= T1PtrType
->getPointeeType();
340 const MemberPointerType
*T1MPType
= T1
->getAs
<MemberPointerType
>(),
341 *T2MPType
= T2
->getAs
<MemberPointerType
>();
342 if (T1MPType
&& T2MPType
) {
343 T1
= T1MPType
->getPointeeType();
344 T2
= T2MPType
->getPointeeType();
348 const BlockPointerType
*T1BPType
= T1
->getAs
<BlockPointerType
>(),
349 *T2BPType
= T2
->getAs
<BlockPointerType
>();
350 if (T1BPType
&& T2BPType
) {
351 T1
= T1BPType
->getPointeeType();
352 T2
= T2BPType
->getPointeeType();
359 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
360 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
361 /// the cast checkers. Both arguments must denote pointer (possibly to member)
364 CastsAwayConstness(Sema
&Self
, QualType SrcType
, QualType DestType
) {
365 // Casting away constness is defined in C++ 5.2.11p8 with reference to
366 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
367 // the rules are non-trivial. So first we construct Tcv *...cv* as described
369 assert((SrcType
->isAnyPointerType() || SrcType
->isMemberPointerType() ||
370 SrcType
->isBlockPointerType()) &&
371 "Source type is not pointer or pointer to member.");
372 assert((DestType
->isAnyPointerType() || DestType
->isMemberPointerType() ||
373 DestType
->isBlockPointerType()) &&
374 "Destination type is not pointer or pointer to member.");
376 QualType UnwrappedSrcType
= Self
.Context
.getCanonicalType(SrcType
),
377 UnwrappedDestType
= Self
.Context
.getCanonicalType(DestType
);
378 llvm::SmallVector
<Qualifiers
, 8> cv1
, cv2
;
380 // Find the qualifications.
381 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType
, UnwrappedDestType
)) {
383 Self
.Context
.getUnqualifiedArrayType(UnwrappedSrcType
, SrcQuals
);
384 cv1
.push_back(SrcQuals
);
386 Qualifiers DestQuals
;
387 Self
.Context
.getUnqualifiedArrayType(UnwrappedDestType
, DestQuals
);
388 cv2
.push_back(DestQuals
);
393 // Construct void pointers with those qualifiers (in reverse order of
394 // unwrapping, of course).
395 QualType SrcConstruct
= Self
.Context
.VoidTy
;
396 QualType DestConstruct
= Self
.Context
.VoidTy
;
397 ASTContext
&Context
= Self
.Context
;
398 for (llvm::SmallVector
<Qualifiers
, 8>::reverse_iterator i1
= cv1
.rbegin(),
400 i1
!= cv1
.rend(); ++i1
, ++i2
) {
402 = Context
.getPointerType(Context
.getQualifiedType(SrcConstruct
, *i1
));
404 = Context
.getPointerType(Context
.getQualifiedType(DestConstruct
, *i2
));
407 // Test if they're compatible.
408 return SrcConstruct
!= DestConstruct
&&
409 !Self
.IsQualificationConversion(SrcConstruct
, DestConstruct
, false);
412 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
413 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
414 /// checked downcasts in class hierarchies.
416 CheckDynamicCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
417 ExprValueKind
&VK
, const SourceRange
&OpRange
,
418 const SourceRange
&DestRange
, CastKind
&Kind
,
419 CXXCastPath
&BasePath
) {
420 QualType OrigDestType
= DestType
, OrigSrcType
= SrcExpr
->getType();
421 DestType
= Self
.Context
.getCanonicalType(DestType
);
423 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
424 // or "pointer to cv void".
426 QualType DestPointee
;
427 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
428 const ReferenceType
*DestReference
= 0;
430 DestPointee
= DestPointer
->getPointeeType();
431 } else if ((DestReference
= DestType
->getAs
<ReferenceType
>())) {
432 DestPointee
= DestReference
->getPointeeType();
433 VK
= isa
<LValueReferenceType
>(DestReference
) ? VK_LValue
434 : isa
<RValueReferenceType
>(DestReference
) ? VK_XValue
437 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr
)
438 << OrigDestType
<< DestRange
;
442 const RecordType
*DestRecord
= DestPointee
->getAs
<RecordType
>();
443 if (DestPointee
->isVoidType()) {
444 assert(DestPointer
&& "Reference to void is not possible");
445 } else if (DestRecord
) {
446 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestPointee
,
447 Self
.PDiag(diag::err_bad_dynamic_cast_incomplete
)
451 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
452 << DestPointee
.getUnqualifiedType() << DestRange
;
456 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
457 // complete class type, [...]. If T is an lvalue reference type, v shall be
458 // an lvalue of a complete class type, [...]. If T is an rvalue reference
459 // type, v shall be an expression having a complete class type, [...]
460 QualType SrcType
= Self
.Context
.getCanonicalType(OrigSrcType
);
463 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
464 SrcPointee
= SrcPointer
->getPointeeType();
466 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ptr
)
467 << OrigSrcType
<< SrcExpr
->getSourceRange();
470 } else if (DestReference
->isLValueReferenceType()) {
471 if (!SrcExpr
->isLValue()) {
472 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_rvalue
)
473 << CT_Dynamic
<< OrigSrcType
<< OrigDestType
<< OpRange
;
475 SrcPointee
= SrcType
;
477 SrcPointee
= SrcType
;
480 const RecordType
*SrcRecord
= SrcPointee
->getAs
<RecordType
>();
482 if (Self
.RequireCompleteType(OpRange
.getBegin(), SrcPointee
,
483 Self
.PDiag(diag::err_bad_dynamic_cast_incomplete
)
484 << SrcExpr
->getSourceRange()))
487 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
488 << SrcPointee
.getUnqualifiedType() << SrcExpr
->getSourceRange();
492 assert((DestPointer
|| DestReference
) &&
493 "Bad destination non-ptr/ref slipped through.");
494 assert((DestRecord
|| DestPointee
->isVoidType()) &&
495 "Bad destination pointee slipped through.");
496 assert(SrcRecord
&& "Bad source pointee slipped through.");
498 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
499 if (!DestPointee
.isAtLeastAsQualifiedAs(SrcPointee
)) {
500 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_const_away
)
501 << CT_Dynamic
<< OrigSrcType
<< OrigDestType
<< OpRange
;
505 // C++ 5.2.7p3: If the type of v is the same as the required result type,
507 if (DestRecord
== SrcRecord
) {
513 // Upcasts are resolved statically.
514 if (DestRecord
&& Self
.IsDerivedFrom(SrcPointee
, DestPointee
)) {
515 if (Self
.CheckDerivedToBaseConversion(SrcPointee
, DestPointee
,
516 OpRange
.getBegin(), OpRange
,
520 Kind
= CK_DerivedToBase
;
522 // If we are casting to or through a virtual base class, we need a
524 if (Self
.BasePathInvolvesVirtualBase(BasePath
))
525 Self
.MarkVTableUsed(OpRange
.getBegin(),
526 cast
<CXXRecordDecl
>(SrcRecord
->getDecl()));
530 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
531 const RecordDecl
*SrcDecl
= SrcRecord
->getDecl()->getDefinition();
532 assert(SrcDecl
&& "Definition missing");
533 if (!cast
<CXXRecordDecl
>(SrcDecl
)->isPolymorphic()) {
534 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic
)
535 << SrcPointee
.getUnqualifiedType() << SrcExpr
->getSourceRange();
537 Self
.MarkVTableUsed(OpRange
.getBegin(),
538 cast
<CXXRecordDecl
>(SrcRecord
->getDecl()));
540 // Done. Everything else is run-time checks.
544 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
545 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
547 /// const char *str = "literal";
548 /// legacy_function(const_cast\<char*\>(str));
550 CheckConstCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
, ExprValueKind
&VK
,
551 const SourceRange
&OpRange
, const SourceRange
&DestRange
) {
552 VK
= Expr::getValueKindForType(DestType
);
554 Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
);
556 unsigned msg
= diag::err_bad_cxx_cast_generic
;
557 if (TryConstCast(Self
, SrcExpr
, DestType
, /*CStyle*/false, msg
) != TC_Success
559 Self
.Diag(OpRange
.getBegin(), msg
) << CT_Const
560 << SrcExpr
->getType() << DestType
<< OpRange
;
563 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
565 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
567 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
569 CheckReinterpretCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
570 ExprValueKind
&VK
, const SourceRange
&OpRange
,
571 const SourceRange
&DestRange
, CastKind
&Kind
) {
572 VK
= Expr::getValueKindForType(DestType
);
574 Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
);
576 unsigned msg
= diag::err_bad_cxx_cast_generic
;
577 if (TryReinterpretCast(Self
, SrcExpr
, DestType
, /*CStyle*/false, OpRange
,
579 != TC_Success
&& msg
!= 0)
581 if (SrcExpr
->getType() == Self
.Context
.OverloadTy
) {
582 //FIXME: &f<int>; is overloaded and resolvable
583 Self
.Diag(OpRange
.getBegin(), diag::err_bad_reinterpret_cast_overload
)
584 << OverloadExpr::find(SrcExpr
).Expression
->getName()
585 << DestType
<< OpRange
;
586 NoteAllOverloadCandidates(SrcExpr
, Self
);
589 diagnoseBadCast(Self
, msg
, CT_Reinterpret
, OpRange
, SrcExpr
, DestType
);
595 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
596 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
597 /// implicit conversions explicit and getting rid of data loss warnings.
599 CheckStaticCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
600 ExprValueKind
&VK
, const SourceRange
&OpRange
,
601 CastKind
&Kind
, CXXCastPath
&BasePath
) {
602 // This test is outside everything else because it's the only case where
603 // a non-lvalue-reference target type does not lead to decay.
604 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
605 if (DestType
->isVoidType()) {
606 Self
.IgnoredValueConversions(SrcExpr
);
611 VK
= Expr::getValueKindForType(DestType
);
612 if (VK
== VK_RValue
&& !DestType
->isRecordType())
613 Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
);
615 unsigned msg
= diag::err_bad_cxx_cast_generic
;
616 if (TryStaticCast(Self
, SrcExpr
, DestType
, /*CStyle*/false, OpRange
, msg
,
617 Kind
, BasePath
) != TC_Success
&& msg
!= 0)
619 if (SrcExpr
->getType() == Self
.Context
.OverloadTy
) {
620 OverloadExpr
* oe
= OverloadExpr::find(SrcExpr
).Expression
;
621 Self
.Diag(OpRange
.getBegin(), diag::err_bad_static_cast_overload
)
622 << oe
->getName() << DestType
<< OpRange
<< oe
->getQualifierRange();
623 NoteAllOverloadCandidates(SrcExpr
, Self
);
625 diagnoseBadCast(Self
, msg
, CT_Static
, OpRange
, SrcExpr
, DestType
);
628 else if (Kind
== CK_BitCast
)
629 Self
.CheckCastAlign(SrcExpr
, DestType
, OpRange
);
632 /// TryStaticCast - Check if a static cast can be performed, and do so if
633 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
634 /// and casting away constness.
635 static TryCastResult
TryStaticCast(Sema
&Self
, Expr
*&SrcExpr
,
636 QualType DestType
, bool CStyle
,
637 const SourceRange
&OpRange
, unsigned &msg
,
639 CXXCastPath
&BasePath
) {
640 // The order the tests is not entirely arbitrary. There is one conversion
641 // that can be handled in two different ways. Given:
643 // struct B : public A {
647 // the cast static_cast<const B&>(a) could be seen as either a static
648 // reference downcast, or an explicit invocation of the user-defined
649 // conversion using B's conversion constructor.
650 // DR 427 specifies that the downcast is to be applied here.
652 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
653 // Done outside this function.
657 // C++ 5.2.9p5, reference downcast.
658 // See the function for details.
659 // DR 427 specifies that this is to be applied before paragraph 2.
660 tcr
= TryStaticReferenceDowncast(Self
, SrcExpr
, DestType
, CStyle
, OpRange
,
661 msg
, Kind
, BasePath
);
662 if (tcr
!= TC_NotApplicable
)
665 // C++0x [expr.static.cast]p3:
666 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
667 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
668 tcr
= TryLValueToRValueCast(Self
, SrcExpr
, DestType
, CStyle
, Kind
, BasePath
,
670 if (tcr
!= TC_NotApplicable
)
673 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
674 // [...] if the declaration "T t(e);" is well-formed, [...].
675 tcr
= TryStaticImplicitCast(Self
, SrcExpr
, DestType
, CStyle
, OpRange
, msg
,
677 if (tcr
!= TC_NotApplicable
)
680 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
681 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
682 // conversions, subject to further restrictions.
683 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
684 // of qualification conversions impossible.
685 // In the CStyle case, the earlier attempt to const_cast should have taken
686 // care of reverse qualification conversions.
688 QualType SrcType
= Self
.Context
.getCanonicalType(SrcExpr
->getType());
690 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
691 // converted to an integral type.
692 if (Self
.getLangOptions().CPlusPlus0x
&& SrcType
->isEnumeralType()) {
693 assert(SrcType
->getAs
<EnumType
>()->getDecl()->isScoped());
694 if (DestType
->isBooleanType()) {
695 Kind
= CK_IntegralToBoolean
;
697 } else if (DestType
->isIntegralType(Self
.Context
)) {
698 Kind
= CK_IntegralCast
;
703 // Reverse integral promotion/conversion. All such conversions are themselves
704 // again integral promotions or conversions and are thus already handled by
705 // p2 (TryDirectInitialization above).
706 // (Note: any data loss warnings should be suppressed.)
707 // The exception is the reverse of enum->integer, i.e. integer->enum (and
708 // enum->enum). See also C++ 5.2.9p7.
709 // The same goes for reverse floating point promotion/conversion and
710 // floating-integral conversions. Again, only floating->enum is relevant.
711 if (DestType
->isEnumeralType()) {
712 if (SrcType
->isComplexType() || SrcType
->isVectorType()) {
713 // Fall through - these cannot be converted.
714 } else if (SrcType
->isArithmeticType() || SrcType
->isEnumeralType()) {
715 Kind
= CK_IntegralCast
;
720 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
721 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
722 tcr
= TryStaticPointerDowncast(Self
, SrcType
, DestType
, CStyle
, OpRange
, msg
,
724 if (tcr
!= TC_NotApplicable
)
727 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
728 // conversion. C++ 5.2.9p9 has additional information.
729 // DR54's access restrictions apply here also.
730 tcr
= TryStaticMemberPointerUpcast(Self
, SrcExpr
, SrcType
, DestType
, CStyle
,
731 OpRange
, msg
, Kind
, BasePath
);
732 if (tcr
!= TC_NotApplicable
)
735 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
736 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
737 // just the usual constness stuff.
738 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
739 QualType SrcPointee
= SrcPointer
->getPointeeType();
740 if (SrcPointee
->isVoidType()) {
741 if (const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>()) {
742 QualType DestPointee
= DestPointer
->getPointeeType();
743 if (DestPointee
->isIncompleteOrObjectType()) {
744 // This is definitely the intended conversion, but it might fail due
745 // to a const violation.
746 if (!CStyle
&& !DestPointee
.isAtLeastAsQualifiedAs(SrcPointee
)) {
747 msg
= diag::err_bad_cxx_cast_const_away
;
754 else if (DestType
->isObjCObjectPointerType()) {
755 // allow both c-style cast and static_cast of objective-c pointers as
756 // they are pervasive.
757 Kind
= CK_AnyPointerToObjCPointerCast
;
760 else if (CStyle
&& DestType
->isBlockPointerType()) {
761 // allow c-style cast of void * to block pointers.
762 Kind
= CK_AnyPointerToBlockPointerCast
;
767 // Allow arbitray objective-c pointer conversion with static casts.
768 if (SrcType
->isObjCObjectPointerType() &&
769 DestType
->isObjCObjectPointerType()) {
774 // We tried everything. Everything! Nothing works! :-(
775 return TC_NotApplicable
;
778 /// Tests whether a conversion according to N2844 is valid.
780 TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
781 bool CStyle
, CastKind
&Kind
, CXXCastPath
&BasePath
,
783 // C++0x [expr.static.cast]p3:
784 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
785 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
786 const RValueReferenceType
*R
= DestType
->getAs
<RValueReferenceType
>();
788 return TC_NotApplicable
;
790 if (!SrcExpr
->isGLValue())
791 return TC_NotApplicable
;
793 // Because we try the reference downcast before this function, from now on
794 // this is the only cast possibility, so we issue an error if we fail now.
795 // FIXME: Should allow casting away constness if CStyle.
798 QualType FromType
= SrcExpr
->getType();
799 QualType ToType
= R
->getPointeeType();
801 FromType
= FromType
.getUnqualifiedType();
802 ToType
= ToType
.getUnqualifiedType();
805 if (Self
.CompareReferenceRelationship(SrcExpr
->getLocStart(),
807 DerivedToBase
, ObjCConversion
) <
808 Sema::Ref_Compatible_With_Added_Qualification
) {
809 msg
= diag::err_bad_lvalue_to_rvalue_cast
;
814 Kind
= CK_DerivedToBase
;
815 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
816 /*DetectVirtual=*/true);
817 if (!Self
.IsDerivedFrom(SrcExpr
->getType(), R
->getPointeeType(), Paths
))
818 return TC_NotApplicable
;
820 Self
.BuildBasePathArray(Paths
, BasePath
);
827 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
829 TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
830 bool CStyle
, const SourceRange
&OpRange
,
831 unsigned &msg
, CastKind
&Kind
,
832 CXXCastPath
&BasePath
) {
833 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
834 // cast to type "reference to cv2 D", where D is a class derived from B,
835 // if a valid standard conversion from "pointer to D" to "pointer to B"
836 // exists, cv2 >= cv1, and B is not a virtual base class of D.
837 // In addition, DR54 clarifies that the base must be accessible in the
838 // current context. Although the wording of DR54 only applies to the pointer
839 // variant of this rule, the intent is clearly for it to apply to the this
840 // conversion as well.
842 const ReferenceType
*DestReference
= DestType
->getAs
<ReferenceType
>();
843 if (!DestReference
) {
844 return TC_NotApplicable
;
846 bool RValueRef
= DestReference
->isRValueReferenceType();
847 if (!RValueRef
&& !SrcExpr
->isLValue()) {
848 // We know the left side is an lvalue reference, so we can suggest a reason.
849 msg
= diag::err_bad_cxx_cast_rvalue
;
850 return TC_NotApplicable
;
853 QualType DestPointee
= DestReference
->getPointeeType();
855 return TryStaticDowncast(Self
,
856 Self
.Context
.getCanonicalType(SrcExpr
->getType()),
857 Self
.Context
.getCanonicalType(DestPointee
), CStyle
,
858 OpRange
, SrcExpr
->getType(), DestType
, msg
, Kind
,
862 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
864 TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
, QualType DestType
,
865 bool CStyle
, const SourceRange
&OpRange
,
866 unsigned &msg
, CastKind
&Kind
,
867 CXXCastPath
&BasePath
) {
868 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
869 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
870 // is a class derived from B, if a valid standard conversion from "pointer
871 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
873 // In addition, DR54 clarifies that the base must be accessible in the
876 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
878 return TC_NotApplicable
;
881 const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>();
883 msg
= diag::err_bad_static_cast_pointer_nonpointer
;
884 return TC_NotApplicable
;
887 return TryStaticDowncast(Self
,
888 Self
.Context
.getCanonicalType(SrcPointer
->getPointeeType()),
889 Self
.Context
.getCanonicalType(DestPointer
->getPointeeType()),
890 CStyle
, OpRange
, SrcType
, DestType
, msg
, Kind
,
894 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
895 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
896 /// DestType is possible and allowed.
898 TryStaticDowncast(Sema
&Self
, CanQualType SrcType
, CanQualType DestType
,
899 bool CStyle
, const SourceRange
&OpRange
, QualType OrigSrcType
,
900 QualType OrigDestType
, unsigned &msg
,
901 CastKind
&Kind
, CXXCastPath
&BasePath
) {
902 // We can only work with complete types. But don't complain if it doesn't work
903 if (Self
.RequireCompleteType(OpRange
.getBegin(), SrcType
, Self
.PDiag(0)) ||
904 Self
.RequireCompleteType(OpRange
.getBegin(), DestType
, Self
.PDiag(0)))
905 return TC_NotApplicable
;
907 // Downcast can only happen in class hierarchies, so we need classes.
908 if (!DestType
->getAs
<RecordType
>() || !SrcType
->getAs
<RecordType
>()) {
909 return TC_NotApplicable
;
912 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
913 /*DetectVirtual=*/true);
914 if (!Self
.IsDerivedFrom(DestType
, SrcType
, Paths
)) {
915 return TC_NotApplicable
;
918 // Target type does derive from source type. Now we're serious. If an error
919 // appears now, it's not ignored.
920 // This may not be entirely in line with the standard. Take for example:
922 // struct B : virtual A {
928 // (void)static_cast<const B&>(*((A*)0));
930 // As far as the standard is concerned, p5 does not apply (A is virtual), so
931 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
932 // However, both GCC and Comeau reject this example, and accepting it would
933 // mean more complex code if we're to preserve the nice error message.
934 // FIXME: Being 100% compliant here would be nice to have.
936 // Must preserve cv, as always, unless we're in C-style mode.
937 if (!CStyle
&& !DestType
.isAtLeastAsQualifiedAs(SrcType
)) {
938 msg
= diag::err_bad_cxx_cast_const_away
;
942 if (Paths
.isAmbiguous(SrcType
.getUnqualifiedType())) {
943 // This code is analoguous to that in CheckDerivedToBaseConversion, except
944 // that it builds the paths in reverse order.
945 // To sum up: record all paths to the base and build a nice string from
946 // them. Use it to spice up the error message.
947 if (!Paths
.isRecordingPaths()) {
949 Paths
.setRecordingPaths(true);
950 Self
.IsDerivedFrom(DestType
, SrcType
, Paths
);
952 std::string PathDisplayStr
;
953 std::set
<unsigned> DisplayedPaths
;
954 for (CXXBasePaths::paths_iterator PI
= Paths
.begin(), PE
= Paths
.end();
956 if (DisplayedPaths
.insert(PI
->back().SubobjectNumber
).second
) {
957 // We haven't displayed a path to this particular base
958 // class subobject yet.
959 PathDisplayStr
+= "\n ";
960 for (CXXBasePath::const_reverse_iterator EI
= PI
->rbegin(),
963 PathDisplayStr
+= EI
->Base
->getType().getAsString() + " -> ";
964 PathDisplayStr
+= QualType(DestType
).getAsString();
968 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_base_to_derived_cast
)
969 << QualType(SrcType
).getUnqualifiedType()
970 << QualType(DestType
).getUnqualifiedType()
971 << PathDisplayStr
<< OpRange
;
976 if (Paths
.getDetectedVirtual() != 0) {
977 QualType
VirtualBase(Paths
.getDetectedVirtual(), 0);
978 Self
.Diag(OpRange
.getBegin(), diag::err_static_downcast_via_virtual
)
979 << OrigSrcType
<< OrigDestType
<< VirtualBase
<< OpRange
;
985 switch (Self
.CheckBaseClassAccess(OpRange
.getBegin(),
988 diag::err_downcast_from_inaccessible_base
)) {
989 case Sema::AR_accessible
:
990 case Sema::AR_delayed
: // be optimistic
991 case Sema::AR_dependent
: // be optimistic
994 case Sema::AR_inaccessible
:
1000 Self
.BuildBasePathArray(Paths
, BasePath
);
1001 Kind
= CK_BaseToDerived
;
1005 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1006 /// C++ 5.2.9p9 is valid:
1008 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1009 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1010 /// where B is a base class of D [...].
1013 TryStaticMemberPointerUpcast(Sema
&Self
, Expr
*&SrcExpr
, QualType SrcType
,
1014 QualType DestType
, bool CStyle
,
1015 const SourceRange
&OpRange
,
1016 unsigned &msg
, CastKind
&Kind
,
1017 CXXCastPath
&BasePath
) {
1018 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>();
1020 return TC_NotApplicable
;
1022 bool WasOverloadedFunction
= false;
1023 DeclAccessPair FoundOverload
;
1024 if (SrcExpr
->getType() == Self
.Context
.OverloadTy
) {
1025 if (FunctionDecl
*Fn
1026 = Self
.ResolveAddressOfOverloadedFunction(SrcExpr
, DestType
, false,
1028 CXXMethodDecl
*M
= cast
<CXXMethodDecl
>(Fn
);
1029 SrcType
= Self
.Context
.getMemberPointerType(Fn
->getType(),
1030 Self
.Context
.getTypeDeclType(M
->getParent()).getTypePtr());
1031 WasOverloadedFunction
= true;
1035 const MemberPointerType
*SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
1037 msg
= diag::err_bad_static_cast_member_pointer_nonmp
;
1038 return TC_NotApplicable
;
1041 // T == T, modulo cv
1042 if (!Self
.Context
.hasSameUnqualifiedType(SrcMemPtr
->getPointeeType(),
1043 DestMemPtr
->getPointeeType()))
1044 return TC_NotApplicable
;
1047 QualType
SrcClass(SrcMemPtr
->getClass(), 0);
1048 QualType
DestClass(DestMemPtr
->getClass(), 0);
1049 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1050 /*DetectVirtual=*/true);
1051 if (!Self
.IsDerivedFrom(SrcClass
, DestClass
, Paths
)) {
1052 return TC_NotApplicable
;
1055 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1056 if (Paths
.isAmbiguous(Self
.Context
.getCanonicalType(DestClass
))) {
1058 Paths
.setRecordingPaths(true);
1059 bool StillOkay
= Self
.IsDerivedFrom(SrcClass
, DestClass
, Paths
);
1062 std::string PathDisplayStr
= Self
.getAmbiguousPathsDisplayString(Paths
);
1063 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_memptr_conv
)
1064 << 1 << SrcClass
<< DestClass
<< PathDisplayStr
<< OpRange
;
1069 if (const RecordType
*VBase
= Paths
.getDetectedVirtual()) {
1070 Self
.Diag(OpRange
.getBegin(), diag::err_memptr_conv_via_virtual
)
1071 << SrcClass
<< DestClass
<< QualType(VBase
, 0) << OpRange
;
1077 switch (Self
.CheckBaseClassAccess(OpRange
.getBegin(),
1078 DestClass
, SrcClass
,
1080 diag::err_upcast_to_inaccessible_base
)) {
1081 case Sema::AR_accessible
:
1082 case Sema::AR_delayed
:
1083 case Sema::AR_dependent
:
1084 // Optimistically assume that the delayed and dependent cases
1088 case Sema::AR_inaccessible
:
1094 if (WasOverloadedFunction
) {
1095 // Resolve the address of the overloaded function again, this time
1096 // allowing complaints if something goes wrong.
1097 FunctionDecl
*Fn
= Self
.ResolveAddressOfOverloadedFunction(SrcExpr
,
1106 SrcExpr
= Self
.FixOverloadedFunctionReference(SrcExpr
, FoundOverload
, Fn
);
1113 Self
.BuildBasePathArray(Paths
, BasePath
);
1114 Kind
= CK_DerivedToBaseMemberPointer
;
1118 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1121 /// An expression e can be explicitly converted to a type T using a
1122 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1124 TryStaticImplicitCast(Sema
&Self
, Expr
*&SrcExpr
, QualType DestType
,
1125 bool CStyle
, const SourceRange
&OpRange
, unsigned &msg
,
1127 if (DestType
->isRecordType()) {
1128 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
1129 diag::err_bad_dynamic_cast_incomplete
)) {
1135 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(DestType
);
1136 InitializationKind InitKind
1137 = InitializationKind::CreateCast(/*FIXME:*/OpRange
, CStyle
);
1138 InitializationSequence
InitSeq(Self
, Entity
, InitKind
, &SrcExpr
, 1);
1140 // At this point of CheckStaticCast, if the destination is a reference,
1141 // or the expression is an overload expression this has to work.
1142 // There is no other way that works.
1143 // On the other hand, if we're checking a C-style cast, we've still got
1144 // the reinterpret_cast way.
1146 if (InitSeq
.getKind() == InitializationSequence::FailedSequence
&&
1147 (CStyle
|| !DestType
->isReferenceType()))
1148 return TC_NotApplicable
;
1151 = InitSeq
.Perform(Self
, Entity
, InitKind
, MultiExprArg(Self
, &SrcExpr
, 1));
1152 if (Result
.isInvalid()) {
1157 if (InitSeq
.isConstructorInitialization())
1158 Kind
= CK_ConstructorConversion
;
1162 SrcExpr
= Result
.takeAs
<Expr
>();
1166 /// TryConstCast - See if a const_cast from source to destination is allowed,
1167 /// and perform it if it is.
1168 static TryCastResult
TryConstCast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
1169 bool CStyle
, unsigned &msg
) {
1170 DestType
= Self
.Context
.getCanonicalType(DestType
);
1171 QualType SrcType
= SrcExpr
->getType();
1172 if (const ReferenceType
*DestTypeTmp
=DestType
->getAs
<ReferenceType
>()) {
1173 if (DestTypeTmp
->isLValueReferenceType() && !SrcExpr
->isLValue()) {
1174 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1175 // is C-style, static_cast might find a way, so we simply suggest a
1176 // message and tell the parent to keep searching.
1177 msg
= diag::err_bad_cxx_cast_rvalue
;
1178 return TC_NotApplicable
;
1181 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1182 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1183 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
1184 SrcType
= Self
.Context
.getPointerType(SrcType
);
1187 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1188 // the rules for const_cast are the same as those used for pointers.
1190 if (!DestType
->isPointerType() &&
1191 !DestType
->isMemberPointerType() &&
1192 !DestType
->isObjCObjectPointerType()) {
1193 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1194 // was a reference type, we converted it to a pointer above.
1195 // The status of rvalue references isn't entirely clear, but it looks like
1196 // conversion to them is simply invalid.
1197 // C++ 5.2.11p3: For two pointer types [...]
1199 msg
= diag::err_bad_const_cast_dest
;
1200 return TC_NotApplicable
;
1202 if (DestType
->isFunctionPointerType() ||
1203 DestType
->isMemberFunctionPointerType()) {
1204 // Cannot cast direct function pointers.
1205 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1206 // T is the ultimate pointee of source and target type.
1208 msg
= diag::err_bad_const_cast_dest
;
1209 return TC_NotApplicable
;
1211 SrcType
= Self
.Context
.getCanonicalType(SrcType
);
1213 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1214 // completely equal.
1215 // FIXME: const_cast should probably not be able to convert between pointers
1216 // to different address spaces.
1217 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1218 // in multi-level pointers may change, but the level count must be the same,
1219 // as must be the final pointee type.
1220 while (SrcType
!= DestType
&&
1221 Self
.Context
.UnwrapSimilarPointerTypes(SrcType
, DestType
)) {
1223 SrcType
= Self
.Context
.getUnqualifiedArrayType(SrcType
, Quals
);
1224 DestType
= Self
.Context
.getUnqualifiedArrayType(DestType
, Quals
);
1227 // Since we're dealing in canonical types, the remainder must be the same.
1228 if (SrcType
!= DestType
)
1229 return TC_NotApplicable
;
1235 static void NoteAllOverloadCandidates(Expr
* const Expr
, Sema
& sema
)
1238 assert(Expr
->getType() == sema
.Context
.OverloadTy
);
1240 OverloadExpr::FindResult Ovl
= OverloadExpr::find(Expr
);
1241 OverloadExpr
*const OvlExpr
= Ovl
.Expression
;
1243 for (UnresolvedSetIterator it
= OvlExpr
->decls_begin(),
1244 end
= OvlExpr
->decls_end(); it
!= end
; ++it
) {
1245 if ( FunctionTemplateDecl
*ftd
=
1246 dyn_cast
<FunctionTemplateDecl
>((*it
)->getUnderlyingDecl()) )
1248 sema
.NoteOverloadCandidate(ftd
->getTemplatedDecl());
1250 else if ( FunctionDecl
*f
=
1251 dyn_cast
<FunctionDecl
>((*it
)->getUnderlyingDecl()) )
1253 sema
.NoteOverloadCandidate(f
);
1259 static TryCastResult
TryReinterpretCast(Sema
&Self
, Expr
*SrcExpr
,
1260 QualType DestType
, bool CStyle
,
1261 const SourceRange
&OpRange
,
1264 bool IsLValueCast
= false;
1266 DestType
= Self
.Context
.getCanonicalType(DestType
);
1267 QualType SrcType
= SrcExpr
->getType();
1269 // Is the source an overloaded name? (i.e. &foo)
1270 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
1271 if (SrcType
== Self
.Context
.OverloadTy
)
1272 return TC_NotApplicable
;
1274 if (const ReferenceType
*DestTypeTmp
= DestType
->getAs
<ReferenceType
>()) {
1275 bool LValue
= DestTypeTmp
->isLValueReferenceType();
1276 if (LValue
&& !SrcExpr
->isLValue()) {
1277 // Cannot cast non-lvalue to lvalue reference type. See the similar
1278 // comment in const_cast.
1279 msg
= diag::err_bad_cxx_cast_rvalue
;
1280 return TC_NotApplicable
;
1283 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1284 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1285 // built-in & and * operators.
1286 // This code does this transformation for the checked types.
1287 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
1288 SrcType
= Self
.Context
.getPointerType(SrcType
);
1290 IsLValueCast
= true;
1293 // Canonicalize source for comparison.
1294 SrcType
= Self
.Context
.getCanonicalType(SrcType
);
1296 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>(),
1297 *SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
1298 if (DestMemPtr
&& SrcMemPtr
) {
1299 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1300 // can be explicitly converted to an rvalue of type "pointer to member
1301 // of Y of type T2" if T1 and T2 are both function types or both object
1303 if (DestMemPtr
->getPointeeType()->isFunctionType() !=
1304 SrcMemPtr
->getPointeeType()->isFunctionType())
1305 return TC_NotApplicable
;
1307 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1309 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1311 if (!CStyle
&& CastsAwayConstness(Self
, SrcType
, DestType
)) {
1312 msg
= diag::err_bad_cxx_cast_const_away
;
1316 // Don't allow casting between member pointers of different sizes.
1317 if (Self
.Context
.getTypeSize(DestMemPtr
) !=
1318 Self
.Context
.getTypeSize(SrcMemPtr
)) {
1319 msg
= diag::err_bad_cxx_cast_member_pointer_size
;
1323 // A valid member pointer cast.
1324 Kind
= IsLValueCast
? CK_LValueBitCast
: CK_BitCast
;
1328 // See below for the enumeral issue.
1329 if (SrcType
->isNullPtrType() && DestType
->isIntegralType(Self
.Context
)) {
1330 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1331 // type large enough to hold it. A value of std::nullptr_t can be
1332 // converted to an integral type; the conversion has the same meaning
1333 // and validity as a conversion of (void*)0 to the integral type.
1334 if (Self
.Context
.getTypeSize(SrcType
) >
1335 Self
.Context
.getTypeSize(DestType
)) {
1336 msg
= diag::err_bad_reinterpret_cast_small_int
;
1339 Kind
= CK_PointerToIntegral
;
1343 bool destIsVector
= DestType
->isVectorType();
1344 bool srcIsVector
= SrcType
->isVectorType();
1345 if (srcIsVector
|| destIsVector
) {
1346 // FIXME: Should this also apply to floating point types?
1347 bool srcIsScalar
= SrcType
->isIntegralType(Self
.Context
);
1348 bool destIsScalar
= DestType
->isIntegralType(Self
.Context
);
1350 // Check if this is a cast between a vector and something else.
1351 if (!(srcIsScalar
&& destIsVector
) && !(srcIsVector
&& destIsScalar
) &&
1352 !(srcIsVector
&& destIsVector
))
1353 return TC_NotApplicable
;
1355 // If both types have the same size, we can successfully cast.
1356 if (Self
.Context
.getTypeSize(SrcType
)
1357 == Self
.Context
.getTypeSize(DestType
)) {
1363 msg
= diag::err_bad_cxx_cast_vector_to_scalar_different_size
;
1364 else if (srcIsScalar
)
1365 msg
= diag::err_bad_cxx_cast_scalar_to_vector_different_size
;
1367 msg
= diag::err_bad_cxx_cast_vector_to_vector_different_size
;
1372 bool destIsPtr
= DestType
->isAnyPointerType() ||
1373 DestType
->isBlockPointerType();
1374 bool srcIsPtr
= SrcType
->isAnyPointerType() ||
1375 SrcType
->isBlockPointerType();
1376 if (!destIsPtr
&& !srcIsPtr
) {
1377 // Except for std::nullptr_t->integer and lvalue->reference, which are
1378 // handled above, at least one of the two arguments must be a pointer.
1379 return TC_NotApplicable
;
1382 if (SrcType
== DestType
) {
1383 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1384 // restrictions, a cast to the same type is allowed. The intent is not
1385 // entirely clear here, since all other paragraphs explicitly forbid casts
1386 // to the same type. However, the behavior of compilers is pretty consistent
1387 // on this point: allow same-type conversion if the involved types are
1388 // pointers, disallow otherwise.
1393 if (DestType
->isIntegralType(Self
.Context
)) {
1394 assert(srcIsPtr
&& "One type must be a pointer");
1395 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1396 // type large enough to hold it.
1397 if (Self
.Context
.getTypeSize(SrcType
) >
1398 Self
.Context
.getTypeSize(DestType
)) {
1399 msg
= diag::err_bad_reinterpret_cast_small_int
;
1402 Kind
= CK_PointerToIntegral
;
1406 if (SrcType
->isIntegralOrEnumerationType()) {
1407 assert(destIsPtr
&& "One type must be a pointer");
1408 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1409 // converted to a pointer.
1410 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1411 // necessarily converted to a null pointer value.]
1412 Kind
= CK_IntegralToPointer
;
1416 if (!destIsPtr
|| !srcIsPtr
) {
1417 // With the valid non-pointer conversions out of the way, we can be even
1419 return TC_NotApplicable
;
1422 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1423 // The C-style cast operator can.
1424 if (!CStyle
&& CastsAwayConstness(Self
, SrcType
, DestType
)) {
1425 msg
= diag::err_bad_cxx_cast_const_away
;
1429 // Cannot convert between block pointers and Objective-C object pointers.
1430 if ((SrcType
->isBlockPointerType() && DestType
->isObjCObjectPointerType()) ||
1431 (DestType
->isBlockPointerType() && SrcType
->isObjCObjectPointerType()))
1432 return TC_NotApplicable
;
1434 // Any pointer can be cast to an Objective-C pointer type with a C-style
1436 if (CStyle
&& DestType
->isObjCObjectPointerType()) {
1437 Kind
= CK_AnyPointerToObjCPointerCast
;
1441 // Not casting away constness, so the only remaining check is for compatible
1442 // pointer categories.
1443 Kind
= IsLValueCast
? CK_LValueBitCast
: CK_BitCast
;
1445 if (SrcType
->isFunctionPointerType()) {
1446 if (DestType
->isFunctionPointerType()) {
1447 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1448 // a pointer to a function of a different type.
1452 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1453 // an object type or vice versa is conditionally-supported.
1454 // Compilers support it in C++03 too, though, because it's necessary for
1455 // casting the return value of dlsym() and GetProcAddress().
1456 // FIXME: Conditionally-supported behavior should be configurable in the
1457 // TargetInfo or similar.
1458 if (!Self
.getLangOptions().CPlusPlus0x
)
1459 Self
.Diag(OpRange
.getBegin(), diag::ext_cast_fn_obj
) << OpRange
;
1463 if (DestType
->isFunctionPointerType()) {
1465 if (!Self
.getLangOptions().CPlusPlus0x
)
1466 Self
.Diag(OpRange
.getBegin(), diag::ext_cast_fn_obj
) << OpRange
;
1470 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1471 // a pointer to an object of different type.
1472 // Void pointers are not specified, but supported by every compiler out there.
1473 // So we finish by allowing everything that remains - it's got to be two
1479 Sema::CXXCheckCStyleCast(SourceRange R
, QualType CastTy
, ExprValueKind
&VK
,
1480 Expr
*&CastExpr
, CastKind
&Kind
,
1481 CXXCastPath
&BasePath
,
1482 bool FunctionalStyle
) {
1483 if (CastExpr
->isBoundMemberFunction(Context
))
1484 return Diag(CastExpr
->getLocStart(),
1485 diag::err_invalid_use_of_bound_member_func
)
1486 << CastExpr
->getSourceRange();
1488 // This test is outside everything else because it's the only case where
1489 // a non-lvalue-reference target type does not lead to decay.
1490 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1491 if (CastTy
->isVoidType()) {
1492 IgnoredValueConversions(CastExpr
);
1497 // Make sure we determine the value kind before we bail out for
1499 VK
= Expr::getValueKindForType(CastTy
);
1501 // If the type is dependent, we won't do any other semantic analysis now.
1502 if (CastTy
->isDependentType() || CastExpr
->isTypeDependent()) {
1503 Kind
= CK_Dependent
;
1507 if (VK
== VK_RValue
&& !CastTy
->isRecordType())
1508 DefaultFunctionArrayLvalueConversion(CastExpr
);
1510 // C++ [expr.cast]p5: The conversions performed by
1513 // - a static_cast followed by a const_cast,
1514 // - a reinterpret_cast, or
1515 // - a reinterpret_cast followed by a const_cast,
1516 // can be performed using the cast notation of explicit type conversion.
1517 // [...] If a conversion can be interpreted in more than one of the ways
1518 // listed above, the interpretation that appears first in the list is used,
1519 // even if a cast resulting from that interpretation is ill-formed.
1520 // In plain language, this means trying a const_cast ...
1521 unsigned msg
= diag::err_bad_cxx_cast_generic
;
1522 TryCastResult tcr
= TryConstCast(*this, CastExpr
, CastTy
, /*CStyle*/true,
1524 if (tcr
== TC_Success
)
1527 if (tcr
== TC_NotApplicable
) {
1528 // ... or if that is not possible, a static_cast, ignoring const, ...
1529 tcr
= TryStaticCast(*this, CastExpr
, CastTy
, /*CStyle*/true, R
, msg
, Kind
,
1531 if (tcr
== TC_NotApplicable
) {
1532 // ... and finally a reinterpret_cast, ignoring const.
1533 tcr
= TryReinterpretCast(*this, CastExpr
, CastTy
, /*CStyle*/true, R
, msg
,
1538 if (tcr
!= TC_Success
&& msg
!= 0) {
1539 if (CastExpr
->getType() == Context
.OverloadTy
) {
1540 DeclAccessPair Found
;
1541 FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(CastExpr
,
1543 /* Complain */ true,
1545 assert(!Fn
&& "cast failed but able to resolve overload expression!!");
1549 diagnoseBadCast(*this, msg
, (FunctionalStyle
? CT_Functional
: CT_CStyle
),
1550 R
, CastExpr
, CastTy
);
1553 else if (Kind
== CK_BitCast
)
1554 CheckCastAlign(CastExpr
, CastTy
, R
);
1556 return tcr
!= TC_Success
;