1 //===--- SemaCast.cpp - Semantic Analysis for 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 cast expressions, including
11 // 1) C-style casts like '(int) x'
12 // 2) C++ functional casts like 'int(x)'
13 // 3) C++ named casts like 'static_cast<int>(x)'
15 //===----------------------------------------------------------------------===//
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "llvm/ADT/SmallVector.h"
26 using namespace clang;
31 TC_NotApplicable, ///< The cast method is not applicable.
32 TC_Success, ///< The cast method is appropriate and successful.
33 TC_Failed ///< The cast method is appropriate, but failed. A
34 ///< diagnostic has been emitted.
38 CT_Const, ///< const_cast
39 CT_Static, ///< static_cast
40 CT_Reinterpret, ///< reinterpret_cast
41 CT_Dynamic, ///< dynamic_cast
42 CT_CStyle, ///< (Type)expr
43 CT_Functional ///< Type(expr)
47 struct CastOperation {
48 CastOperation(Sema &S, QualType destType, ExprResult src)
49 : Self(S), SrcExpr(src), DestType(destType),
50 ResultType(destType.getNonLValueExprType(S.Context)),
51 ValueKind(Expr::getValueKindForType(destType)),
54 if (const BuiltinType *placeholder =
55 src.get()->getType()->getAsPlaceholderType()) {
56 PlaceholderKind = placeholder->getKind();
58 PlaceholderKind = (BuiltinType::Kind) 0;
66 ExprValueKind ValueKind;
68 BuiltinType::Kind PlaceholderKind;
72 SourceRange DestRange;
74 // Top-level semantics-checking routines.
75 void CheckConstCast();
76 void CheckReinterpretCast();
77 void CheckStaticCast();
78 void CheckDynamicCast();
79 void CheckCXXCStyleCast(bool FunctionalCast);
80 void CheckCStyleCast();
82 // Internal convenience methods.
84 /// Try to handle the given placeholder expression kind. Return
85 /// true if the source expression has the appropriate placeholder
86 /// kind. A placeholder can only be claimed once.
87 bool claimPlaceholder(BuiltinType::Kind K) {
88 if (PlaceholderKind != K) return false;
90 PlaceholderKind = (BuiltinType::Kind) 0;
94 bool isPlaceholder() const {
95 return PlaceholderKind != 0;
97 bool isPlaceholder(BuiltinType::Kind K) const {
98 return PlaceholderKind == K;
101 void checkCastAlign() {
102 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
105 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
106 Expr *src = SrcExpr.get();
107 Self.CheckObjCARCConversion(OpRange, DestType, src, CCK);
111 /// Check for and handle non-overload placeholder expressions.
112 void checkNonOverloadPlaceholders() {
113 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
116 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
117 if (SrcExpr.isInvalid())
119 PlaceholderKind = (BuiltinType::Kind) 0;
124 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
125 bool CheckCVR, bool CheckObjCLifetime);
127 // The Try functions attempt a specific way of casting. If they succeed, they
128 // return TC_Success. If their way of casting is not appropriate for the given
129 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
130 // to emit if no other way succeeds. If their way of casting is appropriate but
131 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
132 // they emit a specialized diagnostic.
133 // All diagnostics returned by these functions must expect the same three
135 // %0: Cast Type (a value from the CastType enumeration)
137 // %2: Destination Type
138 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
139 QualType DestType, bool CStyle,
141 CXXCastPath &BasePath,
143 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
144 QualType DestType, bool CStyle,
145 const SourceRange &OpRange,
148 CXXCastPath &BasePath);
149 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
150 QualType DestType, bool CStyle,
151 const SourceRange &OpRange,
154 CXXCastPath &BasePath);
155 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
156 CanQualType DestType, bool CStyle,
157 const SourceRange &OpRange,
158 QualType OrigSrcType,
159 QualType OrigDestType, unsigned &msg,
161 CXXCastPath &BasePath);
162 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
164 QualType DestType,bool CStyle,
165 const SourceRange &OpRange,
168 CXXCastPath &BasePath);
170 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
172 Sema::CheckedConversionKind CCK,
173 const SourceRange &OpRange,
176 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
178 Sema::CheckedConversionKind CCK,
179 const SourceRange &OpRange,
182 CXXCastPath &BasePath);
183 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
184 bool CStyle, unsigned &msg);
185 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
186 QualType DestType, bool CStyle,
187 const SourceRange &OpRange,
192 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
194 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
195 SourceLocation LAngleBracketLoc, Declarator &D,
196 SourceLocation RAngleBracketLoc,
197 SourceLocation LParenLoc, Expr *E,
198 SourceLocation RParenLoc) {
200 assert(!D.isInvalidType());
202 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
203 if (D.isInvalidType())
206 if (getLangOptions().CPlusPlus) {
207 // Check that there are no default arguments (C++ only).
208 CheckExtraCXXDefaultArguments(D);
211 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
212 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
213 SourceRange(LParenLoc, RParenLoc));
217 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
218 TypeSourceInfo *DestTInfo, Expr *E,
219 SourceRange AngleBrackets, SourceRange Parens) {
220 ExprResult Ex = Owned(E);
221 QualType DestType = DestTInfo->getType();
223 // If the type is dependent, we won't do the semantic analysis now.
224 // FIXME: should we check this in a more fine-grained manner?
225 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
227 CastOperation Op(*this, DestType, E);
228 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
229 Op.DestRange = AngleBrackets;
232 default: llvm_unreachable("Unknown C++ cast!");
234 case tok::kw_const_cast:
235 if (!TypeDependent) {
237 if (Op.SrcExpr.isInvalid())
240 return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
241 Op.SrcExpr.take(), DestTInfo, OpLoc,
244 case tok::kw_dynamic_cast: {
245 if (!TypeDependent) {
246 Op.CheckDynamicCast();
247 if (Op.SrcExpr.isInvalid())
250 return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType,
251 Op.ValueKind, Op.Kind,
252 Op.SrcExpr.take(), &Op.BasePath,
253 DestTInfo, OpLoc, Parens.getEnd()));
255 case tok::kw_reinterpret_cast: {
256 if (!TypeDependent) {
257 Op.CheckReinterpretCast();
258 if (Op.SrcExpr.isInvalid())
261 return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
262 Op.ValueKind, Op.Kind,
263 Op.SrcExpr.take(), 0,
267 case tok::kw_static_cast: {
268 if (!TypeDependent) {
269 Op.CheckStaticCast();
270 if (Op.SrcExpr.isInvalid())
274 return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
275 Op.Kind, Op.SrcExpr.take(),
276 &Op.BasePath, DestTInfo, OpLoc,
284 /// Try to diagnose a failed overloaded cast. Returns true if
285 /// diagnostics were emitted.
286 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
287 SourceRange range, Expr *src,
290 // These cast kinds don't consider user-defined conversions.
303 QualType srcType = src->getType();
304 if (!destType->isRecordType() && !srcType->isRecordType())
307 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
308 InitializationKind initKind
309 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
311 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
312 : InitializationKind::CreateCast(/*type range?*/ range);
313 InitializationSequence sequence(S, entity, initKind, &src, 1);
315 assert(sequence.Failed() && "initialization succeeded on second try?");
316 switch (sequence.getFailureKind()) {
317 default: return false;
319 case InitializationSequence::FK_ConstructorOverloadFailed:
320 case InitializationSequence::FK_UserConversionOverloadFailed:
324 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
327 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
329 switch (sequence.getFailedOverloadResult()) {
330 case OR_Success: llvm_unreachable("successful failed overload");
332 case OR_No_Viable_Function:
333 if (candidates.empty())
334 msg = diag::err_ovl_no_conversion_in_cast;
336 msg = diag::err_ovl_no_viable_conversion_in_cast;
337 howManyCandidates = OCD_AllCandidates;
341 msg = diag::err_ovl_ambiguous_conversion_in_cast;
342 howManyCandidates = OCD_ViableCandidates;
346 msg = diag::err_ovl_deleted_conversion_in_cast;
347 howManyCandidates = OCD_ViableCandidates;
351 S.Diag(range.getBegin(), msg)
352 << CT << srcType << destType
353 << range << src->getSourceRange();
355 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
360 /// Diagnose a failed cast.
361 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
362 SourceRange opRange, Expr *src, QualType destType) {
363 if (src->getType() == S.Context.BoundMemberTy) {
364 (void) S.CheckPlaceholderExpr(src); // will always fail
368 if (msg == diag::err_bad_cxx_cast_generic &&
369 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
372 S.Diag(opRange.getBegin(), msg) << castType
373 << src->getType() << destType << opRange << src->getSourceRange();
376 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
377 /// this removes one level of indirection from both types, provided that they're
378 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
379 /// this one doesn't care if the two pointers-to-member don't point into the
380 /// same class. This is because CastsAwayConstness doesn't care.
381 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
382 const PointerType *T1PtrType = T1->getAs<PointerType>(),
383 *T2PtrType = T2->getAs<PointerType>();
384 if (T1PtrType && T2PtrType) {
385 T1 = T1PtrType->getPointeeType();
386 T2 = T2PtrType->getPointeeType();
389 const ObjCObjectPointerType *T1ObjCPtrType =
390 T1->getAs<ObjCObjectPointerType>(),
392 T2->getAs<ObjCObjectPointerType>();
395 T1 = T1ObjCPtrType->getPointeeType();
396 T2 = T2ObjCPtrType->getPointeeType();
399 else if (T2PtrType) {
400 T1 = T1ObjCPtrType->getPointeeType();
401 T2 = T2PtrType->getPointeeType();
405 else if (T2ObjCPtrType) {
407 T2 = T2ObjCPtrType->getPointeeType();
408 T1 = T1PtrType->getPointeeType();
413 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
414 *T2MPType = T2->getAs<MemberPointerType>();
415 if (T1MPType && T2MPType) {
416 T1 = T1MPType->getPointeeType();
417 T2 = T2MPType->getPointeeType();
421 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
422 *T2BPType = T2->getAs<BlockPointerType>();
423 if (T1BPType && T2BPType) {
424 T1 = T1BPType->getPointeeType();
425 T2 = T2BPType->getPointeeType();
432 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
433 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
434 /// the cast checkers. Both arguments must denote pointer (possibly to member)
437 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
439 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
441 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
442 bool CheckCVR, bool CheckObjCLifetime) {
443 // If the only checking we care about is for Objective-C lifetime qualifiers,
444 // and we're not in ARC mode, there's nothing to check.
445 if (!CheckCVR && CheckObjCLifetime &&
446 !Self.Context.getLangOptions().ObjCAutoRefCount)
449 // Casting away constness is defined in C++ 5.2.11p8 with reference to
450 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
451 // the rules are non-trivial. So first we construct Tcv *...cv* as described
453 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
454 SrcType->isBlockPointerType()) &&
455 "Source type is not pointer or pointer to member.");
456 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
457 DestType->isBlockPointerType()) &&
458 "Destination type is not pointer or pointer to member.");
460 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
461 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
462 SmallVector<Qualifiers, 8> cv1, cv2;
464 // Find the qualifiers. We only care about cvr-qualifiers for the
465 // purpose of this check, because other qualifiers (address spaces,
466 // Objective-C GC, etc.) are part of the type's identity.
467 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
468 // Determine the relevant qualifiers at this level.
469 Qualifiers SrcQuals, DestQuals;
470 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
471 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
473 Qualifiers RetainedSrcQuals, RetainedDestQuals;
475 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
476 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
479 if (CheckObjCLifetime &&
480 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
483 cv1.push_back(RetainedSrcQuals);
484 cv2.push_back(RetainedDestQuals);
489 // Construct void pointers with those qualifiers (in reverse order of
490 // unwrapping, of course).
491 QualType SrcConstruct = Self.Context.VoidTy;
492 QualType DestConstruct = Self.Context.VoidTy;
493 ASTContext &Context = Self.Context;
494 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
496 i1 != cv1.rend(); ++i1, ++i2) {
498 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
500 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
503 // Test if they're compatible.
504 bool ObjCLifetimeConversion;
505 return SrcConstruct != DestConstruct &&
506 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
507 ObjCLifetimeConversion);
510 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
511 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
512 /// checked downcasts in class hierarchies.
513 void CastOperation::CheckDynamicCast() {
514 QualType OrigSrcType = SrcExpr.get()->getType();
515 QualType DestType = Self.Context.getCanonicalType(this->DestType);
517 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
518 // or "pointer to cv void".
520 QualType DestPointee;
521 const PointerType *DestPointer = DestType->getAs<PointerType>();
522 const ReferenceType *DestReference = 0;
524 DestPointee = DestPointer->getPointeeType();
525 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
526 DestPointee = DestReference->getPointeeType();
528 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
529 << this->DestType << DestRange;
533 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
534 if (DestPointee->isVoidType()) {
535 assert(DestPointer && "Reference to void is not possible");
536 } else if (DestRecord) {
537 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
538 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
542 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
543 << DestPointee.getUnqualifiedType() << DestRange;
547 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
548 // complete class type, [...]. If T is an lvalue reference type, v shall be
549 // an lvalue of a complete class type, [...]. If T is an rvalue reference
550 // type, v shall be an expression having a complete class type, [...]
551 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
554 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
555 SrcPointee = SrcPointer->getPointeeType();
557 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
558 << OrigSrcType << SrcExpr.get()->getSourceRange();
561 } else if (DestReference->isLValueReferenceType()) {
562 if (!SrcExpr.get()->isLValue()) {
563 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
564 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
566 SrcPointee = SrcType;
568 SrcPointee = SrcType;
571 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
573 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
574 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
575 << SrcExpr.get()->getSourceRange()))
578 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
579 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
583 assert((DestPointer || DestReference) &&
584 "Bad destination non-ptr/ref slipped through.");
585 assert((DestRecord || DestPointee->isVoidType()) &&
586 "Bad destination pointee slipped through.");
587 assert(SrcRecord && "Bad source pointee slipped through.");
589 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
590 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
591 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
592 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
596 // C++ 5.2.7p3: If the type of v is the same as the required result type,
598 if (DestRecord == SrcRecord) {
604 // Upcasts are resolved statically.
605 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
606 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
607 OpRange.getBegin(), OpRange,
611 Kind = CK_DerivedToBase;
613 // If we are casting to or through a virtual base class, we need a
615 if (Self.BasePathInvolvesVirtualBase(BasePath))
616 Self.MarkVTableUsed(OpRange.getBegin(),
617 cast<CXXRecordDecl>(SrcRecord->getDecl()));
621 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
622 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
623 assert(SrcDecl && "Definition missing");
624 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
625 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
626 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
628 Self.MarkVTableUsed(OpRange.getBegin(),
629 cast<CXXRecordDecl>(SrcRecord->getDecl()));
631 // Done. Everything else is run-time checks.
635 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
636 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
638 /// const char *str = "literal";
639 /// legacy_function(const_cast\<char*\>(str));
640 void CastOperation::CheckConstCast() {
641 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
642 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
643 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
647 unsigned msg = diag::err_bad_cxx_cast_generic;
648 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
650 Self.Diag(OpRange.getBegin(), msg) << CT_Const
651 << SrcExpr.get()->getType() << DestType << OpRange;
654 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
656 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
658 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
659 void CastOperation::CheckReinterpretCast() {
660 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
661 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
662 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
666 unsigned msg = diag::err_bad_cxx_cast_generic;
668 TryReinterpretCast(Self, SrcExpr, DestType,
669 /*CStyle*/false, OpRange, msg, Kind);
670 if (tcr != TC_Success && msg != 0)
672 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
674 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
675 //FIXME: &f<int>; is overloaded and resolvable
676 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
677 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
678 << DestType << OpRange;
679 Self.NoteAllOverloadCandidates(SrcExpr.get());
682 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
684 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
685 checkObjCARCConversion(Sema::CCK_OtherCast);
690 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
691 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
692 /// implicit conversions explicit and getting rid of data loss warnings.
693 void CastOperation::CheckStaticCast() {
694 if (isPlaceholder()) {
695 checkNonOverloadPlaceholders();
696 if (SrcExpr.isInvalid())
700 // This test is outside everything else because it's the only case where
701 // a non-lvalue-reference target type does not lead to decay.
702 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
703 if (DestType->isVoidType()) {
706 if (claimPlaceholder(BuiltinType::Overload)) {
707 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
708 false, // Decay Function to ptr
710 OpRange, DestType, diag::err_bad_static_cast_overload);
711 if (SrcExpr.isInvalid())
715 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
719 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
720 !isPlaceholder(BuiltinType::Overload)) {
721 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
722 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
726 unsigned msg = diag::err_bad_cxx_cast_generic;
728 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
730 if (tcr != TC_Success && msg != 0) {
731 if (SrcExpr.isInvalid())
733 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
734 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
735 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
736 << oe->getName() << DestType << OpRange
737 << oe->getQualifierLoc().getSourceRange();
738 Self.NoteAllOverloadCandidates(SrcExpr.get());
740 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
742 } else if (tcr == TC_Success) {
743 if (Kind == CK_BitCast)
745 if (Self.getLangOptions().ObjCAutoRefCount)
746 checkObjCARCConversion(Sema::CCK_OtherCast);
747 } else if (Kind == CK_BitCast) {
752 /// TryStaticCast - Check if a static cast can be performed, and do so if
753 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
754 /// and casting away constness.
755 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
757 Sema::CheckedConversionKind CCK,
758 const SourceRange &OpRange, unsigned &msg,
760 CXXCastPath &BasePath) {
761 // Determine whether we have the semantics of a C-style cast.
763 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
765 // The order the tests is not entirely arbitrary. There is one conversion
766 // that can be handled in two different ways. Given:
768 // struct B : public A {
772 // the cast static_cast<const B&>(a) could be seen as either a static
773 // reference downcast, or an explicit invocation of the user-defined
774 // conversion using B's conversion constructor.
775 // DR 427 specifies that the downcast is to be applied here.
777 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
778 // Done outside this function.
782 // C++ 5.2.9p5, reference downcast.
783 // See the function for details.
784 // DR 427 specifies that this is to be applied before paragraph 2.
785 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
786 msg, Kind, BasePath);
787 if (tcr != TC_NotApplicable)
790 // C++0x [expr.static.cast]p3:
791 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
792 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
793 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
795 if (tcr != TC_NotApplicable)
798 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
799 // [...] if the declaration "T t(e);" is well-formed, [...].
800 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
802 if (SrcExpr.isInvalid())
804 if (tcr != TC_NotApplicable)
807 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
808 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
809 // conversions, subject to further restrictions.
810 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
811 // of qualification conversions impossible.
812 // In the CStyle case, the earlier attempt to const_cast should have taken
813 // care of reverse qualification conversions.
815 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
817 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
818 // converted to an integral type. [...] A value of a scoped enumeration type
819 // can also be explicitly converted to a floating-point type [...].
820 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
821 if (Enum->getDecl()->isScoped()) {
822 if (DestType->isBooleanType()) {
823 Kind = CK_IntegralToBoolean;
825 } else if (DestType->isIntegralType(Self.Context)) {
826 Kind = CK_IntegralCast;
828 } else if (DestType->isRealFloatingType()) {
829 Kind = CK_IntegralToFloating;
835 // Reverse integral promotion/conversion. All such conversions are themselves
836 // again integral promotions or conversions and are thus already handled by
837 // p2 (TryDirectInitialization above).
838 // (Note: any data loss warnings should be suppressed.)
839 // The exception is the reverse of enum->integer, i.e. integer->enum (and
840 // enum->enum). See also C++ 5.2.9p7.
841 // The same goes for reverse floating point promotion/conversion and
842 // floating-integral conversions. Again, only floating->enum is relevant.
843 if (DestType->isEnumeralType()) {
844 if (SrcType->isIntegralOrEnumerationType()) {
845 Kind = CK_IntegralCast;
847 } else if (SrcType->isRealFloatingType()) {
848 Kind = CK_FloatingToIntegral;
853 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
854 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
855 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
857 if (tcr != TC_NotApplicable)
860 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
861 // conversion. C++ 5.2.9p9 has additional information.
862 // DR54's access restrictions apply here also.
863 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
864 OpRange, msg, Kind, BasePath);
865 if (tcr != TC_NotApplicable)
868 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
869 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
870 // just the usual constness stuff.
871 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
872 QualType SrcPointee = SrcPointer->getPointeeType();
873 if (SrcPointee->isVoidType()) {
874 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
875 QualType DestPointee = DestPointer->getPointeeType();
876 if (DestPointee->isIncompleteOrObjectType()) {
877 // This is definitely the intended conversion, but it might fail due
878 // to a qualifier violation. Note that we permit Objective-C lifetime
879 // and GC qualifier mismatches here.
881 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
882 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
883 DestPointeeQuals.removeObjCGCAttr();
884 DestPointeeQuals.removeObjCLifetime();
885 SrcPointeeQuals.removeObjCGCAttr();
886 SrcPointeeQuals.removeObjCLifetime();
887 if (DestPointeeQuals != SrcPointeeQuals &&
888 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
889 msg = diag::err_bad_cxx_cast_qualifiers_away;
897 else if (DestType->isObjCObjectPointerType()) {
898 // allow both c-style cast and static_cast of objective-c pointers as
899 // they are pervasive.
900 Kind = CK_CPointerToObjCPointerCast;
903 else if (CStyle && DestType->isBlockPointerType()) {
904 // allow c-style cast of void * to block pointers.
905 Kind = CK_AnyPointerToBlockPointerCast;
910 // Allow arbitray objective-c pointer conversion with static casts.
911 if (SrcType->isObjCObjectPointerType() &&
912 DestType->isObjCObjectPointerType()) {
917 // We tried everything. Everything! Nothing works! :-(
918 return TC_NotApplicable;
921 /// Tests whether a conversion according to N2844 is valid.
923 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
924 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
926 // C++0x [expr.static.cast]p3:
927 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
928 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
929 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
931 return TC_NotApplicable;
933 if (!SrcExpr->isGLValue())
934 return TC_NotApplicable;
936 // Because we try the reference downcast before this function, from now on
937 // this is the only cast possibility, so we issue an error if we fail now.
938 // FIXME: Should allow casting away constness if CStyle.
941 bool ObjCLifetimeConversion;
942 QualType FromType = SrcExpr->getType();
943 QualType ToType = R->getPointeeType();
945 FromType = FromType.getUnqualifiedType();
946 ToType = ToType.getUnqualifiedType();
949 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
951 DerivedToBase, ObjCConversion,
952 ObjCLifetimeConversion)
953 < Sema::Ref_Compatible_With_Added_Qualification) {
954 msg = diag::err_bad_lvalue_to_rvalue_cast;
959 Kind = CK_DerivedToBase;
960 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
961 /*DetectVirtual=*/true);
962 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
963 return TC_NotApplicable;
965 Self.BuildBasePathArray(Paths, BasePath);
972 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
974 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
975 bool CStyle, const SourceRange &OpRange,
976 unsigned &msg, CastKind &Kind,
977 CXXCastPath &BasePath) {
978 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
979 // cast to type "reference to cv2 D", where D is a class derived from B,
980 // if a valid standard conversion from "pointer to D" to "pointer to B"
981 // exists, cv2 >= cv1, and B is not a virtual base class of D.
982 // In addition, DR54 clarifies that the base must be accessible in the
983 // current context. Although the wording of DR54 only applies to the pointer
984 // variant of this rule, the intent is clearly for it to apply to the this
985 // conversion as well.
987 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
988 if (!DestReference) {
989 return TC_NotApplicable;
991 bool RValueRef = DestReference->isRValueReferenceType();
992 if (!RValueRef && !SrcExpr->isLValue()) {
993 // We know the left side is an lvalue reference, so we can suggest a reason.
994 msg = diag::err_bad_cxx_cast_rvalue;
995 return TC_NotApplicable;
998 QualType DestPointee = DestReference->getPointeeType();
1000 return TryStaticDowncast(Self,
1001 Self.Context.getCanonicalType(SrcExpr->getType()),
1002 Self.Context.getCanonicalType(DestPointee), CStyle,
1003 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1007 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1009 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1010 bool CStyle, const SourceRange &OpRange,
1011 unsigned &msg, CastKind &Kind,
1012 CXXCastPath &BasePath) {
1013 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1014 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1015 // is a class derived from B, if a valid standard conversion from "pointer
1016 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1018 // In addition, DR54 clarifies that the base must be accessible in the
1021 const PointerType *DestPointer = DestType->getAs<PointerType>();
1023 return TC_NotApplicable;
1026 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1028 msg = diag::err_bad_static_cast_pointer_nonpointer;
1029 return TC_NotApplicable;
1032 return TryStaticDowncast(Self,
1033 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1034 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1035 CStyle, OpRange, SrcType, DestType, msg, Kind,
1039 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1040 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1041 /// DestType is possible and allowed.
1043 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1044 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
1045 QualType OrigDestType, unsigned &msg,
1046 CastKind &Kind, CXXCastPath &BasePath) {
1047 // We can only work with complete types. But don't complain if it doesn't work
1048 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1049 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
1050 return TC_NotApplicable;
1052 // Downcast can only happen in class hierarchies, so we need classes.
1053 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1054 return TC_NotApplicable;
1057 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1058 /*DetectVirtual=*/true);
1059 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1060 return TC_NotApplicable;
1063 // Target type does derive from source type. Now we're serious. If an error
1064 // appears now, it's not ignored.
1065 // This may not be entirely in line with the standard. Take for example:
1067 // struct B : virtual A {
1073 // (void)static_cast<const B&>(*((A*)0));
1075 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1076 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1077 // However, both GCC and Comeau reject this example, and accepting it would
1078 // mean more complex code if we're to preserve the nice error message.
1079 // FIXME: Being 100% compliant here would be nice to have.
1081 // Must preserve cv, as always, unless we're in C-style mode.
1082 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1083 msg = diag::err_bad_cxx_cast_qualifiers_away;
1087 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1088 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1089 // that it builds the paths in reverse order.
1090 // To sum up: record all paths to the base and build a nice string from
1091 // them. Use it to spice up the error message.
1092 if (!Paths.isRecordingPaths()) {
1094 Paths.setRecordingPaths(true);
1095 Self.IsDerivedFrom(DestType, SrcType, Paths);
1097 std::string PathDisplayStr;
1098 std::set<unsigned> DisplayedPaths;
1099 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
1101 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1102 // We haven't displayed a path to this particular base
1103 // class subobject yet.
1104 PathDisplayStr += "\n ";
1105 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1108 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
1109 PathDisplayStr += QualType(DestType).getAsString();
1113 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1114 << QualType(SrcType).getUnqualifiedType()
1115 << QualType(DestType).getUnqualifiedType()
1116 << PathDisplayStr << OpRange;
1121 if (Paths.getDetectedVirtual() != 0) {
1122 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1123 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1124 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1130 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1133 diag::err_downcast_from_inaccessible_base)) {
1134 case Sema::AR_accessible:
1135 case Sema::AR_delayed: // be optimistic
1136 case Sema::AR_dependent: // be optimistic
1139 case Sema::AR_inaccessible:
1145 Self.BuildBasePathArray(Paths, BasePath);
1146 Kind = CK_BaseToDerived;
1150 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1151 /// C++ 5.2.9p9 is valid:
1153 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1154 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1155 /// where B is a base class of D [...].
1158 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1159 QualType DestType, bool CStyle,
1160 const SourceRange &OpRange,
1161 unsigned &msg, CastKind &Kind,
1162 CXXCastPath &BasePath) {
1163 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1165 return TC_NotApplicable;
1167 bool WasOverloadedFunction = false;
1168 DeclAccessPair FoundOverload;
1169 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1170 if (FunctionDecl *Fn
1171 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1173 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1174 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1175 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1176 WasOverloadedFunction = true;
1180 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1182 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1183 return TC_NotApplicable;
1186 // T == T, modulo cv
1187 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1188 DestMemPtr->getPointeeType()))
1189 return TC_NotApplicable;
1192 QualType SrcClass(SrcMemPtr->getClass(), 0);
1193 QualType DestClass(DestMemPtr->getClass(), 0);
1194 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1195 /*DetectVirtual=*/true);
1196 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1197 return TC_NotApplicable;
1200 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1201 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1203 Paths.setRecordingPaths(true);
1204 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1207 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1208 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1209 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1214 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1215 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1216 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1222 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1223 DestClass, SrcClass,
1225 diag::err_upcast_to_inaccessible_base)) {
1226 case Sema::AR_accessible:
1227 case Sema::AR_delayed:
1228 case Sema::AR_dependent:
1229 // Optimistically assume that the delayed and dependent cases
1233 case Sema::AR_inaccessible:
1239 if (WasOverloadedFunction) {
1240 // Resolve the address of the overloaded function again, this time
1241 // allowing complaints if something goes wrong.
1242 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1251 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1252 if (!SrcExpr.isUsable()) {
1258 Self.BuildBasePathArray(Paths, BasePath);
1259 Kind = CK_DerivedToBaseMemberPointer;
1263 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1266 /// An expression e can be explicitly converted to a type T using a
1267 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1269 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1270 Sema::CheckedConversionKind CCK,
1271 const SourceRange &OpRange, unsigned &msg,
1273 if (DestType->isRecordType()) {
1274 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1275 diag::err_bad_dynamic_cast_incomplete)) {
1281 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1282 InitializationKind InitKind
1283 = (CCK == Sema::CCK_CStyleCast)
1284 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1285 : (CCK == Sema::CCK_FunctionalCast)
1286 ? InitializationKind::CreateFunctionalCast(OpRange)
1287 : InitializationKind::CreateCast(OpRange);
1288 Expr *SrcExprRaw = SrcExpr.get();
1289 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
1291 // At this point of CheckStaticCast, if the destination is a reference,
1292 // or the expression is an overload expression this has to work.
1293 // There is no other way that works.
1294 // On the other hand, if we're checking a C-style cast, we've still got
1295 // the reinterpret_cast way.
1297 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1298 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1299 return TC_NotApplicable;
1302 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
1303 if (Result.isInvalid()) {
1308 if (InitSeq.isConstructorInitialization())
1309 Kind = CK_ConstructorConversion;
1313 SrcExpr = move(Result);
1317 /// TryConstCast - See if a const_cast from source to destination is allowed,
1318 /// and perform it if it is.
1319 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1320 bool CStyle, unsigned &msg) {
1321 DestType = Self.Context.getCanonicalType(DestType);
1322 QualType SrcType = SrcExpr->getType();
1323 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1324 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
1325 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1326 // is C-style, static_cast might find a way, so we simply suggest a
1327 // message and tell the parent to keep searching.
1328 msg = diag::err_bad_cxx_cast_rvalue;
1329 return TC_NotApplicable;
1332 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1333 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1334 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1335 SrcType = Self.Context.getPointerType(SrcType);
1338 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1339 // the rules for const_cast are the same as those used for pointers.
1341 if (!DestType->isPointerType() &&
1342 !DestType->isMemberPointerType() &&
1343 !DestType->isObjCObjectPointerType()) {
1344 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1345 // was a reference type, we converted it to a pointer above.
1346 // The status of rvalue references isn't entirely clear, but it looks like
1347 // conversion to them is simply invalid.
1348 // C++ 5.2.11p3: For two pointer types [...]
1350 msg = diag::err_bad_const_cast_dest;
1351 return TC_NotApplicable;
1353 if (DestType->isFunctionPointerType() ||
1354 DestType->isMemberFunctionPointerType()) {
1355 // Cannot cast direct function pointers.
1356 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1357 // T is the ultimate pointee of source and target type.
1359 msg = diag::err_bad_const_cast_dest;
1360 return TC_NotApplicable;
1362 SrcType = Self.Context.getCanonicalType(SrcType);
1364 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1365 // completely equal.
1366 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1367 // in multi-level pointers may change, but the level count must be the same,
1368 // as must be the final pointee type.
1369 while (SrcType != DestType &&
1370 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1371 Qualifiers SrcQuals, DestQuals;
1372 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1373 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1375 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1376 // the other qualifiers (e.g., address spaces) are identical.
1377 SrcQuals.removeCVRQualifiers();
1378 DestQuals.removeCVRQualifiers();
1379 if (SrcQuals != DestQuals)
1380 return TC_NotApplicable;
1383 // Since we're dealing in canonical types, the remainder must be the same.
1384 if (SrcType != DestType)
1385 return TC_NotApplicable;
1390 // Checks for undefined behavior in reinterpret_cast.
1391 // The cases that is checked for is:
1392 // *reinterpret_cast<T*>(&a)
1393 // reinterpret_cast<T&>(a)
1394 // where accessing 'a' as type 'T' will result in undefined behavior.
1395 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1397 SourceRange Range) {
1398 unsigned DiagID = IsDereference ?
1399 diag::warn_pointer_indirection_from_incompatible_type :
1400 diag::warn_undefined_reinterpret_cast;
1402 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
1403 DiagnosticsEngine::Ignored) {
1407 QualType SrcTy, DestTy;
1408 if (IsDereference) {
1409 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1412 SrcTy = SrcType->getPointeeType();
1413 DestTy = DestType->getPointeeType();
1415 if (!DestType->getAs<ReferenceType>()) {
1419 DestTy = DestType->getPointeeType();
1422 // Cast is compatible if the types are the same.
1423 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1426 // or one of the types is a char or void type
1427 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1428 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1431 // or one of the types is a tag type.
1432 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1436 // FIXME: Scoped enums?
1437 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1438 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1439 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1444 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1447 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1448 QualType DestType, bool CStyle,
1449 const SourceRange &OpRange,
1452 bool IsLValueCast = false;
1454 DestType = Self.Context.getCanonicalType(DestType);
1455 QualType SrcType = SrcExpr.get()->getType();
1457 // Is the source an overloaded name? (i.e. &foo)
1458 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1459 if (SrcType == Self.Context.OverloadTy) {
1460 // ... unless foo<int> resolves to an lvalue unambiguously.
1461 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1463 ExprResult SingleFunctionExpr = SrcExpr;
1464 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1466 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1467 ) && SingleFunctionExpr.isUsable()) {
1468 SrcExpr = move(SingleFunctionExpr);
1469 SrcType = SrcExpr.get()->getType();
1471 return TC_NotApplicable;
1475 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1476 bool LValue = DestTypeTmp->isLValueReferenceType();
1477 if (LValue && !SrcExpr.get()->isLValue()) {
1478 // Cannot cast non-lvalue to lvalue reference type. See the similar
1479 // comment in const_cast.
1480 msg = diag::err_bad_cxx_cast_rvalue;
1481 return TC_NotApplicable;
1485 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1486 /*isDereference=*/false, OpRange);
1489 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1490 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1491 // built-in & and * operators.
1493 const char *inappropriate = 0;
1494 switch (SrcExpr.get()->getObjectKind()) {
1497 case OK_BitField: inappropriate = "bit-field"; break;
1498 case OK_VectorComponent: inappropriate = "vector element"; break;
1499 case OK_ObjCProperty: inappropriate = "property expression"; break;
1501 if (inappropriate) {
1502 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1503 << inappropriate << DestType
1504 << OpRange << SrcExpr.get()->getSourceRange();
1505 msg = 0; SrcExpr = ExprError();
1506 return TC_NotApplicable;
1509 // This code does this transformation for the checked types.
1510 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1511 SrcType = Self.Context.getPointerType(SrcType);
1513 IsLValueCast = true;
1516 // Canonicalize source for comparison.
1517 SrcType = Self.Context.getCanonicalType(SrcType);
1519 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1520 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1521 if (DestMemPtr && SrcMemPtr) {
1522 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1523 // can be explicitly converted to an rvalue of type "pointer to member
1524 // of Y of type T2" if T1 and T2 are both function types or both object
1526 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1527 SrcMemPtr->getPointeeType()->isFunctionType())
1528 return TC_NotApplicable;
1530 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1532 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1534 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1535 /*CheckObjCLifetime=*/CStyle)) {
1536 msg = diag::err_bad_cxx_cast_qualifiers_away;
1540 // Don't allow casting between member pointers of different sizes.
1541 if (Self.Context.getTypeSize(DestMemPtr) !=
1542 Self.Context.getTypeSize(SrcMemPtr)) {
1543 msg = diag::err_bad_cxx_cast_member_pointer_size;
1547 // A valid member pointer cast.
1548 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
1552 // See below for the enumeral issue.
1553 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1554 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1555 // type large enough to hold it. A value of std::nullptr_t can be
1556 // converted to an integral type; the conversion has the same meaning
1557 // and validity as a conversion of (void*)0 to the integral type.
1558 if (Self.Context.getTypeSize(SrcType) >
1559 Self.Context.getTypeSize(DestType)) {
1560 msg = diag::err_bad_reinterpret_cast_small_int;
1563 Kind = CK_PointerToIntegral;
1567 bool destIsVector = DestType->isVectorType();
1568 bool srcIsVector = SrcType->isVectorType();
1569 if (srcIsVector || destIsVector) {
1570 // FIXME: Should this also apply to floating point types?
1571 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1572 bool destIsScalar = DestType->isIntegralType(Self.Context);
1574 // Check if this is a cast between a vector and something else.
1575 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1576 !(srcIsVector && destIsVector))
1577 return TC_NotApplicable;
1579 // If both types have the same size, we can successfully cast.
1580 if (Self.Context.getTypeSize(SrcType)
1581 == Self.Context.getTypeSize(DestType)) {
1587 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1588 else if (srcIsScalar)
1589 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1591 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1596 bool destIsPtr = DestType->isAnyPointerType() ||
1597 DestType->isBlockPointerType();
1598 bool srcIsPtr = SrcType->isAnyPointerType() ||
1599 SrcType->isBlockPointerType();
1600 if (!destIsPtr && !srcIsPtr) {
1601 // Except for std::nullptr_t->integer and lvalue->reference, which are
1602 // handled above, at least one of the two arguments must be a pointer.
1603 return TC_NotApplicable;
1606 if (SrcType == DestType) {
1607 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1608 // restrictions, a cast to the same type is allowed. The intent is not
1609 // entirely clear here, since all other paragraphs explicitly forbid casts
1610 // to the same type. However, the behavior of compilers is pretty consistent
1611 // on this point: allow same-type conversion if the involved types are
1612 // pointers, disallow otherwise.
1617 if (DestType->isIntegralType(Self.Context)) {
1618 assert(srcIsPtr && "One type must be a pointer");
1619 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1620 // type large enough to hold it; except in Microsoft mode, where the
1621 // integral type size doesn't matter.
1622 if ((Self.Context.getTypeSize(SrcType) >
1623 Self.Context.getTypeSize(DestType)) &&
1624 !Self.getLangOptions().MicrosoftExt) {
1625 msg = diag::err_bad_reinterpret_cast_small_int;
1628 Kind = CK_PointerToIntegral;
1632 if (SrcType->isIntegralOrEnumerationType()) {
1633 assert(destIsPtr && "One type must be a pointer");
1634 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1635 // converted to a pointer.
1636 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1637 // necessarily converted to a null pointer value.]
1638 Kind = CK_IntegralToPointer;
1642 if (!destIsPtr || !srcIsPtr) {
1643 // With the valid non-pointer conversions out of the way, we can be even
1645 return TC_NotApplicable;
1648 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1649 // The C-style cast operator can.
1650 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1651 /*CheckObjCLifetime=*/CStyle)) {
1652 msg = diag::err_bad_cxx_cast_qualifiers_away;
1656 // Cannot convert between block pointers and Objective-C object pointers.
1657 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1658 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1659 return TC_NotApplicable;
1662 Kind = CK_LValueBitCast;
1663 } else if (DestType->isObjCObjectPointerType()) {
1664 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
1665 } else if (DestType->isBlockPointerType()) {
1666 if (!SrcType->isBlockPointerType()) {
1667 Kind = CK_AnyPointerToBlockPointerCast;
1675 // Any pointer can be cast to an Objective-C pointer type with a C-style
1677 if (CStyle && DestType->isObjCObjectPointerType()) {
1681 // Not casting away constness, so the only remaining check is for compatible
1682 // pointer categories.
1684 if (SrcType->isFunctionPointerType()) {
1685 if (DestType->isFunctionPointerType()) {
1686 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1687 // a pointer to a function of a different type.
1691 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1692 // an object type or vice versa is conditionally-supported.
1693 // Compilers support it in C++03 too, though, because it's necessary for
1694 // casting the return value of dlsym() and GetProcAddress().
1695 // FIXME: Conditionally-supported behavior should be configurable in the
1696 // TargetInfo or similar.
1697 if (!Self.getLangOptions().CPlusPlus0x)
1698 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1702 if (DestType->isFunctionPointerType()) {
1704 if (!Self.getLangOptions().CPlusPlus0x)
1705 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1709 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1710 // a pointer to an object of different type.
1711 // Void pointers are not specified, but supported by every compiler out there.
1712 // So we finish by allowing everything that remains - it's got to be two
1717 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
1718 // Handle placeholders.
1719 if (isPlaceholder()) {
1720 // C-style casts can resolve __unknown_any types.
1721 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1722 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1723 SrcExpr.get(), Kind,
1724 ValueKind, BasePath);
1728 checkNonOverloadPlaceholders();
1729 if (SrcExpr.isInvalid())
1733 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1734 // This test is outside everything else because it's the only case where
1735 // a non-lvalue-reference target type does not lead to decay.
1736 if (DestType->isVoidType()) {
1739 if (claimPlaceholder(BuiltinType::Overload)) {
1740 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1741 SrcExpr, /* Decay Function to ptr */ false,
1742 /* Complain */ true, DestRange, DestType,
1743 diag::err_bad_cstyle_cast_overload);
1744 if (SrcExpr.isInvalid())
1748 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1749 if (SrcExpr.isInvalid())
1755 // If the type is dependent, we won't do any other semantic analysis now.
1756 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1757 assert(Kind == CK_Dependent);
1761 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1762 !isPlaceholder(BuiltinType::Overload)) {
1763 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1764 if (SrcExpr.isInvalid())
1768 // AltiVec vector initialization with a single literal.
1769 if (const VectorType *vecTy = DestType->getAs<VectorType>())
1770 if (vecTy->getVectorKind() == VectorType::AltiVecVector
1771 && (SrcExpr.get()->getType()->isIntegerType()
1772 || SrcExpr.get()->getType()->isFloatingType())) {
1773 Kind = CK_VectorSplat;
1777 // C++ [expr.cast]p5: The conversions performed by
1780 // - a static_cast followed by a const_cast,
1781 // - a reinterpret_cast, or
1782 // - a reinterpret_cast followed by a const_cast,
1783 // can be performed using the cast notation of explicit type conversion.
1784 // [...] If a conversion can be interpreted in more than one of the ways
1785 // listed above, the interpretation that appears first in the list is used,
1786 // even if a cast resulting from that interpretation is ill-formed.
1787 // In plain language, this means trying a const_cast ...
1788 unsigned msg = diag::err_bad_cxx_cast_generic;
1789 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1790 /*CStyle*/true, msg);
1791 if (tcr == TC_Success)
1794 Sema::CheckedConversionKind CCK
1795 = FunctionalStyle? Sema::CCK_FunctionalCast
1796 : Sema::CCK_CStyleCast;
1797 if (tcr == TC_NotApplicable) {
1798 // ... or if that is not possible, a static_cast, ignoring const, ...
1799 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1800 msg, Kind, BasePath);
1801 if (SrcExpr.isInvalid())
1804 if (tcr == TC_NotApplicable) {
1805 // ... and finally a reinterpret_cast, ignoring const.
1806 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1807 OpRange, msg, Kind);
1808 if (SrcExpr.isInvalid())
1813 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1814 checkObjCARCConversion(CCK);
1816 if (tcr != TC_Success && msg != 0) {
1817 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1818 DeclAccessPair Found;
1819 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1824 assert(!Fn && "cast failed but able to resolve overload expression!!");
1828 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1829 OpRange, SrcExpr.get(), DestType);
1831 } else if (Kind == CK_BitCast) {
1835 // Clear out SrcExpr if there was a fatal error.
1836 if (tcr != TC_Success)
1837 SrcExpr = ExprError();
1840 /// Check the semantics of a C-style cast operation, in C.
1841 void CastOperation::CheckCStyleCast() {
1842 assert(!Self.getLangOptions().CPlusPlus);
1844 // Handle placeholders.
1845 if (isPlaceholder()) {
1846 // C-style casts can resolve __unknown_any types.
1847 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1848 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1849 SrcExpr.get(), Kind,
1850 ValueKind, BasePath);
1854 // We allow overloads in C, but we don't allow them to be resolved
1855 // by anything except calls.
1856 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
1857 if (SrcExpr.isInvalid())
1861 assert(!isPlaceholder());
1863 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1864 // type needs to be scalar.
1865 if (DestType->isVoidType()) {
1866 // We don't necessarily do lvalue-to-rvalue conversions on this.
1867 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1868 if (SrcExpr.isInvalid())
1871 // Cast to void allows any expr type.
1876 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1877 if (SrcExpr.isInvalid())
1879 QualType SrcType = SrcExpr.get()->getType();
1881 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1882 diag::err_typecheck_cast_to_incomplete)) {
1883 SrcExpr = ExprError();
1887 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1888 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1890 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1891 // GCC struct/union extension: allow cast to self.
1892 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1893 << DestType << SrcExpr.get()->getSourceRange();
1898 // GCC's cast to union extension.
1899 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1900 RecordDecl *RD = DestRecordTy->getDecl();
1901 RecordDecl::field_iterator Field, FieldEnd;
1902 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1903 Field != FieldEnd; ++Field) {
1904 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1905 !Field->isUnnamedBitfield()) {
1906 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1907 << SrcExpr.get()->getSourceRange();
1911 if (Field == FieldEnd) {
1912 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1913 << SrcType << SrcExpr.get()->getSourceRange();
1914 SrcExpr = ExprError();
1921 // Reject any other conversions to non-scalar types.
1922 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1923 << DestType << SrcExpr.get()->getSourceRange();
1924 SrcExpr = ExprError();
1928 // The type we're casting to is known to be a scalar or vector.
1930 // Require the operand to be a scalar or vector.
1931 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1932 Self.Diag(SrcExpr.get()->getExprLoc(),
1933 diag::err_typecheck_expect_scalar_operand)
1934 << SrcType << SrcExpr.get()->getSourceRange();
1935 SrcExpr = ExprError();
1939 if (DestType->isExtVectorType()) {
1940 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1944 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1945 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1946 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1947 Kind = CK_VectorSplat;
1948 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1949 SrcExpr = ExprError();
1954 if (SrcType->isVectorType()) {
1955 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1956 SrcExpr = ExprError();
1960 // The source and target types are both scalars, i.e.
1961 // - arithmetic types (fundamental, enum, and complex)
1962 // - all kinds of pointers
1963 // Note that member pointers were filtered out with C++, above.
1965 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
1966 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
1967 SrcExpr = ExprError();
1971 // If either type is a pointer, the other type has to be either an
1972 // integer or a pointer.
1973 if (!DestType->isArithmeticType()) {
1974 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
1975 Self.Diag(SrcExpr.get()->getExprLoc(),
1976 diag::err_cast_pointer_from_non_pointer_int)
1977 << SrcType << SrcExpr.get()->getSourceRange();
1978 SrcExpr = ExprError();
1981 } else if (!SrcType->isArithmeticType()) {
1982 if (!DestType->isIntegralType(Self.Context) &&
1983 DestType->isArithmeticType()) {
1984 Self.Diag(SrcExpr.get()->getLocStart(),
1985 diag::err_cast_pointer_to_non_pointer_int)
1986 << SrcType << SrcExpr.get()->getSourceRange();
1987 SrcExpr = ExprError();
1992 // ARC imposes extra restrictions on casts.
1993 if (Self.getLangOptions().ObjCAutoRefCount) {
1994 checkObjCARCConversion(Sema::CCK_CStyleCast);
1995 if (SrcExpr.isInvalid())
1998 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
1999 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2000 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2001 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2002 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2003 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2004 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2005 Self.Diag(SrcExpr.get()->getLocStart(),
2006 diag::err_typecheck_incompatible_ownership)
2007 << SrcType << DestType << Sema::AA_Casting
2008 << SrcExpr.get()->getSourceRange();
2013 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2014 Self.Diag(SrcExpr.get()->getLocStart(),
2015 diag::err_arc_convesion_of_weak_unavailable)
2016 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2017 SrcExpr = ExprError();
2022 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2023 if (SrcExpr.isInvalid())
2026 if (Kind == CK_BitCast)
2030 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2031 TypeSourceInfo *CastTypeInfo,
2032 SourceLocation RPLoc,
2034 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2035 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2036 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2038 if (getLangOptions().CPlusPlus) {
2039 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false);
2041 Op.CheckCStyleCast();
2044 if (Op.SrcExpr.isInvalid())
2047 return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
2048 Op.Kind, Op.SrcExpr.take(), &Op.BasePath,
2049 CastTypeInfo, LPLoc, RPLoc));
2052 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2053 SourceLocation LPLoc,
2055 SourceLocation RPLoc) {
2056 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2057 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2058 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2060 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true);
2061 if (Op.SrcExpr.isInvalid())
2064 return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2065 Op.ValueKind, CastTypeInfo,
2066 Op.DestRange.getBegin(),
2067 Op.Kind, Op.SrcExpr.take(),
2068 &Op.BasePath, RPLoc));