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