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/AST/ASTContext.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "llvm/ADT/SmallVector.h"
28 using namespace clang;
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
35 TC_Failed ///< The cast method is appropriate, but failed. A
36 ///< diagnostic has been emitted.
40 CT_Const, ///< const_cast
41 CT_Static, ///< static_cast
42 CT_Reinterpret, ///< reinterpret_cast
43 CT_Dynamic, ///< dynamic_cast
44 CT_CStyle, ///< (Type)expr
45 CT_Functional ///< Type(expr)
49 struct CastOperation {
50 CastOperation(Sema &S, QualType destType, ExprResult src)
51 : Self(S), SrcExpr(src), DestType(destType),
52 ResultType(destType.getNonLValueExprType(S.Context)),
53 ValueKind(Expr::getValueKindForType(destType)),
54 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
56 if (const BuiltinType *placeholder =
57 src.get()->getType()->getAsPlaceholderType()) {
58 PlaceholderKind = placeholder->getKind();
60 PlaceholderKind = (BuiltinType::Kind) 0;
68 ExprValueKind ValueKind;
70 BuiltinType::Kind PlaceholderKind;
72 bool IsARCUnbridgedCast;
75 SourceRange DestRange;
77 // Top-level semantics-checking routines.
78 void CheckConstCast();
79 void CheckReinterpretCast();
80 void CheckStaticCast();
81 void CheckDynamicCast();
82 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
83 void CheckCStyleCast();
85 /// Complete an apparently-successful cast operation that yields
86 /// the given expression.
87 ExprResult complete(CastExpr *castExpr) {
88 // If this is an unbridged cast, wrap the result in an implicit
89 // cast that yields the unbridged-cast placeholder type.
90 if (IsARCUnbridgedCast) {
91 castExpr = ImplicitCastExpr::Create(Self.Context,
92 Self.Context.ARCUnbridgedCastTy,
93 CK_Dependent, castExpr, nullptr,
94 castExpr->getValueKind());
99 // Internal convenience methods.
101 /// Try to handle the given placeholder expression kind. Return
102 /// true if the source expression has the appropriate placeholder
103 /// kind. A placeholder can only be claimed once.
104 bool claimPlaceholder(BuiltinType::Kind K) {
105 if (PlaceholderKind != K) return false;
107 PlaceholderKind = (BuiltinType::Kind) 0;
111 bool isPlaceholder() const {
112 return PlaceholderKind != 0;
114 bool isPlaceholder(BuiltinType::Kind K) const {
115 return PlaceholderKind == K;
118 void checkCastAlign() {
119 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
122 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
123 assert(Self.getLangOpts().ObjCAutoRefCount);
125 Expr *src = SrcExpr.get();
126 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
128 IsARCUnbridgedCast = true;
132 /// Check for and handle non-overload placeholder expressions.
133 void checkNonOverloadPlaceholders() {
134 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
137 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
138 if (SrcExpr.isInvalid())
140 PlaceholderKind = (BuiltinType::Kind) 0;
145 // The Try functions attempt a specific way of casting. If they succeed, they
146 // return TC_Success. If their way of casting is not appropriate for the given
147 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
148 // to emit if no other way succeeds. If their way of casting is appropriate but
149 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
150 // they emit a specialized diagnostic.
151 // All diagnostics returned by these functions must expect the same three
153 // %0: Cast Type (a value from the CastType enumeration)
155 // %2: Destination Type
156 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
157 QualType DestType, bool CStyle,
159 CXXCastPath &BasePath,
161 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
162 QualType DestType, bool CStyle,
163 const SourceRange &OpRange,
166 CXXCastPath &BasePath);
167 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
168 QualType DestType, bool CStyle,
169 const SourceRange &OpRange,
172 CXXCastPath &BasePath);
173 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
174 CanQualType DestType, bool CStyle,
175 const SourceRange &OpRange,
176 QualType OrigSrcType,
177 QualType OrigDestType, unsigned &msg,
179 CXXCastPath &BasePath);
180 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
182 QualType DestType,bool CStyle,
183 const SourceRange &OpRange,
186 CXXCastPath &BasePath);
188 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
190 Sema::CheckedConversionKind CCK,
191 const SourceRange &OpRange,
192 unsigned &msg, CastKind &Kind,
193 bool ListInitialization);
194 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
196 Sema::CheckedConversionKind CCK,
197 const SourceRange &OpRange,
198 unsigned &msg, CastKind &Kind,
199 CXXCastPath &BasePath,
200 bool ListInitialization);
201 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
202 QualType DestType, bool CStyle,
204 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
205 QualType DestType, bool CStyle,
206 const SourceRange &OpRange,
211 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
213 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
214 SourceLocation LAngleBracketLoc, Declarator &D,
215 SourceLocation RAngleBracketLoc,
216 SourceLocation LParenLoc, Expr *E,
217 SourceLocation RParenLoc) {
219 assert(!D.isInvalidType());
221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
222 if (D.isInvalidType())
225 if (getLangOpts().CPlusPlus) {
226 // Check that there are no default arguments (C++ only).
227 CheckExtraCXXDefaultArguments(D);
230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
236 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
237 TypeSourceInfo *DestTInfo, Expr *E,
238 SourceRange AngleBrackets, SourceRange Parens) {
240 QualType DestType = DestTInfo->getType();
242 // If the type is dependent, we won't do the semantic analysis now.
244 DestType->isDependentType() || Ex.get()->isTypeDependent();
246 CastOperation Op(*this, DestType, E);
247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248 Op.DestRange = AngleBrackets;
251 default: llvm_unreachable("Unknown C++ cast!");
253 case tok::kw_const_cast:
254 if (!TypeDependent) {
256 if (Op.SrcExpr.isInvalid())
259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
260 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
261 OpLoc, Parens.getEnd(),
264 case tok::kw_dynamic_cast: {
265 if (!TypeDependent) {
266 Op.CheckDynamicCast();
267 if (Op.SrcExpr.isInvalid())
270 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
271 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
272 &Op.BasePath, DestTInfo,
273 OpLoc, Parens.getEnd(),
276 case tok::kw_reinterpret_cast: {
277 if (!TypeDependent) {
278 Op.CheckReinterpretCast();
279 if (Op.SrcExpr.isInvalid())
282 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
283 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
284 nullptr, DestTInfo, OpLoc,
288 case tok::kw_static_cast: {
289 if (!TypeDependent) {
290 Op.CheckStaticCast();
291 if (Op.SrcExpr.isInvalid())
295 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
296 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
297 &Op.BasePath, DestTInfo,
298 OpLoc, Parens.getEnd(),
304 /// Try to diagnose a failed overloaded cast. Returns true if
305 /// diagnostics were emitted.
306 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
307 SourceRange range, Expr *src,
309 bool listInitialization) {
311 // These cast kinds don't consider user-defined conversions.
324 QualType srcType = src->getType();
325 if (!destType->isRecordType() && !srcType->isRecordType())
328 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
329 InitializationKind initKind
330 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
331 range, listInitialization)
332 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
334 : InitializationKind::CreateCast(/*type range?*/ range);
335 InitializationSequence sequence(S, entity, initKind, src);
337 assert(sequence.Failed() && "initialization succeeded on second try?");
338 switch (sequence.getFailureKind()) {
339 default: return false;
341 case InitializationSequence::FK_ConstructorOverloadFailed:
342 case InitializationSequence::FK_UserConversionOverloadFailed:
346 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
349 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
351 switch (sequence.getFailedOverloadResult()) {
352 case OR_Success: llvm_unreachable("successful failed overload");
353 case OR_No_Viable_Function:
354 if (candidates.empty())
355 msg = diag::err_ovl_no_conversion_in_cast;
357 msg = diag::err_ovl_no_viable_conversion_in_cast;
358 howManyCandidates = OCD_AllCandidates;
362 msg = diag::err_ovl_ambiguous_conversion_in_cast;
363 howManyCandidates = OCD_ViableCandidates;
367 msg = diag::err_ovl_deleted_conversion_in_cast;
368 howManyCandidates = OCD_ViableCandidates;
372 S.Diag(range.getBegin(), msg)
373 << CT << srcType << destType
374 << range << src->getSourceRange();
376 candidates.NoteCandidates(S, howManyCandidates, src);
381 /// Diagnose a failed cast.
382 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
383 SourceRange opRange, Expr *src, QualType destType,
384 bool listInitialization) {
385 if (msg == diag::err_bad_cxx_cast_generic &&
386 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
390 S.Diag(opRange.getBegin(), msg) << castType
391 << src->getType() << destType << opRange << src->getSourceRange();
394 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
395 /// this removes one level of indirection from both types, provided that they're
396 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
397 /// this one doesn't care if the two pointers-to-member don't point into the
398 /// same class. This is because CastsAwayConstness doesn't care.
399 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
400 const PointerType *T1PtrType = T1->getAs<PointerType>(),
401 *T2PtrType = T2->getAs<PointerType>();
402 if (T1PtrType && T2PtrType) {
403 T1 = T1PtrType->getPointeeType();
404 T2 = T2PtrType->getPointeeType();
407 const ObjCObjectPointerType *T1ObjCPtrType =
408 T1->getAs<ObjCObjectPointerType>(),
410 T2->getAs<ObjCObjectPointerType>();
413 T1 = T1ObjCPtrType->getPointeeType();
414 T2 = T2ObjCPtrType->getPointeeType();
417 else if (T2PtrType) {
418 T1 = T1ObjCPtrType->getPointeeType();
419 T2 = T2PtrType->getPointeeType();
423 else if (T2ObjCPtrType) {
425 T2 = T2ObjCPtrType->getPointeeType();
426 T1 = T1PtrType->getPointeeType();
431 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
432 *T2MPType = T2->getAs<MemberPointerType>();
433 if (T1MPType && T2MPType) {
434 T1 = T1MPType->getPointeeType();
435 T2 = T2MPType->getPointeeType();
439 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
440 *T2BPType = T2->getAs<BlockPointerType>();
441 if (T1BPType && T2BPType) {
442 T1 = T1BPType->getPointeeType();
443 T2 = T2BPType->getPointeeType();
450 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
451 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
452 /// the cast checkers. Both arguments must denote pointer (possibly to member)
455 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
457 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
459 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
460 bool CheckCVR, bool CheckObjCLifetime,
461 QualType *TheOffendingSrcType = nullptr,
462 QualType *TheOffendingDestType = nullptr,
463 Qualifiers *CastAwayQualifiers = nullptr) {
464 // If the only checking we care about is for Objective-C lifetime qualifiers,
465 // and we're not in ARC mode, there's nothing to check.
466 if (!CheckCVR && CheckObjCLifetime &&
467 !Self.Context.getLangOpts().ObjCAutoRefCount)
470 // Casting away constness is defined in C++ 5.2.11p8 with reference to
471 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
472 // the rules are non-trivial. So first we construct Tcv *...cv* as described
474 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
475 SrcType->isBlockPointerType()) &&
476 "Source type is not pointer or pointer to member.");
477 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
478 DestType->isBlockPointerType()) &&
479 "Destination type is not pointer or pointer to member.");
481 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
482 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
483 SmallVector<Qualifiers, 8> cv1, cv2;
485 // Find the qualifiers. We only care about cvr-qualifiers for the
486 // purpose of this check, because other qualifiers (address spaces,
487 // Objective-C GC, etc.) are part of the type's identity.
488 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
489 QualType PrevUnwrappedDestType = UnwrappedDestType;
490 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
491 // Determine the relevant qualifiers at this level.
492 Qualifiers SrcQuals, DestQuals;
493 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
494 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
496 Qualifiers RetainedSrcQuals, RetainedDestQuals;
498 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
499 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
501 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
502 TheOffendingDestType && CastAwayQualifiers) {
503 *TheOffendingSrcType = PrevUnwrappedSrcType;
504 *TheOffendingDestType = PrevUnwrappedDestType;
505 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
509 if (CheckObjCLifetime &&
510 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
513 cv1.push_back(RetainedSrcQuals);
514 cv2.push_back(RetainedDestQuals);
516 PrevUnwrappedSrcType = UnwrappedSrcType;
517 PrevUnwrappedDestType = UnwrappedDestType;
522 // Construct void pointers with those qualifiers (in reverse order of
523 // unwrapping, of course).
524 QualType SrcConstruct = Self.Context.VoidTy;
525 QualType DestConstruct = Self.Context.VoidTy;
526 ASTContext &Context = Self.Context;
527 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
529 i1 != cv1.rend(); ++i1, ++i2) {
531 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
533 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
536 // Test if they're compatible.
537 bool ObjCLifetimeConversion;
538 return SrcConstruct != DestConstruct &&
539 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
540 ObjCLifetimeConversion);
543 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
544 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
545 /// checked downcasts in class hierarchies.
546 void CastOperation::CheckDynamicCast() {
547 if (ValueKind == VK_RValue)
548 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
549 else if (isPlaceholder())
550 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
551 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
554 QualType OrigSrcType = SrcExpr.get()->getType();
555 QualType DestType = Self.Context.getCanonicalType(this->DestType);
557 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
558 // or "pointer to cv void".
560 QualType DestPointee;
561 const PointerType *DestPointer = DestType->getAs<PointerType>();
562 const ReferenceType *DestReference = nullptr;
564 DestPointee = DestPointer->getPointeeType();
565 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
566 DestPointee = DestReference->getPointeeType();
568 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
569 << this->DestType << DestRange;
570 SrcExpr = ExprError();
574 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
575 if (DestPointee->isVoidType()) {
576 assert(DestPointer && "Reference to void is not possible");
577 } else if (DestRecord) {
578 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
579 diag::err_bad_dynamic_cast_incomplete,
581 SrcExpr = ExprError();
585 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
586 << DestPointee.getUnqualifiedType() << DestRange;
587 SrcExpr = ExprError();
591 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
592 // complete class type, [...]. If T is an lvalue reference type, v shall be
593 // an lvalue of a complete class type, [...]. If T is an rvalue reference
594 // type, v shall be an expression having a complete class type, [...]
595 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
598 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
599 SrcPointee = SrcPointer->getPointeeType();
601 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
602 << OrigSrcType << SrcExpr.get()->getSourceRange();
603 SrcExpr = ExprError();
606 } else if (DestReference->isLValueReferenceType()) {
607 if (!SrcExpr.get()->isLValue()) {
608 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
609 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
611 SrcPointee = SrcType;
613 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
614 // to materialize the prvalue before we bind the reference to it.
615 if (SrcExpr.get()->isRValue())
616 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
617 SrcType, SrcExpr.get(), /*IsLValueReference*/false);
618 SrcPointee = SrcType;
621 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
623 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
624 diag::err_bad_dynamic_cast_incomplete,
626 SrcExpr = ExprError();
630 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
631 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
632 SrcExpr = ExprError();
636 assert((DestPointer || DestReference) &&
637 "Bad destination non-ptr/ref slipped through.");
638 assert((DestRecord || DestPointee->isVoidType()) &&
639 "Bad destination pointee slipped through.");
640 assert(SrcRecord && "Bad source pointee slipped through.");
642 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
643 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
644 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
645 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
646 SrcExpr = ExprError();
650 // C++ 5.2.7p3: If the type of v is the same as the required result type,
652 if (DestRecord == SrcRecord) {
658 // Upcasts are resolved statically.
659 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
660 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
661 OpRange.getBegin(), OpRange,
663 SrcExpr = ExprError();
667 Kind = CK_DerivedToBase;
669 // If we are casting to or through a virtual base class, we need a
671 if (Self.BasePathInvolvesVirtualBase(BasePath))
672 Self.MarkVTableUsed(OpRange.getBegin(),
673 cast<CXXRecordDecl>(SrcRecord->getDecl()));
677 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
678 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
679 assert(SrcDecl && "Definition missing");
680 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
681 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
682 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
683 SrcExpr = ExprError();
685 Self.MarkVTableUsed(OpRange.getBegin(),
686 cast<CXXRecordDecl>(SrcRecord->getDecl()));
688 // dynamic_cast is not available with -fno-rtti.
689 // As an exception, dynamic_cast to void* is available because it doesn't
691 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
692 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
693 SrcExpr = ExprError();
697 // Done. Everything else is run-time checks.
701 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
702 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
704 /// const char *str = "literal";
705 /// legacy_function(const_cast\<char*\>(str));
706 void CastOperation::CheckConstCast() {
707 if (ValueKind == VK_RValue)
708 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
709 else if (isPlaceholder())
710 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
711 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
714 unsigned msg = diag::err_bad_cxx_cast_generic;
715 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
717 Self.Diag(OpRange.getBegin(), msg) << CT_Const
718 << SrcExpr.get()->getType() << DestType << OpRange;
719 SrcExpr = ExprError();
723 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
724 /// or downcast between respective pointers or references.
725 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
727 SourceRange OpRange) {
728 QualType SrcType = SrcExpr->getType();
729 // When casting from pointer or reference, get pointee type; use original
731 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
732 const CXXRecordDecl *SrcRD =
733 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
735 // Examining subobjects for records is only possible if the complete and
736 // valid definition is available. Also, template instantiation is not
738 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
741 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
743 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
751 CXXBasePaths BasePaths;
753 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
754 ReinterpretKind = ReinterpretUpcast;
755 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
756 ReinterpretKind = ReinterpretDowncast;
760 bool VirtualBase = true;
761 bool NonZeroOffset = false;
762 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
765 const CXXBasePath &Path = *I;
766 CharUnits Offset = CharUnits::Zero();
767 bool IsVirtual = false;
768 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
769 IElem != EElem; ++IElem) {
770 IsVirtual = IElem->Base->isVirtual();
773 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
774 assert(BaseRD && "Base type should be a valid unqualified class type");
775 // Don't check if any base has invalid declaration or has no definition
776 // since it has no layout info.
777 const CXXRecordDecl *Class = IElem->Class,
778 *ClassDefinition = Class->getDefinition();
779 if (Class->isInvalidDecl() || !ClassDefinition ||
780 !ClassDefinition->isCompleteDefinition())
783 const ASTRecordLayout &DerivedLayout =
784 Self.Context.getASTRecordLayout(Class);
785 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
788 // Don't warn if any path is a non-virtually derived base at offset zero.
791 // Offset makes sense only for non-virtual bases.
793 NonZeroOffset = true;
795 VirtualBase = VirtualBase && IsVirtual;
798 (void) NonZeroOffset; // Silence set but not used warning.
799 assert((VirtualBase || NonZeroOffset) &&
800 "Should have returned if has non-virtual base with zero offset");
803 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
804 QualType DerivedType =
805 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
807 SourceLocation BeginLoc = OpRange.getBegin();
808 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
809 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
811 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
812 << int(ReinterpretKind)
813 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
816 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
818 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
820 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
821 void CastOperation::CheckReinterpretCast() {
822 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
823 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
825 checkNonOverloadPlaceholders();
826 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
829 unsigned msg = diag::err_bad_cxx_cast_generic;
831 TryReinterpretCast(Self, SrcExpr, DestType,
832 /*CStyle*/false, OpRange, msg, Kind);
833 if (tcr != TC_Success && msg != 0)
835 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
837 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
838 //FIXME: &f<int>; is overloaded and resolvable
839 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
840 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
841 << DestType << OpRange;
842 Self.NoteAllOverloadCandidates(SrcExpr.get());
845 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
846 DestType, /*listInitialization=*/false);
848 SrcExpr = ExprError();
849 } else if (tcr == TC_Success) {
850 if (Self.getLangOpts().ObjCAutoRefCount)
851 checkObjCARCConversion(Sema::CCK_OtherCast);
852 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
857 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
858 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
859 /// implicit conversions explicit and getting rid of data loss warnings.
860 void CastOperation::CheckStaticCast() {
861 if (isPlaceholder()) {
862 checkNonOverloadPlaceholders();
863 if (SrcExpr.isInvalid())
867 // This test is outside everything else because it's the only case where
868 // a non-lvalue-reference target type does not lead to decay.
869 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
870 if (DestType->isVoidType()) {
873 if (claimPlaceholder(BuiltinType::Overload)) {
874 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
875 false, // Decay Function to ptr
877 OpRange, DestType, diag::err_bad_static_cast_overload);
878 if (SrcExpr.isInvalid())
882 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
886 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
887 !isPlaceholder(BuiltinType::Overload)) {
888 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
889 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
893 unsigned msg = diag::err_bad_cxx_cast_generic;
895 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
896 Kind, BasePath, /*ListInitialization=*/false);
897 if (tcr != TC_Success && msg != 0) {
898 if (SrcExpr.isInvalid())
900 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
901 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
902 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
903 << oe->getName() << DestType << OpRange
904 << oe->getQualifierLoc().getSourceRange();
905 Self.NoteAllOverloadCandidates(SrcExpr.get());
907 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
908 /*listInitialization=*/false);
910 SrcExpr = ExprError();
911 } else if (tcr == TC_Success) {
912 if (Kind == CK_BitCast)
914 if (Self.getLangOpts().ObjCAutoRefCount)
915 checkObjCARCConversion(Sema::CCK_OtherCast);
916 } else if (Kind == CK_BitCast) {
921 /// TryStaticCast - Check if a static cast can be performed, and do so if
922 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
923 /// and casting away constness.
924 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
926 Sema::CheckedConversionKind CCK,
927 const SourceRange &OpRange, unsigned &msg,
928 CastKind &Kind, CXXCastPath &BasePath,
929 bool ListInitialization) {
930 // Determine whether we have the semantics of a C-style cast.
932 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
934 // The order the tests is not entirely arbitrary. There is one conversion
935 // that can be handled in two different ways. Given:
937 // struct B : public A {
941 // the cast static_cast<const B&>(a) could be seen as either a static
942 // reference downcast, or an explicit invocation of the user-defined
943 // conversion using B's conversion constructor.
944 // DR 427 specifies that the downcast is to be applied here.
946 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
947 // Done outside this function.
951 // C++ 5.2.9p5, reference downcast.
952 // See the function for details.
953 // DR 427 specifies that this is to be applied before paragraph 2.
954 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
955 OpRange, msg, Kind, BasePath);
956 if (tcr != TC_NotApplicable)
959 // C++0x [expr.static.cast]p3:
960 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
961 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
962 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
964 if (tcr != TC_NotApplicable)
967 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
968 // [...] if the declaration "T t(e);" is well-formed, [...].
969 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
970 Kind, ListInitialization);
971 if (SrcExpr.isInvalid())
973 if (tcr != TC_NotApplicable)
976 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
977 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
978 // conversions, subject to further restrictions.
979 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
980 // of qualification conversions impossible.
981 // In the CStyle case, the earlier attempt to const_cast should have taken
982 // care of reverse qualification conversions.
984 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
986 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
987 // converted to an integral type. [...] A value of a scoped enumeration type
988 // can also be explicitly converted to a floating-point type [...].
989 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
990 if (Enum->getDecl()->isScoped()) {
991 if (DestType->isBooleanType()) {
992 Kind = CK_IntegralToBoolean;
994 } else if (DestType->isIntegralType(Self.Context)) {
995 Kind = CK_IntegralCast;
997 } else if (DestType->isRealFloatingType()) {
998 Kind = CK_IntegralToFloating;
1004 // Reverse integral promotion/conversion. All such conversions are themselves
1005 // again integral promotions or conversions and are thus already handled by
1006 // p2 (TryDirectInitialization above).
1007 // (Note: any data loss warnings should be suppressed.)
1008 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1009 // enum->enum). See also C++ 5.2.9p7.
1010 // The same goes for reverse floating point promotion/conversion and
1011 // floating-integral conversions. Again, only floating->enum is relevant.
1012 if (DestType->isEnumeralType()) {
1013 if (SrcType->isIntegralOrEnumerationType()) {
1014 Kind = CK_IntegralCast;
1016 } else if (SrcType->isRealFloatingType()) {
1017 Kind = CK_FloatingToIntegral;
1022 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1023 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1024 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1026 if (tcr != TC_NotApplicable)
1029 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1030 // conversion. C++ 5.2.9p9 has additional information.
1031 // DR54's access restrictions apply here also.
1032 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1033 OpRange, msg, Kind, BasePath);
1034 if (tcr != TC_NotApplicable)
1037 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1038 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1039 // just the usual constness stuff.
1040 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1041 QualType SrcPointee = SrcPointer->getPointeeType();
1042 if (SrcPointee->isVoidType()) {
1043 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1044 QualType DestPointee = DestPointer->getPointeeType();
1045 if (DestPointee->isIncompleteOrObjectType()) {
1046 // This is definitely the intended conversion, but it might fail due
1047 // to a qualifier violation. Note that we permit Objective-C lifetime
1048 // and GC qualifier mismatches here.
1050 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1051 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1052 DestPointeeQuals.removeObjCGCAttr();
1053 DestPointeeQuals.removeObjCLifetime();
1054 SrcPointeeQuals.removeObjCGCAttr();
1055 SrcPointeeQuals.removeObjCLifetime();
1056 if (DestPointeeQuals != SrcPointeeQuals &&
1057 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1058 msg = diag::err_bad_cxx_cast_qualifiers_away;
1066 else if (DestType->isObjCObjectPointerType()) {
1067 // allow both c-style cast and static_cast of objective-c pointers as
1068 // they are pervasive.
1069 Kind = CK_CPointerToObjCPointerCast;
1072 else if (CStyle && DestType->isBlockPointerType()) {
1073 // allow c-style cast of void * to block pointers.
1074 Kind = CK_AnyPointerToBlockPointerCast;
1079 // Allow arbitray objective-c pointer conversion with static casts.
1080 if (SrcType->isObjCObjectPointerType() &&
1081 DestType->isObjCObjectPointerType()) {
1085 // Allow ns-pointer to cf-pointer conversion in either direction
1086 // with static casts.
1088 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1091 // We tried everything. Everything! Nothing works! :-(
1092 return TC_NotApplicable;
1095 /// Tests whether a conversion according to N2844 is valid.
1097 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1098 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1100 // C++0x [expr.static.cast]p3:
1101 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1102 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1103 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1105 return TC_NotApplicable;
1107 if (!SrcExpr->isGLValue())
1108 return TC_NotApplicable;
1110 // Because we try the reference downcast before this function, from now on
1111 // this is the only cast possibility, so we issue an error if we fail now.
1112 // FIXME: Should allow casting away constness if CStyle.
1114 bool ObjCConversion;
1115 bool ObjCLifetimeConversion;
1116 QualType FromType = SrcExpr->getType();
1117 QualType ToType = R->getPointeeType();
1119 FromType = FromType.getUnqualifiedType();
1120 ToType = ToType.getUnqualifiedType();
1123 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
1125 DerivedToBase, ObjCConversion,
1126 ObjCLifetimeConversion)
1127 < Sema::Ref_Compatible_With_Added_Qualification) {
1128 msg = diag::err_bad_lvalue_to_rvalue_cast;
1132 if (DerivedToBase) {
1133 Kind = CK_DerivedToBase;
1134 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1135 /*DetectVirtual=*/true);
1136 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1137 return TC_NotApplicable;
1139 Self.BuildBasePathArray(Paths, BasePath);
1146 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1148 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1149 bool CStyle, const SourceRange &OpRange,
1150 unsigned &msg, CastKind &Kind,
1151 CXXCastPath &BasePath) {
1152 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1153 // cast to type "reference to cv2 D", where D is a class derived from B,
1154 // if a valid standard conversion from "pointer to D" to "pointer to B"
1155 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1156 // In addition, DR54 clarifies that the base must be accessible in the
1157 // current context. Although the wording of DR54 only applies to the pointer
1158 // variant of this rule, the intent is clearly for it to apply to the this
1159 // conversion as well.
1161 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1162 if (!DestReference) {
1163 return TC_NotApplicable;
1165 bool RValueRef = DestReference->isRValueReferenceType();
1166 if (!RValueRef && !SrcExpr->isLValue()) {
1167 // We know the left side is an lvalue reference, so we can suggest a reason.
1168 msg = diag::err_bad_cxx_cast_rvalue;
1169 return TC_NotApplicable;
1172 QualType DestPointee = DestReference->getPointeeType();
1174 // FIXME: If the source is a prvalue, we should issue a warning (because the
1175 // cast always has undefined behavior), and for AST consistency, we should
1176 // materialize a temporary.
1177 return TryStaticDowncast(Self,
1178 Self.Context.getCanonicalType(SrcExpr->getType()),
1179 Self.Context.getCanonicalType(DestPointee), CStyle,
1180 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1184 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1186 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1187 bool CStyle, const SourceRange &OpRange,
1188 unsigned &msg, CastKind &Kind,
1189 CXXCastPath &BasePath) {
1190 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1191 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1192 // is a class derived from B, if a valid standard conversion from "pointer
1193 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1195 // In addition, DR54 clarifies that the base must be accessible in the
1198 const PointerType *DestPointer = DestType->getAs<PointerType>();
1200 return TC_NotApplicable;
1203 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1205 msg = diag::err_bad_static_cast_pointer_nonpointer;
1206 return TC_NotApplicable;
1209 return TryStaticDowncast(Self,
1210 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1211 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1212 CStyle, OpRange, SrcType, DestType, msg, Kind,
1216 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1217 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1218 /// DestType is possible and allowed.
1220 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1221 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
1222 QualType OrigDestType, unsigned &msg,
1223 CastKind &Kind, CXXCastPath &BasePath) {
1224 // We can only work with complete types. But don't complain if it doesn't work
1225 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1226 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
1227 return TC_NotApplicable;
1229 // Downcast can only happen in class hierarchies, so we need classes.
1230 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1231 return TC_NotApplicable;
1234 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1235 /*DetectVirtual=*/true);
1236 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1237 return TC_NotApplicable;
1240 // Target type does derive from source type. Now we're serious. If an error
1241 // appears now, it's not ignored.
1242 // This may not be entirely in line with the standard. Take for example:
1244 // struct B : virtual A {
1250 // (void)static_cast<const B&>(*((A*)0));
1252 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1253 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1254 // However, both GCC and Comeau reject this example, and accepting it would
1255 // mean more complex code if we're to preserve the nice error message.
1256 // FIXME: Being 100% compliant here would be nice to have.
1258 // Must preserve cv, as always, unless we're in C-style mode.
1259 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1260 msg = diag::err_bad_cxx_cast_qualifiers_away;
1264 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1265 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1266 // that it builds the paths in reverse order.
1267 // To sum up: record all paths to the base and build a nice string from
1268 // them. Use it to spice up the error message.
1269 if (!Paths.isRecordingPaths()) {
1271 Paths.setRecordingPaths(true);
1272 Self.IsDerivedFrom(DestType, SrcType, Paths);
1274 std::string PathDisplayStr;
1275 std::set<unsigned> DisplayedPaths;
1276 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
1278 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1279 // We haven't displayed a path to this particular base
1280 // class subobject yet.
1281 PathDisplayStr += "\n ";
1282 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1285 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
1286 PathDisplayStr += QualType(DestType).getAsString();
1290 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1291 << QualType(SrcType).getUnqualifiedType()
1292 << QualType(DestType).getUnqualifiedType()
1293 << PathDisplayStr << OpRange;
1298 if (Paths.getDetectedVirtual() != nullptr) {
1299 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1300 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1301 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1307 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1310 diag::err_downcast_from_inaccessible_base)) {
1311 case Sema::AR_accessible:
1312 case Sema::AR_delayed: // be optimistic
1313 case Sema::AR_dependent: // be optimistic
1316 case Sema::AR_inaccessible:
1322 Self.BuildBasePathArray(Paths, BasePath);
1323 Kind = CK_BaseToDerived;
1327 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1328 /// C++ 5.2.9p9 is valid:
1330 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1331 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1332 /// where B is a base class of D [...].
1335 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1336 QualType DestType, bool CStyle,
1337 const SourceRange &OpRange,
1338 unsigned &msg, CastKind &Kind,
1339 CXXCastPath &BasePath) {
1340 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1342 return TC_NotApplicable;
1344 bool WasOverloadedFunction = false;
1345 DeclAccessPair FoundOverload;
1346 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1347 if (FunctionDecl *Fn
1348 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1350 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1351 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1352 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1353 WasOverloadedFunction = true;
1357 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1359 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1360 return TC_NotApplicable;
1363 // T == T, modulo cv
1364 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1365 DestMemPtr->getPointeeType()))
1366 return TC_NotApplicable;
1369 QualType SrcClass(SrcMemPtr->getClass(), 0);
1370 QualType DestClass(DestMemPtr->getClass(), 0);
1371 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1372 /*DetectVirtual=*/true);
1373 if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
1374 !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1375 return TC_NotApplicable;
1378 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1379 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1381 Paths.setRecordingPaths(true);
1382 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1385 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1386 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1387 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1392 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1393 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1394 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1400 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1401 DestClass, SrcClass,
1403 diag::err_upcast_to_inaccessible_base)) {
1404 case Sema::AR_accessible:
1405 case Sema::AR_delayed:
1406 case Sema::AR_dependent:
1407 // Optimistically assume that the delayed and dependent cases
1411 case Sema::AR_inaccessible:
1417 if (WasOverloadedFunction) {
1418 // Resolve the address of the overloaded function again, this time
1419 // allowing complaints if something goes wrong.
1420 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1429 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1430 if (!SrcExpr.isUsable()) {
1436 Self.BuildBasePathArray(Paths, BasePath);
1437 Kind = CK_DerivedToBaseMemberPointer;
1441 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1444 /// An expression e can be explicitly converted to a type T using a
1445 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1447 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1448 Sema::CheckedConversionKind CCK,
1449 const SourceRange &OpRange, unsigned &msg,
1450 CastKind &Kind, bool ListInitialization) {
1451 if (DestType->isRecordType()) {
1452 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1453 diag::err_bad_dynamic_cast_incomplete) ||
1454 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1455 diag::err_allocation_of_abstract_type)) {
1459 } else if (DestType->isMemberPointerType()) {
1460 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1461 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1465 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1466 InitializationKind InitKind
1467 = (CCK == Sema::CCK_CStyleCast)
1468 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1470 : (CCK == Sema::CCK_FunctionalCast)
1471 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1472 : InitializationKind::CreateCast(OpRange);
1473 Expr *SrcExprRaw = SrcExpr.get();
1474 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1476 // At this point of CheckStaticCast, if the destination is a reference,
1477 // or the expression is an overload expression this has to work.
1478 // There is no other way that works.
1479 // On the other hand, if we're checking a C-style cast, we've still got
1480 // the reinterpret_cast way.
1482 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1483 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1484 return TC_NotApplicable;
1486 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1487 if (Result.isInvalid()) {
1492 if (InitSeq.isConstructorInitialization())
1493 Kind = CK_ConstructorConversion;
1501 /// TryConstCast - See if a const_cast from source to destination is allowed,
1502 /// and perform it if it is.
1503 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1504 QualType DestType, bool CStyle,
1506 DestType = Self.Context.getCanonicalType(DestType);
1507 QualType SrcType = SrcExpr.get()->getType();
1508 bool NeedToMaterializeTemporary = false;
1510 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1512 // if a pointer to T1 can be explicitly converted to the type "pointer to
1513 // T2" using a const_cast, then the following conversions can also be
1515 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1516 // type T2 using the cast const_cast<T2&>;
1517 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1518 // type T2 using the cast const_cast<T2&&>; and
1519 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1520 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1522 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1523 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1524 // is C-style, static_cast might find a way, so we simply suggest a
1525 // message and tell the parent to keep searching.
1526 msg = diag::err_bad_cxx_cast_rvalue;
1527 return TC_NotApplicable;
1530 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1531 if (!SrcType->isRecordType()) {
1532 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1533 // this is C-style, static_cast can do this.
1534 msg = diag::err_bad_cxx_cast_rvalue;
1535 return TC_NotApplicable;
1538 // Materialize the class prvalue so that the const_cast can bind a
1540 NeedToMaterializeTemporary = true;
1543 // It's not completely clear under the standard whether we can
1544 // const_cast bit-field gl-values. Doing so would not be
1545 // intrinsically complicated, but for now, we say no for
1546 // consistency with other compilers and await the word of the
1548 if (SrcExpr.get()->refersToBitField()) {
1549 msg = diag::err_bad_cxx_cast_bitfield;
1550 return TC_NotApplicable;
1553 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1554 SrcType = Self.Context.getPointerType(SrcType);
1557 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1558 // the rules for const_cast are the same as those used for pointers.
1560 if (!DestType->isPointerType() &&
1561 !DestType->isMemberPointerType() &&
1562 !DestType->isObjCObjectPointerType()) {
1563 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1564 // was a reference type, we converted it to a pointer above.
1565 // The status of rvalue references isn't entirely clear, but it looks like
1566 // conversion to them is simply invalid.
1567 // C++ 5.2.11p3: For two pointer types [...]
1569 msg = diag::err_bad_const_cast_dest;
1570 return TC_NotApplicable;
1572 if (DestType->isFunctionPointerType() ||
1573 DestType->isMemberFunctionPointerType()) {
1574 // Cannot cast direct function pointers.
1575 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1576 // T is the ultimate pointee of source and target type.
1578 msg = diag::err_bad_const_cast_dest;
1579 return TC_NotApplicable;
1581 SrcType = Self.Context.getCanonicalType(SrcType);
1583 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1584 // completely equal.
1585 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1586 // in multi-level pointers may change, but the level count must be the same,
1587 // as must be the final pointee type.
1588 while (SrcType != DestType &&
1589 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1590 Qualifiers SrcQuals, DestQuals;
1591 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1592 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1594 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1595 // the other qualifiers (e.g., address spaces) are identical.
1596 SrcQuals.removeCVRQualifiers();
1597 DestQuals.removeCVRQualifiers();
1598 if (SrcQuals != DestQuals)
1599 return TC_NotApplicable;
1602 // Since we're dealing in canonical types, the remainder must be the same.
1603 if (SrcType != DestType)
1604 return TC_NotApplicable;
1606 if (NeedToMaterializeTemporary)
1607 // This is a const_cast from a class prvalue to an rvalue reference type.
1608 // Materialize a temporary to store the result of the conversion.
1609 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1610 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
1615 // Checks for undefined behavior in reinterpret_cast.
1616 // The cases that is checked for is:
1617 // *reinterpret_cast<T*>(&a)
1618 // reinterpret_cast<T&>(a)
1619 // where accessing 'a' as type 'T' will result in undefined behavior.
1620 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1622 SourceRange Range) {
1623 unsigned DiagID = IsDereference ?
1624 diag::warn_pointer_indirection_from_incompatible_type :
1625 diag::warn_undefined_reinterpret_cast;
1627 if (Diags.isIgnored(DiagID, Range.getBegin()))
1630 QualType SrcTy, DestTy;
1631 if (IsDereference) {
1632 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1635 SrcTy = SrcType->getPointeeType();
1636 DestTy = DestType->getPointeeType();
1638 if (!DestType->getAs<ReferenceType>()) {
1642 DestTy = DestType->getPointeeType();
1645 // Cast is compatible if the types are the same.
1646 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1649 // or one of the types is a char or void type
1650 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1651 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1654 // or one of the types is a tag type.
1655 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1659 // FIXME: Scoped enums?
1660 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1661 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1662 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1667 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1670 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1671 QualType DestType) {
1672 QualType SrcType = SrcExpr.get()->getType();
1673 if (Self.Context.hasSameType(SrcType, DestType))
1675 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1676 if (SrcPtrTy->isObjCSelType()) {
1677 QualType DT = DestType;
1678 if (isa<PointerType>(DestType))
1679 DT = DestType->getPointeeType();
1680 if (!DT.getUnqualifiedType()->isVoidType())
1681 Self.Diag(SrcExpr.get()->getExprLoc(),
1682 diag::warn_cast_pointer_from_sel)
1683 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1687 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1688 const Expr *SrcExpr, QualType DestType,
1690 QualType SrcType = SrcExpr->getType();
1692 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1693 // are not explicit design choices, but consistent with GCC's behavior.
1694 // Feel free to modify them if you've reason/evidence for an alternative.
1695 if (CStyle && SrcType->isIntegralType(Self.Context)
1696 && !SrcType->isBooleanType()
1697 && !SrcType->isEnumeralType()
1698 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1699 && Self.Context.getTypeSize(DestType) >
1700 Self.Context.getTypeSize(SrcType)) {
1701 // Separate between casts to void* and non-void* pointers.
1702 // Some APIs use (abuse) void* for something like a user context,
1703 // and often that value is an integer even if it isn't a pointer itself.
1704 // Having a separate warning flag allows users to control the warning
1705 // for their workflow.
1706 unsigned Diag = DestType->isVoidPointerType() ?
1707 diag::warn_int_to_void_pointer_cast
1708 : diag::warn_int_to_pointer_cast;
1709 Self.Diag(Loc, Diag) << SrcType << DestType;
1713 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1714 QualType DestType, bool CStyle,
1715 const SourceRange &OpRange,
1718 bool IsLValueCast = false;
1720 DestType = Self.Context.getCanonicalType(DestType);
1721 QualType SrcType = SrcExpr.get()->getType();
1723 // Is the source an overloaded name? (i.e. &foo)
1724 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1725 if (SrcType == Self.Context.OverloadTy) {
1726 // ... unless foo<int> resolves to an lvalue unambiguously.
1727 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1729 ExprResult SingleFunctionExpr = SrcExpr;
1730 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1732 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1733 ) && SingleFunctionExpr.isUsable()) {
1734 SrcExpr = SingleFunctionExpr;
1735 SrcType = SrcExpr.get()->getType();
1737 return TC_NotApplicable;
1741 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1742 if (!SrcExpr.get()->isGLValue()) {
1743 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1744 // similar comment in const_cast.
1745 msg = diag::err_bad_cxx_cast_rvalue;
1746 return TC_NotApplicable;
1750 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1751 /*isDereference=*/false, OpRange);
1754 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1755 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1756 // built-in & and * operators.
1758 const char *inappropriate = nullptr;
1759 switch (SrcExpr.get()->getObjectKind()) {
1762 case OK_BitField: inappropriate = "bit-field"; break;
1763 case OK_VectorComponent: inappropriate = "vector element"; break;
1764 case OK_ObjCProperty: inappropriate = "property expression"; break;
1765 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1768 if (inappropriate) {
1769 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1770 << inappropriate << DestType
1771 << OpRange << SrcExpr.get()->getSourceRange();
1772 msg = 0; SrcExpr = ExprError();
1773 return TC_NotApplicable;
1776 // This code does this transformation for the checked types.
1777 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1778 SrcType = Self.Context.getPointerType(SrcType);
1780 IsLValueCast = true;
1783 // Canonicalize source for comparison.
1784 SrcType = Self.Context.getCanonicalType(SrcType);
1786 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1787 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1788 if (DestMemPtr && SrcMemPtr) {
1789 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1790 // can be explicitly converted to an rvalue of type "pointer to member
1791 // of Y of type T2" if T1 and T2 are both function types or both object
1793 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1794 SrcMemPtr->getPointeeType()->isFunctionType())
1795 return TC_NotApplicable;
1797 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1799 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1801 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1802 /*CheckObjCLifetime=*/CStyle)) {
1803 msg = diag::err_bad_cxx_cast_qualifiers_away;
1807 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1808 // We need to determine the inheritance model that the class will use if
1810 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
1811 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1814 // Don't allow casting between member pointers of different sizes.
1815 if (Self.Context.getTypeSize(DestMemPtr) !=
1816 Self.Context.getTypeSize(SrcMemPtr)) {
1817 msg = diag::err_bad_cxx_cast_member_pointer_size;
1821 // A valid member pointer cast.
1822 assert(!IsLValueCast);
1823 Kind = CK_ReinterpretMemberPointer;
1827 // See below for the enumeral issue.
1828 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1829 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1830 // type large enough to hold it. A value of std::nullptr_t can be
1831 // converted to an integral type; the conversion has the same meaning
1832 // and validity as a conversion of (void*)0 to the integral type.
1833 if (Self.Context.getTypeSize(SrcType) >
1834 Self.Context.getTypeSize(DestType)) {
1835 msg = diag::err_bad_reinterpret_cast_small_int;
1838 Kind = CK_PointerToIntegral;
1842 bool destIsVector = DestType->isVectorType();
1843 bool srcIsVector = SrcType->isVectorType();
1844 if (srcIsVector || destIsVector) {
1845 // FIXME: Should this also apply to floating point types?
1846 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1847 bool destIsScalar = DestType->isIntegralType(Self.Context);
1849 // Check if this is a cast between a vector and something else.
1850 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1851 !(srcIsVector && destIsVector))
1852 return TC_NotApplicable;
1854 // If both types have the same size, we can successfully cast.
1855 if (Self.Context.getTypeSize(SrcType)
1856 == Self.Context.getTypeSize(DestType)) {
1862 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1863 else if (srcIsScalar)
1864 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1866 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1871 if (SrcType == DestType) {
1872 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1873 // restrictions, a cast to the same type is allowed so long as it does not
1874 // cast away constness. In C++98, the intent was not entirely clear here,
1875 // since all other paragraphs explicitly forbid casts to the same type.
1876 // C++11 clarifies this case with p2.
1878 // The only allowed types are: integral, enumeration, pointer, or
1879 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1881 TryCastResult Result = TC_NotApplicable;
1882 if (SrcType->isIntegralOrEnumerationType() ||
1883 SrcType->isAnyPointerType() ||
1884 SrcType->isMemberPointerType() ||
1885 SrcType->isBlockPointerType()) {
1886 Result = TC_Success;
1891 bool destIsPtr = DestType->isAnyPointerType() ||
1892 DestType->isBlockPointerType();
1893 bool srcIsPtr = SrcType->isAnyPointerType() ||
1894 SrcType->isBlockPointerType();
1895 if (!destIsPtr && !srcIsPtr) {
1896 // Except for std::nullptr_t->integer and lvalue->reference, which are
1897 // handled above, at least one of the two arguments must be a pointer.
1898 return TC_NotApplicable;
1901 if (DestType->isIntegralType(Self.Context)) {
1902 assert(srcIsPtr && "One type must be a pointer");
1903 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1904 // type large enough to hold it; except in Microsoft mode, where the
1905 // integral type size doesn't matter (except we don't allow bool).
1906 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1907 !DestType->isBooleanType();
1908 if ((Self.Context.getTypeSize(SrcType) >
1909 Self.Context.getTypeSize(DestType)) &&
1910 !MicrosoftException) {
1911 msg = diag::err_bad_reinterpret_cast_small_int;
1914 Kind = CK_PointerToIntegral;
1918 if (SrcType->isIntegralOrEnumerationType()) {
1919 assert(destIsPtr && "One type must be a pointer");
1920 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1922 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1923 // converted to a pointer.
1924 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1925 // necessarily converted to a null pointer value.]
1926 Kind = CK_IntegralToPointer;
1930 if (!destIsPtr || !srcIsPtr) {
1931 // With the valid non-pointer conversions out of the way, we can be even
1933 return TC_NotApplicable;
1936 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1937 // The C-style cast operator can.
1938 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1939 /*CheckObjCLifetime=*/CStyle)) {
1940 msg = diag::err_bad_cxx_cast_qualifiers_away;
1944 // Cannot convert between block pointers and Objective-C object pointers.
1945 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1946 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1947 return TC_NotApplicable;
1950 Kind = CK_LValueBitCast;
1951 } else if (DestType->isObjCObjectPointerType()) {
1952 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
1953 } else if (DestType->isBlockPointerType()) {
1954 if (!SrcType->isBlockPointerType()) {
1955 Kind = CK_AnyPointerToBlockPointerCast;
1963 // Any pointer can be cast to an Objective-C pointer type with a C-style
1965 if (CStyle && DestType->isObjCObjectPointerType()) {
1969 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1971 // Not casting away constness, so the only remaining check is for compatible
1972 // pointer categories.
1974 if (SrcType->isFunctionPointerType()) {
1975 if (DestType->isFunctionPointerType()) {
1976 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1977 // a pointer to a function of a different type.
1981 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1982 // an object type or vice versa is conditionally-supported.
1983 // Compilers support it in C++03 too, though, because it's necessary for
1984 // casting the return value of dlsym() and GetProcAddress().
1985 // FIXME: Conditionally-supported behavior should be configurable in the
1986 // TargetInfo or similar.
1987 Self.Diag(OpRange.getBegin(),
1988 Self.getLangOpts().CPlusPlus11 ?
1989 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1994 if (DestType->isFunctionPointerType()) {
1996 Self.Diag(OpRange.getBegin(),
1997 Self.getLangOpts().CPlusPlus11 ?
1998 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2003 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2004 // a pointer to an object of different type.
2005 // Void pointers are not specified, but supported by every compiler out there.
2006 // So we finish by allowing everything that remains - it's got to be two
2011 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2012 bool ListInitialization) {
2013 // Handle placeholders.
2014 if (isPlaceholder()) {
2015 // C-style casts can resolve __unknown_any types.
2016 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2017 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2018 SrcExpr.get(), Kind,
2019 ValueKind, BasePath);
2023 checkNonOverloadPlaceholders();
2024 if (SrcExpr.isInvalid())
2028 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2029 // This test is outside everything else because it's the only case where
2030 // a non-lvalue-reference target type does not lead to decay.
2031 if (DestType->isVoidType()) {
2034 if (claimPlaceholder(BuiltinType::Overload)) {
2035 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2036 SrcExpr, /* Decay Function to ptr */ false,
2037 /* Complain */ true, DestRange, DestType,
2038 diag::err_bad_cstyle_cast_overload);
2039 if (SrcExpr.isInvalid())
2043 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2047 // If the type is dependent, we won't do any other semantic analysis now.
2048 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2049 SrcExpr.get()->isValueDependent()) {
2050 assert(Kind == CK_Dependent);
2054 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2055 !isPlaceholder(BuiltinType::Overload)) {
2056 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2057 if (SrcExpr.isInvalid())
2061 // AltiVec vector initialization with a single literal.
2062 if (const VectorType *vecTy = DestType->getAs<VectorType>())
2063 if (vecTy->getVectorKind() == VectorType::AltiVecVector
2064 && (SrcExpr.get()->getType()->isIntegerType()
2065 || SrcExpr.get()->getType()->isFloatingType())) {
2066 Kind = CK_VectorSplat;
2070 // C++ [expr.cast]p5: The conversions performed by
2073 // - a static_cast followed by a const_cast,
2074 // - a reinterpret_cast, or
2075 // - a reinterpret_cast followed by a const_cast,
2076 // can be performed using the cast notation of explicit type conversion.
2077 // [...] If a conversion can be interpreted in more than one of the ways
2078 // listed above, the interpretation that appears first in the list is used,
2079 // even if a cast resulting from that interpretation is ill-formed.
2080 // In plain language, this means trying a const_cast ...
2081 unsigned msg = diag::err_bad_cxx_cast_generic;
2082 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2083 /*CStyle*/true, msg);
2084 if (SrcExpr.isInvalid())
2086 if (tcr == TC_Success)
2089 Sema::CheckedConversionKind CCK
2090 = FunctionalStyle? Sema::CCK_FunctionalCast
2091 : Sema::CCK_CStyleCast;
2092 if (tcr == TC_NotApplicable) {
2093 // ... or if that is not possible, a static_cast, ignoring const, ...
2094 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2095 msg, Kind, BasePath, ListInitialization);
2096 if (SrcExpr.isInvalid())
2099 if (tcr == TC_NotApplicable) {
2100 // ... and finally a reinterpret_cast, ignoring const.
2101 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2102 OpRange, msg, Kind);
2103 if (SrcExpr.isInvalid())
2108 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
2109 checkObjCARCConversion(CCK);
2111 if (tcr != TC_Success && msg != 0) {
2112 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2113 DeclAccessPair Found;
2114 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2119 // If DestType is a function type (not to be confused with the function
2120 // pointer type), it will be possible to resolve the function address,
2121 // but the type cast should be considered as failure.
2122 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2123 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2124 << OE->getName() << DestType << OpRange
2125 << OE->getQualifierLoc().getSourceRange();
2126 Self.NoteAllOverloadCandidates(SrcExpr.get());
2129 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2130 OpRange, SrcExpr.get(), DestType, ListInitialization);
2132 } else if (Kind == CK_BitCast) {
2136 // Clear out SrcExpr if there was a fatal error.
2137 if (tcr != TC_Success)
2138 SrcExpr = ExprError();
2141 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2142 /// non-matching type. Such as enum function call to int, int call to
2143 /// pointer; etc. Cast to 'void' is an exception.
2144 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2145 QualType DestType) {
2146 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2147 SrcExpr.get()->getExprLoc()))
2150 if (!isa<CallExpr>(SrcExpr.get()))
2153 QualType SrcType = SrcExpr.get()->getType();
2154 if (DestType.getUnqualifiedType()->isVoidType())
2156 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2157 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2159 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2160 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2161 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2163 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2165 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2167 if (SrcType->isComplexType() && DestType->isComplexType())
2169 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2172 Self.Diag(SrcExpr.get()->getExprLoc(),
2173 diag::warn_bad_function_cast)
2174 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2177 /// Check the semantics of a C-style cast operation, in C.
2178 void CastOperation::CheckCStyleCast() {
2179 assert(!Self.getLangOpts().CPlusPlus);
2181 // C-style casts can resolve __unknown_any types.
2182 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2183 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2184 SrcExpr.get(), Kind,
2185 ValueKind, BasePath);
2189 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2190 // type needs to be scalar.
2191 if (DestType->isVoidType()) {
2192 // We don't necessarily do lvalue-to-rvalue conversions on this.
2193 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2194 if (SrcExpr.isInvalid())
2197 // Cast to void allows any expr type.
2202 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2203 if (SrcExpr.isInvalid())
2205 QualType SrcType = SrcExpr.get()->getType();
2207 assert(!SrcType->isPlaceholderType());
2209 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2210 // address space B is illegal.
2211 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2212 SrcType->isPointerType()) {
2213 const PointerType *DestPtr = DestType->getAs<PointerType>();
2214 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
2215 Self.Diag(OpRange.getBegin(),
2216 diag::err_typecheck_incompatible_address_space)
2217 << SrcType << DestType << Sema::AA_Casting
2218 << SrcExpr.get()->getSourceRange();
2219 SrcExpr = ExprError();
2224 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2225 diag::err_typecheck_cast_to_incomplete)) {
2226 SrcExpr = ExprError();
2230 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2231 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2233 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2234 // GCC struct/union extension: allow cast to self.
2235 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2236 << DestType << SrcExpr.get()->getSourceRange();
2241 // GCC's cast to union extension.
2242 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2243 RecordDecl *RD = DestRecordTy->getDecl();
2244 RecordDecl::field_iterator Field, FieldEnd;
2245 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2246 Field != FieldEnd; ++Field) {
2247 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2248 !Field->isUnnamedBitfield()) {
2249 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2250 << SrcExpr.get()->getSourceRange();
2254 if (Field == FieldEnd) {
2255 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2256 << SrcType << SrcExpr.get()->getSourceRange();
2257 SrcExpr = ExprError();
2264 // Reject any other conversions to non-scalar types.
2265 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2266 << DestType << SrcExpr.get()->getSourceRange();
2267 SrcExpr = ExprError();
2271 // The type we're casting to is known to be a scalar or vector.
2273 // Require the operand to be a scalar or vector.
2274 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2275 Self.Diag(SrcExpr.get()->getExprLoc(),
2276 diag::err_typecheck_expect_scalar_operand)
2277 << SrcType << SrcExpr.get()->getSourceRange();
2278 SrcExpr = ExprError();
2282 if (DestType->isExtVectorType()) {
2283 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2287 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2288 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2289 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2290 Kind = CK_VectorSplat;
2291 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2292 SrcExpr = ExprError();
2297 if (SrcType->isVectorType()) {
2298 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2299 SrcExpr = ExprError();
2303 // The source and target types are both scalars, i.e.
2304 // - arithmetic types (fundamental, enum, and complex)
2305 // - all kinds of pointers
2306 // Note that member pointers were filtered out with C++, above.
2308 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2309 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2310 SrcExpr = ExprError();
2314 // If either type is a pointer, the other type has to be either an
2315 // integer or a pointer.
2316 if (!DestType->isArithmeticType()) {
2317 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2318 Self.Diag(SrcExpr.get()->getExprLoc(),
2319 diag::err_cast_pointer_from_non_pointer_int)
2320 << SrcType << SrcExpr.get()->getSourceRange();
2321 SrcExpr = ExprError();
2324 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2326 } else if (!SrcType->isArithmeticType()) {
2327 if (!DestType->isIntegralType(Self.Context) &&
2328 DestType->isArithmeticType()) {
2329 Self.Diag(SrcExpr.get()->getLocStart(),
2330 diag::err_cast_pointer_to_non_pointer_int)
2331 << DestType << SrcExpr.get()->getSourceRange();
2332 SrcExpr = ExprError();
2337 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2338 if (DestType->isHalfType()) {
2339 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2340 << DestType << SrcExpr.get()->getSourceRange();
2341 SrcExpr = ExprError();
2346 // ARC imposes extra restrictions on casts.
2347 if (Self.getLangOpts().ObjCAutoRefCount) {
2348 checkObjCARCConversion(Sema::CCK_CStyleCast);
2349 if (SrcExpr.isInvalid())
2352 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2353 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2354 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2355 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2356 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2357 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2358 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2359 Self.Diag(SrcExpr.get()->getLocStart(),
2360 diag::err_typecheck_incompatible_ownership)
2361 << SrcType << DestType << Sema::AA_Casting
2362 << SrcExpr.get()->getSourceRange();
2367 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2368 Self.Diag(SrcExpr.get()->getLocStart(),
2369 diag::err_arc_convesion_of_weak_unavailable)
2370 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2371 SrcExpr = ExprError();
2376 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2377 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2378 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2379 if (SrcExpr.isInvalid())
2382 if (Kind == CK_BitCast)
2386 QualType TheOffendingSrcType, TheOffendingDestType;
2387 Qualifiers CastAwayQualifiers;
2388 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
2389 CastsAwayConstness(Self, SrcType, DestType, true, false,
2390 &TheOffendingSrcType, &TheOffendingDestType,
2391 &CastAwayQualifiers)) {
2392 int qualifiers = -1;
2393 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2395 } else if (CastAwayQualifiers.hasConst()) {
2397 } else if (CastAwayQualifiers.hasVolatile()) {
2400 // This is a variant of int **x; const int **y = (const int **)x;
2401 if (qualifiers == -1)
2402 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
2403 SrcType << DestType;
2405 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
2406 TheOffendingSrcType << TheOffendingDestType << qualifiers;
2410 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2411 TypeSourceInfo *CastTypeInfo,
2412 SourceLocation RPLoc,
2414 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2415 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2416 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2418 if (getLangOpts().CPlusPlus) {
2419 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2420 isa<InitListExpr>(CastExpr));
2422 Op.CheckCStyleCast();
2425 if (Op.SrcExpr.isInvalid())
2428 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2429 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
2430 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2433 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2434 SourceLocation LPLoc,
2436 SourceLocation RPLoc) {
2437 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2438 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2439 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2440 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2442 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2443 if (Op.SrcExpr.isInvalid())
2446 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2447 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
2449 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2450 Op.ValueKind, CastTypeInfo, Op.Kind,
2451 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));