1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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)' 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "clang/Sema/SemaInternal.h" 18 #include "clang/Sema/Initialization.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/CXXInheritance.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include <set> 26 using namespace clang; 27 28 29 30 enum TryCastResult { 31 TC_NotApplicable, ///< The cast method is not applicable. 32 TC_Success, ///< The cast method is appropriate and successful. 33 TC_Failed ///< The cast method is appropriate, but failed. A 34 ///< diagnostic has been emitted. 35 }; 36 37 enum CastType { 38 CT_Const, ///< const_cast 39 CT_Static, ///< static_cast 40 CT_Reinterpret, ///< reinterpret_cast 41 CT_Dynamic, ///< dynamic_cast 42 CT_CStyle, ///< (Type)expr 43 CT_Functional ///< Type(expr) 44 }; 45 46 namespace { 47 struct CastOperation { 48 CastOperation(Sema &S, QualType destType, ExprResult src) 49 : Self(S), SrcExpr(src), DestType(destType), 50 ResultType(destType.getNonLValueExprType(S.Context)), 51 ValueKind(Expr::getValueKindForType(destType)), 52 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 53 54 if (const BuiltinType *placeholder = 55 src.get()->getType()->getAsPlaceholderType()) { 56 PlaceholderKind = placeholder->getKind(); 57 } else { 58 PlaceholderKind = (BuiltinType::Kind) 0; 59 } 60 } 61 62 Sema &Self; 63 ExprResult SrcExpr; 64 QualType DestType; 65 QualType ResultType; 66 ExprValueKind ValueKind; 67 CastKind Kind; 68 BuiltinType::Kind PlaceholderKind; 69 CXXCastPath BasePath; 70 bool IsARCUnbridgedCast; 71 72 SourceRange OpRange; 73 SourceRange DestRange; 74 75 // Top-level semantics-checking routines. 76 void CheckConstCast(); 77 void CheckReinterpretCast(); 78 void CheckStaticCast(); 79 void CheckDynamicCast(); 80 void CheckCXXCStyleCast(bool FunctionalCast); 81 void CheckCStyleCast(); 82 83 /// Complete an apparently-successful cast operation that yields 84 /// the given expression. 85 ExprResult complete(CastExpr *castExpr) { 86 // If this is an unbridged cast, wrap the result in an implicit 87 // cast that yields the unbridged-cast placeholder type. 88 if (IsARCUnbridgedCast) { 89 castExpr = ImplicitCastExpr::Create(Self.Context, 90 Self.Context.ARCUnbridgedCastTy, 91 CK_Dependent, castExpr, 0, 92 castExpr->getValueKind()); 93 } 94 return Self.Owned(castExpr); 95 } 96 97 // Internal convenience methods. 98 99 /// Try to handle the given placeholder expression kind. Return 100 /// true if the source expression has the appropriate placeholder 101 /// kind. A placeholder can only be claimed once. 102 bool claimPlaceholder(BuiltinType::Kind K) { 103 if (PlaceholderKind != K) return false; 104 105 PlaceholderKind = (BuiltinType::Kind) 0; 106 return true; 107 } 108 109 bool isPlaceholder() const { 110 return PlaceholderKind != 0; 111 } 112 bool isPlaceholder(BuiltinType::Kind K) const { 113 return PlaceholderKind == K; 114 } 115 116 void checkCastAlign() { 117 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 118 } 119 120 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) { 121 assert(Self.getLangOptions().ObjCAutoRefCount); 122 123 Expr *src = SrcExpr.get(); 124 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) == 125 Sema::ACR_unbridged) 126 IsARCUnbridgedCast = true; 127 SrcExpr = src; 128 } 129 130 /// Check for and handle non-overload placeholder expressions. 131 void checkNonOverloadPlaceholders() { 132 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 133 return; 134 135 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 136 if (SrcExpr.isInvalid()) 137 return; 138 PlaceholderKind = (BuiltinType::Kind) 0; 139 } 140 }; 141 } 142 143 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 144 bool CheckCVR, bool CheckObjCLifetime); 145 146 // The Try functions attempt a specific way of casting. If they succeed, they 147 // return TC_Success. If their way of casting is not appropriate for the given 148 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 149 // to emit if no other way succeeds. If their way of casting is appropriate but 150 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if 151 // they emit a specialized diagnostic. 152 // All diagnostics returned by these functions must expect the same three 153 // arguments: 154 // %0: Cast Type (a value from the CastType enumeration) 155 // %1: Source Type 156 // %2: Destination Type 157 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 158 QualType DestType, bool CStyle, 159 CastKind &Kind, 160 CXXCastPath &BasePath, 161 unsigned &msg); 162 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 163 QualType DestType, bool CStyle, 164 const SourceRange &OpRange, 165 unsigned &msg, 166 CastKind &Kind, 167 CXXCastPath &BasePath); 168 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 169 QualType DestType, bool CStyle, 170 const SourceRange &OpRange, 171 unsigned &msg, 172 CastKind &Kind, 173 CXXCastPath &BasePath); 174 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 175 CanQualType DestType, bool CStyle, 176 const SourceRange &OpRange, 177 QualType OrigSrcType, 178 QualType OrigDestType, unsigned &msg, 179 CastKind &Kind, 180 CXXCastPath &BasePath); 181 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 182 QualType SrcType, 183 QualType DestType,bool CStyle, 184 const SourceRange &OpRange, 185 unsigned &msg, 186 CastKind &Kind, 187 CXXCastPath &BasePath); 188 189 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 190 QualType DestType, 191 Sema::CheckedConversionKind CCK, 192 const SourceRange &OpRange, 193 unsigned &msg, 194 CastKind &Kind); 195 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 196 QualType DestType, 197 Sema::CheckedConversionKind CCK, 198 const SourceRange &OpRange, 199 unsigned &msg, 200 CastKind &Kind, 201 CXXCastPath &BasePath); 202 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 203 bool CStyle, unsigned &msg); 204 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 205 QualType DestType, bool CStyle, 206 const SourceRange &OpRange, 207 unsigned &msg, 208 CastKind &Kind); 209 210 211 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 212 ExprResult 213 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 214 SourceLocation LAngleBracketLoc, Declarator &D, 215 SourceLocation RAngleBracketLoc, 216 SourceLocation LParenLoc, Expr *E, 217 SourceLocation RParenLoc) { 218 219 assert(!D.isInvalidType()); 220 221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); 222 if (D.isInvalidType()) 223 return ExprError(); 224 225 if (getLangOptions().CPlusPlus) { 226 // Check that there are no default arguments (C++ only). 227 CheckExtraCXXDefaultArguments(D); 228 } 229 230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E), 231 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 232 SourceRange(LParenLoc, RParenLoc)); 233 } 234 235 ExprResult 236 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 237 TypeSourceInfo *DestTInfo, Expr *E, 238 SourceRange AngleBrackets, SourceRange Parens) { 239 ExprResult Ex = Owned(E); 240 QualType DestType = DestTInfo->getType(); 241 242 // If the type is dependent, we won't do the semantic analysis now. 243 // FIXME: should we check this in a more fine-grained manner? 244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent(); 245 246 CastOperation Op(*this, DestType, E); 247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 248 Op.DestRange = AngleBrackets; 249 250 switch (Kind) { 251 default: llvm_unreachable("Unknown C++ cast!"); 252 253 case tok::kw_const_cast: 254 if (!TypeDependent) { 255 Op.CheckConstCast(); 256 if (Op.SrcExpr.isInvalid()) 257 return ExprError(); 258 } 259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, 260 Op.ValueKind, Op.SrcExpr.take(), DestTInfo, 261 OpLoc, Parens.getEnd())); 262 263 case tok::kw_dynamic_cast: { 264 if (!TypeDependent) { 265 Op.CheckDynamicCast(); 266 if (Op.SrcExpr.isInvalid()) 267 return ExprError(); 268 } 269 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 270 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 271 &Op.BasePath, DestTInfo, 272 OpLoc, Parens.getEnd())); 273 } 274 case tok::kw_reinterpret_cast: { 275 if (!TypeDependent) { 276 Op.CheckReinterpretCast(); 277 if (Op.SrcExpr.isInvalid()) 278 return ExprError(); 279 } 280 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 281 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 282 0, DestTInfo, OpLoc, 283 Parens.getEnd())); 284 } 285 case tok::kw_static_cast: { 286 if (!TypeDependent) { 287 Op.CheckStaticCast(); 288 if (Op.SrcExpr.isInvalid()) 289 return ExprError(); 290 } 291 292 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, 293 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 294 &Op.BasePath, DestTInfo, 295 OpLoc, Parens.getEnd())); 296 } 297 } 298 299 return ExprError(); 300 } 301 302 /// Try to diagnose a failed overloaded cast. Returns true if 303 /// diagnostics were emitted. 304 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 305 SourceRange range, Expr *src, 306 QualType destType) { 307 switch (CT) { 308 // These cast kinds don't consider user-defined conversions. 309 case CT_Const: 310 case CT_Reinterpret: 311 case CT_Dynamic: 312 return false; 313 314 // These do. 315 case CT_Static: 316 case CT_CStyle: 317 case CT_Functional: 318 break; 319 } 320 321 QualType srcType = src->getType(); 322 if (!destType->isRecordType() && !srcType->isRecordType()) 323 return false; 324 325 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 326 InitializationKind initKind 327 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 328 range) 329 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range) 330 : InitializationKind::CreateCast(/*type range?*/ range); 331 InitializationSequence sequence(S, entity, initKind, &src, 1); 332 333 assert(sequence.Failed() && "initialization succeeded on second try?"); 334 switch (sequence.getFailureKind()) { 335 default: return false; 336 337 case InitializationSequence::FK_ConstructorOverloadFailed: 338 case InitializationSequence::FK_UserConversionOverloadFailed: 339 break; 340 } 341 342 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 343 344 unsigned msg = 0; 345 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 346 347 switch (sequence.getFailedOverloadResult()) { 348 case OR_Success: llvm_unreachable("successful failed overload"); 349 return false; 350 case OR_No_Viable_Function: 351 if (candidates.empty()) 352 msg = diag::err_ovl_no_conversion_in_cast; 353 else 354 msg = diag::err_ovl_no_viable_conversion_in_cast; 355 howManyCandidates = OCD_AllCandidates; 356 break; 357 358 case OR_Ambiguous: 359 msg = diag::err_ovl_ambiguous_conversion_in_cast; 360 howManyCandidates = OCD_ViableCandidates; 361 break; 362 363 case OR_Deleted: 364 msg = diag::err_ovl_deleted_conversion_in_cast; 365 howManyCandidates = OCD_ViableCandidates; 366 break; 367 } 368 369 S.Diag(range.getBegin(), msg) 370 << CT << srcType << destType 371 << range << src->getSourceRange(); 372 373 candidates.NoteCandidates(S, howManyCandidates, &src, 1); 374 375 return true; 376 } 377 378 /// Diagnose a failed cast. 379 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 380 SourceRange opRange, Expr *src, QualType destType) { 381 if (src->getType() == S.Context.BoundMemberTy) { 382 (void) S.CheckPlaceholderExpr(src); // will always fail 383 return; 384 } 385 386 if (msg == diag::err_bad_cxx_cast_generic && 387 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType)) 388 return; 389 390 S.Diag(opRange.getBegin(), msg) << castType 391 << src->getType() << destType << opRange << src->getSourceRange(); 392 } 393 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(); 405 return true; 406 } 407 const ObjCObjectPointerType *T1ObjCPtrType = 408 T1->getAs<ObjCObjectPointerType>(), 409 *T2ObjCPtrType = 410 T2->getAs<ObjCObjectPointerType>(); 411 if (T1ObjCPtrType) { 412 if (T2ObjCPtrType) { 413 T1 = T1ObjCPtrType->getPointeeType(); 414 T2 = T2ObjCPtrType->getPointeeType(); 415 return true; 416 } 417 else if (T2PtrType) { 418 T1 = T1ObjCPtrType->getPointeeType(); 419 T2 = T2PtrType->getPointeeType(); 420 return true; 421 } 422 } 423 else if (T2ObjCPtrType) { 424 if (T1PtrType) { 425 T2 = T2ObjCPtrType->getPointeeType(); 426 T1 = T1PtrType->getPointeeType(); 427 return true; 428 } 429 } 430 431 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 432 *T2MPType = T2->getAs<MemberPointerType>(); 433 if (T1MPType && T2MPType) { 434 T1 = T1MPType->getPointeeType(); 435 T2 = T2MPType->getPointeeType(); 436 return true; 437 } 438 439 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(), 440 *T2BPType = T2->getAs<BlockPointerType>(); 441 if (T1BPType && T2BPType) { 442 T1 = T1BPType->getPointeeType(); 443 T2 = T2BPType->getPointeeType(); 444 return true; 445 } 446 447 return false; 448 } 449 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) 453 /// types. 454 /// 455 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 456 /// 457 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 458 static bool 459 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 460 bool CheckCVR, bool CheckObjCLifetime) { 461 // If the only checking we care about is for Objective-C lifetime qualifiers, 462 // and we're not in ARC mode, there's nothing to check. 463 if (!CheckCVR && CheckObjCLifetime && 464 !Self.Context.getLangOptions().ObjCAutoRefCount) 465 return false; 466 467 // Casting away constness is defined in C++ 5.2.11p8 with reference to 468 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since 469 // the rules are non-trivial. So first we construct Tcv *...cv* as described 470 // in C++ 5.2.11p8. 471 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 472 SrcType->isBlockPointerType()) && 473 "Source type is not pointer or pointer to member."); 474 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 475 DestType->isBlockPointerType()) && 476 "Destination type is not pointer or pointer to member."); 477 478 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 479 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 480 SmallVector<Qualifiers, 8> cv1, cv2; 481 482 // Find the qualifiers. We only care about cvr-qualifiers for the 483 // purpose of this check, because other qualifiers (address spaces, 484 // Objective-C GC, etc.) are part of the type's identity. 485 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 486 // Determine the relevant qualifiers at this level. 487 Qualifiers SrcQuals, DestQuals; 488 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 489 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 490 491 Qualifiers RetainedSrcQuals, RetainedDestQuals; 492 if (CheckCVR) { 493 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers()); 494 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers()); 495 } 496 497 if (CheckObjCLifetime && 498 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 499 return true; 500 501 cv1.push_back(RetainedSrcQuals); 502 cv2.push_back(RetainedDestQuals); 503 } 504 if (cv1.empty()) 505 return false; 506 507 // Construct void pointers with those qualifiers (in reverse order of 508 // unwrapping, of course). 509 QualType SrcConstruct = Self.Context.VoidTy; 510 QualType DestConstruct = Self.Context.VoidTy; 511 ASTContext &Context = Self.Context; 512 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(), 513 i2 = cv2.rbegin(); 514 i1 != cv1.rend(); ++i1, ++i2) { 515 SrcConstruct 516 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1)); 517 DestConstruct 518 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2)); 519 } 520 521 // Test if they're compatible. 522 bool ObjCLifetimeConversion; 523 return SrcConstruct != DestConstruct && 524 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false, 525 ObjCLifetimeConversion); 526 } 527 528 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 529 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 530 /// checked downcasts in class hierarchies. 531 void CastOperation::CheckDynamicCast() { 532 QualType OrigSrcType = SrcExpr.get()->getType(); 533 QualType DestType = Self.Context.getCanonicalType(this->DestType); 534 535 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 536 // or "pointer to cv void". 537 538 QualType DestPointee; 539 const PointerType *DestPointer = DestType->getAs<PointerType>(); 540 const ReferenceType *DestReference = 0; 541 if (DestPointer) { 542 DestPointee = DestPointer->getPointeeType(); 543 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 544 DestPointee = DestReference->getPointeeType(); 545 } else { 546 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 547 << this->DestType << DestRange; 548 return; 549 } 550 551 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 552 if (DestPointee->isVoidType()) { 553 assert(DestPointer && "Reference to void is not possible"); 554 } else if (DestRecord) { 555 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 556 Self.PDiag(diag::err_bad_dynamic_cast_incomplete) 557 << DestRange)) 558 return; 559 } else { 560 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 561 << DestPointee.getUnqualifiedType() << DestRange; 562 return; 563 } 564 565 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 566 // complete class type, [...]. If T is an lvalue reference type, v shall be 567 // an lvalue of a complete class type, [...]. If T is an rvalue reference 568 // type, v shall be an expression having a complete class type, [...] 569 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 570 QualType SrcPointee; 571 if (DestPointer) { 572 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 573 SrcPointee = SrcPointer->getPointeeType(); 574 } else { 575 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 576 << OrigSrcType << SrcExpr.get()->getSourceRange(); 577 return; 578 } 579 } else if (DestReference->isLValueReferenceType()) { 580 if (!SrcExpr.get()->isLValue()) { 581 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 582 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 583 } 584 SrcPointee = SrcType; 585 } else { 586 SrcPointee = SrcType; 587 } 588 589 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 590 if (SrcRecord) { 591 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 592 Self.PDiag(diag::err_bad_dynamic_cast_incomplete) 593 << SrcExpr.get()->getSourceRange())) 594 return; 595 } else { 596 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 597 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 598 return; 599 } 600 601 assert((DestPointer || DestReference) && 602 "Bad destination non-ptr/ref slipped through."); 603 assert((DestRecord || DestPointee->isVoidType()) && 604 "Bad destination pointee slipped through."); 605 assert(SrcRecord && "Bad source pointee slipped through."); 606 607 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 608 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 609 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 610 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 611 return; 612 } 613 614 // C++ 5.2.7p3: If the type of v is the same as the required result type, 615 // [except for cv]. 616 if (DestRecord == SrcRecord) { 617 Kind = CK_NoOp; 618 return; 619 } 620 621 // C++ 5.2.7p5 622 // Upcasts are resolved statically. 623 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) { 624 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 625 OpRange.getBegin(), OpRange, 626 &BasePath)) 627 return; 628 629 Kind = CK_DerivedToBase; 630 631 // If we are casting to or through a virtual base class, we need a 632 // vtable. 633 if (Self.BasePathInvolvesVirtualBase(BasePath)) 634 Self.MarkVTableUsed(OpRange.getBegin(), 635 cast<CXXRecordDecl>(SrcRecord->getDecl())); 636 return; 637 } 638 639 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 640 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 641 assert(SrcDecl && "Definition missing"); 642 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 643 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 644 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 645 } 646 Self.MarkVTableUsed(OpRange.getBegin(), 647 cast<CXXRecordDecl>(SrcRecord->getDecl())); 648 649 // Done. Everything else is run-time checks. 650 Kind = CK_Dynamic; 651 } 652 653 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 654 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code 655 /// like this: 656 /// const char *str = "literal"; 657 /// legacy_function(const_cast\<char*\>(str)); 658 void CastOperation::CheckConstCast() { 659 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) { 660 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 661 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 662 return; 663 } 664 665 unsigned msg = diag::err_bad_cxx_cast_generic; 666 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success 667 && msg != 0) 668 Self.Diag(OpRange.getBegin(), msg) << CT_Const 669 << SrcExpr.get()->getType() << DestType << OpRange; 670 } 671 672 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 673 /// valid. 674 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 675 /// like this: 676 /// char *bytes = reinterpret_cast\<char*\>(int_ptr); 677 void CastOperation::CheckReinterpretCast() { 678 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) { 679 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 680 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 681 return; 682 } 683 684 unsigned msg = diag::err_bad_cxx_cast_generic; 685 TryCastResult tcr = 686 TryReinterpretCast(Self, SrcExpr, DestType, 687 /*CStyle*/false, OpRange, msg, Kind); 688 if (tcr != TC_Success && msg != 0) 689 { 690 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 691 return; 692 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 693 //FIXME: &f<int>; is overloaded and resolvable 694 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 695 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 696 << DestType << OpRange; 697 Self.NoteAllOverloadCandidates(SrcExpr.get()); 698 699 } else { 700 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType); 701 } 702 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) { 703 checkObjCARCConversion(Sema::CCK_OtherCast); 704 } 705 } 706 707 708 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 709 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 710 /// implicit conversions explicit and getting rid of data loss warnings. 711 void CastOperation::CheckStaticCast() { 712 if (isPlaceholder()) { 713 checkNonOverloadPlaceholders(); 714 if (SrcExpr.isInvalid()) 715 return; 716 } 717 718 // This test is outside everything else because it's the only case where 719 // a non-lvalue-reference target type does not lead to decay. 720 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 721 if (DestType->isVoidType()) { 722 Kind = CK_ToVoid; 723 724 if (claimPlaceholder(BuiltinType::Overload)) { 725 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 726 false, // Decay Function to ptr 727 true, // Complain 728 OpRange, DestType, diag::err_bad_static_cast_overload); 729 if (SrcExpr.isInvalid()) 730 return; 731 } 732 733 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 734 return; 735 } 736 737 if (ValueKind == VK_RValue && !DestType->isRecordType() && 738 !isPlaceholder(BuiltinType::Overload)) { 739 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 740 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 741 return; 742 } 743 744 unsigned msg = diag::err_bad_cxx_cast_generic; 745 TryCastResult tcr 746 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 747 Kind, BasePath); 748 if (tcr != TC_Success && msg != 0) { 749 if (SrcExpr.isInvalid()) 750 return; 751 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 752 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 753 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 754 << oe->getName() << DestType << OpRange 755 << oe->getQualifierLoc().getSourceRange(); 756 Self.NoteAllOverloadCandidates(SrcExpr.get()); 757 } else { 758 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType); 759 } 760 } else if (tcr == TC_Success) { 761 if (Kind == CK_BitCast) 762 checkCastAlign(); 763 if (Self.getLangOptions().ObjCAutoRefCount) 764 checkObjCARCConversion(Sema::CCK_OtherCast); 765 } else if (Kind == CK_BitCast) { 766 checkCastAlign(); 767 } 768 } 769 770 /// TryStaticCast - Check if a static cast can be performed, and do so if 771 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting 772 /// and casting away constness. 773 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 774 QualType DestType, 775 Sema::CheckedConversionKind CCK, 776 const SourceRange &OpRange, unsigned &msg, 777 CastKind &Kind, 778 CXXCastPath &BasePath) { 779 // Determine whether we have the semantics of a C-style cast. 780 bool CStyle 781 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 782 783 // The order the tests is not entirely arbitrary. There is one conversion 784 // that can be handled in two different ways. Given: 785 // struct A {}; 786 // struct B : public A { 787 // B(); B(const A&); 788 // }; 789 // const A &a = B(); 790 // the cast static_cast<const B&>(a) could be seen as either a static 791 // reference downcast, or an explicit invocation of the user-defined 792 // conversion using B's conversion constructor. 793 // DR 427 specifies that the downcast is to be applied here. 794 795 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 796 // Done outside this function. 797 798 TryCastResult tcr; 799 800 // C++ 5.2.9p5, reference downcast. 801 // See the function for details. 802 // DR 427 specifies that this is to be applied before paragraph 2. 803 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange, 804 msg, Kind, BasePath); 805 if (tcr != TC_NotApplicable) 806 return tcr; 807 808 // C++0x [expr.static.cast]p3: 809 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 810 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 811 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath, 812 msg); 813 if (tcr != TC_NotApplicable) 814 return tcr; 815 816 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 817 // [...] if the declaration "T t(e);" is well-formed, [...]. 818 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 819 Kind); 820 if (SrcExpr.isInvalid()) 821 return TC_Failed; 822 if (tcr != TC_NotApplicable) 823 return tcr; 824 825 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 826 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 827 // conversions, subject to further restrictions. 828 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 829 // of qualification conversions impossible. 830 // In the CStyle case, the earlier attempt to const_cast should have taken 831 // care of reverse qualification conversions. 832 833 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 834 835 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 836 // converted to an integral type. [...] A value of a scoped enumeration type 837 // can also be explicitly converted to a floating-point type [...]. 838 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 839 if (Enum->getDecl()->isScoped()) { 840 if (DestType->isBooleanType()) { 841 Kind = CK_IntegralToBoolean; 842 return TC_Success; 843 } else if (DestType->isIntegralType(Self.Context)) { 844 Kind = CK_IntegralCast; 845 return TC_Success; 846 } else if (DestType->isRealFloatingType()) { 847 Kind = CK_IntegralToFloating; 848 return TC_Success; 849 } 850 } 851 } 852 853 // Reverse integral promotion/conversion. All such conversions are themselves 854 // again integral promotions or conversions and are thus already handled by 855 // p2 (TryDirectInitialization above). 856 // (Note: any data loss warnings should be suppressed.) 857 // The exception is the reverse of enum->integer, i.e. integer->enum (and 858 // enum->enum). See also C++ 5.2.9p7. 859 // The same goes for reverse floating point promotion/conversion and 860 // floating-integral conversions. Again, only floating->enum is relevant. 861 if (DestType->isEnumeralType()) { 862 if (SrcType->isIntegralOrEnumerationType()) { 863 Kind = CK_IntegralCast; 864 return TC_Success; 865 } else if (SrcType->isRealFloatingType()) { 866 Kind = CK_FloatingToIntegral; 867 return TC_Success; 868 } 869 } 870 871 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 872 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 873 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 874 Kind, BasePath); 875 if (tcr != TC_NotApplicable) 876 return tcr; 877 878 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 879 // conversion. C++ 5.2.9p9 has additional information. 880 // DR54's access restrictions apply here also. 881 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 882 OpRange, msg, Kind, BasePath); 883 if (tcr != TC_NotApplicable) 884 return tcr; 885 886 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 887 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 888 // just the usual constness stuff. 889 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 890 QualType SrcPointee = SrcPointer->getPointeeType(); 891 if (SrcPointee->isVoidType()) { 892 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 893 QualType DestPointee = DestPointer->getPointeeType(); 894 if (DestPointee->isIncompleteOrObjectType()) { 895 // This is definitely the intended conversion, but it might fail due 896 // to a qualifier violation. Note that we permit Objective-C lifetime 897 // and GC qualifier mismatches here. 898 if (!CStyle) { 899 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 900 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 901 DestPointeeQuals.removeObjCGCAttr(); 902 DestPointeeQuals.removeObjCLifetime(); 903 SrcPointeeQuals.removeObjCGCAttr(); 904 SrcPointeeQuals.removeObjCLifetime(); 905 if (DestPointeeQuals != SrcPointeeQuals && 906 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 907 msg = diag::err_bad_cxx_cast_qualifiers_away; 908 return TC_Failed; 909 } 910 } 911 Kind = CK_BitCast; 912 return TC_Success; 913 } 914 } 915 else if (DestType->isObjCObjectPointerType()) { 916 // allow both c-style cast and static_cast of objective-c pointers as 917 // they are pervasive. 918 Kind = CK_CPointerToObjCPointerCast; 919 return TC_Success; 920 } 921 else if (CStyle && DestType->isBlockPointerType()) { 922 // allow c-style cast of void * to block pointers. 923 Kind = CK_AnyPointerToBlockPointerCast; 924 return TC_Success; 925 } 926 } 927 } 928 // Allow arbitray objective-c pointer conversion with static casts. 929 if (SrcType->isObjCObjectPointerType() && 930 DestType->isObjCObjectPointerType()) { 931 Kind = CK_BitCast; 932 return TC_Success; 933 } 934 935 // We tried everything. Everything! Nothing works! :-( 936 return TC_NotApplicable; 937 } 938 939 /// Tests whether a conversion according to N2844 is valid. 940 TryCastResult 941 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, 942 bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 943 unsigned &msg) { 944 // C++0x [expr.static.cast]p3: 945 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 946 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 947 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 948 if (!R) 949 return TC_NotApplicable; 950 951 if (!SrcExpr->isGLValue()) 952 return TC_NotApplicable; 953 954 // Because we try the reference downcast before this function, from now on 955 // this is the only cast possibility, so we issue an error if we fail now. 956 // FIXME: Should allow casting away constness if CStyle. 957 bool DerivedToBase; 958 bool ObjCConversion; 959 bool ObjCLifetimeConversion; 960 QualType FromType = SrcExpr->getType(); 961 QualType ToType = R->getPointeeType(); 962 if (CStyle) { 963 FromType = FromType.getUnqualifiedType(); 964 ToType = ToType.getUnqualifiedType(); 965 } 966 967 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(), 968 ToType, FromType, 969 DerivedToBase, ObjCConversion, 970 ObjCLifetimeConversion) 971 < Sema::Ref_Compatible_With_Added_Qualification) { 972 msg = diag::err_bad_lvalue_to_rvalue_cast; 973 return TC_Failed; 974 } 975 976 if (DerivedToBase) { 977 Kind = CK_DerivedToBase; 978 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 979 /*DetectVirtual=*/true); 980 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths)) 981 return TC_NotApplicable; 982 983 Self.BuildBasePathArray(Paths, BasePath); 984 } else 985 Kind = CK_NoOp; 986 987 return TC_Success; 988 } 989 990 /// Tests whether a conversion according to C++ 5.2.9p5 is valid. 991 TryCastResult 992 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 993 bool CStyle, const SourceRange &OpRange, 994 unsigned &msg, CastKind &Kind, 995 CXXCastPath &BasePath) { 996 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 997 // cast to type "reference to cv2 D", where D is a class derived from B, 998 // if a valid standard conversion from "pointer to D" to "pointer to B" 999 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1000 // In addition, DR54 clarifies that the base must be accessible in the 1001 // current context. Although the wording of DR54 only applies to the pointer 1002 // variant of this rule, the intent is clearly for it to apply to the this 1003 // conversion as well. 1004 1005 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1006 if (!DestReference) { 1007 return TC_NotApplicable; 1008 } 1009 bool RValueRef = DestReference->isRValueReferenceType(); 1010 if (!RValueRef && !SrcExpr->isLValue()) { 1011 // We know the left side is an lvalue reference, so we can suggest a reason. 1012 msg = diag::err_bad_cxx_cast_rvalue; 1013 return TC_NotApplicable; 1014 } 1015 1016 QualType DestPointee = DestReference->getPointeeType(); 1017 1018 return TryStaticDowncast(Self, 1019 Self.Context.getCanonicalType(SrcExpr->getType()), 1020 Self.Context.getCanonicalType(DestPointee), CStyle, 1021 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1022 BasePath); 1023 } 1024 1025 /// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1026 TryCastResult 1027 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1028 bool CStyle, const SourceRange &OpRange, 1029 unsigned &msg, CastKind &Kind, 1030 CXXCastPath &BasePath) { 1031 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1032 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1033 // is a class derived from B, if a valid standard conversion from "pointer 1034 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1035 // class of D. 1036 // In addition, DR54 clarifies that the base must be accessible in the 1037 // current context. 1038 1039 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1040 if (!DestPointer) { 1041 return TC_NotApplicable; 1042 } 1043 1044 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1045 if (!SrcPointer) { 1046 msg = diag::err_bad_static_cast_pointer_nonpointer; 1047 return TC_NotApplicable; 1048 } 1049 1050 return TryStaticDowncast(Self, 1051 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1052 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1053 CStyle, OpRange, SrcType, DestType, msg, Kind, 1054 BasePath); 1055 } 1056 1057 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1058 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1059 /// DestType is possible and allowed. 1060 TryCastResult 1061 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1062 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType, 1063 QualType OrigDestType, unsigned &msg, 1064 CastKind &Kind, CXXCastPath &BasePath) { 1065 // We can only work with complete types. But don't complain if it doesn't work 1066 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) || 1067 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0))) 1068 return TC_NotApplicable; 1069 1070 // Downcast can only happen in class hierarchies, so we need classes. 1071 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1072 return TC_NotApplicable; 1073 } 1074 1075 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1076 /*DetectVirtual=*/true); 1077 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) { 1078 return TC_NotApplicable; 1079 } 1080 1081 // Target type does derive from source type. Now we're serious. If an error 1082 // appears now, it's not ignored. 1083 // This may not be entirely in line with the standard. Take for example: 1084 // struct A {}; 1085 // struct B : virtual A { 1086 // B(A&); 1087 // }; 1088 // 1089 // void f() 1090 // { 1091 // (void)static_cast<const B&>(*((A*)0)); 1092 // } 1093 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1094 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1095 // However, both GCC and Comeau reject this example, and accepting it would 1096 // mean more complex code if we're to preserve the nice error message. 1097 // FIXME: Being 100% compliant here would be nice to have. 1098 1099 // Must preserve cv, as always, unless we're in C-style mode. 1100 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1101 msg = diag::err_bad_cxx_cast_qualifiers_away; 1102 return TC_Failed; 1103 } 1104 1105 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1106 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1107 // that it builds the paths in reverse order. 1108 // To sum up: record all paths to the base and build a nice string from 1109 // them. Use it to spice up the error message. 1110 if (!Paths.isRecordingPaths()) { 1111 Paths.clear(); 1112 Paths.setRecordingPaths(true); 1113 Self.IsDerivedFrom(DestType, SrcType, Paths); 1114 } 1115 std::string PathDisplayStr; 1116 std::set<unsigned> DisplayedPaths; 1117 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end(); 1118 PI != PE; ++PI) { 1119 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) { 1120 // We haven't displayed a path to this particular base 1121 // class subobject yet. 1122 PathDisplayStr += "\n "; 1123 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(), 1124 EE = PI->rend(); 1125 EI != EE; ++EI) 1126 PathDisplayStr += EI->Base->getType().getAsString() + " -> "; 1127 PathDisplayStr += QualType(DestType).getAsString(); 1128 } 1129 } 1130 1131 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1132 << QualType(SrcType).getUnqualifiedType() 1133 << QualType(DestType).getUnqualifiedType() 1134 << PathDisplayStr << OpRange; 1135 msg = 0; 1136 return TC_Failed; 1137 } 1138 1139 if (Paths.getDetectedVirtual() != 0) { 1140 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1141 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1142 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1143 msg = 0; 1144 return TC_Failed; 1145 } 1146 1147 if (!CStyle) { 1148 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1149 SrcType, DestType, 1150 Paths.front(), 1151 diag::err_downcast_from_inaccessible_base)) { 1152 case Sema::AR_accessible: 1153 case Sema::AR_delayed: // be optimistic 1154 case Sema::AR_dependent: // be optimistic 1155 break; 1156 1157 case Sema::AR_inaccessible: 1158 msg = 0; 1159 return TC_Failed; 1160 } 1161 } 1162 1163 Self.BuildBasePathArray(Paths, BasePath); 1164 Kind = CK_BaseToDerived; 1165 return TC_Success; 1166 } 1167 1168 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1169 /// C++ 5.2.9p9 is valid: 1170 /// 1171 /// An rvalue of type "pointer to member of D of type cv1 T" can be 1172 /// converted to an rvalue of type "pointer to member of B of type cv2 T", 1173 /// where B is a base class of D [...]. 1174 /// 1175 TryCastResult 1176 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1177 QualType DestType, bool CStyle, 1178 const SourceRange &OpRange, 1179 unsigned &msg, CastKind &Kind, 1180 CXXCastPath &BasePath) { 1181 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1182 if (!DestMemPtr) 1183 return TC_NotApplicable; 1184 1185 bool WasOverloadedFunction = false; 1186 DeclAccessPair FoundOverload; 1187 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1188 if (FunctionDecl *Fn 1189 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1190 FoundOverload)) { 1191 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1192 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1193 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1194 WasOverloadedFunction = true; 1195 } 1196 } 1197 1198 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1199 if (!SrcMemPtr) { 1200 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1201 return TC_NotApplicable; 1202 } 1203 1204 // T == T, modulo cv 1205 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1206 DestMemPtr->getPointeeType())) 1207 return TC_NotApplicable; 1208 1209 // B base of D 1210 QualType SrcClass(SrcMemPtr->getClass(), 0); 1211 QualType DestClass(DestMemPtr->getClass(), 0); 1212 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1213 /*DetectVirtual=*/true); 1214 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) { 1215 return TC_NotApplicable; 1216 } 1217 1218 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1219 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1220 Paths.clear(); 1221 Paths.setRecordingPaths(true); 1222 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths); 1223 assert(StillOkay); 1224 (void)StillOkay; 1225 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1226 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1227 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1228 msg = 0; 1229 return TC_Failed; 1230 } 1231 1232 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1233 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1234 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1235 msg = 0; 1236 return TC_Failed; 1237 } 1238 1239 if (!CStyle) { 1240 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1241 DestClass, SrcClass, 1242 Paths.front(), 1243 diag::err_upcast_to_inaccessible_base)) { 1244 case Sema::AR_accessible: 1245 case Sema::AR_delayed: 1246 case Sema::AR_dependent: 1247 // Optimistically assume that the delayed and dependent cases 1248 // will work out. 1249 break; 1250 1251 case Sema::AR_inaccessible: 1252 msg = 0; 1253 return TC_Failed; 1254 } 1255 } 1256 1257 if (WasOverloadedFunction) { 1258 // Resolve the address of the overloaded function again, this time 1259 // allowing complaints if something goes wrong. 1260 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1261 DestType, 1262 true, 1263 FoundOverload); 1264 if (!Fn) { 1265 msg = 0; 1266 return TC_Failed; 1267 } 1268 1269 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1270 if (!SrcExpr.isUsable()) { 1271 msg = 0; 1272 return TC_Failed; 1273 } 1274 } 1275 1276 Self.BuildBasePathArray(Paths, BasePath); 1277 Kind = CK_DerivedToBaseMemberPointer; 1278 return TC_Success; 1279 } 1280 1281 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1282 /// is valid: 1283 /// 1284 /// An expression e can be explicitly converted to a type T using a 1285 /// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1286 TryCastResult 1287 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1288 Sema::CheckedConversionKind CCK, 1289 const SourceRange &OpRange, unsigned &msg, 1290 CastKind &Kind) { 1291 if (DestType->isRecordType()) { 1292 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1293 diag::err_bad_dynamic_cast_incomplete)) { 1294 msg = 0; 1295 return TC_Failed; 1296 } 1297 } 1298 1299 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1300 InitializationKind InitKind 1301 = (CCK == Sema::CCK_CStyleCast) 1302 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange) 1303 : (CCK == Sema::CCK_FunctionalCast) 1304 ? InitializationKind::CreateFunctionalCast(OpRange) 1305 : InitializationKind::CreateCast(OpRange); 1306 Expr *SrcExprRaw = SrcExpr.get(); 1307 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1); 1308 1309 // At this point of CheckStaticCast, if the destination is a reference, 1310 // or the expression is an overload expression this has to work. 1311 // There is no other way that works. 1312 // On the other hand, if we're checking a C-style cast, we've still got 1313 // the reinterpret_cast way. 1314 bool CStyle 1315 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1316 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1317 return TC_NotApplicable; 1318 1319 ExprResult Result 1320 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1)); 1321 if (Result.isInvalid()) { 1322 msg = 0; 1323 return TC_Failed; 1324 } 1325 1326 if (InitSeq.isConstructorInitialization()) 1327 Kind = CK_ConstructorConversion; 1328 else 1329 Kind = CK_NoOp; 1330 1331 SrcExpr = move(Result); 1332 return TC_Success; 1333 } 1334 1335 /// TryConstCast - See if a const_cast from source to destination is allowed, 1336 /// and perform it if it is. 1337 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 1338 bool CStyle, unsigned &msg) { 1339 DestType = Self.Context.getCanonicalType(DestType); 1340 QualType SrcType = SrcExpr->getType(); 1341 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1342 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) { 1343 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1344 // is C-style, static_cast might find a way, so we simply suggest a 1345 // message and tell the parent to keep searching. 1346 msg = diag::err_bad_cxx_cast_rvalue; 1347 return TC_NotApplicable; 1348 } 1349 1350 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2 1351 // [...] if a pointer to T1 can be [cast] to the type pointer to T2. 1352 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1353 SrcType = Self.Context.getPointerType(SrcType); 1354 } 1355 1356 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1357 // the rules for const_cast are the same as those used for pointers. 1358 1359 if (!DestType->isPointerType() && 1360 !DestType->isMemberPointerType() && 1361 !DestType->isObjCObjectPointerType()) { 1362 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1363 // was a reference type, we converted it to a pointer above. 1364 // The status of rvalue references isn't entirely clear, but it looks like 1365 // conversion to them is simply invalid. 1366 // C++ 5.2.11p3: For two pointer types [...] 1367 if (!CStyle) 1368 msg = diag::err_bad_const_cast_dest; 1369 return TC_NotApplicable; 1370 } 1371 if (DestType->isFunctionPointerType() || 1372 DestType->isMemberFunctionPointerType()) { 1373 // Cannot cast direct function pointers. 1374 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1375 // T is the ultimate pointee of source and target type. 1376 if (!CStyle) 1377 msg = diag::err_bad_const_cast_dest; 1378 return TC_NotApplicable; 1379 } 1380 SrcType = Self.Context.getCanonicalType(SrcType); 1381 1382 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 1383 // completely equal. 1384 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 1385 // in multi-level pointers may change, but the level count must be the same, 1386 // as must be the final pointee type. 1387 while (SrcType != DestType && 1388 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 1389 Qualifiers SrcQuals, DestQuals; 1390 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 1391 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 1392 1393 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 1394 // the other qualifiers (e.g., address spaces) are identical. 1395 SrcQuals.removeCVRQualifiers(); 1396 DestQuals.removeCVRQualifiers(); 1397 if (SrcQuals != DestQuals) 1398 return TC_NotApplicable; 1399 } 1400 1401 // Since we're dealing in canonical types, the remainder must be the same. 1402 if (SrcType != DestType) 1403 return TC_NotApplicable; 1404 1405 return TC_Success; 1406 } 1407 1408 // Checks for undefined behavior in reinterpret_cast. 1409 // The cases that is checked for is: 1410 // *reinterpret_cast<T*>(&a) 1411 // reinterpret_cast<T&>(a) 1412 // where accessing 'a' as type 'T' will result in undefined behavior. 1413 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 1414 bool IsDereference, 1415 SourceRange Range) { 1416 unsigned DiagID = IsDereference ? 1417 diag::warn_pointer_indirection_from_incompatible_type : 1418 diag::warn_undefined_reinterpret_cast; 1419 1420 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) == 1421 DiagnosticsEngine::Ignored) { 1422 return; 1423 } 1424 1425 QualType SrcTy, DestTy; 1426 if (IsDereference) { 1427 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 1428 return; 1429 } 1430 SrcTy = SrcType->getPointeeType(); 1431 DestTy = DestType->getPointeeType(); 1432 } else { 1433 if (!DestType->getAs<ReferenceType>()) { 1434 return; 1435 } 1436 SrcTy = SrcType; 1437 DestTy = DestType->getPointeeType(); 1438 } 1439 1440 // Cast is compatible if the types are the same. 1441 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 1442 return; 1443 } 1444 // or one of the types is a char or void type 1445 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 1446 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 1447 return; 1448 } 1449 // or one of the types is a tag type. 1450 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 1451 return; 1452 } 1453 1454 // FIXME: Scoped enums? 1455 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 1456 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 1457 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 1458 return; 1459 } 1460 } 1461 1462 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 1463 } 1464 1465 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 1466 QualType DestType, bool CStyle, 1467 const SourceRange &OpRange, 1468 unsigned &msg, 1469 CastKind &Kind) { 1470 bool IsLValueCast = false; 1471 1472 DestType = Self.Context.getCanonicalType(DestType); 1473 QualType SrcType = SrcExpr.get()->getType(); 1474 1475 // Is the source an overloaded name? (i.e. &foo) 1476 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ... 1477 if (SrcType == Self.Context.OverloadTy) { 1478 // ... unless foo<int> resolves to an lvalue unambiguously. 1479 // TODO: what if this fails because of DiagnoseUseOfDecl or something 1480 // like it? 1481 ExprResult SingleFunctionExpr = SrcExpr; 1482 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1483 SingleFunctionExpr, 1484 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 1485 ) && SingleFunctionExpr.isUsable()) { 1486 SrcExpr = move(SingleFunctionExpr); 1487 SrcType = SrcExpr.get()->getType(); 1488 } else { 1489 return TC_NotApplicable; 1490 } 1491 } 1492 1493 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 1494 bool LValue = DestTypeTmp->isLValueReferenceType(); 1495 if (LValue && !SrcExpr.get()->isLValue()) { 1496 // Cannot cast non-lvalue to lvalue reference type. See the similar 1497 // comment in const_cast. 1498 msg = diag::err_bad_cxx_cast_rvalue; 1499 return TC_NotApplicable; 1500 } 1501 1502 if (!CStyle) { 1503 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 1504 /*isDereference=*/false, OpRange); 1505 } 1506 1507 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 1508 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 1509 // built-in & and * operators. 1510 1511 const char *inappropriate = 0; 1512 switch (SrcExpr.get()->getObjectKind()) { 1513 case OK_Ordinary: 1514 break; 1515 case OK_BitField: inappropriate = "bit-field"; break; 1516 case OK_VectorComponent: inappropriate = "vector element"; break; 1517 case OK_ObjCProperty: inappropriate = "property expression"; break; 1518 } 1519 if (inappropriate) { 1520 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 1521 << inappropriate << DestType 1522 << OpRange << SrcExpr.get()->getSourceRange(); 1523 msg = 0; SrcExpr = ExprError(); 1524 return TC_NotApplicable; 1525 } 1526 1527 // This code does this transformation for the checked types. 1528 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1529 SrcType = Self.Context.getPointerType(SrcType); 1530 1531 IsLValueCast = true; 1532 } 1533 1534 // Canonicalize source for comparison. 1535 SrcType = Self.Context.getCanonicalType(SrcType); 1536 1537 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 1538 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1539 if (DestMemPtr && SrcMemPtr) { 1540 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 1541 // can be explicitly converted to an rvalue of type "pointer to member 1542 // of Y of type T2" if T1 and T2 are both function types or both object 1543 // types. 1544 if (DestMemPtr->getPointeeType()->isFunctionType() != 1545 SrcMemPtr->getPointeeType()->isFunctionType()) 1546 return TC_NotApplicable; 1547 1548 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 1549 // constness. 1550 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 1551 // we accept it. 1552 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1553 /*CheckObjCLifetime=*/CStyle)) { 1554 msg = diag::err_bad_cxx_cast_qualifiers_away; 1555 return TC_Failed; 1556 } 1557 1558 // Don't allow casting between member pointers of different sizes. 1559 if (Self.Context.getTypeSize(DestMemPtr) != 1560 Self.Context.getTypeSize(SrcMemPtr)) { 1561 msg = diag::err_bad_cxx_cast_member_pointer_size; 1562 return TC_Failed; 1563 } 1564 1565 // A valid member pointer cast. 1566 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast; 1567 return TC_Success; 1568 } 1569 1570 // See below for the enumeral issue. 1571 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 1572 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 1573 // type large enough to hold it. A value of std::nullptr_t can be 1574 // converted to an integral type; the conversion has the same meaning 1575 // and validity as a conversion of (void*)0 to the integral type. 1576 if (Self.Context.getTypeSize(SrcType) > 1577 Self.Context.getTypeSize(DestType)) { 1578 msg = diag::err_bad_reinterpret_cast_small_int; 1579 return TC_Failed; 1580 } 1581 Kind = CK_PointerToIntegral; 1582 return TC_Success; 1583 } 1584 1585 bool destIsVector = DestType->isVectorType(); 1586 bool srcIsVector = SrcType->isVectorType(); 1587 if (srcIsVector || destIsVector) { 1588 // FIXME: Should this also apply to floating point types? 1589 bool srcIsScalar = SrcType->isIntegralType(Self.Context); 1590 bool destIsScalar = DestType->isIntegralType(Self.Context); 1591 1592 // Check if this is a cast between a vector and something else. 1593 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) && 1594 !(srcIsVector && destIsVector)) 1595 return TC_NotApplicable; 1596 1597 // If both types have the same size, we can successfully cast. 1598 if (Self.Context.getTypeSize(SrcType) 1599 == Self.Context.getTypeSize(DestType)) { 1600 Kind = CK_BitCast; 1601 return TC_Success; 1602 } 1603 1604 if (destIsScalar) 1605 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 1606 else if (srcIsScalar) 1607 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 1608 else 1609 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 1610 1611 return TC_Failed; 1612 } 1613 1614 bool destIsPtr = DestType->isAnyPointerType() || 1615 DestType->isBlockPointerType(); 1616 bool srcIsPtr = SrcType->isAnyPointerType() || 1617 SrcType->isBlockPointerType(); 1618 if (!destIsPtr && !srcIsPtr) { 1619 // Except for std::nullptr_t->integer and lvalue->reference, which are 1620 // handled above, at least one of the two arguments must be a pointer. 1621 return TC_NotApplicable; 1622 } 1623 1624 if (SrcType == DestType) { 1625 // C++ 5.2.10p2 has a note that mentions that, subject to all other 1626 // restrictions, a cast to the same type is allowed. The intent is not 1627 // entirely clear here, since all other paragraphs explicitly forbid casts 1628 // to the same type. However, the behavior of compilers is pretty consistent 1629 // on this point: allow same-type conversion if the involved types are 1630 // pointers, disallow otherwise. 1631 Kind = CK_NoOp; 1632 return TC_Success; 1633 } 1634 1635 if (DestType->isIntegralType(Self.Context)) { 1636 assert(srcIsPtr && "One type must be a pointer"); 1637 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 1638 // type large enough to hold it; except in Microsoft mode, where the 1639 // integral type size doesn't matter. 1640 if ((Self.Context.getTypeSize(SrcType) > 1641 Self.Context.getTypeSize(DestType)) && 1642 !Self.getLangOptions().MicrosoftExt) { 1643 msg = diag::err_bad_reinterpret_cast_small_int; 1644 return TC_Failed; 1645 } 1646 Kind = CK_PointerToIntegral; 1647 return TC_Success; 1648 } 1649 1650 if (SrcType->isIntegralOrEnumerationType()) { 1651 assert(destIsPtr && "One type must be a pointer"); 1652 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 1653 // converted to a pointer. 1654 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 1655 // necessarily converted to a null pointer value.] 1656 Kind = CK_IntegralToPointer; 1657 return TC_Success; 1658 } 1659 1660 if (!destIsPtr || !srcIsPtr) { 1661 // With the valid non-pointer conversions out of the way, we can be even 1662 // more stringent. 1663 return TC_NotApplicable; 1664 } 1665 1666 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 1667 // The C-style cast operator can. 1668 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1669 /*CheckObjCLifetime=*/CStyle)) { 1670 msg = diag::err_bad_cxx_cast_qualifiers_away; 1671 return TC_Failed; 1672 } 1673 1674 // Cannot convert between block pointers and Objective-C object pointers. 1675 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 1676 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 1677 return TC_NotApplicable; 1678 1679 if (IsLValueCast) { 1680 Kind = CK_LValueBitCast; 1681 } else if (DestType->isObjCObjectPointerType()) { 1682 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 1683 } else if (DestType->isBlockPointerType()) { 1684 if (!SrcType->isBlockPointerType()) { 1685 Kind = CK_AnyPointerToBlockPointerCast; 1686 } else { 1687 Kind = CK_BitCast; 1688 } 1689 } else { 1690 Kind = CK_BitCast; 1691 } 1692 1693 // Any pointer can be cast to an Objective-C pointer type with a C-style 1694 // cast. 1695 if (CStyle && DestType->isObjCObjectPointerType()) { 1696 return TC_Success; 1697 } 1698 1699 // Not casting away constness, so the only remaining check is for compatible 1700 // pointer categories. 1701 1702 if (SrcType->isFunctionPointerType()) { 1703 if (DestType->isFunctionPointerType()) { 1704 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 1705 // a pointer to a function of a different type. 1706 return TC_Success; 1707 } 1708 1709 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 1710 // an object type or vice versa is conditionally-supported. 1711 // Compilers support it in C++03 too, though, because it's necessary for 1712 // casting the return value of dlsym() and GetProcAddress(). 1713 // FIXME: Conditionally-supported behavior should be configurable in the 1714 // TargetInfo or similar. 1715 Self.Diag(OpRange.getBegin(), 1716 Self.getLangOptions().CPlusPlus0x ? 1717 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 1718 << OpRange; 1719 return TC_Success; 1720 } 1721 1722 if (DestType->isFunctionPointerType()) { 1723 // See above. 1724 Self.Diag(OpRange.getBegin(), 1725 Self.getLangOptions().CPlusPlus0x ? 1726 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 1727 << OpRange; 1728 return TC_Success; 1729 } 1730 1731 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 1732 // a pointer to an object of different type. 1733 // Void pointers are not specified, but supported by every compiler out there. 1734 // So we finish by allowing everything that remains - it's got to be two 1735 // object pointers. 1736 return TC_Success; 1737 } 1738 1739 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) { 1740 // Handle placeholders. 1741 if (isPlaceholder()) { 1742 // C-style casts can resolve __unknown_any types. 1743 if (claimPlaceholder(BuiltinType::UnknownAny)) { 1744 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 1745 SrcExpr.get(), Kind, 1746 ValueKind, BasePath); 1747 return; 1748 } 1749 1750 checkNonOverloadPlaceholders(); 1751 if (SrcExpr.isInvalid()) 1752 return; 1753 } 1754 1755 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1756 // This test is outside everything else because it's the only case where 1757 // a non-lvalue-reference target type does not lead to decay. 1758 if (DestType->isVoidType()) { 1759 Kind = CK_ToVoid; 1760 1761 if (claimPlaceholder(BuiltinType::Overload)) { 1762 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1763 SrcExpr, /* Decay Function to ptr */ false, 1764 /* Complain */ true, DestRange, DestType, 1765 diag::err_bad_cstyle_cast_overload); 1766 if (SrcExpr.isInvalid()) 1767 return; 1768 } 1769 1770 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 1771 if (SrcExpr.isInvalid()) 1772 return; 1773 1774 return; 1775 } 1776 1777 // If the type is dependent, we won't do any other semantic analysis now. 1778 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) { 1779 assert(Kind == CK_Dependent); 1780 return; 1781 } 1782 1783 if (ValueKind == VK_RValue && !DestType->isRecordType() && 1784 !isPlaceholder(BuiltinType::Overload)) { 1785 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 1786 if (SrcExpr.isInvalid()) 1787 return; 1788 } 1789 1790 // AltiVec vector initialization with a single literal. 1791 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 1792 if (vecTy->getVectorKind() == VectorType::AltiVecVector 1793 && (SrcExpr.get()->getType()->isIntegerType() 1794 || SrcExpr.get()->getType()->isFloatingType())) { 1795 Kind = CK_VectorSplat; 1796 return; 1797 } 1798 1799 // C++ [expr.cast]p5: The conversions performed by 1800 // - a const_cast, 1801 // - a static_cast, 1802 // - a static_cast followed by a const_cast, 1803 // - a reinterpret_cast, or 1804 // - a reinterpret_cast followed by a const_cast, 1805 // can be performed using the cast notation of explicit type conversion. 1806 // [...] If a conversion can be interpreted in more than one of the ways 1807 // listed above, the interpretation that appears first in the list is used, 1808 // even if a cast resulting from that interpretation is ill-formed. 1809 // In plain language, this means trying a const_cast ... 1810 unsigned msg = diag::err_bad_cxx_cast_generic; 1811 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType, 1812 /*CStyle*/true, msg); 1813 if (tcr == TC_Success) 1814 Kind = CK_NoOp; 1815 1816 Sema::CheckedConversionKind CCK 1817 = FunctionalStyle? Sema::CCK_FunctionalCast 1818 : Sema::CCK_CStyleCast; 1819 if (tcr == TC_NotApplicable) { 1820 // ... or if that is not possible, a static_cast, ignoring const, ... 1821 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 1822 msg, Kind, BasePath); 1823 if (SrcExpr.isInvalid()) 1824 return; 1825 1826 if (tcr == TC_NotApplicable) { 1827 // ... and finally a reinterpret_cast, ignoring const. 1828 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 1829 OpRange, msg, Kind); 1830 if (SrcExpr.isInvalid()) 1831 return; 1832 } 1833 } 1834 1835 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success) 1836 checkObjCARCConversion(CCK); 1837 1838 if (tcr != TC_Success && msg != 0) { 1839 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1840 DeclAccessPair Found; 1841 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1842 DestType, 1843 /*Complain*/ true, 1844 Found); 1845 1846 assert(!Fn && "cast failed but able to resolve overload expression!!"); 1847 (void)Fn; 1848 1849 } else { 1850 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 1851 OpRange, SrcExpr.get(), DestType); 1852 } 1853 } else if (Kind == CK_BitCast) { 1854 checkCastAlign(); 1855 } 1856 1857 // Clear out SrcExpr if there was a fatal error. 1858 if (tcr != TC_Success) 1859 SrcExpr = ExprError(); 1860 } 1861 1862 /// Check the semantics of a C-style cast operation, in C. 1863 void CastOperation::CheckCStyleCast() { 1864 assert(!Self.getLangOptions().CPlusPlus); 1865 1866 // C-style casts can resolve __unknown_any types. 1867 if (claimPlaceholder(BuiltinType::UnknownAny)) { 1868 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 1869 SrcExpr.get(), Kind, 1870 ValueKind, BasePath); 1871 return; 1872 } 1873 1874 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 1875 // type needs to be scalar. 1876 if (DestType->isVoidType()) { 1877 // We don't necessarily do lvalue-to-rvalue conversions on this. 1878 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 1879 if (SrcExpr.isInvalid()) 1880 return; 1881 1882 // Cast to void allows any expr type. 1883 Kind = CK_ToVoid; 1884 return; 1885 } 1886 1887 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 1888 if (SrcExpr.isInvalid()) 1889 return; 1890 QualType SrcType = SrcExpr.get()->getType(); 1891 assert(!SrcType->isPlaceholderType()); 1892 1893 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1894 diag::err_typecheck_cast_to_incomplete)) { 1895 SrcExpr = ExprError(); 1896 return; 1897 } 1898 1899 if (!DestType->isScalarType() && !DestType->isVectorType()) { 1900 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 1901 1902 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 1903 // GCC struct/union extension: allow cast to self. 1904 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 1905 << DestType << SrcExpr.get()->getSourceRange(); 1906 Kind = CK_NoOp; 1907 return; 1908 } 1909 1910 // GCC's cast to union extension. 1911 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 1912 RecordDecl *RD = DestRecordTy->getDecl(); 1913 RecordDecl::field_iterator Field, FieldEnd; 1914 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 1915 Field != FieldEnd; ++Field) { 1916 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 1917 !Field->isUnnamedBitfield()) { 1918 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 1919 << SrcExpr.get()->getSourceRange(); 1920 break; 1921 } 1922 } 1923 if (Field == FieldEnd) { 1924 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 1925 << SrcType << SrcExpr.get()->getSourceRange(); 1926 SrcExpr = ExprError(); 1927 return; 1928 } 1929 Kind = CK_ToUnion; 1930 return; 1931 } 1932 1933 // Reject any other conversions to non-scalar types. 1934 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 1935 << DestType << SrcExpr.get()->getSourceRange(); 1936 SrcExpr = ExprError(); 1937 return; 1938 } 1939 1940 // The type we're casting to is known to be a scalar or vector. 1941 1942 // Require the operand to be a scalar or vector. 1943 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 1944 Self.Diag(SrcExpr.get()->getExprLoc(), 1945 diag::err_typecheck_expect_scalar_operand) 1946 << SrcType << SrcExpr.get()->getSourceRange(); 1947 SrcExpr = ExprError(); 1948 return; 1949 } 1950 1951 if (DestType->isExtVectorType()) { 1952 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind); 1953 return; 1954 } 1955 1956 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 1957 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 1958 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 1959 Kind = CK_VectorSplat; 1960 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 1961 SrcExpr = ExprError(); 1962 } 1963 return; 1964 } 1965 1966 if (SrcType->isVectorType()) { 1967 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 1968 SrcExpr = ExprError(); 1969 return; 1970 } 1971 1972 // The source and target types are both scalars, i.e. 1973 // - arithmetic types (fundamental, enum, and complex) 1974 // - all kinds of pointers 1975 // Note that member pointers were filtered out with C++, above. 1976 1977 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 1978 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 1979 SrcExpr = ExprError(); 1980 return; 1981 } 1982 1983 // If either type is a pointer, the other type has to be either an 1984 // integer or a pointer. 1985 if (!DestType->isArithmeticType()) { 1986 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 1987 Self.Diag(SrcExpr.get()->getExprLoc(), 1988 diag::err_cast_pointer_from_non_pointer_int) 1989 << SrcType << SrcExpr.get()->getSourceRange(); 1990 SrcExpr = ExprError(); 1991 return; 1992 } 1993 } else if (!SrcType->isArithmeticType()) { 1994 if (!DestType->isIntegralType(Self.Context) && 1995 DestType->isArithmeticType()) { 1996 Self.Diag(SrcExpr.get()->getLocStart(), 1997 diag::err_cast_pointer_to_non_pointer_int) 1998 << SrcType << SrcExpr.get()->getSourceRange(); 1999 SrcExpr = ExprError(); 2000 return; 2001 } 2002 } 2003 2004 // ARC imposes extra restrictions on casts. 2005 if (Self.getLangOptions().ObjCAutoRefCount) { 2006 checkObjCARCConversion(Sema::CCK_CStyleCast); 2007 if (SrcExpr.isInvalid()) 2008 return; 2009 2010 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) { 2011 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 2012 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 2013 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 2014 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 2015 ExprPtr->getPointeeType()->isObjCLifetimeType() && 2016 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 2017 Self.Diag(SrcExpr.get()->getLocStart(), 2018 diag::err_typecheck_incompatible_ownership) 2019 << SrcType << DestType << Sema::AA_Casting 2020 << SrcExpr.get()->getSourceRange(); 2021 return; 2022 } 2023 } 2024 } 2025 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 2026 Self.Diag(SrcExpr.get()->getLocStart(), 2027 diag::err_arc_convesion_of_weak_unavailable) 2028 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2029 SrcExpr = ExprError(); 2030 return; 2031 } 2032 } 2033 2034 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 2035 if (SrcExpr.isInvalid()) 2036 return; 2037 2038 if (Kind == CK_BitCast) 2039 checkCastAlign(); 2040 } 2041 2042 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 2043 TypeSourceInfo *CastTypeInfo, 2044 SourceLocation RPLoc, 2045 Expr *CastExpr) { 2046 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2047 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2048 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 2049 2050 if (getLangOptions().CPlusPlus) { 2051 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false); 2052 } else { 2053 Op.CheckCStyleCast(); 2054 } 2055 2056 if (Op.SrcExpr.isInvalid()) 2057 return ExprError(); 2058 2059 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 2060 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 2061 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 2062 } 2063 2064 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 2065 SourceLocation LPLoc, 2066 Expr *CastExpr, 2067 SourceLocation RPLoc) { 2068 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2069 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2070 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 2071 2072 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true); 2073 if (Op.SrcExpr.isInvalid()) 2074 return ExprError(); 2075 2076 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 2077 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(), 2078 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc)); 2079 } 2080