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/Sema/Initialization.h"
25 #include "llvm/ADT/SmallVector.h"
27 using namespace clang;
32 TC_NotApplicable, ///< The cast method is not applicable.
33 TC_Success, ///< The cast method is appropriate and successful.
34 TC_Failed ///< The cast method is appropriate, but failed. A
35 ///< diagnostic has been emitted.
39 CT_Const, ///< const_cast
40 CT_Static, ///< static_cast
41 CT_Reinterpret, ///< reinterpret_cast
42 CT_Dynamic, ///< dynamic_cast
43 CT_CStyle, ///< (Type)expr
44 CT_Functional ///< Type(expr)
48 struct CastOperation {
49 CastOperation(Sema &S, QualType destType, ExprResult src)
50 : Self(S), SrcExpr(src), DestType(destType),
51 ResultType(destType.getNonLValueExprType(S.Context)),
52 ValueKind(Expr::getValueKindForType(destType)),
53 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
55 if (const BuiltinType *placeholder =
56 src.get()->getType()->getAsPlaceholderType()) {
57 PlaceholderKind = placeholder->getKind();
59 PlaceholderKind = (BuiltinType::Kind) 0;
67 ExprValueKind ValueKind;
69 BuiltinType::Kind PlaceholderKind;
71 bool IsARCUnbridgedCast;
74 SourceRange DestRange;
76 // Top-level semantics-checking routines.
77 void CheckConstCast();
78 void CheckReinterpretCast();
79 void CheckStaticCast();
80 void CheckDynamicCast();
81 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
82 void CheckCStyleCast();
84 /// Complete an apparently-successful cast operation that yields
85 /// the given expression.
86 ExprResult complete(CastExpr *castExpr) {
87 // If this is an unbridged cast, wrap the result in an implicit
88 // cast that yields the unbridged-cast placeholder type.
89 if (IsARCUnbridgedCast) {
90 castExpr = ImplicitCastExpr::Create(Self.Context,
91 Self.Context.ARCUnbridgedCastTy,
92 CK_Dependent, castExpr, 0,
93 castExpr->getValueKind());
95 return Self.Owned(castExpr);
98 // Internal convenience methods.
100 /// Try to handle the given placeholder expression kind. Return
101 /// true if the source expression has the appropriate placeholder
102 /// kind. A placeholder can only be claimed once.
103 bool claimPlaceholder(BuiltinType::Kind K) {
104 if (PlaceholderKind != K) return false;
106 PlaceholderKind = (BuiltinType::Kind) 0;
110 bool isPlaceholder() const {
111 return PlaceholderKind != 0;
113 bool isPlaceholder(BuiltinType::Kind K) const {
114 return PlaceholderKind == K;
117 void checkCastAlign() {
118 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
121 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
122 assert(Self.getLangOpts().ObjCAutoRefCount);
124 Expr *src = SrcExpr.get();
125 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127 IsARCUnbridgedCast = true;
131 /// Check for and handle non-overload placeholder expressions.
132 void checkNonOverloadPlaceholders() {
133 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
136 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
137 if (SrcExpr.isInvalid())
139 PlaceholderKind = (BuiltinType::Kind) 0;
144 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145 bool CheckCVR, bool CheckObjCLifetime);
147 // The Try functions attempt a specific way of casting. If they succeed, they
148 // return TC_Success. If their way of casting is not appropriate for the given
149 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
150 // to emit if no other way succeeds. If their way of casting is appropriate but
151 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
152 // they emit a specialized diagnostic.
153 // All diagnostics returned by these functions must expect the same three
155 // %0: Cast Type (a value from the CastType enumeration)
157 // %2: Destination Type
158 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
159 QualType DestType, bool CStyle,
161 CXXCastPath &BasePath,
163 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
164 QualType DestType, bool CStyle,
165 const SourceRange &OpRange,
168 CXXCastPath &BasePath);
169 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170 QualType DestType, bool CStyle,
171 const SourceRange &OpRange,
174 CXXCastPath &BasePath);
175 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176 CanQualType DestType, bool CStyle,
177 const SourceRange &OpRange,
178 QualType OrigSrcType,
179 QualType OrigDestType, unsigned &msg,
181 CXXCastPath &BasePath);
182 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
184 QualType DestType,bool CStyle,
185 const SourceRange &OpRange,
188 CXXCastPath &BasePath);
190 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
192 Sema::CheckedConversionKind CCK,
193 const SourceRange &OpRange,
194 unsigned &msg, CastKind &Kind,
195 bool ListInitialization);
196 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
198 Sema::CheckedConversionKind CCK,
199 const SourceRange &OpRange,
200 unsigned &msg, CastKind &Kind,
201 CXXCastPath &BasePath,
202 bool ListInitialization);
203 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
204 QualType DestType, bool CStyle,
206 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
207 QualType DestType, bool CStyle,
208 const SourceRange &OpRange,
213 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
215 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
216 SourceLocation LAngleBracketLoc, Declarator &D,
217 SourceLocation RAngleBracketLoc,
218 SourceLocation LParenLoc, Expr *E,
219 SourceLocation RParenLoc) {
221 assert(!D.isInvalidType());
223 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
224 if (D.isInvalidType())
227 if (getLangOpts().CPlusPlus) {
228 // Check that there are no default arguments (C++ only).
229 CheckExtraCXXDefaultArguments(D);
232 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
233 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
234 SourceRange(LParenLoc, RParenLoc));
238 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
239 TypeSourceInfo *DestTInfo, Expr *E,
240 SourceRange AngleBrackets, SourceRange Parens) {
241 ExprResult Ex = Owned(E);
242 QualType DestType = DestTInfo->getType();
244 // If the type is dependent, we won't do the semantic analysis now.
245 // FIXME: should we check this in a more fine-grained manner?
246 bool TypeDependent = DestType->isDependentType() ||
247 Ex.get()->isTypeDependent() ||
248 Ex.get()->isValueDependent();
250 CastOperation Op(*this, DestType, E);
251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252 Op.DestRange = AngleBrackets;
255 default: llvm_unreachable("Unknown C++ cast!");
257 case tok::kw_const_cast:
258 if (!TypeDependent) {
260 if (Op.SrcExpr.isInvalid())
263 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
264 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
265 OpLoc, Parens.getEnd(),
268 case tok::kw_dynamic_cast: {
269 if (!TypeDependent) {
270 Op.CheckDynamicCast();
271 if (Op.SrcExpr.isInvalid())
274 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
275 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
276 &Op.BasePath, DestTInfo,
277 OpLoc, Parens.getEnd(),
280 case tok::kw_reinterpret_cast: {
281 if (!TypeDependent) {
282 Op.CheckReinterpretCast();
283 if (Op.SrcExpr.isInvalid())
286 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
287 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
292 case tok::kw_static_cast: {
293 if (!TypeDependent) {
294 Op.CheckStaticCast();
295 if (Op.SrcExpr.isInvalid())
299 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
300 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
301 &Op.BasePath, DestTInfo,
302 OpLoc, Parens.getEnd(),
308 /// Try to diagnose a failed overloaded cast. Returns true if
309 /// diagnostics were emitted.
310 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
311 SourceRange range, Expr *src,
313 bool listInitialization) {
315 // These cast kinds don't consider user-defined conversions.
328 QualType srcType = src->getType();
329 if (!destType->isRecordType() && !srcType->isRecordType())
332 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
333 InitializationKind initKind
334 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
335 range, listInitialization)
336 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
338 : InitializationKind::CreateCast(/*type range?*/ range);
339 InitializationSequence sequence(S, entity, initKind, src);
341 assert(sequence.Failed() && "initialization succeeded on second try?");
342 switch (sequence.getFailureKind()) {
343 default: return false;
345 case InitializationSequence::FK_ConstructorOverloadFailed:
346 case InitializationSequence::FK_UserConversionOverloadFailed:
350 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
353 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
355 switch (sequence.getFailedOverloadResult()) {
356 case OR_Success: llvm_unreachable("successful failed overload");
357 case OR_No_Viable_Function:
358 if (candidates.empty())
359 msg = diag::err_ovl_no_conversion_in_cast;
361 msg = diag::err_ovl_no_viable_conversion_in_cast;
362 howManyCandidates = OCD_AllCandidates;
366 msg = diag::err_ovl_ambiguous_conversion_in_cast;
367 howManyCandidates = OCD_ViableCandidates;
371 msg = diag::err_ovl_deleted_conversion_in_cast;
372 howManyCandidates = OCD_ViableCandidates;
376 S.Diag(range.getBegin(), msg)
377 << CT << srcType << destType
378 << range << src->getSourceRange();
380 candidates.NoteCandidates(S, howManyCandidates, src);
385 /// Diagnose a failed cast.
386 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
387 SourceRange opRange, Expr *src, QualType destType,
388 bool listInitialization) {
389 if (msg == diag::err_bad_cxx_cast_generic &&
390 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
394 S.Diag(opRange.getBegin(), msg) << castType
395 << src->getType() << destType << opRange << src->getSourceRange();
398 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
399 /// this removes one level of indirection from both types, provided that they're
400 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
401 /// this one doesn't care if the two pointers-to-member don't point into the
402 /// same class. This is because CastsAwayConstness doesn't care.
403 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
404 const PointerType *T1PtrType = T1->getAs<PointerType>(),
405 *T2PtrType = T2->getAs<PointerType>();
406 if (T1PtrType && T2PtrType) {
407 T1 = T1PtrType->getPointeeType();
408 T2 = T2PtrType->getPointeeType();
411 const ObjCObjectPointerType *T1ObjCPtrType =
412 T1->getAs<ObjCObjectPointerType>(),
414 T2->getAs<ObjCObjectPointerType>();
417 T1 = T1ObjCPtrType->getPointeeType();
418 T2 = T2ObjCPtrType->getPointeeType();
421 else if (T2PtrType) {
422 T1 = T1ObjCPtrType->getPointeeType();
423 T2 = T2PtrType->getPointeeType();
427 else if (T2ObjCPtrType) {
429 T2 = T2ObjCPtrType->getPointeeType();
430 T1 = T1PtrType->getPointeeType();
435 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
436 *T2MPType = T2->getAs<MemberPointerType>();
437 if (T1MPType && T2MPType) {
438 T1 = T1MPType->getPointeeType();
439 T2 = T2MPType->getPointeeType();
443 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
444 *T2BPType = T2->getAs<BlockPointerType>();
445 if (T1BPType && T2BPType) {
446 T1 = T1BPType->getPointeeType();
447 T2 = T2BPType->getPointeeType();
454 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
455 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
456 /// the cast checkers. Both arguments must denote pointer (possibly to member)
459 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
461 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
463 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
464 bool CheckCVR, bool CheckObjCLifetime) {
465 // If the only checking we care about is for Objective-C lifetime qualifiers,
466 // and we're not in ARC mode, there's nothing to check.
467 if (!CheckCVR && CheckObjCLifetime &&
468 !Self.Context.getLangOpts().ObjCAutoRefCount)
471 // Casting away constness is defined in C++ 5.2.11p8 with reference to
472 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
473 // the rules are non-trivial. So first we construct Tcv *...cv* as described
475 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
476 SrcType->isBlockPointerType()) &&
477 "Source type is not pointer or pointer to member.");
478 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
479 DestType->isBlockPointerType()) &&
480 "Destination type is not pointer or pointer to member.");
482 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
483 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
484 SmallVector<Qualifiers, 8> cv1, cv2;
486 // Find the qualifiers. We only care about cvr-qualifiers for the
487 // purpose of this check, because other qualifiers (address spaces,
488 // Objective-C GC, etc.) are part of the type's identity.
489 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
490 // Determine the relevant qualifiers at this level.
491 Qualifiers SrcQuals, DestQuals;
492 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
493 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
495 Qualifiers RetainedSrcQuals, RetainedDestQuals;
497 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
498 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
501 if (CheckObjCLifetime &&
502 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
505 cv1.push_back(RetainedSrcQuals);
506 cv2.push_back(RetainedDestQuals);
511 // Construct void pointers with those qualifiers (in reverse order of
512 // unwrapping, of course).
513 QualType SrcConstruct = Self.Context.VoidTy;
514 QualType DestConstruct = Self.Context.VoidTy;
515 ASTContext &Context = Self.Context;
516 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
518 i1 != cv1.rend(); ++i1, ++i2) {
520 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
522 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
525 // Test if they're compatible.
526 bool ObjCLifetimeConversion;
527 return SrcConstruct != DestConstruct &&
528 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
529 ObjCLifetimeConversion);
532 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
533 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
534 /// checked downcasts in class hierarchies.
535 void CastOperation::CheckDynamicCast() {
536 if (ValueKind == VK_RValue)
537 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
538 else if (isPlaceholder())
539 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
540 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
543 QualType OrigSrcType = SrcExpr.get()->getType();
544 QualType DestType = Self.Context.getCanonicalType(this->DestType);
546 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
547 // or "pointer to cv void".
549 QualType DestPointee;
550 const PointerType *DestPointer = DestType->getAs<PointerType>();
551 const ReferenceType *DestReference = 0;
553 DestPointee = DestPointer->getPointeeType();
554 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
555 DestPointee = DestReference->getPointeeType();
557 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
558 << this->DestType << DestRange;
559 SrcExpr = ExprError();
563 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
564 if (DestPointee->isVoidType()) {
565 assert(DestPointer && "Reference to void is not possible");
566 } else if (DestRecord) {
567 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
568 diag::err_bad_dynamic_cast_incomplete,
570 SrcExpr = ExprError();
574 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
575 << DestPointee.getUnqualifiedType() << DestRange;
576 SrcExpr = ExprError();
580 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
581 // complete class type, [...]. If T is an lvalue reference type, v shall be
582 // an lvalue of a complete class type, [...]. If T is an rvalue reference
583 // type, v shall be an expression having a complete class type, [...]
584 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
587 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
588 SrcPointee = SrcPointer->getPointeeType();
590 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
591 << OrigSrcType << SrcExpr.get()->getSourceRange();
592 SrcExpr = ExprError();
595 } else if (DestReference->isLValueReferenceType()) {
596 if (!SrcExpr.get()->isLValue()) {
597 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
598 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
600 SrcPointee = SrcType;
602 SrcPointee = SrcType;
605 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
607 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
608 diag::err_bad_dynamic_cast_incomplete,
610 SrcExpr = ExprError();
614 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
615 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
616 SrcExpr = ExprError();
620 assert((DestPointer || DestReference) &&
621 "Bad destination non-ptr/ref slipped through.");
622 assert((DestRecord || DestPointee->isVoidType()) &&
623 "Bad destination pointee slipped through.");
624 assert(SrcRecord && "Bad source pointee slipped through.");
626 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
627 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
628 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
629 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
630 SrcExpr = ExprError();
634 // C++ 5.2.7p3: If the type of v is the same as the required result type,
636 if (DestRecord == SrcRecord) {
642 // Upcasts are resolved statically.
643 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
644 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
645 OpRange.getBegin(), OpRange,
647 SrcExpr = ExprError();
651 Kind = CK_DerivedToBase;
653 // If we are casting to or through a virtual base class, we need a
655 if (Self.BasePathInvolvesVirtualBase(BasePath))
656 Self.MarkVTableUsed(OpRange.getBegin(),
657 cast<CXXRecordDecl>(SrcRecord->getDecl()));
661 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
662 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
663 assert(SrcDecl && "Definition missing");
664 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
665 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
666 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
667 SrcExpr = ExprError();
669 Self.MarkVTableUsed(OpRange.getBegin(),
670 cast<CXXRecordDecl>(SrcRecord->getDecl()));
672 // dynamic_cast is not available with -fno-rtti.
673 // As an exception, dynamic_cast to void* is available because it doesn't
675 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
676 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
677 SrcExpr = ExprError();
681 // Done. Everything else is run-time checks.
685 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
686 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
688 /// const char *str = "literal";
689 /// legacy_function(const_cast\<char*\>(str));
690 void CastOperation::CheckConstCast() {
691 if (ValueKind == VK_RValue)
692 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
693 else if (isPlaceholder())
694 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
695 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
698 unsigned msg = diag::err_bad_cxx_cast_generic;
699 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
701 Self.Diag(OpRange.getBegin(), msg) << CT_Const
702 << SrcExpr.get()->getType() << DestType << OpRange;
703 SrcExpr = ExprError();
707 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
708 /// or downcast between respective pointers or references.
709 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
711 SourceRange OpRange) {
712 QualType SrcType = SrcExpr->getType();
713 // When casting from pointer or reference, get pointee type; use original
715 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
716 const CXXRecordDecl *SrcRD =
717 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
719 // Examining subobjects for records is only possible if the complete and
720 // valid definition is available. Also, template instantiation is not
722 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
725 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
727 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
735 CXXBasePaths BasePaths;
737 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
738 ReinterpretKind = ReinterpretUpcast;
739 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
740 ReinterpretKind = ReinterpretDowncast;
744 bool VirtualBase = true;
745 bool NonZeroOffset = false;
746 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
749 const CXXBasePath &Path = *I;
750 CharUnits Offset = CharUnits::Zero();
751 bool IsVirtual = false;
752 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
753 IElem != EElem; ++IElem) {
754 IsVirtual = IElem->Base->isVirtual();
757 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
758 assert(BaseRD && "Base type should be a valid unqualified class type");
759 // Don't check if any base has invalid declaration or has no definition
760 // since it has no layout info.
761 const CXXRecordDecl *Class = IElem->Class,
762 *ClassDefinition = Class->getDefinition();
763 if (Class->isInvalidDecl() || !ClassDefinition ||
764 !ClassDefinition->isCompleteDefinition())
767 const ASTRecordLayout &DerivedLayout =
768 Self.Context.getASTRecordLayout(Class);
769 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
772 // Don't warn if any path is a non-virtually derived base at offset zero.
775 // Offset makes sense only for non-virtual bases.
777 NonZeroOffset = true;
779 VirtualBase = VirtualBase && IsVirtual;
782 (void) NonZeroOffset; // Silence set but not used warning.
783 assert((VirtualBase || NonZeroOffset) &&
784 "Should have returned if has non-virtual base with zero offset");
787 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
788 QualType DerivedType =
789 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
791 SourceLocation BeginLoc = OpRange.getBegin();
792 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
793 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
795 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
796 << int(ReinterpretKind)
797 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
800 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
802 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
804 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
805 void CastOperation::CheckReinterpretCast() {
806 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
807 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
809 checkNonOverloadPlaceholders();
810 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
813 unsigned msg = diag::err_bad_cxx_cast_generic;
815 TryReinterpretCast(Self, SrcExpr, DestType,
816 /*CStyle*/false, OpRange, msg, Kind);
817 if (tcr != TC_Success && msg != 0)
819 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
821 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
822 //FIXME: &f<int>; is overloaded and resolvable
823 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
824 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
825 << DestType << OpRange;
826 Self.NoteAllOverloadCandidates(SrcExpr.get());
829 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
830 DestType, /*listInitialization=*/false);
832 SrcExpr = ExprError();
833 } else if (tcr == TC_Success) {
834 if (Self.getLangOpts().ObjCAutoRefCount)
835 checkObjCARCConversion(Sema::CCK_OtherCast);
836 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
841 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
842 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
843 /// implicit conversions explicit and getting rid of data loss warnings.
844 void CastOperation::CheckStaticCast() {
845 if (isPlaceholder()) {
846 checkNonOverloadPlaceholders();
847 if (SrcExpr.isInvalid())
851 // This test is outside everything else because it's the only case where
852 // a non-lvalue-reference target type does not lead to decay.
853 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
854 if (DestType->isVoidType()) {
857 if (claimPlaceholder(BuiltinType::Overload)) {
858 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
859 false, // Decay Function to ptr
861 OpRange, DestType, diag::err_bad_static_cast_overload);
862 if (SrcExpr.isInvalid())
866 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
870 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
871 !isPlaceholder(BuiltinType::Overload)) {
872 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
873 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
877 unsigned msg = diag::err_bad_cxx_cast_generic;
879 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
880 Kind, BasePath, /*ListInitialization=*/false);
881 if (tcr != TC_Success && msg != 0) {
882 if (SrcExpr.isInvalid())
884 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
885 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
886 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
887 << oe->getName() << DestType << OpRange
888 << oe->getQualifierLoc().getSourceRange();
889 Self.NoteAllOverloadCandidates(SrcExpr.get());
891 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
892 /*listInitialization=*/false);
894 SrcExpr = ExprError();
895 } else if (tcr == TC_Success) {
896 if (Kind == CK_BitCast)
898 if (Self.getLangOpts().ObjCAutoRefCount)
899 checkObjCARCConversion(Sema::CCK_OtherCast);
900 } else if (Kind == CK_BitCast) {
905 /// TryStaticCast - Check if a static cast can be performed, and do so if
906 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
907 /// and casting away constness.
908 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
910 Sema::CheckedConversionKind CCK,
911 const SourceRange &OpRange, unsigned &msg,
912 CastKind &Kind, CXXCastPath &BasePath,
913 bool ListInitialization) {
914 // Determine whether we have the semantics of a C-style cast.
916 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
918 // The order the tests is not entirely arbitrary. There is one conversion
919 // that can be handled in two different ways. Given:
921 // struct B : public A {
925 // the cast static_cast<const B&>(a) could be seen as either a static
926 // reference downcast, or an explicit invocation of the user-defined
927 // conversion using B's conversion constructor.
928 // DR 427 specifies that the downcast is to be applied here.
930 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
931 // Done outside this function.
935 // C++ 5.2.9p5, reference downcast.
936 // See the function for details.
937 // DR 427 specifies that this is to be applied before paragraph 2.
938 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
939 OpRange, msg, Kind, BasePath);
940 if (tcr != TC_NotApplicable)
943 // C++0x [expr.static.cast]p3:
944 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
945 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
946 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
948 if (tcr != TC_NotApplicable)
951 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
952 // [...] if the declaration "T t(e);" is well-formed, [...].
953 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
954 Kind, ListInitialization);
955 if (SrcExpr.isInvalid())
957 if (tcr != TC_NotApplicable)
960 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
961 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
962 // conversions, subject to further restrictions.
963 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
964 // of qualification conversions impossible.
965 // In the CStyle case, the earlier attempt to const_cast should have taken
966 // care of reverse qualification conversions.
968 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
970 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
971 // converted to an integral type. [...] A value of a scoped enumeration type
972 // can also be explicitly converted to a floating-point type [...].
973 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
974 if (Enum->getDecl()->isScoped()) {
975 if (DestType->isBooleanType()) {
976 Kind = CK_IntegralToBoolean;
978 } else if (DestType->isIntegralType(Self.Context)) {
979 Kind = CK_IntegralCast;
981 } else if (DestType->isRealFloatingType()) {
982 Kind = CK_IntegralToFloating;
988 // Reverse integral promotion/conversion. All such conversions are themselves
989 // again integral promotions or conversions and are thus already handled by
990 // p2 (TryDirectInitialization above).
991 // (Note: any data loss warnings should be suppressed.)
992 // The exception is the reverse of enum->integer, i.e. integer->enum (and
993 // enum->enum). See also C++ 5.2.9p7.
994 // The same goes for reverse floating point promotion/conversion and
995 // floating-integral conversions. Again, only floating->enum is relevant.
996 if (DestType->isEnumeralType()) {
997 if (SrcType->isIntegralOrEnumerationType()) {
998 Kind = CK_IntegralCast;
1000 } else if (SrcType->isRealFloatingType()) {
1001 Kind = CK_FloatingToIntegral;
1006 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1007 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1008 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1010 if (tcr != TC_NotApplicable)
1013 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1014 // conversion. C++ 5.2.9p9 has additional information.
1015 // DR54's access restrictions apply here also.
1016 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1017 OpRange, msg, Kind, BasePath);
1018 if (tcr != TC_NotApplicable)
1021 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1022 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1023 // just the usual constness stuff.
1024 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1025 QualType SrcPointee = SrcPointer->getPointeeType();
1026 if (SrcPointee->isVoidType()) {
1027 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1028 QualType DestPointee = DestPointer->getPointeeType();
1029 if (DestPointee->isIncompleteOrObjectType()) {
1030 // This is definitely the intended conversion, but it might fail due
1031 // to a qualifier violation. Note that we permit Objective-C lifetime
1032 // and GC qualifier mismatches here.
1034 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1035 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1036 DestPointeeQuals.removeObjCGCAttr();
1037 DestPointeeQuals.removeObjCLifetime();
1038 SrcPointeeQuals.removeObjCGCAttr();
1039 SrcPointeeQuals.removeObjCLifetime();
1040 if (DestPointeeQuals != SrcPointeeQuals &&
1041 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1042 msg = diag::err_bad_cxx_cast_qualifiers_away;
1050 else if (DestType->isObjCObjectPointerType()) {
1051 // allow both c-style cast and static_cast of objective-c pointers as
1052 // they are pervasive.
1053 Kind = CK_CPointerToObjCPointerCast;
1056 else if (CStyle && DestType->isBlockPointerType()) {
1057 // allow c-style cast of void * to block pointers.
1058 Kind = CK_AnyPointerToBlockPointerCast;
1063 // Allow arbitray objective-c pointer conversion with static casts.
1064 if (SrcType->isObjCObjectPointerType() &&
1065 DestType->isObjCObjectPointerType()) {
1070 // We tried everything. Everything! Nothing works! :-(
1071 return TC_NotApplicable;
1074 /// Tests whether a conversion according to N2844 is valid.
1076 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1077 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1079 // C++0x [expr.static.cast]p3:
1080 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1081 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1082 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1084 return TC_NotApplicable;
1086 if (!SrcExpr->isGLValue())
1087 return TC_NotApplicable;
1089 // Because we try the reference downcast before this function, from now on
1090 // this is the only cast possibility, so we issue an error if we fail now.
1091 // FIXME: Should allow casting away constness if CStyle.
1093 bool ObjCConversion;
1094 bool ObjCLifetimeConversion;
1095 QualType FromType = SrcExpr->getType();
1096 QualType ToType = R->getPointeeType();
1098 FromType = FromType.getUnqualifiedType();
1099 ToType = ToType.getUnqualifiedType();
1102 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
1104 DerivedToBase, ObjCConversion,
1105 ObjCLifetimeConversion)
1106 < Sema::Ref_Compatible_With_Added_Qualification) {
1107 msg = diag::err_bad_lvalue_to_rvalue_cast;
1111 if (DerivedToBase) {
1112 Kind = CK_DerivedToBase;
1113 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1114 /*DetectVirtual=*/true);
1115 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1116 return TC_NotApplicable;
1118 Self.BuildBasePathArray(Paths, BasePath);
1125 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1127 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1128 bool CStyle, const SourceRange &OpRange,
1129 unsigned &msg, CastKind &Kind,
1130 CXXCastPath &BasePath) {
1131 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1132 // cast to type "reference to cv2 D", where D is a class derived from B,
1133 // if a valid standard conversion from "pointer to D" to "pointer to B"
1134 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1135 // In addition, DR54 clarifies that the base must be accessible in the
1136 // current context. Although the wording of DR54 only applies to the pointer
1137 // variant of this rule, the intent is clearly for it to apply to the this
1138 // conversion as well.
1140 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1141 if (!DestReference) {
1142 return TC_NotApplicable;
1144 bool RValueRef = DestReference->isRValueReferenceType();
1145 if (!RValueRef && !SrcExpr->isLValue()) {
1146 // We know the left side is an lvalue reference, so we can suggest a reason.
1147 msg = diag::err_bad_cxx_cast_rvalue;
1148 return TC_NotApplicable;
1151 QualType DestPointee = DestReference->getPointeeType();
1153 return TryStaticDowncast(Self,
1154 Self.Context.getCanonicalType(SrcExpr->getType()),
1155 Self.Context.getCanonicalType(DestPointee), CStyle,
1156 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1160 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1162 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1163 bool CStyle, const SourceRange &OpRange,
1164 unsigned &msg, CastKind &Kind,
1165 CXXCastPath &BasePath) {
1166 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1167 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1168 // is a class derived from B, if a valid standard conversion from "pointer
1169 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1171 // In addition, DR54 clarifies that the base must be accessible in the
1174 const PointerType *DestPointer = DestType->getAs<PointerType>();
1176 return TC_NotApplicable;
1179 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1181 msg = diag::err_bad_static_cast_pointer_nonpointer;
1182 return TC_NotApplicable;
1185 return TryStaticDowncast(Self,
1186 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1187 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1188 CStyle, OpRange, SrcType, DestType, msg, Kind,
1192 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1193 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1194 /// DestType is possible and allowed.
1196 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1197 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
1198 QualType OrigDestType, unsigned &msg,
1199 CastKind &Kind, CXXCastPath &BasePath) {
1200 // We can only work with complete types. But don't complain if it doesn't work
1201 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1202 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
1203 return TC_NotApplicable;
1205 // Downcast can only happen in class hierarchies, so we need classes.
1206 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1207 return TC_NotApplicable;
1210 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1211 /*DetectVirtual=*/true);
1212 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1213 return TC_NotApplicable;
1216 // Target type does derive from source type. Now we're serious. If an error
1217 // appears now, it's not ignored.
1218 // This may not be entirely in line with the standard. Take for example:
1220 // struct B : virtual A {
1226 // (void)static_cast<const B&>(*((A*)0));
1228 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1229 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1230 // However, both GCC and Comeau reject this example, and accepting it would
1231 // mean more complex code if we're to preserve the nice error message.
1232 // FIXME: Being 100% compliant here would be nice to have.
1234 // Must preserve cv, as always, unless we're in C-style mode.
1235 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1236 msg = diag::err_bad_cxx_cast_qualifiers_away;
1240 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1241 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1242 // that it builds the paths in reverse order.
1243 // To sum up: record all paths to the base and build a nice string from
1244 // them. Use it to spice up the error message.
1245 if (!Paths.isRecordingPaths()) {
1247 Paths.setRecordingPaths(true);
1248 Self.IsDerivedFrom(DestType, SrcType, Paths);
1250 std::string PathDisplayStr;
1251 std::set<unsigned> DisplayedPaths;
1252 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
1254 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1255 // We haven't displayed a path to this particular base
1256 // class subobject yet.
1257 PathDisplayStr += "\n ";
1258 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1261 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
1262 PathDisplayStr += QualType(DestType).getAsString();
1266 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1267 << QualType(SrcType).getUnqualifiedType()
1268 << QualType(DestType).getUnqualifiedType()
1269 << PathDisplayStr << OpRange;
1274 if (Paths.getDetectedVirtual() != 0) {
1275 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1276 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1277 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1283 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1286 diag::err_downcast_from_inaccessible_base)) {
1287 case Sema::AR_accessible:
1288 case Sema::AR_delayed: // be optimistic
1289 case Sema::AR_dependent: // be optimistic
1292 case Sema::AR_inaccessible:
1298 Self.BuildBasePathArray(Paths, BasePath);
1299 Kind = CK_BaseToDerived;
1303 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1304 /// C++ 5.2.9p9 is valid:
1306 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1307 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1308 /// where B is a base class of D [...].
1311 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1312 QualType DestType, bool CStyle,
1313 const SourceRange &OpRange,
1314 unsigned &msg, CastKind &Kind,
1315 CXXCastPath &BasePath) {
1316 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1318 return TC_NotApplicable;
1320 bool WasOverloadedFunction = false;
1321 DeclAccessPair FoundOverload;
1322 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1323 if (FunctionDecl *Fn
1324 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1326 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1327 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1328 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1329 WasOverloadedFunction = true;
1333 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1335 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1336 return TC_NotApplicable;
1339 // T == T, modulo cv
1340 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1341 DestMemPtr->getPointeeType()))
1342 return TC_NotApplicable;
1345 QualType SrcClass(SrcMemPtr->getClass(), 0);
1346 QualType DestClass(DestMemPtr->getClass(), 0);
1347 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1348 /*DetectVirtual=*/true);
1349 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1350 return TC_NotApplicable;
1353 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1354 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1356 Paths.setRecordingPaths(true);
1357 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1360 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1361 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1362 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1367 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1368 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1369 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1375 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1376 DestClass, SrcClass,
1378 diag::err_upcast_to_inaccessible_base)) {
1379 case Sema::AR_accessible:
1380 case Sema::AR_delayed:
1381 case Sema::AR_dependent:
1382 // Optimistically assume that the delayed and dependent cases
1386 case Sema::AR_inaccessible:
1392 if (WasOverloadedFunction) {
1393 // Resolve the address of the overloaded function again, this time
1394 // allowing complaints if something goes wrong.
1395 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1404 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1405 if (!SrcExpr.isUsable()) {
1411 Self.BuildBasePathArray(Paths, BasePath);
1412 Kind = CK_DerivedToBaseMemberPointer;
1416 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1419 /// An expression e can be explicitly converted to a type T using a
1420 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1422 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1423 Sema::CheckedConversionKind CCK,
1424 const SourceRange &OpRange, unsigned &msg,
1425 CastKind &Kind, bool ListInitialization) {
1426 if (DestType->isRecordType()) {
1427 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1428 diag::err_bad_dynamic_cast_incomplete) ||
1429 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1430 diag::err_allocation_of_abstract_type)) {
1436 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1437 InitializationKind InitKind
1438 = (CCK == Sema::CCK_CStyleCast)
1439 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1441 : (CCK == Sema::CCK_FunctionalCast)
1442 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1443 : InitializationKind::CreateCast(OpRange);
1444 Expr *SrcExprRaw = SrcExpr.get();
1445 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1447 // At this point of CheckStaticCast, if the destination is a reference,
1448 // or the expression is an overload expression this has to work.
1449 // There is no other way that works.
1450 // On the other hand, if we're checking a C-style cast, we've still got
1451 // the reinterpret_cast way.
1453 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1454 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1455 return TC_NotApplicable;
1457 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1458 if (Result.isInvalid()) {
1463 if (InitSeq.isConstructorInitialization())
1464 Kind = CK_ConstructorConversion;
1472 /// TryConstCast - See if a const_cast from source to destination is allowed,
1473 /// and perform it if it is.
1474 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1475 QualType DestType, bool CStyle,
1477 DestType = Self.Context.getCanonicalType(DestType);
1478 QualType SrcType = SrcExpr.get()->getType();
1479 bool NeedToMaterializeTemporary = false;
1481 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1483 // if a pointer to T1 can be explicitly converted to the type "pointer to
1484 // T2" using a const_cast, then the following conversions can also be
1486 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1487 // type T2 using the cast const_cast<T2&>;
1488 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1489 // type T2 using the cast const_cast<T2&&>; and
1490 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1491 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1493 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1494 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1495 // is C-style, static_cast might find a way, so we simply suggest a
1496 // message and tell the parent to keep searching.
1497 msg = diag::err_bad_cxx_cast_rvalue;
1498 return TC_NotApplicable;
1501 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1502 if (!SrcType->isRecordType()) {
1503 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1504 // this is C-style, static_cast can do this.
1505 msg = diag::err_bad_cxx_cast_rvalue;
1506 return TC_NotApplicable;
1509 // Materialize the class prvalue so that the const_cast can bind a
1511 NeedToMaterializeTemporary = true;
1514 // It's not completely clear under the standard whether we can
1515 // const_cast bit-field gl-values. Doing so would not be
1516 // intrinsically complicated, but for now, we say no for
1517 // consistency with other compilers and await the word of the
1519 if (SrcExpr.get()->refersToBitField()) {
1520 msg = diag::err_bad_cxx_cast_bitfield;
1521 return TC_NotApplicable;
1524 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1525 SrcType = Self.Context.getPointerType(SrcType);
1528 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1529 // the rules for const_cast are the same as those used for pointers.
1531 if (!DestType->isPointerType() &&
1532 !DestType->isMemberPointerType() &&
1533 !DestType->isObjCObjectPointerType()) {
1534 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1535 // was a reference type, we converted it to a pointer above.
1536 // The status of rvalue references isn't entirely clear, but it looks like
1537 // conversion to them is simply invalid.
1538 // C++ 5.2.11p3: For two pointer types [...]
1540 msg = diag::err_bad_const_cast_dest;
1541 return TC_NotApplicable;
1543 if (DestType->isFunctionPointerType() ||
1544 DestType->isMemberFunctionPointerType()) {
1545 // Cannot cast direct function pointers.
1546 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1547 // T is the ultimate pointee of source and target type.
1549 msg = diag::err_bad_const_cast_dest;
1550 return TC_NotApplicable;
1552 SrcType = Self.Context.getCanonicalType(SrcType);
1554 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1555 // completely equal.
1556 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1557 // in multi-level pointers may change, but the level count must be the same,
1558 // as must be the final pointee type.
1559 while (SrcType != DestType &&
1560 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1561 Qualifiers SrcQuals, DestQuals;
1562 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1563 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1565 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1566 // the other qualifiers (e.g., address spaces) are identical.
1567 SrcQuals.removeCVRQualifiers();
1568 DestQuals.removeCVRQualifiers();
1569 if (SrcQuals != DestQuals)
1570 return TC_NotApplicable;
1573 // Since we're dealing in canonical types, the remainder must be the same.
1574 if (SrcType != DestType)
1575 return TC_NotApplicable;
1577 if (NeedToMaterializeTemporary)
1578 // This is a const_cast from a class prvalue to an rvalue reference type.
1579 // Materialize a temporary to store the result of the conversion.
1580 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1581 SrcType, SrcExpr.take(), /*IsLValueReference*/ false,
1582 /*ExtendingDecl*/ 0);
1587 // Checks for undefined behavior in reinterpret_cast.
1588 // The cases that is checked for is:
1589 // *reinterpret_cast<T*>(&a)
1590 // reinterpret_cast<T&>(a)
1591 // where accessing 'a' as type 'T' will result in undefined behavior.
1592 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1594 SourceRange Range) {
1595 unsigned DiagID = IsDereference ?
1596 diag::warn_pointer_indirection_from_incompatible_type :
1597 diag::warn_undefined_reinterpret_cast;
1599 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
1600 DiagnosticsEngine::Ignored) {
1604 QualType SrcTy, DestTy;
1605 if (IsDereference) {
1606 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1609 SrcTy = SrcType->getPointeeType();
1610 DestTy = DestType->getPointeeType();
1612 if (!DestType->getAs<ReferenceType>()) {
1616 DestTy = DestType->getPointeeType();
1619 // Cast is compatible if the types are the same.
1620 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1623 // or one of the types is a char or void type
1624 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1625 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1628 // or one of the types is a tag type.
1629 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1633 // FIXME: Scoped enums?
1634 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1635 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1636 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1641 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1644 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1645 QualType DestType) {
1646 QualType SrcType = SrcExpr.get()->getType();
1647 if (Self.Context.hasSameType(SrcType, DestType))
1649 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1650 if (SrcPtrTy->isObjCSelType()) {
1651 QualType DT = DestType;
1652 if (isa<PointerType>(DestType))
1653 DT = DestType->getPointeeType();
1654 if (!DT.getUnqualifiedType()->isVoidType())
1655 Self.Diag(SrcExpr.get()->getExprLoc(),
1656 diag::warn_cast_pointer_from_sel)
1657 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1661 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1662 const Expr *SrcExpr, QualType DestType,
1664 QualType SrcType = SrcExpr->getType();
1666 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1667 // are not explicit design choices, but consistent with GCC's behavior.
1668 // Feel free to modify them if you've reason/evidence for an alternative.
1669 if (CStyle && SrcType->isIntegralType(Self.Context)
1670 && !SrcType->isBooleanType()
1671 && !SrcType->isEnumeralType()
1672 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1673 && Self.Context.getTypeSize(DestType) >
1674 Self.Context.getTypeSize(SrcType)) {
1675 // Separate between casts to void* and non-void* pointers.
1676 // Some APIs use (abuse) void* for something like a user context,
1677 // and often that value is an integer even if it isn't a pointer itself.
1678 // Having a separate warning flag allows users to control the warning
1679 // for their workflow.
1680 unsigned Diag = DestType->isVoidPointerType() ?
1681 diag::warn_int_to_void_pointer_cast
1682 : diag::warn_int_to_pointer_cast;
1683 Self.Diag(Loc, Diag) << SrcType << DestType;
1687 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1688 QualType DestType, bool CStyle,
1689 const SourceRange &OpRange,
1692 bool IsLValueCast = false;
1694 DestType = Self.Context.getCanonicalType(DestType);
1695 QualType SrcType = SrcExpr.get()->getType();
1697 // Is the source an overloaded name? (i.e. &foo)
1698 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1699 if (SrcType == Self.Context.OverloadTy) {
1700 // ... unless foo<int> resolves to an lvalue unambiguously.
1701 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1703 ExprResult SingleFunctionExpr = SrcExpr;
1704 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1706 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1707 ) && SingleFunctionExpr.isUsable()) {
1708 SrcExpr = SingleFunctionExpr;
1709 SrcType = SrcExpr.get()->getType();
1711 return TC_NotApplicable;
1715 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1716 if (!SrcExpr.get()->isGLValue()) {
1717 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1718 // similar comment in const_cast.
1719 msg = diag::err_bad_cxx_cast_rvalue;
1720 return TC_NotApplicable;
1724 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1725 /*isDereference=*/false, OpRange);
1728 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1729 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1730 // built-in & and * operators.
1732 const char *inappropriate = 0;
1733 switch (SrcExpr.get()->getObjectKind()) {
1736 case OK_BitField: inappropriate = "bit-field"; break;
1737 case OK_VectorComponent: inappropriate = "vector element"; break;
1738 case OK_ObjCProperty: inappropriate = "property expression"; break;
1739 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1742 if (inappropriate) {
1743 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1744 << inappropriate << DestType
1745 << OpRange << SrcExpr.get()->getSourceRange();
1746 msg = 0; SrcExpr = ExprError();
1747 return TC_NotApplicable;
1750 // This code does this transformation for the checked types.
1751 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1752 SrcType = Self.Context.getPointerType(SrcType);
1754 IsLValueCast = true;
1757 // Canonicalize source for comparison.
1758 SrcType = Self.Context.getCanonicalType(SrcType);
1760 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1761 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1762 if (DestMemPtr && SrcMemPtr) {
1763 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1764 // can be explicitly converted to an rvalue of type "pointer to member
1765 // of Y of type T2" if T1 and T2 are both function types or both object
1767 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1768 SrcMemPtr->getPointeeType()->isFunctionType())
1769 return TC_NotApplicable;
1771 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1773 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1775 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1776 /*CheckObjCLifetime=*/CStyle)) {
1777 msg = diag::err_bad_cxx_cast_qualifiers_away;
1781 // Don't allow casting between member pointers of different sizes.
1782 if (Self.Context.getTypeSize(DestMemPtr) !=
1783 Self.Context.getTypeSize(SrcMemPtr)) {
1784 msg = diag::err_bad_cxx_cast_member_pointer_size;
1788 // A valid member pointer cast.
1789 assert(!IsLValueCast);
1790 Kind = CK_ReinterpretMemberPointer;
1794 // See below for the enumeral issue.
1795 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1796 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1797 // type large enough to hold it. A value of std::nullptr_t can be
1798 // converted to an integral type; the conversion has the same meaning
1799 // and validity as a conversion of (void*)0 to the integral type.
1800 if (Self.Context.getTypeSize(SrcType) >
1801 Self.Context.getTypeSize(DestType)) {
1802 msg = diag::err_bad_reinterpret_cast_small_int;
1805 Kind = CK_PointerToIntegral;
1809 bool destIsVector = DestType->isVectorType();
1810 bool srcIsVector = SrcType->isVectorType();
1811 if (srcIsVector || destIsVector) {
1812 // FIXME: Should this also apply to floating point types?
1813 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1814 bool destIsScalar = DestType->isIntegralType(Self.Context);
1816 // Check if this is a cast between a vector and something else.
1817 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1818 !(srcIsVector && destIsVector))
1819 return TC_NotApplicable;
1821 // If both types have the same size, we can successfully cast.
1822 if (Self.Context.getTypeSize(SrcType)
1823 == Self.Context.getTypeSize(DestType)) {
1829 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1830 else if (srcIsScalar)
1831 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1833 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1838 if (SrcType == DestType) {
1839 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1840 // restrictions, a cast to the same type is allowed so long as it does not
1841 // cast away constness. In C++98, the intent was not entirely clear here,
1842 // since all other paragraphs explicitly forbid casts to the same type.
1843 // C++11 clarifies this case with p2.
1845 // The only allowed types are: integral, enumeration, pointer, or
1846 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1848 TryCastResult Result = TC_NotApplicable;
1849 if (SrcType->isIntegralOrEnumerationType() ||
1850 SrcType->isAnyPointerType() ||
1851 SrcType->isMemberPointerType() ||
1852 SrcType->isBlockPointerType()) {
1853 Result = TC_Success;
1858 bool destIsPtr = DestType->isAnyPointerType() ||
1859 DestType->isBlockPointerType();
1860 bool srcIsPtr = SrcType->isAnyPointerType() ||
1861 SrcType->isBlockPointerType();
1862 if (!destIsPtr && !srcIsPtr) {
1863 // Except for std::nullptr_t->integer and lvalue->reference, which are
1864 // handled above, at least one of the two arguments must be a pointer.
1865 return TC_NotApplicable;
1868 if (DestType->isIntegralType(Self.Context)) {
1869 assert(srcIsPtr && "One type must be a pointer");
1870 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1871 // type large enough to hold it; except in Microsoft mode, where the
1872 // integral type size doesn't matter (except we don't allow bool).
1873 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1874 !DestType->isBooleanType();
1875 if ((Self.Context.getTypeSize(SrcType) >
1876 Self.Context.getTypeSize(DestType)) &&
1877 !MicrosoftException) {
1878 msg = diag::err_bad_reinterpret_cast_small_int;
1881 Kind = CK_PointerToIntegral;
1885 if (SrcType->isIntegralOrEnumerationType()) {
1886 assert(destIsPtr && "One type must be a pointer");
1887 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1889 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1890 // converted to a pointer.
1891 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1892 // necessarily converted to a null pointer value.]
1893 Kind = CK_IntegralToPointer;
1897 if (!destIsPtr || !srcIsPtr) {
1898 // With the valid non-pointer conversions out of the way, we can be even
1900 return TC_NotApplicable;
1903 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1904 // The C-style cast operator can.
1905 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1906 /*CheckObjCLifetime=*/CStyle)) {
1907 msg = diag::err_bad_cxx_cast_qualifiers_away;
1911 // Cannot convert between block pointers and Objective-C object pointers.
1912 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1913 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1914 return TC_NotApplicable;
1917 Kind = CK_LValueBitCast;
1918 } else if (DestType->isObjCObjectPointerType()) {
1919 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
1920 } else if (DestType->isBlockPointerType()) {
1921 if (!SrcType->isBlockPointerType()) {
1922 Kind = CK_AnyPointerToBlockPointerCast;
1930 // Any pointer can be cast to an Objective-C pointer type with a C-style
1932 if (CStyle && DestType->isObjCObjectPointerType()) {
1936 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1938 // Not casting away constness, so the only remaining check is for compatible
1939 // pointer categories.
1941 if (SrcType->isFunctionPointerType()) {
1942 if (DestType->isFunctionPointerType()) {
1943 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1944 // a pointer to a function of a different type.
1948 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1949 // an object type or vice versa is conditionally-supported.
1950 // Compilers support it in C++03 too, though, because it's necessary for
1951 // casting the return value of dlsym() and GetProcAddress().
1952 // FIXME: Conditionally-supported behavior should be configurable in the
1953 // TargetInfo or similar.
1954 Self.Diag(OpRange.getBegin(),
1955 Self.getLangOpts().CPlusPlus11 ?
1956 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1961 if (DestType->isFunctionPointerType()) {
1963 Self.Diag(OpRange.getBegin(),
1964 Self.getLangOpts().CPlusPlus11 ?
1965 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1970 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1971 // a pointer to an object of different type.
1972 // Void pointers are not specified, but supported by every compiler out there.
1973 // So we finish by allowing everything that remains - it's got to be two
1978 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1979 bool ListInitialization) {
1980 // Handle placeholders.
1981 if (isPlaceholder()) {
1982 // C-style casts can resolve __unknown_any types.
1983 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1984 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1985 SrcExpr.get(), Kind,
1986 ValueKind, BasePath);
1990 checkNonOverloadPlaceholders();
1991 if (SrcExpr.isInvalid())
1995 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1996 // This test is outside everything else because it's the only case where
1997 // a non-lvalue-reference target type does not lead to decay.
1998 if (DestType->isVoidType()) {
2001 if (claimPlaceholder(BuiltinType::Overload)) {
2002 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2003 SrcExpr, /* Decay Function to ptr */ false,
2004 /* Complain */ true, DestRange, DestType,
2005 diag::err_bad_cstyle_cast_overload);
2006 if (SrcExpr.isInvalid())
2010 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2014 // If the type is dependent, we won't do any other semantic analysis now.
2015 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2016 SrcExpr.get()->isValueDependent()) {
2017 assert(Kind == CK_Dependent);
2021 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2022 !isPlaceholder(BuiltinType::Overload)) {
2023 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2024 if (SrcExpr.isInvalid())
2028 // AltiVec vector initialization with a single literal.
2029 if (const VectorType *vecTy = DestType->getAs<VectorType>())
2030 if (vecTy->getVectorKind() == VectorType::AltiVecVector
2031 && (SrcExpr.get()->getType()->isIntegerType()
2032 || SrcExpr.get()->getType()->isFloatingType())) {
2033 Kind = CK_VectorSplat;
2037 // C++ [expr.cast]p5: The conversions performed by
2040 // - a static_cast followed by a const_cast,
2041 // - a reinterpret_cast, or
2042 // - a reinterpret_cast followed by a const_cast,
2043 // can be performed using the cast notation of explicit type conversion.
2044 // [...] If a conversion can be interpreted in more than one of the ways
2045 // listed above, the interpretation that appears first in the list is used,
2046 // even if a cast resulting from that interpretation is ill-formed.
2047 // In plain language, this means trying a const_cast ...
2048 unsigned msg = diag::err_bad_cxx_cast_generic;
2049 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2050 /*CStyle*/true, msg);
2051 if (SrcExpr.isInvalid())
2053 if (tcr == TC_Success)
2056 Sema::CheckedConversionKind CCK
2057 = FunctionalStyle? Sema::CCK_FunctionalCast
2058 : Sema::CCK_CStyleCast;
2059 if (tcr == TC_NotApplicable) {
2060 // ... or if that is not possible, a static_cast, ignoring const, ...
2061 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2062 msg, Kind, BasePath, ListInitialization);
2063 if (SrcExpr.isInvalid())
2066 if (tcr == TC_NotApplicable) {
2067 // ... and finally a reinterpret_cast, ignoring const.
2068 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2069 OpRange, msg, Kind);
2070 if (SrcExpr.isInvalid())
2075 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
2076 checkObjCARCConversion(CCK);
2078 if (tcr != TC_Success && msg != 0) {
2079 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2080 DeclAccessPair Found;
2081 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2086 assert(!Fn && "cast failed but able to resolve overload expression!!");
2090 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2091 OpRange, SrcExpr.get(), DestType, ListInitialization);
2093 } else if (Kind == CK_BitCast) {
2097 // Clear out SrcExpr if there was a fatal error.
2098 if (tcr != TC_Success)
2099 SrcExpr = ExprError();
2102 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2103 /// non-matching type. Such as enum function call to int, int call to
2104 /// pointer; etc. Cast to 'void' is an exception.
2105 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2106 QualType DestType) {
2107 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2108 SrcExpr.get()->getExprLoc())
2109 == DiagnosticsEngine::Ignored)
2112 if (!isa<CallExpr>(SrcExpr.get()))
2115 QualType SrcType = SrcExpr.get()->getType();
2116 if (DestType.getUnqualifiedType()->isVoidType())
2118 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2119 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2121 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2122 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2123 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2125 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2127 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2129 if (SrcType->isComplexType() && DestType->isComplexType())
2131 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2134 Self.Diag(SrcExpr.get()->getExprLoc(),
2135 diag::warn_bad_function_cast)
2136 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2139 /// Check the semantics of a C-style cast operation, in C.
2140 void CastOperation::CheckCStyleCast() {
2141 assert(!Self.getLangOpts().CPlusPlus);
2143 // C-style casts can resolve __unknown_any types.
2144 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2145 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2146 SrcExpr.get(), Kind,
2147 ValueKind, BasePath);
2151 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2152 // type needs to be scalar.
2153 if (DestType->isVoidType()) {
2154 // We don't necessarily do lvalue-to-rvalue conversions on this.
2155 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2156 if (SrcExpr.isInvalid())
2159 // Cast to void allows any expr type.
2164 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2165 if (SrcExpr.isInvalid())
2167 QualType SrcType = SrcExpr.get()->getType();
2169 assert(!SrcType->isPlaceholderType());
2171 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2172 diag::err_typecheck_cast_to_incomplete)) {
2173 SrcExpr = ExprError();
2177 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2178 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2180 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2181 // GCC struct/union extension: allow cast to self.
2182 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2183 << DestType << SrcExpr.get()->getSourceRange();
2188 // GCC's cast to union extension.
2189 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2190 RecordDecl *RD = DestRecordTy->getDecl();
2191 RecordDecl::field_iterator Field, FieldEnd;
2192 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2193 Field != FieldEnd; ++Field) {
2194 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2195 !Field->isUnnamedBitfield()) {
2196 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2197 << SrcExpr.get()->getSourceRange();
2201 if (Field == FieldEnd) {
2202 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2203 << SrcType << SrcExpr.get()->getSourceRange();
2204 SrcExpr = ExprError();
2211 // Reject any other conversions to non-scalar types.
2212 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2213 << DestType << SrcExpr.get()->getSourceRange();
2214 SrcExpr = ExprError();
2218 // The type we're casting to is known to be a scalar or vector.
2220 // Require the operand to be a scalar or vector.
2221 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2222 Self.Diag(SrcExpr.get()->getExprLoc(),
2223 diag::err_typecheck_expect_scalar_operand)
2224 << SrcType << SrcExpr.get()->getSourceRange();
2225 SrcExpr = ExprError();
2229 if (DestType->isExtVectorType()) {
2230 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2234 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2235 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2236 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2237 Kind = CK_VectorSplat;
2238 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2239 SrcExpr = ExprError();
2244 if (SrcType->isVectorType()) {
2245 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2246 SrcExpr = ExprError();
2250 // The source and target types are both scalars, i.e.
2251 // - arithmetic types (fundamental, enum, and complex)
2252 // - all kinds of pointers
2253 // Note that member pointers were filtered out with C++, above.
2255 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2256 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2257 SrcExpr = ExprError();
2261 // If either type is a pointer, the other type has to be either an
2262 // integer or a pointer.
2263 if (!DestType->isArithmeticType()) {
2264 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2265 Self.Diag(SrcExpr.get()->getExprLoc(),
2266 diag::err_cast_pointer_from_non_pointer_int)
2267 << SrcType << SrcExpr.get()->getSourceRange();
2268 SrcExpr = ExprError();
2271 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2273 } else if (!SrcType->isArithmeticType()) {
2274 if (!DestType->isIntegralType(Self.Context) &&
2275 DestType->isArithmeticType()) {
2276 Self.Diag(SrcExpr.get()->getLocStart(),
2277 diag::err_cast_pointer_to_non_pointer_int)
2278 << DestType << SrcExpr.get()->getSourceRange();
2279 SrcExpr = ExprError();
2284 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2285 if (DestType->isHalfType()) {
2286 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2287 << DestType << SrcExpr.get()->getSourceRange();
2288 SrcExpr = ExprError();
2293 // ARC imposes extra restrictions on casts.
2294 if (Self.getLangOpts().ObjCAutoRefCount) {
2295 checkObjCARCConversion(Sema::CCK_CStyleCast);
2296 if (SrcExpr.isInvalid())
2299 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2300 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2301 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2302 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2303 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2304 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2305 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2306 Self.Diag(SrcExpr.get()->getLocStart(),
2307 diag::err_typecheck_incompatible_ownership)
2308 << SrcType << DestType << Sema::AA_Casting
2309 << SrcExpr.get()->getSourceRange();
2314 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2315 Self.Diag(SrcExpr.get()->getLocStart(),
2316 diag::err_arc_convesion_of_weak_unavailable)
2317 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2318 SrcExpr = ExprError();
2322 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2323 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2324 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2325 if (SrcExpr.isInvalid())
2328 if (Kind == CK_BitCast)
2332 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2333 TypeSourceInfo *CastTypeInfo,
2334 SourceLocation RPLoc,
2336 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2337 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2338 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2340 if (getLangOpts().CPlusPlus) {
2341 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2342 isa<InitListExpr>(CastExpr));
2344 Op.CheckCStyleCast();
2347 if (Op.SrcExpr.isInvalid())
2350 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2351 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2352 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2355 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2356 SourceLocation LPLoc,
2358 SourceLocation RPLoc) {
2359 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2360 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2361 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2362 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2364 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2365 if (Op.SrcExpr.isInvalid())
2368 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2369 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
2371 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2372 Op.ValueKind, CastTypeInfo, Op.Kind,
2373 Op.SrcExpr.take(), &Op.BasePath, LPLoc, RPLoc));