SemaCast.cpp revision 321369
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/AST/ASTContext.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/ExprObjC.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Basic/TargetInfo.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Sema/Initialization.h" 27#include "llvm/ADT/SmallVector.h" 28#include <set> 29using namespace clang; 30 31 32 33enum TryCastResult { 34 TC_NotApplicable, ///< The cast method is not applicable. 35 TC_Success, ///< The cast method is appropriate and successful. 36 TC_Failed ///< The cast method is appropriate, but failed. A 37 ///< diagnostic has been emitted. 38}; 39 40enum CastType { 41 CT_Const, ///< const_cast 42 CT_Static, ///< static_cast 43 CT_Reinterpret, ///< reinterpret_cast 44 CT_Dynamic, ///< dynamic_cast 45 CT_CStyle, ///< (Type)expr 46 CT_Functional ///< Type(expr) 47}; 48 49namespace { 50 struct CastOperation { 51 CastOperation(Sema &S, QualType destType, ExprResult src) 52 : Self(S), SrcExpr(src), DestType(destType), 53 ResultType(destType.getNonLValueExprType(S.Context)), 54 ValueKind(Expr::getValueKindForType(destType)), 55 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 56 57 if (const BuiltinType *placeholder = 58 src.get()->getType()->getAsPlaceholderType()) { 59 PlaceholderKind = placeholder->getKind(); 60 } else { 61 PlaceholderKind = (BuiltinType::Kind) 0; 62 } 63 } 64 65 Sema &Self; 66 ExprResult SrcExpr; 67 QualType DestType; 68 QualType ResultType; 69 ExprValueKind ValueKind; 70 CastKind Kind; 71 BuiltinType::Kind PlaceholderKind; 72 CXXCastPath BasePath; 73 bool IsARCUnbridgedCast; 74 75 SourceRange OpRange; 76 SourceRange DestRange; 77 78 // Top-level semantics-checking routines. 79 void CheckConstCast(); 80 void CheckReinterpretCast(); 81 void CheckStaticCast(); 82 void CheckDynamicCast(); 83 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); 84 void CheckCStyleCast(); 85 86 /// Complete an apparently-successful cast operation that yields 87 /// the given expression. 88 ExprResult complete(CastExpr *castExpr) { 89 // If this is an unbridged cast, wrap the result in an implicit 90 // cast that yields the unbridged-cast placeholder type. 91 if (IsARCUnbridgedCast) { 92 castExpr = ImplicitCastExpr::Create(Self.Context, 93 Self.Context.ARCUnbridgedCastTy, 94 CK_Dependent, castExpr, nullptr, 95 castExpr->getValueKind()); 96 } 97 return castExpr; 98 } 99 100 // Internal convenience methods. 101 102 /// Try to handle the given placeholder expression kind. Return 103 /// true if the source expression has the appropriate placeholder 104 /// kind. A placeholder can only be claimed once. 105 bool claimPlaceholder(BuiltinType::Kind K) { 106 if (PlaceholderKind != K) return false; 107 108 PlaceholderKind = (BuiltinType::Kind) 0; 109 return true; 110 } 111 112 bool isPlaceholder() const { 113 return PlaceholderKind != 0; 114 } 115 bool isPlaceholder(BuiltinType::Kind K) const { 116 return PlaceholderKind == K; 117 } 118 119 void checkCastAlign() { 120 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 121 } 122 123 void checkObjCConversion(Sema::CheckedConversionKind CCK) { 124 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()); 125 126 Expr *src = SrcExpr.get(); 127 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) == 128 Sema::ACR_unbridged) 129 IsARCUnbridgedCast = true; 130 SrcExpr = src; 131 } 132 133 /// Check for and handle non-overload placeholder expressions. 134 void checkNonOverloadPlaceholders() { 135 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 136 return; 137 138 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 139 if (SrcExpr.isInvalid()) 140 return; 141 PlaceholderKind = (BuiltinType::Kind) 0; 142 } 143 }; 144} 145 146static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, 147 QualType DestType); 148 149// The Try functions attempt a specific way of casting. If they succeed, they 150// return TC_Success. If their way of casting is not appropriate for the given 151// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 152// to emit if no other way succeeds. If their way of casting is appropriate but 153// fails, they return TC_Failed and *must* set diag; they can set it to 0 if 154// they emit a specialized diagnostic. 155// All diagnostics returned by these functions must expect the same three 156// arguments: 157// %0: Cast Type (a value from the CastType enumeration) 158// %1: Source Type 159// %2: Destination Type 160static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 161 QualType DestType, bool CStyle, 162 CastKind &Kind, 163 CXXCastPath &BasePath, 164 unsigned &msg); 165static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 166 QualType DestType, bool CStyle, 167 SourceRange OpRange, 168 unsigned &msg, 169 CastKind &Kind, 170 CXXCastPath &BasePath); 171static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 172 QualType DestType, bool CStyle, 173 SourceRange OpRange, 174 unsigned &msg, 175 CastKind &Kind, 176 CXXCastPath &BasePath); 177static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 178 CanQualType DestType, bool CStyle, 179 SourceRange OpRange, 180 QualType OrigSrcType, 181 QualType OrigDestType, unsigned &msg, 182 CastKind &Kind, 183 CXXCastPath &BasePath); 184static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 185 QualType SrcType, 186 QualType DestType,bool CStyle, 187 SourceRange OpRange, 188 unsigned &msg, 189 CastKind &Kind, 190 CXXCastPath &BasePath); 191 192static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 193 QualType DestType, 194 Sema::CheckedConversionKind CCK, 195 SourceRange OpRange, 196 unsigned &msg, CastKind &Kind, 197 bool ListInitialization); 198static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 199 QualType DestType, 200 Sema::CheckedConversionKind CCK, 201 SourceRange OpRange, 202 unsigned &msg, CastKind &Kind, 203 CXXCastPath &BasePath, 204 bool ListInitialization); 205static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 206 QualType DestType, bool CStyle, 207 unsigned &msg); 208static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 209 QualType DestType, bool CStyle, 210 SourceRange OpRange, 211 unsigned &msg, 212 CastKind &Kind); 213 214 215/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 216ExprResult 217Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 218 SourceLocation LAngleBracketLoc, Declarator &D, 219 SourceLocation RAngleBracketLoc, 220 SourceLocation LParenLoc, Expr *E, 221 SourceLocation RParenLoc) { 222 223 assert(!D.isInvalidType()); 224 225 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); 226 if (D.isInvalidType()) 227 return ExprError(); 228 229 if (getLangOpts().CPlusPlus) { 230 // Check that there are no default arguments (C++ only). 231 CheckExtraCXXDefaultArguments(D); 232 } 233 234 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E, 235 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 236 SourceRange(LParenLoc, RParenLoc)); 237} 238 239ExprResult 240Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 241 TypeSourceInfo *DestTInfo, Expr *E, 242 SourceRange AngleBrackets, SourceRange Parens) { 243 ExprResult Ex = E; 244 QualType DestType = DestTInfo->getType(); 245 246 // If the type is dependent, we won't do the semantic analysis now. 247 bool TypeDependent = 248 DestType->isDependentType() || Ex.get()->isTypeDependent(); 249 250 CastOperation Op(*this, DestType, E); 251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 252 Op.DestRange = AngleBrackets; 253 254 switch (Kind) { 255 default: llvm_unreachable("Unknown C++ cast!"); 256 257 case tok::kw_const_cast: 258 if (!TypeDependent) { 259 Op.CheckConstCast(); 260 if (Op.SrcExpr.isInvalid()) 261 return ExprError(); 262 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 263 } 264 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, 265 Op.ValueKind, Op.SrcExpr.get(), DestTInfo, 266 OpLoc, Parens.getEnd(), 267 AngleBrackets)); 268 269 case tok::kw_dynamic_cast: { 270 if (!TypeDependent) { 271 Op.CheckDynamicCast(); 272 if (Op.SrcExpr.isInvalid()) 273 return ExprError(); 274 } 275 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 276 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 277 &Op.BasePath, DestTInfo, 278 OpLoc, Parens.getEnd(), 279 AngleBrackets)); 280 } 281 case tok::kw_reinterpret_cast: { 282 if (!TypeDependent) { 283 Op.CheckReinterpretCast(); 284 if (Op.SrcExpr.isInvalid()) 285 return ExprError(); 286 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 287 } 288 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 289 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 290 nullptr, DestTInfo, OpLoc, 291 Parens.getEnd(), 292 AngleBrackets)); 293 } 294 case tok::kw_static_cast: { 295 if (!TypeDependent) { 296 Op.CheckStaticCast(); 297 if (Op.SrcExpr.isInvalid()) 298 return ExprError(); 299 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 300 } 301 302 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, 303 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 304 &Op.BasePath, DestTInfo, 305 OpLoc, Parens.getEnd(), 306 AngleBrackets)); 307 } 308 } 309} 310 311/// Try to diagnose a failed overloaded cast. Returns true if 312/// diagnostics were emitted. 313static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 314 SourceRange range, Expr *src, 315 QualType destType, 316 bool listInitialization) { 317 switch (CT) { 318 // These cast kinds don't consider user-defined conversions. 319 case CT_Const: 320 case CT_Reinterpret: 321 case CT_Dynamic: 322 return false; 323 324 // These do. 325 case CT_Static: 326 case CT_CStyle: 327 case CT_Functional: 328 break; 329 } 330 331 QualType srcType = src->getType(); 332 if (!destType->isRecordType() && !srcType->isRecordType()) 333 return false; 334 335 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 336 InitializationKind initKind 337 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 338 range, listInitialization) 339 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, 340 listInitialization) 341 : InitializationKind::CreateCast(/*type range?*/ range); 342 InitializationSequence sequence(S, entity, initKind, src); 343 344 assert(sequence.Failed() && "initialization succeeded on second try?"); 345 switch (sequence.getFailureKind()) { 346 default: return false; 347 348 case InitializationSequence::FK_ConstructorOverloadFailed: 349 case InitializationSequence::FK_UserConversionOverloadFailed: 350 break; 351 } 352 353 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 354 355 unsigned msg = 0; 356 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 357 358 switch (sequence.getFailedOverloadResult()) { 359 case OR_Success: llvm_unreachable("successful failed overload"); 360 case OR_No_Viable_Function: 361 if (candidates.empty()) 362 msg = diag::err_ovl_no_conversion_in_cast; 363 else 364 msg = diag::err_ovl_no_viable_conversion_in_cast; 365 howManyCandidates = OCD_AllCandidates; 366 break; 367 368 case OR_Ambiguous: 369 msg = diag::err_ovl_ambiguous_conversion_in_cast; 370 howManyCandidates = OCD_ViableCandidates; 371 break; 372 373 case OR_Deleted: 374 msg = diag::err_ovl_deleted_conversion_in_cast; 375 howManyCandidates = OCD_ViableCandidates; 376 break; 377 } 378 379 S.Diag(range.getBegin(), msg) 380 << CT << srcType << destType 381 << range << src->getSourceRange(); 382 383 candidates.NoteCandidates(S, howManyCandidates, src); 384 385 return true; 386} 387 388/// Diagnose a failed cast. 389static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 390 SourceRange opRange, Expr *src, QualType destType, 391 bool listInitialization) { 392 if (msg == diag::err_bad_cxx_cast_generic && 393 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, 394 listInitialization)) 395 return; 396 397 S.Diag(opRange.getBegin(), msg) << castType 398 << src->getType() << destType << opRange << src->getSourceRange(); 399 400 // Detect if both types are (ptr to) class, and note any incompleteness. 401 int DifferentPtrness = 0; 402 QualType From = destType; 403 if (auto Ptr = From->getAs<PointerType>()) { 404 From = Ptr->getPointeeType(); 405 DifferentPtrness++; 406 } 407 QualType To = src->getType(); 408 if (auto Ptr = To->getAs<PointerType>()) { 409 To = Ptr->getPointeeType(); 410 DifferentPtrness--; 411 } 412 if (!DifferentPtrness) { 413 auto RecFrom = From->getAs<RecordType>(); 414 auto RecTo = To->getAs<RecordType>(); 415 if (RecFrom && RecTo) { 416 auto DeclFrom = RecFrom->getAsCXXRecordDecl(); 417 if (!DeclFrom->isCompleteDefinition()) 418 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) 419 << DeclFrom->getDeclName(); 420 auto DeclTo = RecTo->getAsCXXRecordDecl(); 421 if (!DeclTo->isCompleteDefinition()) 422 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) 423 << DeclTo->getDeclName(); 424 } 425 } 426} 427 428/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes, 429/// this removes one level of indirection from both types, provided that they're 430/// the same kind of pointer (plain or to-member). Unlike the Sema function, 431/// this one doesn't care if the two pointers-to-member don't point into the 432/// same class. This is because CastsAwayConstness doesn't care. 433/// And additionally, it handles C++ references. If both the types are 434/// references, then their pointee types are returned, 435/// else if only one of them is reference, it's pointee type is returned, 436/// and the other type is returned as-is. 437static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) { 438 const PointerType *T1PtrType = T1->getAs<PointerType>(), 439 *T2PtrType = T2->getAs<PointerType>(); 440 if (T1PtrType && T2PtrType) { 441 T1 = T1PtrType->getPointeeType(); 442 T2 = T2PtrType->getPointeeType(); 443 return true; 444 } 445 const ObjCObjectPointerType *T1ObjCPtrType = 446 T1->getAs<ObjCObjectPointerType>(), 447 *T2ObjCPtrType = 448 T2->getAs<ObjCObjectPointerType>(); 449 if (T1ObjCPtrType) { 450 if (T2ObjCPtrType) { 451 T1 = T1ObjCPtrType->getPointeeType(); 452 T2 = T2ObjCPtrType->getPointeeType(); 453 return true; 454 } 455 else if (T2PtrType) { 456 T1 = T1ObjCPtrType->getPointeeType(); 457 T2 = T2PtrType->getPointeeType(); 458 return true; 459 } 460 } 461 else if (T2ObjCPtrType) { 462 if (T1PtrType) { 463 T2 = T2ObjCPtrType->getPointeeType(); 464 T1 = T1PtrType->getPointeeType(); 465 return true; 466 } 467 } 468 469 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 470 *T2MPType = T2->getAs<MemberPointerType>(); 471 if (T1MPType && T2MPType) { 472 T1 = T1MPType->getPointeeType(); 473 T2 = T2MPType->getPointeeType(); 474 return true; 475 } 476 477 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(), 478 *T2BPType = T2->getAs<BlockPointerType>(); 479 if (T1BPType && T2BPType) { 480 T1 = T1BPType->getPointeeType(); 481 T2 = T2BPType->getPointeeType(); 482 return true; 483 } 484 485 const LValueReferenceType *T1RefType = T1->getAs<LValueReferenceType>(), 486 *T2RefType = T2->getAs<LValueReferenceType>(); 487 if (T1RefType && T2RefType) { 488 T1 = T1RefType->getPointeeType(); 489 T2 = T2RefType->getPointeeType(); 490 return true; 491 } 492 493 if (T1RefType) { 494 T1 = T1RefType->getPointeeType(); 495 // T2 = T2; 496 return true; 497 } 498 499 if (T2RefType) { 500 // T1 = T1; 501 T2 = T2RefType->getPointeeType(); 502 return true; 503 } 504 505 return false; 506} 507 508/// CastsAwayConstness - Check if the pointer conversion from SrcType to 509/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by 510/// the cast checkers. Both arguments must denote pointer (possibly to member) 511/// types. 512/// 513/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 514/// 515/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 516static bool 517CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 518 bool CheckCVR, bool CheckObjCLifetime, 519 QualType *TheOffendingSrcType = nullptr, 520 QualType *TheOffendingDestType = nullptr, 521 Qualifiers *CastAwayQualifiers = nullptr) { 522 // If the only checking we care about is for Objective-C lifetime qualifiers, 523 // and we're not in ObjC mode, there's nothing to check. 524 if (!CheckCVR && CheckObjCLifetime && 525 !Self.Context.getLangOpts().ObjC1) 526 return false; 527 528 // Casting away constness is defined in C++ 5.2.11p8 with reference to 529 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since 530 // the rules are non-trivial. So first we construct Tcv *...cv* as described 531 // in C++ 5.2.11p8. 532 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 533 SrcType->isBlockPointerType() || 534 DestType->isLValueReferenceType()) && 535 "Source type is not pointer or pointer to member."); 536 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 537 DestType->isBlockPointerType() || 538 DestType->isLValueReferenceType()) && 539 "Destination type is not pointer or pointer to member, or reference."); 540 541 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 542 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 543 SmallVector<Qualifiers, 8> cv1, cv2; 544 545 // Find the qualifiers. We only care about cvr-qualifiers for the 546 // purpose of this check, because other qualifiers (address spaces, 547 // Objective-C GC, etc.) are part of the type's identity. 548 QualType PrevUnwrappedSrcType = UnwrappedSrcType; 549 QualType PrevUnwrappedDestType = UnwrappedDestType; 550 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 551 // Determine the relevant qualifiers at this level. 552 Qualifiers SrcQuals, DestQuals; 553 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 554 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 555 556 Qualifiers RetainedSrcQuals, RetainedDestQuals; 557 if (CheckCVR) { 558 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers()); 559 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers()); 560 561 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType && 562 TheOffendingDestType && CastAwayQualifiers) { 563 *TheOffendingSrcType = PrevUnwrappedSrcType; 564 *TheOffendingDestType = PrevUnwrappedDestType; 565 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals; 566 } 567 } 568 569 if (CheckObjCLifetime && 570 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 571 return true; 572 573 cv1.push_back(RetainedSrcQuals); 574 cv2.push_back(RetainedDestQuals); 575 576 PrevUnwrappedSrcType = UnwrappedSrcType; 577 PrevUnwrappedDestType = UnwrappedDestType; 578 } 579 if (cv1.empty()) 580 return false; 581 582 // Construct void pointers with those qualifiers (in reverse order of 583 // unwrapping, of course). 584 QualType SrcConstruct = Self.Context.VoidTy; 585 QualType DestConstruct = Self.Context.VoidTy; 586 ASTContext &Context = Self.Context; 587 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(), 588 i2 = cv2.rbegin(); 589 i1 != cv1.rend(); ++i1, ++i2) { 590 SrcConstruct 591 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1)); 592 DestConstruct 593 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2)); 594 } 595 596 // Test if they're compatible. 597 bool ObjCLifetimeConversion; 598 return SrcConstruct != DestConstruct && 599 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false, 600 ObjCLifetimeConversion); 601} 602 603/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 604/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 605/// checked downcasts in class hierarchies. 606void CastOperation::CheckDynamicCast() { 607 if (ValueKind == VK_RValue) 608 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 609 else if (isPlaceholder()) 610 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 611 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 612 return; 613 614 QualType OrigSrcType = SrcExpr.get()->getType(); 615 QualType DestType = Self.Context.getCanonicalType(this->DestType); 616 617 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 618 // or "pointer to cv void". 619 620 QualType DestPointee; 621 const PointerType *DestPointer = DestType->getAs<PointerType>(); 622 const ReferenceType *DestReference = nullptr; 623 if (DestPointer) { 624 DestPointee = DestPointer->getPointeeType(); 625 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 626 DestPointee = DestReference->getPointeeType(); 627 } else { 628 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 629 << this->DestType << DestRange; 630 SrcExpr = ExprError(); 631 return; 632 } 633 634 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 635 if (DestPointee->isVoidType()) { 636 assert(DestPointer && "Reference to void is not possible"); 637 } else if (DestRecord) { 638 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 639 diag::err_bad_dynamic_cast_incomplete, 640 DestRange)) { 641 SrcExpr = ExprError(); 642 return; 643 } 644 } else { 645 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 646 << DestPointee.getUnqualifiedType() << DestRange; 647 SrcExpr = ExprError(); 648 return; 649 } 650 651 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 652 // complete class type, [...]. If T is an lvalue reference type, v shall be 653 // an lvalue of a complete class type, [...]. If T is an rvalue reference 654 // type, v shall be an expression having a complete class type, [...] 655 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 656 QualType SrcPointee; 657 if (DestPointer) { 658 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 659 SrcPointee = SrcPointer->getPointeeType(); 660 } else { 661 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 662 << OrigSrcType << SrcExpr.get()->getSourceRange(); 663 SrcExpr = ExprError(); 664 return; 665 } 666 } else if (DestReference->isLValueReferenceType()) { 667 if (!SrcExpr.get()->isLValue()) { 668 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 669 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 670 } 671 SrcPointee = SrcType; 672 } else { 673 // If we're dynamic_casting from a prvalue to an rvalue reference, we need 674 // to materialize the prvalue before we bind the reference to it. 675 if (SrcExpr.get()->isRValue()) 676 SrcExpr = Self.CreateMaterializeTemporaryExpr( 677 SrcType, SrcExpr.get(), /*IsLValueReference*/ false); 678 SrcPointee = SrcType; 679 } 680 681 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 682 if (SrcRecord) { 683 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 684 diag::err_bad_dynamic_cast_incomplete, 685 SrcExpr.get())) { 686 SrcExpr = ExprError(); 687 return; 688 } 689 } else { 690 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 691 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 692 SrcExpr = ExprError(); 693 return; 694 } 695 696 assert((DestPointer || DestReference) && 697 "Bad destination non-ptr/ref slipped through."); 698 assert((DestRecord || DestPointee->isVoidType()) && 699 "Bad destination pointee slipped through."); 700 assert(SrcRecord && "Bad source pointee slipped through."); 701 702 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 703 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 704 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 705 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 706 SrcExpr = ExprError(); 707 return; 708 } 709 710 // C++ 5.2.7p3: If the type of v is the same as the required result type, 711 // [except for cv]. 712 if (DestRecord == SrcRecord) { 713 Kind = CK_NoOp; 714 return; 715 } 716 717 // C++ 5.2.7p5 718 // Upcasts are resolved statically. 719 if (DestRecord && 720 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { 721 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 722 OpRange.getBegin(), OpRange, 723 &BasePath)) { 724 SrcExpr = ExprError(); 725 return; 726 } 727 728 Kind = CK_DerivedToBase; 729 return; 730 } 731 732 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 733 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 734 assert(SrcDecl && "Definition missing"); 735 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 736 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 737 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 738 SrcExpr = ExprError(); 739 } 740 741 // dynamic_cast is not available with -fno-rtti. 742 // As an exception, dynamic_cast to void* is available because it doesn't 743 // use RTTI. 744 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { 745 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); 746 SrcExpr = ExprError(); 747 return; 748 } 749 750 // Done. Everything else is run-time checks. 751 Kind = CK_Dynamic; 752} 753 754/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 755/// Refer to C++ 5.2.11 for details. const_cast is typically used in code 756/// like this: 757/// const char *str = "literal"; 758/// legacy_function(const_cast\<char*\>(str)); 759void CastOperation::CheckConstCast() { 760 if (ValueKind == VK_RValue) 761 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 762 else if (isPlaceholder()) 763 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 764 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 765 return; 766 767 unsigned msg = diag::err_bad_cxx_cast_generic; 768 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success 769 && msg != 0) { 770 Self.Diag(OpRange.getBegin(), msg) << CT_Const 771 << SrcExpr.get()->getType() << DestType << OpRange; 772 SrcExpr = ExprError(); 773 } 774} 775 776/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast 777/// or downcast between respective pointers or references. 778static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, 779 QualType DestType, 780 SourceRange OpRange) { 781 QualType SrcType = SrcExpr->getType(); 782 // When casting from pointer or reference, get pointee type; use original 783 // type otherwise. 784 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); 785 const CXXRecordDecl *SrcRD = 786 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); 787 788 // Examining subobjects for records is only possible if the complete and 789 // valid definition is available. Also, template instantiation is not 790 // allowed here. 791 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) 792 return; 793 794 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); 795 796 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) 797 return; 798 799 enum { 800 ReinterpretUpcast, 801 ReinterpretDowncast 802 } ReinterpretKind; 803 804 CXXBasePaths BasePaths; 805 806 if (SrcRD->isDerivedFrom(DestRD, BasePaths)) 807 ReinterpretKind = ReinterpretUpcast; 808 else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) 809 ReinterpretKind = ReinterpretDowncast; 810 else 811 return; 812 813 bool VirtualBase = true; 814 bool NonZeroOffset = false; 815 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), 816 E = BasePaths.end(); 817 I != E; ++I) { 818 const CXXBasePath &Path = *I; 819 CharUnits Offset = CharUnits::Zero(); 820 bool IsVirtual = false; 821 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); 822 IElem != EElem; ++IElem) { 823 IsVirtual = IElem->Base->isVirtual(); 824 if (IsVirtual) 825 break; 826 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); 827 assert(BaseRD && "Base type should be a valid unqualified class type"); 828 // Don't check if any base has invalid declaration or has no definition 829 // since it has no layout info. 830 const CXXRecordDecl *Class = IElem->Class, 831 *ClassDefinition = Class->getDefinition(); 832 if (Class->isInvalidDecl() || !ClassDefinition || 833 !ClassDefinition->isCompleteDefinition()) 834 return; 835 836 const ASTRecordLayout &DerivedLayout = 837 Self.Context.getASTRecordLayout(Class); 838 Offset += DerivedLayout.getBaseClassOffset(BaseRD); 839 } 840 if (!IsVirtual) { 841 // Don't warn if any path is a non-virtually derived base at offset zero. 842 if (Offset.isZero()) 843 return; 844 // Offset makes sense only for non-virtual bases. 845 else 846 NonZeroOffset = true; 847 } 848 VirtualBase = VirtualBase && IsVirtual; 849 } 850 851 (void) NonZeroOffset; // Silence set but not used warning. 852 assert((VirtualBase || NonZeroOffset) && 853 "Should have returned if has non-virtual base with zero offset"); 854 855 QualType BaseType = 856 ReinterpretKind == ReinterpretUpcast? DestType : SrcType; 857 QualType DerivedType = 858 ReinterpretKind == ReinterpretUpcast? SrcType : DestType; 859 860 SourceLocation BeginLoc = OpRange.getBegin(); 861 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) 862 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) 863 << OpRange; 864 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) 865 << int(ReinterpretKind) 866 << FixItHint::CreateReplacement(BeginLoc, "static_cast"); 867} 868 869/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 870/// valid. 871/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 872/// like this: 873/// char *bytes = reinterpret_cast\<char*\>(int_ptr); 874void CastOperation::CheckReinterpretCast() { 875 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) 876 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 877 else 878 checkNonOverloadPlaceholders(); 879 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 880 return; 881 882 unsigned msg = diag::err_bad_cxx_cast_generic; 883 TryCastResult tcr = 884 TryReinterpretCast(Self, SrcExpr, DestType, 885 /*CStyle*/false, OpRange, msg, Kind); 886 if (tcr != TC_Success && msg != 0) 887 { 888 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 889 return; 890 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 891 //FIXME: &f<int>; is overloaded and resolvable 892 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 893 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 894 << DestType << OpRange; 895 Self.NoteAllOverloadCandidates(SrcExpr.get()); 896 897 } else { 898 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), 899 DestType, /*listInitialization=*/false); 900 } 901 SrcExpr = ExprError(); 902 } else if (tcr == TC_Success) { 903 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 904 checkObjCConversion(Sema::CCK_OtherCast); 905 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); 906 } 907} 908 909 910/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 911/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 912/// implicit conversions explicit and getting rid of data loss warnings. 913void CastOperation::CheckStaticCast() { 914 if (isPlaceholder()) { 915 checkNonOverloadPlaceholders(); 916 if (SrcExpr.isInvalid()) 917 return; 918 } 919 920 // This test is outside everything else because it's the only case where 921 // a non-lvalue-reference target type does not lead to decay. 922 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 923 if (DestType->isVoidType()) { 924 Kind = CK_ToVoid; 925 926 if (claimPlaceholder(BuiltinType::Overload)) { 927 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 928 false, // Decay Function to ptr 929 true, // Complain 930 OpRange, DestType, diag::err_bad_static_cast_overload); 931 if (SrcExpr.isInvalid()) 932 return; 933 } 934 935 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 936 return; 937 } 938 939 if (ValueKind == VK_RValue && !DestType->isRecordType() && 940 !isPlaceholder(BuiltinType::Overload)) { 941 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 942 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 943 return; 944 } 945 946 unsigned msg = diag::err_bad_cxx_cast_generic; 947 TryCastResult tcr 948 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 949 Kind, BasePath, /*ListInitialization=*/false); 950 if (tcr != TC_Success && msg != 0) { 951 if (SrcExpr.isInvalid()) 952 return; 953 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 954 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 955 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 956 << oe->getName() << DestType << OpRange 957 << oe->getQualifierLoc().getSourceRange(); 958 Self.NoteAllOverloadCandidates(SrcExpr.get()); 959 } else { 960 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, 961 /*listInitialization=*/false); 962 } 963 SrcExpr = ExprError(); 964 } else if (tcr == TC_Success) { 965 if (Kind == CK_BitCast) 966 checkCastAlign(); 967 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 968 checkObjCConversion(Sema::CCK_OtherCast); 969 } else if (Kind == CK_BitCast) { 970 checkCastAlign(); 971 } 972} 973 974/// TryStaticCast - Check if a static cast can be performed, and do so if 975/// possible. If @p CStyle, ignore access restrictions on hierarchy casting 976/// and casting away constness. 977static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 978 QualType DestType, 979 Sema::CheckedConversionKind CCK, 980 SourceRange OpRange, unsigned &msg, 981 CastKind &Kind, CXXCastPath &BasePath, 982 bool ListInitialization) { 983 // Determine whether we have the semantics of a C-style cast. 984 bool CStyle 985 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 986 987 // The order the tests is not entirely arbitrary. There is one conversion 988 // that can be handled in two different ways. Given: 989 // struct A {}; 990 // struct B : public A { 991 // B(); B(const A&); 992 // }; 993 // const A &a = B(); 994 // the cast static_cast<const B&>(a) could be seen as either a static 995 // reference downcast, or an explicit invocation of the user-defined 996 // conversion using B's conversion constructor. 997 // DR 427 specifies that the downcast is to be applied here. 998 999 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1000 // Done outside this function. 1001 1002 TryCastResult tcr; 1003 1004 // C++ 5.2.9p5, reference downcast. 1005 // See the function for details. 1006 // DR 427 specifies that this is to be applied before paragraph 2. 1007 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, 1008 OpRange, msg, Kind, BasePath); 1009 if (tcr != TC_NotApplicable) 1010 return tcr; 1011 1012 // C++11 [expr.static.cast]p3: 1013 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 1014 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1015 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 1016 BasePath, msg); 1017 if (tcr != TC_NotApplicable) 1018 return tcr; 1019 1020 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 1021 // [...] if the declaration "T t(e);" is well-formed, [...]. 1022 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 1023 Kind, ListInitialization); 1024 if (SrcExpr.isInvalid()) 1025 return TC_Failed; 1026 if (tcr != TC_NotApplicable) 1027 return tcr; 1028 1029 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 1030 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 1031 // conversions, subject to further restrictions. 1032 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 1033 // of qualification conversions impossible. 1034 // In the CStyle case, the earlier attempt to const_cast should have taken 1035 // care of reverse qualification conversions. 1036 1037 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 1038 1039 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 1040 // converted to an integral type. [...] A value of a scoped enumeration type 1041 // can also be explicitly converted to a floating-point type [...]. 1042 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 1043 if (Enum->getDecl()->isScoped()) { 1044 if (DestType->isBooleanType()) { 1045 Kind = CK_IntegralToBoolean; 1046 return TC_Success; 1047 } else if (DestType->isIntegralType(Self.Context)) { 1048 Kind = CK_IntegralCast; 1049 return TC_Success; 1050 } else if (DestType->isRealFloatingType()) { 1051 Kind = CK_IntegralToFloating; 1052 return TC_Success; 1053 } 1054 } 1055 } 1056 1057 // Reverse integral promotion/conversion. All such conversions are themselves 1058 // again integral promotions or conversions and are thus already handled by 1059 // p2 (TryDirectInitialization above). 1060 // (Note: any data loss warnings should be suppressed.) 1061 // The exception is the reverse of enum->integer, i.e. integer->enum (and 1062 // enum->enum). See also C++ 5.2.9p7. 1063 // The same goes for reverse floating point promotion/conversion and 1064 // floating-integral conversions. Again, only floating->enum is relevant. 1065 if (DestType->isEnumeralType()) { 1066 if (SrcType->isIntegralOrEnumerationType()) { 1067 Kind = CK_IntegralCast; 1068 return TC_Success; 1069 } else if (SrcType->isRealFloatingType()) { 1070 Kind = CK_FloatingToIntegral; 1071 return TC_Success; 1072 } 1073 } 1074 1075 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 1076 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 1077 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 1078 Kind, BasePath); 1079 if (tcr != TC_NotApplicable) 1080 return tcr; 1081 1082 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 1083 // conversion. C++ 5.2.9p9 has additional information. 1084 // DR54's access restrictions apply here also. 1085 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 1086 OpRange, msg, Kind, BasePath); 1087 if (tcr != TC_NotApplicable) 1088 return tcr; 1089 1090 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 1091 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 1092 // just the usual constness stuff. 1093 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 1094 QualType SrcPointee = SrcPointer->getPointeeType(); 1095 if (SrcPointee->isVoidType()) { 1096 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 1097 QualType DestPointee = DestPointer->getPointeeType(); 1098 if (DestPointee->isIncompleteOrObjectType()) { 1099 // This is definitely the intended conversion, but it might fail due 1100 // to a qualifier violation. Note that we permit Objective-C lifetime 1101 // and GC qualifier mismatches here. 1102 if (!CStyle) { 1103 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 1104 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 1105 DestPointeeQuals.removeObjCGCAttr(); 1106 DestPointeeQuals.removeObjCLifetime(); 1107 SrcPointeeQuals.removeObjCGCAttr(); 1108 SrcPointeeQuals.removeObjCLifetime(); 1109 if (DestPointeeQuals != SrcPointeeQuals && 1110 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 1111 msg = diag::err_bad_cxx_cast_qualifiers_away; 1112 return TC_Failed; 1113 } 1114 } 1115 Kind = CK_BitCast; 1116 return TC_Success; 1117 } 1118 1119 // Microsoft permits static_cast from 'pointer-to-void' to 1120 // 'pointer-to-function'. 1121 if (!CStyle && Self.getLangOpts().MSVCCompat && 1122 DestPointee->isFunctionType()) { 1123 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; 1124 Kind = CK_BitCast; 1125 return TC_Success; 1126 } 1127 } 1128 else if (DestType->isObjCObjectPointerType()) { 1129 // allow both c-style cast and static_cast of objective-c pointers as 1130 // they are pervasive. 1131 Kind = CK_CPointerToObjCPointerCast; 1132 return TC_Success; 1133 } 1134 else if (CStyle && DestType->isBlockPointerType()) { 1135 // allow c-style cast of void * to block pointers. 1136 Kind = CK_AnyPointerToBlockPointerCast; 1137 return TC_Success; 1138 } 1139 } 1140 } 1141 // Allow arbitray objective-c pointer conversion with static casts. 1142 if (SrcType->isObjCObjectPointerType() && 1143 DestType->isObjCObjectPointerType()) { 1144 Kind = CK_BitCast; 1145 return TC_Success; 1146 } 1147 // Allow ns-pointer to cf-pointer conversion in either direction 1148 // with static casts. 1149 if (!CStyle && 1150 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) 1151 return TC_Success; 1152 1153 // See if it looks like the user is trying to convert between 1154 // related record types, and select a better diagnostic if so. 1155 if (auto SrcPointer = SrcType->getAs<PointerType>()) 1156 if (auto DestPointer = DestType->getAs<PointerType>()) 1157 if (SrcPointer->getPointeeType()->getAs<RecordType>() && 1158 DestPointer->getPointeeType()->getAs<RecordType>()) 1159 msg = diag::err_bad_cxx_cast_unrelated_class; 1160 1161 // We tried everything. Everything! Nothing works! :-( 1162 return TC_NotApplicable; 1163} 1164 1165/// Tests whether a conversion according to N2844 is valid. 1166TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 1167 QualType DestType, bool CStyle, 1168 CastKind &Kind, CXXCastPath &BasePath, 1169 unsigned &msg) { 1170 // C++11 [expr.static.cast]p3: 1171 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 1172 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1173 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 1174 if (!R) 1175 return TC_NotApplicable; 1176 1177 if (!SrcExpr->isGLValue()) 1178 return TC_NotApplicable; 1179 1180 // Because we try the reference downcast before this function, from now on 1181 // this is the only cast possibility, so we issue an error if we fail now. 1182 // FIXME: Should allow casting away constness if CStyle. 1183 bool DerivedToBase; 1184 bool ObjCConversion; 1185 bool ObjCLifetimeConversion; 1186 QualType FromType = SrcExpr->getType(); 1187 QualType ToType = R->getPointeeType(); 1188 if (CStyle) { 1189 FromType = FromType.getUnqualifiedType(); 1190 ToType = ToType.getUnqualifiedType(); 1191 } 1192 1193 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship( 1194 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion, 1195 ObjCLifetimeConversion); 1196 if (RefResult != Sema::Ref_Compatible) { 1197 if (CStyle || RefResult == Sema::Ref_Incompatible) 1198 return TC_NotApplicable; 1199 // Diagnose types which are reference-related but not compatible here since 1200 // we can provide better diagnostics. In these cases forwarding to 1201 // [expr.static.cast]p4 should never result in a well-formed cast. 1202 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast 1203 : diag::err_bad_rvalue_to_rvalue_cast; 1204 return TC_Failed; 1205 } 1206 1207 if (DerivedToBase) { 1208 Kind = CK_DerivedToBase; 1209 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1210 /*DetectVirtual=*/true); 1211 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(), 1212 R->getPointeeType(), Paths)) 1213 return TC_NotApplicable; 1214 1215 Self.BuildBasePathArray(Paths, BasePath); 1216 } else 1217 Kind = CK_NoOp; 1218 1219 return TC_Success; 1220} 1221 1222/// Tests whether a conversion according to C++ 5.2.9p5 is valid. 1223TryCastResult 1224TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 1225 bool CStyle, SourceRange OpRange, 1226 unsigned &msg, CastKind &Kind, 1227 CXXCastPath &BasePath) { 1228 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 1229 // cast to type "reference to cv2 D", where D is a class derived from B, 1230 // if a valid standard conversion from "pointer to D" to "pointer to B" 1231 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1232 // In addition, DR54 clarifies that the base must be accessible in the 1233 // current context. Although the wording of DR54 only applies to the pointer 1234 // variant of this rule, the intent is clearly for it to apply to the this 1235 // conversion as well. 1236 1237 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1238 if (!DestReference) { 1239 return TC_NotApplicable; 1240 } 1241 bool RValueRef = DestReference->isRValueReferenceType(); 1242 if (!RValueRef && !SrcExpr->isLValue()) { 1243 // We know the left side is an lvalue reference, so we can suggest a reason. 1244 msg = diag::err_bad_cxx_cast_rvalue; 1245 return TC_NotApplicable; 1246 } 1247 1248 QualType DestPointee = DestReference->getPointeeType(); 1249 1250 // FIXME: If the source is a prvalue, we should issue a warning (because the 1251 // cast always has undefined behavior), and for AST consistency, we should 1252 // materialize a temporary. 1253 return TryStaticDowncast(Self, 1254 Self.Context.getCanonicalType(SrcExpr->getType()), 1255 Self.Context.getCanonicalType(DestPointee), CStyle, 1256 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1257 BasePath); 1258} 1259 1260/// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1261TryCastResult 1262TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1263 bool CStyle, SourceRange OpRange, 1264 unsigned &msg, CastKind &Kind, 1265 CXXCastPath &BasePath) { 1266 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1267 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1268 // is a class derived from B, if a valid standard conversion from "pointer 1269 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1270 // class of D. 1271 // In addition, DR54 clarifies that the base must be accessible in the 1272 // current context. 1273 1274 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1275 if (!DestPointer) { 1276 return TC_NotApplicable; 1277 } 1278 1279 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1280 if (!SrcPointer) { 1281 msg = diag::err_bad_static_cast_pointer_nonpointer; 1282 return TC_NotApplicable; 1283 } 1284 1285 return TryStaticDowncast(Self, 1286 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1287 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1288 CStyle, OpRange, SrcType, DestType, msg, Kind, 1289 BasePath); 1290} 1291 1292/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1293/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1294/// DestType is possible and allowed. 1295TryCastResult 1296TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1297 bool CStyle, SourceRange OpRange, QualType OrigSrcType, 1298 QualType OrigDestType, unsigned &msg, 1299 CastKind &Kind, CXXCastPath &BasePath) { 1300 // We can only work with complete types. But don't complain if it doesn't work 1301 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || 1302 !Self.isCompleteType(OpRange.getBegin(), DestType)) 1303 return TC_NotApplicable; 1304 1305 // Downcast can only happen in class hierarchies, so we need classes. 1306 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1307 return TC_NotApplicable; 1308 } 1309 1310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1311 /*DetectVirtual=*/true); 1312 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { 1313 return TC_NotApplicable; 1314 } 1315 1316 // Target type does derive from source type. Now we're serious. If an error 1317 // appears now, it's not ignored. 1318 // This may not be entirely in line with the standard. Take for example: 1319 // struct A {}; 1320 // struct B : virtual A { 1321 // B(A&); 1322 // }; 1323 // 1324 // void f() 1325 // { 1326 // (void)static_cast<const B&>(*((A*)0)); 1327 // } 1328 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1329 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1330 // However, both GCC and Comeau reject this example, and accepting it would 1331 // mean more complex code if we're to preserve the nice error message. 1332 // FIXME: Being 100% compliant here would be nice to have. 1333 1334 // Must preserve cv, as always, unless we're in C-style mode. 1335 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1336 msg = diag::err_bad_cxx_cast_qualifiers_away; 1337 return TC_Failed; 1338 } 1339 1340 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1341 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1342 // that it builds the paths in reverse order. 1343 // To sum up: record all paths to the base and build a nice string from 1344 // them. Use it to spice up the error message. 1345 if (!Paths.isRecordingPaths()) { 1346 Paths.clear(); 1347 Paths.setRecordingPaths(true); 1348 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); 1349 } 1350 std::string PathDisplayStr; 1351 std::set<unsigned> DisplayedPaths; 1352 for (clang::CXXBasePath &Path : Paths) { 1353 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) { 1354 // We haven't displayed a path to this particular base 1355 // class subobject yet. 1356 PathDisplayStr += "\n "; 1357 for (CXXBasePathElement &PE : llvm::reverse(Path)) 1358 PathDisplayStr += PE.Base->getType().getAsString() + " -> "; 1359 PathDisplayStr += QualType(DestType).getAsString(); 1360 } 1361 } 1362 1363 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1364 << QualType(SrcType).getUnqualifiedType() 1365 << QualType(DestType).getUnqualifiedType() 1366 << PathDisplayStr << OpRange; 1367 msg = 0; 1368 return TC_Failed; 1369 } 1370 1371 if (Paths.getDetectedVirtual() != nullptr) { 1372 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1373 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1374 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1375 msg = 0; 1376 return TC_Failed; 1377 } 1378 1379 if (!CStyle) { 1380 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1381 SrcType, DestType, 1382 Paths.front(), 1383 diag::err_downcast_from_inaccessible_base)) { 1384 case Sema::AR_accessible: 1385 case Sema::AR_delayed: // be optimistic 1386 case Sema::AR_dependent: // be optimistic 1387 break; 1388 1389 case Sema::AR_inaccessible: 1390 msg = 0; 1391 return TC_Failed; 1392 } 1393 } 1394 1395 Self.BuildBasePathArray(Paths, BasePath); 1396 Kind = CK_BaseToDerived; 1397 return TC_Success; 1398} 1399 1400/// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1401/// C++ 5.2.9p9 is valid: 1402/// 1403/// An rvalue of type "pointer to member of D of type cv1 T" can be 1404/// converted to an rvalue of type "pointer to member of B of type cv2 T", 1405/// where B is a base class of D [...]. 1406/// 1407TryCastResult 1408TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1409 QualType DestType, bool CStyle, 1410 SourceRange OpRange, 1411 unsigned &msg, CastKind &Kind, 1412 CXXCastPath &BasePath) { 1413 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1414 if (!DestMemPtr) 1415 return TC_NotApplicable; 1416 1417 bool WasOverloadedFunction = false; 1418 DeclAccessPair FoundOverload; 1419 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1420 if (FunctionDecl *Fn 1421 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1422 FoundOverload)) { 1423 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1424 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1425 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1426 WasOverloadedFunction = true; 1427 } 1428 } 1429 1430 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1431 if (!SrcMemPtr) { 1432 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1433 return TC_NotApplicable; 1434 } 1435 1436 // Lock down the inheritance model right now in MS ABI, whether or not the 1437 // pointee types are the same. 1438 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1439 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 1440 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 1441 } 1442 1443 // T == T, modulo cv 1444 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1445 DestMemPtr->getPointeeType())) 1446 return TC_NotApplicable; 1447 1448 // B base of D 1449 QualType SrcClass(SrcMemPtr->getClass(), 0); 1450 QualType DestClass(DestMemPtr->getClass(), 0); 1451 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1452 /*DetectVirtual=*/true); 1453 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) 1454 return TC_NotApplicable; 1455 1456 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1457 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1458 Paths.clear(); 1459 Paths.setRecordingPaths(true); 1460 bool StillOkay = 1461 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); 1462 assert(StillOkay); 1463 (void)StillOkay; 1464 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1465 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1466 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1467 msg = 0; 1468 return TC_Failed; 1469 } 1470 1471 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1472 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1473 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1474 msg = 0; 1475 return TC_Failed; 1476 } 1477 1478 if (!CStyle) { 1479 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1480 DestClass, SrcClass, 1481 Paths.front(), 1482 diag::err_upcast_to_inaccessible_base)) { 1483 case Sema::AR_accessible: 1484 case Sema::AR_delayed: 1485 case Sema::AR_dependent: 1486 // Optimistically assume that the delayed and dependent cases 1487 // will work out. 1488 break; 1489 1490 case Sema::AR_inaccessible: 1491 msg = 0; 1492 return TC_Failed; 1493 } 1494 } 1495 1496 if (WasOverloadedFunction) { 1497 // Resolve the address of the overloaded function again, this time 1498 // allowing complaints if something goes wrong. 1499 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1500 DestType, 1501 true, 1502 FoundOverload); 1503 if (!Fn) { 1504 msg = 0; 1505 return TC_Failed; 1506 } 1507 1508 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1509 if (!SrcExpr.isUsable()) { 1510 msg = 0; 1511 return TC_Failed; 1512 } 1513 } 1514 1515 Self.BuildBasePathArray(Paths, BasePath); 1516 Kind = CK_DerivedToBaseMemberPointer; 1517 return TC_Success; 1518} 1519 1520/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1521/// is valid: 1522/// 1523/// An expression e can be explicitly converted to a type T using a 1524/// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1525TryCastResult 1526TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1527 Sema::CheckedConversionKind CCK, 1528 SourceRange OpRange, unsigned &msg, 1529 CastKind &Kind, bool ListInitialization) { 1530 if (DestType->isRecordType()) { 1531 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1532 diag::err_bad_dynamic_cast_incomplete) || 1533 Self.RequireNonAbstractType(OpRange.getBegin(), DestType, 1534 diag::err_allocation_of_abstract_type)) { 1535 msg = 0; 1536 return TC_Failed; 1537 } 1538 } 1539 1540 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1541 InitializationKind InitKind 1542 = (CCK == Sema::CCK_CStyleCast) 1543 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, 1544 ListInitialization) 1545 : (CCK == Sema::CCK_FunctionalCast) 1546 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) 1547 : InitializationKind::CreateCast(OpRange); 1548 Expr *SrcExprRaw = SrcExpr.get(); 1549 // FIXME: Per DR242, we should check for an implicit conversion sequence 1550 // or for a constructor that could be invoked by direct-initialization 1551 // here, not for an initialization sequence. 1552 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); 1553 1554 // At this point of CheckStaticCast, if the destination is a reference, 1555 // or the expression is an overload expression this has to work. 1556 // There is no other way that works. 1557 // On the other hand, if we're checking a C-style cast, we've still got 1558 // the reinterpret_cast way. 1559 bool CStyle 1560 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1561 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1562 return TC_NotApplicable; 1563 1564 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); 1565 if (Result.isInvalid()) { 1566 msg = 0; 1567 return TC_Failed; 1568 } 1569 1570 if (InitSeq.isConstructorInitialization()) 1571 Kind = CK_ConstructorConversion; 1572 else 1573 Kind = CK_NoOp; 1574 1575 SrcExpr = Result; 1576 return TC_Success; 1577} 1578 1579/// TryConstCast - See if a const_cast from source to destination is allowed, 1580/// and perform it if it is. 1581static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 1582 QualType DestType, bool CStyle, 1583 unsigned &msg) { 1584 DestType = Self.Context.getCanonicalType(DestType); 1585 QualType SrcType = SrcExpr.get()->getType(); 1586 bool NeedToMaterializeTemporary = false; 1587 1588 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1589 // C++11 5.2.11p4: 1590 // if a pointer to T1 can be explicitly converted to the type "pointer to 1591 // T2" using a const_cast, then the following conversions can also be 1592 // made: 1593 // -- an lvalue of type T1 can be explicitly converted to an lvalue of 1594 // type T2 using the cast const_cast<T2&>; 1595 // -- a glvalue of type T1 can be explicitly converted to an xvalue of 1596 // type T2 using the cast const_cast<T2&&>; and 1597 // -- if T1 is a class type, a prvalue of type T1 can be explicitly 1598 // converted to an xvalue of type T2 using the cast const_cast<T2&&>. 1599 1600 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { 1601 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1602 // is C-style, static_cast might find a way, so we simply suggest a 1603 // message and tell the parent to keep searching. 1604 msg = diag::err_bad_cxx_cast_rvalue; 1605 return TC_NotApplicable; 1606 } 1607 1608 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) { 1609 if (!SrcType->isRecordType()) { 1610 // Cannot const_cast non-class prvalue to rvalue reference type. But if 1611 // this is C-style, static_cast can do this. 1612 msg = diag::err_bad_cxx_cast_rvalue; 1613 return TC_NotApplicable; 1614 } 1615 1616 // Materialize the class prvalue so that the const_cast can bind a 1617 // reference to it. 1618 NeedToMaterializeTemporary = true; 1619 } 1620 1621 // It's not completely clear under the standard whether we can 1622 // const_cast bit-field gl-values. Doing so would not be 1623 // intrinsically complicated, but for now, we say no for 1624 // consistency with other compilers and await the word of the 1625 // committee. 1626 if (SrcExpr.get()->refersToBitField()) { 1627 msg = diag::err_bad_cxx_cast_bitfield; 1628 return TC_NotApplicable; 1629 } 1630 1631 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1632 SrcType = Self.Context.getPointerType(SrcType); 1633 } 1634 1635 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1636 // the rules for const_cast are the same as those used for pointers. 1637 1638 if (!DestType->isPointerType() && 1639 !DestType->isMemberPointerType() && 1640 !DestType->isObjCObjectPointerType()) { 1641 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1642 // was a reference type, we converted it to a pointer above. 1643 // The status of rvalue references isn't entirely clear, but it looks like 1644 // conversion to them is simply invalid. 1645 // C++ 5.2.11p3: For two pointer types [...] 1646 if (!CStyle) 1647 msg = diag::err_bad_const_cast_dest; 1648 return TC_NotApplicable; 1649 } 1650 if (DestType->isFunctionPointerType() || 1651 DestType->isMemberFunctionPointerType()) { 1652 // Cannot cast direct function pointers. 1653 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1654 // T is the ultimate pointee of source and target type. 1655 if (!CStyle) 1656 msg = diag::err_bad_const_cast_dest; 1657 return TC_NotApplicable; 1658 } 1659 SrcType = Self.Context.getCanonicalType(SrcType); 1660 1661 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 1662 // completely equal. 1663 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 1664 // in multi-level pointers may change, but the level count must be the same, 1665 // as must be the final pointee type. 1666 while (SrcType != DestType && 1667 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 1668 Qualifiers SrcQuals, DestQuals; 1669 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 1670 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 1671 1672 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 1673 // the other qualifiers (e.g., address spaces) are identical. 1674 SrcQuals.removeCVRQualifiers(); 1675 DestQuals.removeCVRQualifiers(); 1676 if (SrcQuals != DestQuals) 1677 return TC_NotApplicable; 1678 } 1679 1680 // Since we're dealing in canonical types, the remainder must be the same. 1681 if (SrcType != DestType) 1682 return TC_NotApplicable; 1683 1684 if (NeedToMaterializeTemporary) 1685 // This is a const_cast from a class prvalue to an rvalue reference type. 1686 // Materialize a temporary to store the result of the conversion. 1687 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(), 1688 SrcExpr.get(), 1689 /*IsLValueReference*/ false); 1690 1691 return TC_Success; 1692} 1693 1694// Checks for undefined behavior in reinterpret_cast. 1695// The cases that is checked for is: 1696// *reinterpret_cast<T*>(&a) 1697// reinterpret_cast<T&>(a) 1698// where accessing 'a' as type 'T' will result in undefined behavior. 1699void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 1700 bool IsDereference, 1701 SourceRange Range) { 1702 unsigned DiagID = IsDereference ? 1703 diag::warn_pointer_indirection_from_incompatible_type : 1704 diag::warn_undefined_reinterpret_cast; 1705 1706 if (Diags.isIgnored(DiagID, Range.getBegin())) 1707 return; 1708 1709 QualType SrcTy, DestTy; 1710 if (IsDereference) { 1711 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 1712 return; 1713 } 1714 SrcTy = SrcType->getPointeeType(); 1715 DestTy = DestType->getPointeeType(); 1716 } else { 1717 if (!DestType->getAs<ReferenceType>()) { 1718 return; 1719 } 1720 SrcTy = SrcType; 1721 DestTy = DestType->getPointeeType(); 1722 } 1723 1724 // Cast is compatible if the types are the same. 1725 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 1726 return; 1727 } 1728 // or one of the types is a char or void type 1729 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 1730 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 1731 return; 1732 } 1733 // or one of the types is a tag type. 1734 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 1735 return; 1736 } 1737 1738 // FIXME: Scoped enums? 1739 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 1740 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 1741 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 1742 return; 1743 } 1744 } 1745 1746 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 1747} 1748 1749static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, 1750 QualType DestType) { 1751 QualType SrcType = SrcExpr.get()->getType(); 1752 if (Self.Context.hasSameType(SrcType, DestType)) 1753 return; 1754 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) 1755 if (SrcPtrTy->isObjCSelType()) { 1756 QualType DT = DestType; 1757 if (isa<PointerType>(DestType)) 1758 DT = DestType->getPointeeType(); 1759 if (!DT.getUnqualifiedType()->isVoidType()) 1760 Self.Diag(SrcExpr.get()->getExprLoc(), 1761 diag::warn_cast_pointer_from_sel) 1762 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 1763 } 1764} 1765 1766/// Diagnose casts that change the calling convention of a pointer to a function 1767/// defined in the current TU. 1768static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, 1769 QualType DstType, SourceRange OpRange) { 1770 // Check if this cast would change the calling convention of a function 1771 // pointer type. 1772 QualType SrcType = SrcExpr.get()->getType(); 1773 if (Self.Context.hasSameType(SrcType, DstType) || 1774 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType()) 1775 return; 1776 const auto *SrcFTy = 1777 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); 1778 const auto *DstFTy = 1779 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); 1780 CallingConv SrcCC = SrcFTy->getCallConv(); 1781 CallingConv DstCC = DstFTy->getCallConv(); 1782 if (SrcCC == DstCC) 1783 return; 1784 1785 // We have a calling convention cast. Check if the source is a pointer to a 1786 // known, specific function that has already been defined. 1787 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts(); 1788 if (auto *UO = dyn_cast<UnaryOperator>(Src)) 1789 if (UO->getOpcode() == UO_AddrOf) 1790 Src = UO->getSubExpr()->IgnoreParenImpCasts(); 1791 auto *DRE = dyn_cast<DeclRefExpr>(Src); 1792 if (!DRE) 1793 return; 1794 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 1795 if (!FD) 1796 return; 1797 1798 // Only warn if we are casting from the default convention to a non-default 1799 // convention. This can happen when the programmer forgot to apply the calling 1800 // convention to the function declaration and then inserted this cast to 1801 // satisfy the type system. 1802 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention( 1803 FD->isVariadic(), FD->isCXXInstanceMember()); 1804 if (DstCC == DefaultCC || SrcCC != DefaultCC) 1805 return; 1806 1807 // Diagnose this cast, as it is probably bad. 1808 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC); 1809 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC); 1810 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv) 1811 << SrcCCName << DstCCName << OpRange; 1812 1813 // The checks above are cheaper than checking if the diagnostic is enabled. 1814 // However, it's worth checking if the warning is enabled before we construct 1815 // a fixit. 1816 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin())) 1817 return; 1818 1819 // Try to suggest a fixit to change the calling convention of the function 1820 // whose address was taken. Try to use the latest macro for the convention. 1821 // For example, users probably want to write "WINAPI" instead of "__stdcall" 1822 // to match the Windows header declarations. 1823 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc(); 1824 Preprocessor &PP = Self.getPreprocessor(); 1825 SmallVector<TokenValue, 6> AttrTokens; 1826 SmallString<64> CCAttrText; 1827 llvm::raw_svector_ostream OS(CCAttrText); 1828 if (Self.getLangOpts().MicrosoftExt) { 1829 // __stdcall or __vectorcall 1830 OS << "__" << DstCCName; 1831 IdentifierInfo *II = PP.getIdentifierInfo(OS.str()); 1832 AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) 1833 ? TokenValue(II->getTokenID()) 1834 : TokenValue(II)); 1835 } else { 1836 // __attribute__((stdcall)) or __attribute__((vectorcall)) 1837 OS << "__attribute__((" << DstCCName << "))"; 1838 AttrTokens.push_back(tok::kw___attribute); 1839 AttrTokens.push_back(tok::l_paren); 1840 AttrTokens.push_back(tok::l_paren); 1841 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName); 1842 AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) 1843 ? TokenValue(II->getTokenID()) 1844 : TokenValue(II)); 1845 AttrTokens.push_back(tok::r_paren); 1846 AttrTokens.push_back(tok::r_paren); 1847 } 1848 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens); 1849 if (!AttrSpelling.empty()) 1850 CCAttrText = AttrSpelling; 1851 OS << ' '; 1852 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit) 1853 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText); 1854} 1855 1856static void checkIntToPointerCast(bool CStyle, SourceLocation Loc, 1857 const Expr *SrcExpr, QualType DestType, 1858 Sema &Self) { 1859 QualType SrcType = SrcExpr->getType(); 1860 1861 // Not warning on reinterpret_cast, boolean, constant expressions, etc 1862 // are not explicit design choices, but consistent with GCC's behavior. 1863 // Feel free to modify them if you've reason/evidence for an alternative. 1864 if (CStyle && SrcType->isIntegralType(Self.Context) 1865 && !SrcType->isBooleanType() 1866 && !SrcType->isEnumeralType() 1867 && !SrcExpr->isIntegerConstantExpr(Self.Context) 1868 && Self.Context.getTypeSize(DestType) > 1869 Self.Context.getTypeSize(SrcType)) { 1870 // Separate between casts to void* and non-void* pointers. 1871 // Some APIs use (abuse) void* for something like a user context, 1872 // and often that value is an integer even if it isn't a pointer itself. 1873 // Having a separate warning flag allows users to control the warning 1874 // for their workflow. 1875 unsigned Diag = DestType->isVoidPointerType() ? 1876 diag::warn_int_to_void_pointer_cast 1877 : diag::warn_int_to_pointer_cast; 1878 Self.Diag(Loc, Diag) << SrcType << DestType; 1879 } 1880} 1881 1882static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, 1883 ExprResult &Result) { 1884 // We can only fix an overloaded reinterpret_cast if 1885 // - it is a template with explicit arguments that resolves to an lvalue 1886 // unambiguously, or 1887 // - it is the only function in an overload set that may have its address 1888 // taken. 1889 1890 Expr *E = Result.get(); 1891 // TODO: what if this fails because of DiagnoseUseOfDecl or something 1892 // like it? 1893 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1894 Result, 1895 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 1896 ) && 1897 Result.isUsable()) 1898 return true; 1899 1900 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 1901 // preserves Result. 1902 Result = E; 1903 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate( 1904 Result, /*DoFunctionPointerConversion=*/true)) 1905 return false; 1906 return Result.isUsable(); 1907} 1908 1909static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 1910 QualType DestType, bool CStyle, 1911 SourceRange OpRange, 1912 unsigned &msg, 1913 CastKind &Kind) { 1914 bool IsLValueCast = false; 1915 1916 DestType = Self.Context.getCanonicalType(DestType); 1917 QualType SrcType = SrcExpr.get()->getType(); 1918 1919 // Is the source an overloaded name? (i.e. &foo) 1920 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) 1921 if (SrcType == Self.Context.OverloadTy) { 1922 ExprResult FixedExpr = SrcExpr; 1923 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) 1924 return TC_NotApplicable; 1925 1926 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr"); 1927 SrcExpr = FixedExpr; 1928 SrcType = SrcExpr.get()->getType(); 1929 } 1930 1931 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 1932 if (!SrcExpr.get()->isGLValue()) { 1933 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the 1934 // similar comment in const_cast. 1935 msg = diag::err_bad_cxx_cast_rvalue; 1936 return TC_NotApplicable; 1937 } 1938 1939 if (!CStyle) { 1940 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 1941 /*isDereference=*/false, OpRange); 1942 } 1943 1944 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 1945 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 1946 // built-in & and * operators. 1947 1948 const char *inappropriate = nullptr; 1949 switch (SrcExpr.get()->getObjectKind()) { 1950 case OK_Ordinary: 1951 break; 1952 case OK_BitField: 1953 msg = diag::err_bad_cxx_cast_bitfield; 1954 return TC_NotApplicable; 1955 // FIXME: Use a specific diagnostic for the rest of these cases. 1956 case OK_VectorComponent: inappropriate = "vector element"; break; 1957 case OK_ObjCProperty: inappropriate = "property expression"; break; 1958 case OK_ObjCSubscript: inappropriate = "container subscripting expression"; 1959 break; 1960 } 1961 if (inappropriate) { 1962 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 1963 << inappropriate << DestType 1964 << OpRange << SrcExpr.get()->getSourceRange(); 1965 msg = 0; SrcExpr = ExprError(); 1966 return TC_NotApplicable; 1967 } 1968 1969 // This code does this transformation for the checked types. 1970 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1971 SrcType = Self.Context.getPointerType(SrcType); 1972 1973 IsLValueCast = true; 1974 } 1975 1976 // Canonicalize source for comparison. 1977 SrcType = Self.Context.getCanonicalType(SrcType); 1978 1979 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 1980 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1981 if (DestMemPtr && SrcMemPtr) { 1982 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 1983 // can be explicitly converted to an rvalue of type "pointer to member 1984 // of Y of type T2" if T1 and T2 are both function types or both object 1985 // types. 1986 if (DestMemPtr->isMemberFunctionPointer() != 1987 SrcMemPtr->isMemberFunctionPointer()) 1988 return TC_NotApplicable; 1989 1990 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 1991 // constness. 1992 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 1993 // we accept it. 1994 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1995 /*CheckObjCLifetime=*/CStyle)) { 1996 msg = diag::err_bad_cxx_cast_qualifiers_away; 1997 return TC_Failed; 1998 } 1999 2000 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2001 // We need to determine the inheritance model that the class will use if 2002 // haven't yet. 2003 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 2004 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 2005 } 2006 2007 // Don't allow casting between member pointers of different sizes. 2008 if (Self.Context.getTypeSize(DestMemPtr) != 2009 Self.Context.getTypeSize(SrcMemPtr)) { 2010 msg = diag::err_bad_cxx_cast_member_pointer_size; 2011 return TC_Failed; 2012 } 2013 2014 // A valid member pointer cast. 2015 assert(!IsLValueCast); 2016 Kind = CK_ReinterpretMemberPointer; 2017 return TC_Success; 2018 } 2019 2020 // See below for the enumeral issue. 2021 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 2022 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 2023 // type large enough to hold it. A value of std::nullptr_t can be 2024 // converted to an integral type; the conversion has the same meaning 2025 // and validity as a conversion of (void*)0 to the integral type. 2026 if (Self.Context.getTypeSize(SrcType) > 2027 Self.Context.getTypeSize(DestType)) { 2028 msg = diag::err_bad_reinterpret_cast_small_int; 2029 return TC_Failed; 2030 } 2031 Kind = CK_PointerToIntegral; 2032 return TC_Success; 2033 } 2034 2035 // Allow reinterpret_casts between vectors of the same size and 2036 // between vectors and integers of the same size. 2037 bool destIsVector = DestType->isVectorType(); 2038 bool srcIsVector = SrcType->isVectorType(); 2039 if (srcIsVector || destIsVector) { 2040 // The non-vector type, if any, must have integral type. This is 2041 // the same rule that C vector casts use; note, however, that enum 2042 // types are not integral in C++. 2043 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) || 2044 (!srcIsVector && !SrcType->isIntegralType(Self.Context))) 2045 return TC_NotApplicable; 2046 2047 // The size we want to consider is eltCount * eltSize. 2048 // That's exactly what the lax-conversion rules will check. 2049 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { 2050 Kind = CK_BitCast; 2051 return TC_Success; 2052 } 2053 2054 // Otherwise, pick a reasonable diagnostic. 2055 if (!destIsVector) 2056 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 2057 else if (!srcIsVector) 2058 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 2059 else 2060 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 2061 2062 return TC_Failed; 2063 } 2064 2065 if (SrcType == DestType) { 2066 // C++ 5.2.10p2 has a note that mentions that, subject to all other 2067 // restrictions, a cast to the same type is allowed so long as it does not 2068 // cast away constness. In C++98, the intent was not entirely clear here, 2069 // since all other paragraphs explicitly forbid casts to the same type. 2070 // C++11 clarifies this case with p2. 2071 // 2072 // The only allowed types are: integral, enumeration, pointer, or 2073 // pointer-to-member types. We also won't restrict Obj-C pointers either. 2074 Kind = CK_NoOp; 2075 TryCastResult Result = TC_NotApplicable; 2076 if (SrcType->isIntegralOrEnumerationType() || 2077 SrcType->isAnyPointerType() || 2078 SrcType->isMemberPointerType() || 2079 SrcType->isBlockPointerType()) { 2080 Result = TC_Success; 2081 } 2082 return Result; 2083 } 2084 2085 bool destIsPtr = DestType->isAnyPointerType() || 2086 DestType->isBlockPointerType(); 2087 bool srcIsPtr = SrcType->isAnyPointerType() || 2088 SrcType->isBlockPointerType(); 2089 if (!destIsPtr && !srcIsPtr) { 2090 // Except for std::nullptr_t->integer and lvalue->reference, which are 2091 // handled above, at least one of the two arguments must be a pointer. 2092 return TC_NotApplicable; 2093 } 2094 2095 if (DestType->isIntegralType(Self.Context)) { 2096 assert(srcIsPtr && "One type must be a pointer"); 2097 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 2098 // type large enough to hold it; except in Microsoft mode, where the 2099 // integral type size doesn't matter (except we don't allow bool). 2100 bool MicrosoftException = Self.getLangOpts().MicrosoftExt && 2101 !DestType->isBooleanType(); 2102 if ((Self.Context.getTypeSize(SrcType) > 2103 Self.Context.getTypeSize(DestType)) && 2104 !MicrosoftException) { 2105 msg = diag::err_bad_reinterpret_cast_small_int; 2106 return TC_Failed; 2107 } 2108 Kind = CK_PointerToIntegral; 2109 return TC_Success; 2110 } 2111 2112 if (SrcType->isIntegralOrEnumerationType()) { 2113 assert(destIsPtr && "One type must be a pointer"); 2114 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType, 2115 Self); 2116 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 2117 // converted to a pointer. 2118 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 2119 // necessarily converted to a null pointer value.] 2120 Kind = CK_IntegralToPointer; 2121 return TC_Success; 2122 } 2123 2124 if (!destIsPtr || !srcIsPtr) { 2125 // With the valid non-pointer conversions out of the way, we can be even 2126 // more stringent. 2127 return TC_NotApplicable; 2128 } 2129 2130 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 2131 // The C-style cast operator can. 2132 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 2133 /*CheckObjCLifetime=*/CStyle)) { 2134 msg = diag::err_bad_cxx_cast_qualifiers_away; 2135 return TC_Failed; 2136 } 2137 2138 // Cannot convert between block pointers and Objective-C object pointers. 2139 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 2140 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 2141 return TC_NotApplicable; 2142 2143 if (IsLValueCast) { 2144 Kind = CK_LValueBitCast; 2145 } else if (DestType->isObjCObjectPointerType()) { 2146 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 2147 } else if (DestType->isBlockPointerType()) { 2148 if (!SrcType->isBlockPointerType()) { 2149 Kind = CK_AnyPointerToBlockPointerCast; 2150 } else { 2151 Kind = CK_BitCast; 2152 } 2153 } else { 2154 Kind = CK_BitCast; 2155 } 2156 2157 // Any pointer can be cast to an Objective-C pointer type with a C-style 2158 // cast. 2159 if (CStyle && DestType->isObjCObjectPointerType()) { 2160 return TC_Success; 2161 } 2162 if (CStyle) 2163 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2164 2165 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); 2166 2167 // Not casting away constness, so the only remaining check is for compatible 2168 // pointer categories. 2169 2170 if (SrcType->isFunctionPointerType()) { 2171 if (DestType->isFunctionPointerType()) { 2172 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 2173 // a pointer to a function of a different type. 2174 return TC_Success; 2175 } 2176 2177 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 2178 // an object type or vice versa is conditionally-supported. 2179 // Compilers support it in C++03 too, though, because it's necessary for 2180 // casting the return value of dlsym() and GetProcAddress(). 2181 // FIXME: Conditionally-supported behavior should be configurable in the 2182 // TargetInfo or similar. 2183 Self.Diag(OpRange.getBegin(), 2184 Self.getLangOpts().CPlusPlus11 ? 2185 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2186 << OpRange; 2187 return TC_Success; 2188 } 2189 2190 if (DestType->isFunctionPointerType()) { 2191 // See above. 2192 Self.Diag(OpRange.getBegin(), 2193 Self.getLangOpts().CPlusPlus11 ? 2194 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2195 << OpRange; 2196 return TC_Success; 2197 } 2198 2199 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 2200 // a pointer to an object of different type. 2201 // Void pointers are not specified, but supported by every compiler out there. 2202 // So we finish by allowing everything that remains - it's got to be two 2203 // object pointers. 2204 return TC_Success; 2205} 2206 2207void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, 2208 bool ListInitialization) { 2209 assert(Self.getLangOpts().CPlusPlus); 2210 2211 // Handle placeholders. 2212 if (isPlaceholder()) { 2213 // C-style casts can resolve __unknown_any types. 2214 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2215 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2216 SrcExpr.get(), Kind, 2217 ValueKind, BasePath); 2218 return; 2219 } 2220 2221 checkNonOverloadPlaceholders(); 2222 if (SrcExpr.isInvalid()) 2223 return; 2224 } 2225 2226 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 2227 // This test is outside everything else because it's the only case where 2228 // a non-lvalue-reference target type does not lead to decay. 2229 if (DestType->isVoidType()) { 2230 Kind = CK_ToVoid; 2231 2232 if (claimPlaceholder(BuiltinType::Overload)) { 2233 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2234 SrcExpr, /* Decay Function to ptr */ false, 2235 /* Complain */ true, DestRange, DestType, 2236 diag::err_bad_cstyle_cast_overload); 2237 if (SrcExpr.isInvalid()) 2238 return; 2239 } 2240 2241 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2242 return; 2243 } 2244 2245 // If the type is dependent, we won't do any other semantic analysis now. 2246 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || 2247 SrcExpr.get()->isValueDependent()) { 2248 assert(Kind == CK_Dependent); 2249 return; 2250 } 2251 2252 if (ValueKind == VK_RValue && !DestType->isRecordType() && 2253 !isPlaceholder(BuiltinType::Overload)) { 2254 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2255 if (SrcExpr.isInvalid()) 2256 return; 2257 } 2258 2259 // AltiVec vector initialization with a single literal. 2260 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 2261 if (vecTy->getVectorKind() == VectorType::AltiVecVector 2262 && (SrcExpr.get()->getType()->isIntegerType() 2263 || SrcExpr.get()->getType()->isFloatingType())) { 2264 Kind = CK_VectorSplat; 2265 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2266 return; 2267 } 2268 2269 // C++ [expr.cast]p5: The conversions performed by 2270 // - a const_cast, 2271 // - a static_cast, 2272 // - a static_cast followed by a const_cast, 2273 // - a reinterpret_cast, or 2274 // - a reinterpret_cast followed by a const_cast, 2275 // can be performed using the cast notation of explicit type conversion. 2276 // [...] If a conversion can be interpreted in more than one of the ways 2277 // listed above, the interpretation that appears first in the list is used, 2278 // even if a cast resulting from that interpretation is ill-formed. 2279 // In plain language, this means trying a const_cast ... 2280 unsigned msg = diag::err_bad_cxx_cast_generic; 2281 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, 2282 /*CStyle*/true, msg); 2283 if (SrcExpr.isInvalid()) 2284 return; 2285 if (tcr == TC_Success) 2286 Kind = CK_NoOp; 2287 2288 Sema::CheckedConversionKind CCK 2289 = FunctionalStyle? Sema::CCK_FunctionalCast 2290 : Sema::CCK_CStyleCast; 2291 if (tcr == TC_NotApplicable) { 2292 // ... or if that is not possible, a static_cast, ignoring const, ... 2293 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 2294 msg, Kind, BasePath, ListInitialization); 2295 if (SrcExpr.isInvalid()) 2296 return; 2297 2298 if (tcr == TC_NotApplicable) { 2299 // ... and finally a reinterpret_cast, ignoring const. 2300 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 2301 OpRange, msg, Kind); 2302 if (SrcExpr.isInvalid()) 2303 return; 2304 } 2305 } 2306 2307 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 2308 tcr == TC_Success) 2309 checkObjCConversion(CCK); 2310 2311 if (tcr != TC_Success && msg != 0) { 2312 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2313 DeclAccessPair Found; 2314 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 2315 DestType, 2316 /*Complain*/ true, 2317 Found); 2318 if (Fn) { 2319 // If DestType is a function type (not to be confused with the function 2320 // pointer type), it will be possible to resolve the function address, 2321 // but the type cast should be considered as failure. 2322 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; 2323 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) 2324 << OE->getName() << DestType << OpRange 2325 << OE->getQualifierLoc().getSourceRange(); 2326 Self.NoteAllOverloadCandidates(SrcExpr.get()); 2327 } 2328 } else { 2329 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 2330 OpRange, SrcExpr.get(), DestType, ListInitialization); 2331 } 2332 } else if (Kind == CK_BitCast) { 2333 checkCastAlign(); 2334 } 2335 2336 // Clear out SrcExpr if there was a fatal error. 2337 if (tcr != TC_Success) 2338 SrcExpr = ExprError(); 2339} 2340 2341/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a 2342/// non-matching type. Such as enum function call to int, int call to 2343/// pointer; etc. Cast to 'void' is an exception. 2344static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, 2345 QualType DestType) { 2346 if (Self.Diags.isIgnored(diag::warn_bad_function_cast, 2347 SrcExpr.get()->getExprLoc())) 2348 return; 2349 2350 if (!isa<CallExpr>(SrcExpr.get())) 2351 return; 2352 2353 QualType SrcType = SrcExpr.get()->getType(); 2354 if (DestType.getUnqualifiedType()->isVoidType()) 2355 return; 2356 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) 2357 && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) 2358 return; 2359 if (SrcType->isIntegerType() && DestType->isIntegerType() && 2360 (SrcType->isBooleanType() == DestType->isBooleanType()) && 2361 (SrcType->isEnumeralType() == DestType->isEnumeralType())) 2362 return; 2363 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) 2364 return; 2365 if (SrcType->isEnumeralType() && DestType->isEnumeralType()) 2366 return; 2367 if (SrcType->isComplexType() && DestType->isComplexType()) 2368 return; 2369 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) 2370 return; 2371 2372 Self.Diag(SrcExpr.get()->getExprLoc(), 2373 diag::warn_bad_function_cast) 2374 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2375} 2376 2377/// Check the semantics of a C-style cast operation, in C. 2378void CastOperation::CheckCStyleCast() { 2379 assert(!Self.getLangOpts().CPlusPlus); 2380 2381 // C-style casts can resolve __unknown_any types. 2382 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2383 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2384 SrcExpr.get(), Kind, 2385 ValueKind, BasePath); 2386 return; 2387 } 2388 2389 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2390 // type needs to be scalar. 2391 if (DestType->isVoidType()) { 2392 // We don't necessarily do lvalue-to-rvalue conversions on this. 2393 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2394 if (SrcExpr.isInvalid()) 2395 return; 2396 2397 // Cast to void allows any expr type. 2398 Kind = CK_ToVoid; 2399 return; 2400 } 2401 2402 // Overloads are allowed with C extensions, so we need to support them. 2403 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2404 DeclAccessPair DAP; 2405 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( 2406 SrcExpr.get(), DestType, /*Complain=*/true, DAP)) 2407 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); 2408 else 2409 return; 2410 assert(SrcExpr.isUsable()); 2411 } 2412 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2413 if (SrcExpr.isInvalid()) 2414 return; 2415 QualType SrcType = SrcExpr.get()->getType(); 2416 2417 assert(!SrcType->isPlaceholderType()); 2418 2419 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to 2420 // address space B is illegal. 2421 if (Self.getLangOpts().OpenCL && DestType->isPointerType() && 2422 SrcType->isPointerType()) { 2423 const PointerType *DestPtr = DestType->getAs<PointerType>(); 2424 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) { 2425 Self.Diag(OpRange.getBegin(), 2426 diag::err_typecheck_incompatible_address_space) 2427 << SrcType << DestType << Sema::AA_Casting 2428 << SrcExpr.get()->getSourceRange(); 2429 SrcExpr = ExprError(); 2430 return; 2431 } 2432 } 2433 2434 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 2435 diag::err_typecheck_cast_to_incomplete)) { 2436 SrcExpr = ExprError(); 2437 return; 2438 } 2439 2440 if (!DestType->isScalarType() && !DestType->isVectorType()) { 2441 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 2442 2443 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 2444 // GCC struct/union extension: allow cast to self. 2445 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 2446 << DestType << SrcExpr.get()->getSourceRange(); 2447 Kind = CK_NoOp; 2448 return; 2449 } 2450 2451 // GCC's cast to union extension. 2452 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 2453 RecordDecl *RD = DestRecordTy->getDecl(); 2454 RecordDecl::field_iterator Field, FieldEnd; 2455 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2456 Field != FieldEnd; ++Field) { 2457 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 2458 !Field->isUnnamedBitfield()) { 2459 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 2460 << SrcExpr.get()->getSourceRange(); 2461 break; 2462 } 2463 } 2464 if (Field == FieldEnd) { 2465 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2466 << SrcType << SrcExpr.get()->getSourceRange(); 2467 SrcExpr = ExprError(); 2468 return; 2469 } 2470 Kind = CK_ToUnion; 2471 return; 2472 } 2473 2474 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type. 2475 if (Self.getLangOpts().OpenCL && DestType->isEventT()) { 2476 llvm::APSInt CastInt; 2477 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) { 2478 if (0 == CastInt) { 2479 Kind = CK_ZeroToOCLEvent; 2480 return; 2481 } 2482 Self.Diag(OpRange.getBegin(), 2483 diag::err_opencl_cast_non_zero_to_event_t) 2484 << CastInt.toString(10) << SrcExpr.get()->getSourceRange(); 2485 SrcExpr = ExprError(); 2486 return; 2487 } 2488 } 2489 2490 // Reject any other conversions to non-scalar types. 2491 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 2492 << DestType << SrcExpr.get()->getSourceRange(); 2493 SrcExpr = ExprError(); 2494 return; 2495 } 2496 2497 // The type we're casting to is known to be a scalar or vector. 2498 2499 // Require the operand to be a scalar or vector. 2500 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 2501 Self.Diag(SrcExpr.get()->getExprLoc(), 2502 diag::err_typecheck_expect_scalar_operand) 2503 << SrcType << SrcExpr.get()->getSourceRange(); 2504 SrcExpr = ExprError(); 2505 return; 2506 } 2507 2508 if (DestType->isExtVectorType()) { 2509 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); 2510 return; 2511 } 2512 2513 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 2514 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 2515 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 2516 Kind = CK_VectorSplat; 2517 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2518 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 2519 SrcExpr = ExprError(); 2520 } 2521 return; 2522 } 2523 2524 if (SrcType->isVectorType()) { 2525 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 2526 SrcExpr = ExprError(); 2527 return; 2528 } 2529 2530 // The source and target types are both scalars, i.e. 2531 // - arithmetic types (fundamental, enum, and complex) 2532 // - all kinds of pointers 2533 // Note that member pointers were filtered out with C++, above. 2534 2535 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 2536 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 2537 SrcExpr = ExprError(); 2538 return; 2539 } 2540 2541 // If either type is a pointer, the other type has to be either an 2542 // integer or a pointer. 2543 if (!DestType->isArithmeticType()) { 2544 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 2545 Self.Diag(SrcExpr.get()->getExprLoc(), 2546 diag::err_cast_pointer_from_non_pointer_int) 2547 << SrcType << SrcExpr.get()->getSourceRange(); 2548 SrcExpr = ExprError(); 2549 return; 2550 } 2551 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(), 2552 DestType, Self); 2553 } else if (!SrcType->isArithmeticType()) { 2554 if (!DestType->isIntegralType(Self.Context) && 2555 DestType->isArithmeticType()) { 2556 Self.Diag(SrcExpr.get()->getLocStart(), 2557 diag::err_cast_pointer_to_non_pointer_int) 2558 << DestType << SrcExpr.get()->getSourceRange(); 2559 SrcExpr = ExprError(); 2560 return; 2561 } 2562 } 2563 2564 if (Self.getLangOpts().OpenCL && 2565 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 2566 if (DestType->isHalfType()) { 2567 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half) 2568 << DestType << SrcExpr.get()->getSourceRange(); 2569 SrcExpr = ExprError(); 2570 return; 2571 } 2572 } 2573 2574 // ARC imposes extra restrictions on casts. 2575 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) { 2576 checkObjCConversion(Sema::CCK_CStyleCast); 2577 if (SrcExpr.isInvalid()) 2578 return; 2579 2580 const PointerType *CastPtr = DestType->getAs<PointerType>(); 2581 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) { 2582 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 2583 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 2584 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 2585 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 2586 ExprPtr->getPointeeType()->isObjCLifetimeType() && 2587 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 2588 Self.Diag(SrcExpr.get()->getLocStart(), 2589 diag::err_typecheck_incompatible_ownership) 2590 << SrcType << DestType << Sema::AA_Casting 2591 << SrcExpr.get()->getSourceRange(); 2592 return; 2593 } 2594 } 2595 } 2596 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 2597 Self.Diag(SrcExpr.get()->getLocStart(), 2598 diag::err_arc_convesion_of_weak_unavailable) 2599 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2600 SrcExpr = ExprError(); 2601 return; 2602 } 2603 } 2604 2605 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2606 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); 2607 DiagnoseBadFunctionCast(Self, SrcExpr, DestType); 2608 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 2609 if (SrcExpr.isInvalid()) 2610 return; 2611 2612 if (Kind == CK_BitCast) 2613 checkCastAlign(); 2614} 2615 2616/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either 2617/// const, volatile or both. 2618static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, 2619 QualType DestType) { 2620 if (SrcExpr.isInvalid()) 2621 return; 2622 2623 QualType SrcType = SrcExpr.get()->getType(); 2624 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) || 2625 DestType->isLValueReferenceType())) 2626 return; 2627 2628 QualType TheOffendingSrcType, TheOffendingDestType; 2629 Qualifiers CastAwayQualifiers; 2630 if (!CastsAwayConstness(Self, SrcType, DestType, true, false, 2631 &TheOffendingSrcType, &TheOffendingDestType, 2632 &CastAwayQualifiers)) 2633 return; 2634 2635 int qualifiers = -1; 2636 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { 2637 qualifiers = 0; 2638 } else if (CastAwayQualifiers.hasConst()) { 2639 qualifiers = 1; 2640 } else if (CastAwayQualifiers.hasVolatile()) { 2641 qualifiers = 2; 2642 } 2643 // This is a variant of int **x; const int **y = (const int **)x; 2644 if (qualifiers == -1) 2645 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) 2646 << SrcType << DestType; 2647 else 2648 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) 2649 << TheOffendingSrcType << TheOffendingDestType << qualifiers; 2650} 2651 2652ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 2653 TypeSourceInfo *CastTypeInfo, 2654 SourceLocation RPLoc, 2655 Expr *CastExpr) { 2656 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2657 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2658 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 2659 2660 if (getLangOpts().CPlusPlus) { 2661 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false, 2662 isa<InitListExpr>(CastExpr)); 2663 } else { 2664 Op.CheckCStyleCast(); 2665 } 2666 2667 if (Op.SrcExpr.isInvalid()) 2668 return ExprError(); 2669 2670 // -Wcast-qual 2671 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType); 2672 2673 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 2674 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 2675 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 2676} 2677 2678ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 2679 QualType Type, 2680 SourceLocation LPLoc, 2681 Expr *CastExpr, 2682 SourceLocation RPLoc) { 2683 assert(LPLoc.isValid() && "List-initialization shouldn't get here."); 2684 CastOperation Op(*this, Type, CastExpr); 2685 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2686 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 2687 2688 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false); 2689 if (Op.SrcExpr.isInvalid()) 2690 return ExprError(); 2691 2692 auto *SubExpr = Op.SrcExpr.get(); 2693 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 2694 SubExpr = BindExpr->getSubExpr(); 2695 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) 2696 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); 2697 2698 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 2699 Op.ValueKind, CastTypeInfo, Op.Kind, 2700 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc)); 2701} 2702