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