1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for cast expressions, including 10 // 1) C-style casts like '(int) x' 11 // 2) C++ functional casts like 'int(x)' 12 // 3) C++ named casts like 'static_cast<int>(x)' 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTStructuralEquivalence.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/PartialDiagnostic.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/Lex/Preprocessor.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/SemaInternal.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_Extension, ///< The cast method is appropriate and accepted as a 37 ///< language extension. 38 TC_Failed ///< The cast method is appropriate, but failed. A 39 ///< diagnostic has been emitted. 40 }; 41 42 static bool isValidCast(TryCastResult TCR) { 43 return TCR == TC_Success || TCR == TC_Extension; 44 } 45 46 enum CastType { 47 CT_Const, ///< const_cast 48 CT_Static, ///< static_cast 49 CT_Reinterpret, ///< reinterpret_cast 50 CT_Dynamic, ///< dynamic_cast 51 CT_CStyle, ///< (Type)expr 52 CT_Functional, ///< Type(expr) 53 CT_Addrspace ///< addrspace_cast 54 }; 55 56 namespace { 57 struct CastOperation { 58 CastOperation(Sema &S, QualType destType, ExprResult src) 59 : Self(S), SrcExpr(src), DestType(destType), 60 ResultType(destType.getNonLValueExprType(S.Context)), 61 ValueKind(Expr::getValueKindForType(destType)), 62 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 63 64 // C++ [expr.type]/8.2.2: 65 // If a pr-value initially has the type cv-T, where T is a 66 // cv-unqualified non-class, non-array type, the type of the 67 // expression is adjusted to T prior to any further analysis. 68 if (!S.Context.getLangOpts().ObjC && !DestType->isRecordType() && 69 !DestType->isArrayType()) { 70 DestType = DestType.getUnqualifiedType(); 71 } 72 73 if (const BuiltinType *placeholder = 74 src.get()->getType()->getAsPlaceholderType()) { 75 PlaceholderKind = placeholder->getKind(); 76 } else { 77 PlaceholderKind = (BuiltinType::Kind) 0; 78 } 79 } 80 81 Sema &Self; 82 ExprResult SrcExpr; 83 QualType DestType; 84 QualType ResultType; 85 ExprValueKind ValueKind; 86 CastKind Kind; 87 BuiltinType::Kind PlaceholderKind; 88 CXXCastPath BasePath; 89 bool IsARCUnbridgedCast; 90 91 SourceRange OpRange; 92 SourceRange DestRange; 93 94 // Top-level semantics-checking routines. 95 void CheckConstCast(); 96 void CheckReinterpretCast(); 97 void CheckStaticCast(); 98 void CheckDynamicCast(); 99 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); 100 void CheckCStyleCast(); 101 void CheckBuiltinBitCast(); 102 void CheckAddrspaceCast(); 103 104 void updatePartOfExplicitCastFlags(CastExpr *CE) { 105 // Walk down from the CE to the OrigSrcExpr, and mark all immediate 106 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE 107 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched. 108 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE) 109 ICE->setIsPartOfExplicitCast(true); 110 } 111 112 /// Complete an apparently-successful cast operation that yields 113 /// the given expression. 114 ExprResult complete(CastExpr *castExpr) { 115 // If this is an unbridged cast, wrap the result in an implicit 116 // cast that yields the unbridged-cast placeholder type. 117 if (IsARCUnbridgedCast) { 118 castExpr = ImplicitCastExpr::Create( 119 Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent, 120 castExpr, nullptr, castExpr->getValueKind(), 121 Self.CurFPFeatureOverrides()); 122 } 123 updatePartOfExplicitCastFlags(castExpr); 124 return castExpr; 125 } 126 127 // Internal convenience methods. 128 129 /// Try to handle the given placeholder expression kind. Return 130 /// true if the source expression has the appropriate placeholder 131 /// kind. A placeholder can only be claimed once. 132 bool claimPlaceholder(BuiltinType::Kind K) { 133 if (PlaceholderKind != K) return false; 134 135 PlaceholderKind = (BuiltinType::Kind) 0; 136 return true; 137 } 138 139 bool isPlaceholder() const { 140 return PlaceholderKind != 0; 141 } 142 bool isPlaceholder(BuiltinType::Kind K) const { 143 return PlaceholderKind == K; 144 } 145 146 // Language specific cast restrictions for address spaces. 147 void checkAddressSpaceCast(QualType SrcType, QualType DestType); 148 149 void checkCastAlign() { 150 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 151 } 152 153 void checkObjCConversion(Sema::CheckedConversionKind CCK) { 154 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()); 155 156 Expr *src = SrcExpr.get(); 157 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) == 158 Sema::ACR_unbridged) 159 IsARCUnbridgedCast = true; 160 SrcExpr = src; 161 } 162 163 /// Check for and handle non-overload placeholder expressions. 164 void checkNonOverloadPlaceholders() { 165 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 166 return; 167 168 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 169 if (SrcExpr.isInvalid()) 170 return; 171 PlaceholderKind = (BuiltinType::Kind) 0; 172 } 173 }; 174 175 void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType, 176 SourceLocation OpLoc) { 177 if (const auto *PtrType = dyn_cast<PointerType>(FromType)) { 178 if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 179 if (const auto *DestType = dyn_cast<PointerType>(ToType)) { 180 if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) { 181 S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer); 182 } 183 } 184 } 185 } 186 } 187 188 struct CheckNoDerefRAII { 189 CheckNoDerefRAII(CastOperation &Op) : Op(Op) {} 190 ~CheckNoDerefRAII() { 191 if (!Op.SrcExpr.isInvalid()) 192 CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType, 193 Op.OpRange.getBegin()); 194 } 195 196 CastOperation &Op; 197 }; 198 } 199 200 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, 201 QualType DestType); 202 203 // The Try functions attempt a specific way of casting. If they succeed, they 204 // return TC_Success. If their way of casting is not appropriate for the given 205 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 206 // to emit if no other way succeeds. If their way of casting is appropriate but 207 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if 208 // they emit a specialized diagnostic. 209 // All diagnostics returned by these functions must expect the same three 210 // arguments: 211 // %0: Cast Type (a value from the CastType enumeration) 212 // %1: Source Type 213 // %2: Destination Type 214 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 215 QualType DestType, bool CStyle, 216 CastKind &Kind, 217 CXXCastPath &BasePath, 218 unsigned &msg); 219 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 220 QualType DestType, bool CStyle, 221 SourceRange OpRange, 222 unsigned &msg, 223 CastKind &Kind, 224 CXXCastPath &BasePath); 225 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 226 QualType DestType, bool CStyle, 227 SourceRange OpRange, 228 unsigned &msg, 229 CastKind &Kind, 230 CXXCastPath &BasePath); 231 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 232 CanQualType DestType, bool CStyle, 233 SourceRange OpRange, 234 QualType OrigSrcType, 235 QualType OrigDestType, unsigned &msg, 236 CastKind &Kind, 237 CXXCastPath &BasePath); 238 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 239 QualType SrcType, 240 QualType DestType,bool CStyle, 241 SourceRange OpRange, 242 unsigned &msg, 243 CastKind &Kind, 244 CXXCastPath &BasePath); 245 246 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 247 QualType DestType, 248 Sema::CheckedConversionKind CCK, 249 SourceRange OpRange, 250 unsigned &msg, CastKind &Kind, 251 bool ListInitialization); 252 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 253 QualType DestType, 254 Sema::CheckedConversionKind CCK, 255 SourceRange OpRange, 256 unsigned &msg, CastKind &Kind, 257 CXXCastPath &BasePath, 258 bool ListInitialization); 259 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 260 QualType DestType, bool CStyle, 261 unsigned &msg); 262 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 263 QualType DestType, bool CStyle, 264 SourceRange OpRange, unsigned &msg, 265 CastKind &Kind); 266 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, 267 QualType DestType, bool CStyle, 268 unsigned &msg, CastKind &Kind); 269 270 /// ActOnCXXNamedCast - Parse 271 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 272 ExprResult 273 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 274 SourceLocation LAngleBracketLoc, Declarator &D, 275 SourceLocation RAngleBracketLoc, 276 SourceLocation LParenLoc, Expr *E, 277 SourceLocation RParenLoc) { 278 279 assert(!D.isInvalidType()); 280 281 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); 282 if (D.isInvalidType()) 283 return ExprError(); 284 285 if (getLangOpts().CPlusPlus) { 286 // Check that there are no default arguments (C++ only). 287 CheckExtraCXXDefaultArguments(D); 288 } 289 290 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E, 291 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 292 SourceRange(LParenLoc, RParenLoc)); 293 } 294 295 ExprResult 296 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 297 TypeSourceInfo *DestTInfo, Expr *E, 298 SourceRange AngleBrackets, SourceRange Parens) { 299 ExprResult Ex = E; 300 QualType DestType = DestTInfo->getType(); 301 302 // If the type is dependent, we won't do the semantic analysis now. 303 bool TypeDependent = 304 DestType->isDependentType() || Ex.get()->isTypeDependent(); 305 306 CastOperation Op(*this, DestType, E); 307 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 308 Op.DestRange = AngleBrackets; 309 310 switch (Kind) { 311 default: llvm_unreachable("Unknown C++ cast!"); 312 313 case tok::kw_addrspace_cast: 314 if (!TypeDependent) { 315 Op.CheckAddrspaceCast(); 316 if (Op.SrcExpr.isInvalid()) 317 return ExprError(); 318 } 319 return Op.complete(CXXAddrspaceCastExpr::Create( 320 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 321 DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); 322 323 case tok::kw_const_cast: 324 if (!TypeDependent) { 325 Op.CheckConstCast(); 326 if (Op.SrcExpr.isInvalid()) 327 return ExprError(); 328 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 329 } 330 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, 331 Op.ValueKind, Op.SrcExpr.get(), DestTInfo, 332 OpLoc, Parens.getEnd(), 333 AngleBrackets)); 334 335 case tok::kw_dynamic_cast: { 336 // dynamic_cast is not supported in C++ for OpenCL. 337 if (getLangOpts().OpenCLCPlusPlus) { 338 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 339 << "dynamic_cast"); 340 } 341 342 if (!TypeDependent) { 343 Op.CheckDynamicCast(); 344 if (Op.SrcExpr.isInvalid()) 345 return ExprError(); 346 } 347 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 348 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 349 &Op.BasePath, DestTInfo, 350 OpLoc, Parens.getEnd(), 351 AngleBrackets)); 352 } 353 case tok::kw_reinterpret_cast: { 354 if (!TypeDependent) { 355 Op.CheckReinterpretCast(); 356 if (Op.SrcExpr.isInvalid()) 357 return ExprError(); 358 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 359 } 360 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 361 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 362 nullptr, DestTInfo, OpLoc, 363 Parens.getEnd(), 364 AngleBrackets)); 365 } 366 case tok::kw_static_cast: { 367 if (!TypeDependent) { 368 Op.CheckStaticCast(); 369 if (Op.SrcExpr.isInvalid()) 370 return ExprError(); 371 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 372 } 373 374 return Op.complete(CXXStaticCastExpr::Create( 375 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 376 &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc, 377 Parens.getEnd(), AngleBrackets)); 378 } 379 } 380 } 381 382 ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D, 383 ExprResult Operand, 384 SourceLocation RParenLoc) { 385 assert(!D.isInvalidType()); 386 387 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType()); 388 if (D.isInvalidType()) 389 return ExprError(); 390 391 return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc); 392 } 393 394 ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc, 395 TypeSourceInfo *TSI, Expr *Operand, 396 SourceLocation RParenLoc) { 397 CastOperation Op(*this, TSI->getType(), Operand); 398 Op.OpRange = SourceRange(KWLoc, RParenLoc); 399 TypeLoc TL = TSI->getTypeLoc(); 400 Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); 401 402 if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) { 403 Op.CheckBuiltinBitCast(); 404 if (Op.SrcExpr.isInvalid()) 405 return ExprError(); 406 } 407 408 BuiltinBitCastExpr *BCE = 409 new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind, 410 Op.SrcExpr.get(), TSI, KWLoc, RParenLoc); 411 return Op.complete(BCE); 412 } 413 414 /// Try to diagnose a failed overloaded cast. Returns true if 415 /// diagnostics were emitted. 416 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 417 SourceRange range, Expr *src, 418 QualType destType, 419 bool listInitialization) { 420 switch (CT) { 421 // These cast kinds don't consider user-defined conversions. 422 case CT_Const: 423 case CT_Reinterpret: 424 case CT_Dynamic: 425 case CT_Addrspace: 426 return false; 427 428 // These do. 429 case CT_Static: 430 case CT_CStyle: 431 case CT_Functional: 432 break; 433 } 434 435 QualType srcType = src->getType(); 436 if (!destType->isRecordType() && !srcType->isRecordType()) 437 return false; 438 439 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 440 InitializationKind initKind 441 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 442 range, listInitialization) 443 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, 444 listInitialization) 445 : InitializationKind::CreateCast(/*type range?*/ range); 446 InitializationSequence sequence(S, entity, initKind, src); 447 448 assert(sequence.Failed() && "initialization succeeded on second try?"); 449 switch (sequence.getFailureKind()) { 450 default: return false; 451 452 case InitializationSequence::FK_ConstructorOverloadFailed: 453 case InitializationSequence::FK_UserConversionOverloadFailed: 454 case InitializationSequence::FK_ParenthesizedListInitFailed: 455 break; 456 } 457 458 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 459 460 unsigned msg = 0; 461 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 462 463 switch (sequence.getFailedOverloadResult()) { 464 case OR_Success: llvm_unreachable("successful failed overload"); 465 case OR_No_Viable_Function: 466 if (candidates.empty()) 467 msg = diag::err_ovl_no_conversion_in_cast; 468 else 469 msg = diag::err_ovl_no_viable_conversion_in_cast; 470 howManyCandidates = OCD_AllCandidates; 471 break; 472 473 case OR_Ambiguous: 474 msg = diag::err_ovl_ambiguous_conversion_in_cast; 475 howManyCandidates = OCD_AmbiguousCandidates; 476 break; 477 478 case OR_Deleted: 479 msg = diag::err_ovl_deleted_conversion_in_cast; 480 howManyCandidates = OCD_ViableCandidates; 481 break; 482 } 483 484 candidates.NoteCandidates( 485 PartialDiagnosticAt(range.getBegin(), 486 S.PDiag(msg) << CT << srcType << destType << range 487 << src->getSourceRange()), 488 S, howManyCandidates, src); 489 490 return true; 491 } 492 493 /// Diagnose a failed cast. 494 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 495 SourceRange opRange, Expr *src, QualType destType, 496 bool listInitialization) { 497 if (msg == diag::err_bad_cxx_cast_generic && 498 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, 499 listInitialization)) 500 return; 501 502 S.Diag(opRange.getBegin(), msg) << castType 503 << src->getType() << destType << opRange << src->getSourceRange(); 504 505 // Detect if both types are (ptr to) class, and note any incompleteness. 506 int DifferentPtrness = 0; 507 QualType From = destType; 508 if (auto Ptr = From->getAs<PointerType>()) { 509 From = Ptr->getPointeeType(); 510 DifferentPtrness++; 511 } 512 QualType To = src->getType(); 513 if (auto Ptr = To->getAs<PointerType>()) { 514 To = Ptr->getPointeeType(); 515 DifferentPtrness--; 516 } 517 if (!DifferentPtrness) { 518 auto RecFrom = From->getAs<RecordType>(); 519 auto RecTo = To->getAs<RecordType>(); 520 if (RecFrom && RecTo) { 521 auto DeclFrom = RecFrom->getAsCXXRecordDecl(); 522 if (!DeclFrom->isCompleteDefinition()) 523 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom; 524 auto DeclTo = RecTo->getAsCXXRecordDecl(); 525 if (!DeclTo->isCompleteDefinition()) 526 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo; 527 } 528 } 529 } 530 531 namespace { 532 /// The kind of unwrapping we did when determining whether a conversion casts 533 /// away constness. 534 enum CastAwayConstnessKind { 535 /// The conversion does not cast away constness. 536 CACK_None = 0, 537 /// We unwrapped similar types. 538 CACK_Similar = 1, 539 /// We unwrapped dissimilar types with similar representations (eg, a pointer 540 /// versus an Objective-C object pointer). 541 CACK_SimilarKind = 2, 542 /// We unwrapped representationally-unrelated types, such as a pointer versus 543 /// a pointer-to-member. 544 CACK_Incoherent = 3, 545 }; 546 } 547 548 /// Unwrap one level of types for CastsAwayConstness. 549 /// 550 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from 551 /// both types, provided that they're both pointer-like or array-like. Unlike 552 /// the Sema function, doesn't care if the unwrapped pieces are related. 553 /// 554 /// This function may remove additional levels as necessary for correctness: 555 /// the resulting T1 is unwrapped sufficiently that it is never an array type, 556 /// so that its qualifiers can be directly compared to those of T2 (which will 557 /// have the combined set of qualifiers from all indermediate levels of T2), 558 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers 559 /// with those from T2. 560 static CastAwayConstnessKind 561 unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) { 562 enum { None, Ptr, MemPtr, BlockPtr, Array }; 563 auto Classify = [](QualType T) { 564 if (T->isAnyPointerType()) return Ptr; 565 if (T->isMemberPointerType()) return MemPtr; 566 if (T->isBlockPointerType()) return BlockPtr; 567 // We somewhat-arbitrarily don't look through VLA types here. This is at 568 // least consistent with the behavior of UnwrapSimilarTypes. 569 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array; 570 return None; 571 }; 572 573 auto Unwrap = [&](QualType T) { 574 if (auto *AT = Context.getAsArrayType(T)) 575 return AT->getElementType(); 576 return T->getPointeeType(); 577 }; 578 579 CastAwayConstnessKind Kind; 580 581 if (T2->isReferenceType()) { 582 // Special case: if the destination type is a reference type, unwrap it as 583 // the first level. (The source will have been an lvalue expression in this 584 // case, so there is no corresponding "reference to" in T1 to remove.) This 585 // simulates removing a "pointer to" from both sides. 586 T2 = T2->getPointeeType(); 587 Kind = CastAwayConstnessKind::CACK_Similar; 588 } else if (Context.UnwrapSimilarTypes(T1, T2)) { 589 Kind = CastAwayConstnessKind::CACK_Similar; 590 } else { 591 // Try unwrapping mismatching levels. 592 int T1Class = Classify(T1); 593 if (T1Class == None) 594 return CastAwayConstnessKind::CACK_None; 595 596 int T2Class = Classify(T2); 597 if (T2Class == None) 598 return CastAwayConstnessKind::CACK_None; 599 600 T1 = Unwrap(T1); 601 T2 = Unwrap(T2); 602 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind 603 : CastAwayConstnessKind::CACK_Incoherent; 604 } 605 606 // We've unwrapped at least one level. If the resulting T1 is a (possibly 607 // multidimensional) array type, any qualifier on any matching layer of 608 // T2 is considered to correspond to T1. Decompose down to the element 609 // type of T1 so that we can compare properly. 610 while (true) { 611 Context.UnwrapSimilarArrayTypes(T1, T2); 612 613 if (Classify(T1) != Array) 614 break; 615 616 auto T2Class = Classify(T2); 617 if (T2Class == None) 618 break; 619 620 if (T2Class != Array) 621 Kind = CastAwayConstnessKind::CACK_Incoherent; 622 else if (Kind != CastAwayConstnessKind::CACK_Incoherent) 623 Kind = CastAwayConstnessKind::CACK_SimilarKind; 624 625 T1 = Unwrap(T1); 626 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers()); 627 } 628 629 return Kind; 630 } 631 632 /// Check if the pointer conversion from SrcType to DestType casts away 633 /// constness as defined in C++ [expr.const.cast]. This is used by the cast 634 /// checkers. Both arguments must denote pointer (possibly to member) types. 635 /// 636 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 637 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 638 static CastAwayConstnessKind 639 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 640 bool CheckCVR, bool CheckObjCLifetime, 641 QualType *TheOffendingSrcType = nullptr, 642 QualType *TheOffendingDestType = nullptr, 643 Qualifiers *CastAwayQualifiers = nullptr) { 644 // If the only checking we care about is for Objective-C lifetime qualifiers, 645 // and we're not in ObjC mode, there's nothing to check. 646 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC) 647 return CastAwayConstnessKind::CACK_None; 648 649 if (!DestType->isReferenceType()) { 650 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 651 SrcType->isBlockPointerType()) && 652 "Source type is not pointer or pointer to member."); 653 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 654 DestType->isBlockPointerType()) && 655 "Destination type is not pointer or pointer to member."); 656 } 657 658 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 659 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 660 661 // Find the qualifiers. We only care about cvr-qualifiers for the 662 // purpose of this check, because other qualifiers (address spaces, 663 // Objective-C GC, etc.) are part of the type's identity. 664 QualType PrevUnwrappedSrcType = UnwrappedSrcType; 665 QualType PrevUnwrappedDestType = UnwrappedDestType; 666 auto WorstKind = CastAwayConstnessKind::CACK_Similar; 667 bool AllConstSoFar = true; 668 while (auto Kind = unwrapCastAwayConstnessLevel( 669 Self.Context, UnwrappedSrcType, UnwrappedDestType)) { 670 // Track the worst kind of unwrap we needed to do before we found a 671 // problem. 672 if (Kind > WorstKind) 673 WorstKind = Kind; 674 675 // Determine the relevant qualifiers at this level. 676 Qualifiers SrcQuals, DestQuals; 677 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 678 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 679 680 // We do not meaningfully track object const-ness of Objective-C object 681 // types. Remove const from the source type if either the source or 682 // the destination is an Objective-C object type. 683 if (UnwrappedSrcType->isObjCObjectType() || 684 UnwrappedDestType->isObjCObjectType()) 685 SrcQuals.removeConst(); 686 687 if (CheckCVR) { 688 Qualifiers SrcCvrQuals = 689 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()); 690 Qualifiers DestCvrQuals = 691 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()); 692 693 if (SrcCvrQuals != DestCvrQuals) { 694 if (CastAwayQualifiers) 695 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals; 696 697 // If we removed a cvr-qualifier, this is casting away 'constness'. 698 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) { 699 if (TheOffendingSrcType) 700 *TheOffendingSrcType = PrevUnwrappedSrcType; 701 if (TheOffendingDestType) 702 *TheOffendingDestType = PrevUnwrappedDestType; 703 return WorstKind; 704 } 705 706 // If any prior level was not 'const', this is also casting away 707 // 'constness'. We noted the outermost type missing a 'const' already. 708 if (!AllConstSoFar) 709 return WorstKind; 710 } 711 } 712 713 if (CheckObjCLifetime && 714 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 715 return WorstKind; 716 717 // If we found our first non-const-qualified type, this may be the place 718 // where things start to go wrong. 719 if (AllConstSoFar && !DestQuals.hasConst()) { 720 AllConstSoFar = false; 721 if (TheOffendingSrcType) 722 *TheOffendingSrcType = PrevUnwrappedSrcType; 723 if (TheOffendingDestType) 724 *TheOffendingDestType = PrevUnwrappedDestType; 725 } 726 727 PrevUnwrappedSrcType = UnwrappedSrcType; 728 PrevUnwrappedDestType = UnwrappedDestType; 729 } 730 731 return CastAwayConstnessKind::CACK_None; 732 } 733 734 static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK, 735 unsigned &DiagID) { 736 switch (CACK) { 737 case CastAwayConstnessKind::CACK_None: 738 llvm_unreachable("did not cast away constness"); 739 740 case CastAwayConstnessKind::CACK_Similar: 741 // FIXME: Accept these as an extension too? 742 case CastAwayConstnessKind::CACK_SimilarKind: 743 DiagID = diag::err_bad_cxx_cast_qualifiers_away; 744 return TC_Failed; 745 746 case CastAwayConstnessKind::CACK_Incoherent: 747 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent; 748 return TC_Extension; 749 } 750 751 llvm_unreachable("unexpected cast away constness kind"); 752 } 753 754 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 755 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 756 /// checked downcasts in class hierarchies. 757 void CastOperation::CheckDynamicCast() { 758 CheckNoDerefRAII NoderefCheck(*this); 759 760 if (ValueKind == VK_PRValue) 761 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 762 else if (isPlaceholder()) 763 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 764 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 765 return; 766 767 QualType OrigSrcType = SrcExpr.get()->getType(); 768 QualType DestType = Self.Context.getCanonicalType(this->DestType); 769 770 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 771 // or "pointer to cv void". 772 773 QualType DestPointee; 774 const PointerType *DestPointer = DestType->getAs<PointerType>(); 775 const ReferenceType *DestReference = nullptr; 776 if (DestPointer) { 777 DestPointee = DestPointer->getPointeeType(); 778 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 779 DestPointee = DestReference->getPointeeType(); 780 } else { 781 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 782 << this->DestType << DestRange; 783 SrcExpr = ExprError(); 784 return; 785 } 786 787 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 788 if (DestPointee->isVoidType()) { 789 assert(DestPointer && "Reference to void is not possible"); 790 } else if (DestRecord) { 791 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 792 diag::err_bad_cast_incomplete, 793 DestRange)) { 794 SrcExpr = ExprError(); 795 return; 796 } 797 } else { 798 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 799 << DestPointee.getUnqualifiedType() << DestRange; 800 SrcExpr = ExprError(); 801 return; 802 } 803 804 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 805 // complete class type, [...]. If T is an lvalue reference type, v shall be 806 // an lvalue of a complete class type, [...]. If T is an rvalue reference 807 // type, v shall be an expression having a complete class type, [...] 808 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 809 QualType SrcPointee; 810 if (DestPointer) { 811 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 812 SrcPointee = SrcPointer->getPointeeType(); 813 } else { 814 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 815 << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange(); 816 SrcExpr = ExprError(); 817 return; 818 } 819 } else if (DestReference->isLValueReferenceType()) { 820 if (!SrcExpr.get()->isLValue()) { 821 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 822 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 823 } 824 SrcPointee = SrcType; 825 } else { 826 // If we're dynamic_casting from a prvalue to an rvalue reference, we need 827 // to materialize the prvalue before we bind the reference to it. 828 if (SrcExpr.get()->isPRValue()) 829 SrcExpr = Self.CreateMaterializeTemporaryExpr( 830 SrcType, SrcExpr.get(), /*IsLValueReference*/ false); 831 SrcPointee = SrcType; 832 } 833 834 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 835 if (SrcRecord) { 836 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 837 diag::err_bad_cast_incomplete, 838 SrcExpr.get())) { 839 SrcExpr = ExprError(); 840 return; 841 } 842 } else { 843 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 844 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 845 SrcExpr = ExprError(); 846 return; 847 } 848 849 assert((DestPointer || DestReference) && 850 "Bad destination non-ptr/ref slipped through."); 851 assert((DestRecord || DestPointee->isVoidType()) && 852 "Bad destination pointee slipped through."); 853 assert(SrcRecord && "Bad source pointee slipped through."); 854 855 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 856 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 857 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 858 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 859 SrcExpr = ExprError(); 860 return; 861 } 862 863 // C++ 5.2.7p3: If the type of v is the same as the required result type, 864 // [except for cv]. 865 if (DestRecord == SrcRecord) { 866 Kind = CK_NoOp; 867 return; 868 } 869 870 // C++ 5.2.7p5 871 // Upcasts are resolved statically. 872 if (DestRecord && 873 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { 874 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 875 OpRange.getBegin(), OpRange, 876 &BasePath)) { 877 SrcExpr = ExprError(); 878 return; 879 } 880 881 Kind = CK_DerivedToBase; 882 return; 883 } 884 885 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 886 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 887 assert(SrcDecl && "Definition missing"); 888 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 889 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 890 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 891 SrcExpr = ExprError(); 892 } 893 894 // dynamic_cast is not available with -fno-rtti. 895 // As an exception, dynamic_cast to void* is available because it doesn't 896 // use RTTI. 897 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { 898 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); 899 SrcExpr = ExprError(); 900 return; 901 } 902 903 // Warns when dynamic_cast is used with RTTI data disabled. 904 if (!Self.getLangOpts().RTTIData) { 905 bool MicrosoftABI = 906 Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft(); 907 bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() == 908 DiagnosticOptions::MSVC; 909 if (MicrosoftABI || !DestPointee->isVoidType()) 910 Self.Diag(OpRange.getBegin(), 911 diag::warn_no_dynamic_cast_with_rtti_disabled) 912 << isClangCL; 913 } 914 915 // Done. Everything else is run-time checks. 916 Kind = CK_Dynamic; 917 } 918 919 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 920 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code 921 /// like this: 922 /// const char *str = "literal"; 923 /// legacy_function(const_cast\<char*\>(str)); 924 void CastOperation::CheckConstCast() { 925 CheckNoDerefRAII NoderefCheck(*this); 926 927 if (ValueKind == VK_PRValue) 928 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 929 else if (isPlaceholder()) 930 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 931 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 932 return; 933 934 unsigned msg = diag::err_bad_cxx_cast_generic; 935 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg); 936 if (TCR != TC_Success && msg != 0) { 937 Self.Diag(OpRange.getBegin(), msg) << CT_Const 938 << SrcExpr.get()->getType() << DestType << OpRange; 939 } 940 if (!isValidCast(TCR)) 941 SrcExpr = ExprError(); 942 } 943 944 void CastOperation::CheckAddrspaceCast() { 945 unsigned msg = diag::err_bad_cxx_cast_generic; 946 auto TCR = 947 TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind); 948 if (TCR != TC_Success && msg != 0) { 949 Self.Diag(OpRange.getBegin(), msg) 950 << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange; 951 } 952 if (!isValidCast(TCR)) 953 SrcExpr = ExprError(); 954 } 955 956 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast 957 /// or downcast between respective pointers or references. 958 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, 959 QualType DestType, 960 SourceRange OpRange) { 961 QualType SrcType = SrcExpr->getType(); 962 // When casting from pointer or reference, get pointee type; use original 963 // type otherwise. 964 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); 965 const CXXRecordDecl *SrcRD = 966 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); 967 968 // Examining subobjects for records is only possible if the complete and 969 // valid definition is available. Also, template instantiation is not 970 // allowed here. 971 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) 972 return; 973 974 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); 975 976 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) 977 return; 978 979 enum { 980 ReinterpretUpcast, 981 ReinterpretDowncast 982 } ReinterpretKind; 983 984 CXXBasePaths BasePaths; 985 986 if (SrcRD->isDerivedFrom(DestRD, BasePaths)) 987 ReinterpretKind = ReinterpretUpcast; 988 else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) 989 ReinterpretKind = ReinterpretDowncast; 990 else 991 return; 992 993 bool VirtualBase = true; 994 bool NonZeroOffset = false; 995 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), 996 E = BasePaths.end(); 997 I != E; ++I) { 998 const CXXBasePath &Path = *I; 999 CharUnits Offset = CharUnits::Zero(); 1000 bool IsVirtual = false; 1001 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); 1002 IElem != EElem; ++IElem) { 1003 IsVirtual = IElem->Base->isVirtual(); 1004 if (IsVirtual) 1005 break; 1006 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); 1007 assert(BaseRD && "Base type should be a valid unqualified class type"); 1008 // Don't check if any base has invalid declaration or has no definition 1009 // since it has no layout info. 1010 const CXXRecordDecl *Class = IElem->Class, 1011 *ClassDefinition = Class->getDefinition(); 1012 if (Class->isInvalidDecl() || !ClassDefinition || 1013 !ClassDefinition->isCompleteDefinition()) 1014 return; 1015 1016 const ASTRecordLayout &DerivedLayout = 1017 Self.Context.getASTRecordLayout(Class); 1018 Offset += DerivedLayout.getBaseClassOffset(BaseRD); 1019 } 1020 if (!IsVirtual) { 1021 // Don't warn if any path is a non-virtually derived base at offset zero. 1022 if (Offset.isZero()) 1023 return; 1024 // Offset makes sense only for non-virtual bases. 1025 else 1026 NonZeroOffset = true; 1027 } 1028 VirtualBase = VirtualBase && IsVirtual; 1029 } 1030 1031 (void) NonZeroOffset; // Silence set but not used warning. 1032 assert((VirtualBase || NonZeroOffset) && 1033 "Should have returned if has non-virtual base with zero offset"); 1034 1035 QualType BaseType = 1036 ReinterpretKind == ReinterpretUpcast? DestType : SrcType; 1037 QualType DerivedType = 1038 ReinterpretKind == ReinterpretUpcast? SrcType : DestType; 1039 1040 SourceLocation BeginLoc = OpRange.getBegin(); 1041 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) 1042 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) 1043 << OpRange; 1044 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) 1045 << int(ReinterpretKind) 1046 << FixItHint::CreateReplacement(BeginLoc, "static_cast"); 1047 } 1048 1049 static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType, 1050 ASTContext &Context) { 1051 if (SrcType->isPointerType() && DestType->isPointerType()) 1052 return true; 1053 1054 // Allow integral type mismatch if their size are equal. 1055 if (SrcType->isIntegralType(Context) && DestType->isIntegralType(Context)) 1056 if (Context.getTypeInfoInChars(SrcType).Width == 1057 Context.getTypeInfoInChars(DestType).Width) 1058 return true; 1059 1060 return Context.hasSameUnqualifiedType(SrcType, DestType); 1061 } 1062 1063 static unsigned int checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr, 1064 QualType DestType) { 1065 unsigned int DiagID = 0; 1066 const unsigned int DiagList[] = {diag::warn_cast_function_type_strict, 1067 diag::warn_cast_function_type}; 1068 for (auto ID : DiagList) { 1069 if (!Self.Diags.isIgnored(ID, SrcExpr.get()->getExprLoc())) { 1070 DiagID = ID; 1071 break; 1072 } 1073 } 1074 if (!DiagID) 1075 return 0; 1076 1077 QualType SrcType = SrcExpr.get()->getType(); 1078 const FunctionType *SrcFTy = nullptr; 1079 const FunctionType *DstFTy = nullptr; 1080 if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) && 1081 DestType->isFunctionPointerType()) || 1082 (SrcType->isMemberFunctionPointerType() && 1083 DestType->isMemberFunctionPointerType())) { 1084 SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>(); 1085 DstFTy = DestType->getPointeeType()->castAs<FunctionType>(); 1086 } else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) { 1087 SrcFTy = SrcType->castAs<FunctionType>(); 1088 DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>(); 1089 } else { 1090 return 0; 1091 } 1092 assert(SrcFTy && DstFTy); 1093 1094 if (Self.Context.hasSameType(SrcFTy, DstFTy)) 1095 return 0; 1096 1097 // For strict checks, ensure we have an exact match. 1098 if (DiagID == diag::warn_cast_function_type_strict) 1099 return DiagID; 1100 1101 auto IsVoidVoid = [](const FunctionType *T) { 1102 if (!T->getReturnType()->isVoidType()) 1103 return false; 1104 if (const auto *PT = T->getAs<FunctionProtoType>()) 1105 return !PT->isVariadic() && PT->getNumParams() == 0; 1106 return false; 1107 }; 1108 1109 // Skip if either function type is void(*)(void) 1110 if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy)) 1111 return 0; 1112 1113 // Check return type. 1114 if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(), 1115 Self.Context)) 1116 return DiagID; 1117 1118 // Check if either has unspecified number of parameters 1119 if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType()) 1120 return 0; 1121 1122 // Check parameter types. 1123 1124 const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy); 1125 const auto *DstFPTy = cast<FunctionProtoType>(DstFTy); 1126 1127 // In a cast involving function types with a variable argument list only the 1128 // types of initial arguments that are provided are considered. 1129 unsigned NumParams = SrcFPTy->getNumParams(); 1130 unsigned DstNumParams = DstFPTy->getNumParams(); 1131 if (NumParams > DstNumParams) { 1132 if (!DstFPTy->isVariadic()) 1133 return DiagID; 1134 NumParams = DstNumParams; 1135 } else if (NumParams < DstNumParams) { 1136 if (!SrcFPTy->isVariadic()) 1137 return DiagID; 1138 } 1139 1140 for (unsigned i = 0; i < NumParams; ++i) 1141 if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i), 1142 DstFPTy->getParamType(i), Self.Context)) 1143 return DiagID; 1144 1145 return 0; 1146 } 1147 1148 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 1149 /// valid. 1150 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 1151 /// like this: 1152 /// char *bytes = reinterpret_cast\<char*\>(int_ptr); 1153 void CastOperation::CheckReinterpretCast() { 1154 if (ValueKind == VK_PRValue && !isPlaceholder(BuiltinType::Overload)) 1155 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 1156 else 1157 checkNonOverloadPlaceholders(); 1158 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 1159 return; 1160 1161 unsigned msg = diag::err_bad_cxx_cast_generic; 1162 TryCastResult tcr = 1163 TryReinterpretCast(Self, SrcExpr, DestType, 1164 /*CStyle*/false, OpRange, msg, Kind); 1165 if (tcr != TC_Success && msg != 0) { 1166 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 1167 return; 1168 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1169 //FIXME: &f<int>; is overloaded and resolvable 1170 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 1171 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 1172 << DestType << OpRange; 1173 Self.NoteAllOverloadCandidates(SrcExpr.get()); 1174 1175 } else { 1176 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), 1177 DestType, /*listInitialization=*/false); 1178 } 1179 } 1180 1181 if (isValidCast(tcr)) { 1182 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 1183 checkObjCConversion(Sema::CCK_OtherCast); 1184 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); 1185 1186 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType)) 1187 Self.Diag(OpRange.getBegin(), DiagID) 1188 << SrcExpr.get()->getType() << DestType << OpRange; 1189 } else { 1190 SrcExpr = ExprError(); 1191 } 1192 } 1193 1194 1195 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 1196 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 1197 /// implicit conversions explicit and getting rid of data loss warnings. 1198 void CastOperation::CheckStaticCast() { 1199 CheckNoDerefRAII NoderefCheck(*this); 1200 1201 if (isPlaceholder()) { 1202 checkNonOverloadPlaceholders(); 1203 if (SrcExpr.isInvalid()) 1204 return; 1205 } 1206 1207 // This test is outside everything else because it's the only case where 1208 // a non-lvalue-reference target type does not lead to decay. 1209 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1210 if (DestType->isVoidType()) { 1211 Kind = CK_ToVoid; 1212 1213 if (claimPlaceholder(BuiltinType::Overload)) { 1214 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 1215 false, // Decay Function to ptr 1216 true, // Complain 1217 OpRange, DestType, diag::err_bad_static_cast_overload); 1218 if (SrcExpr.isInvalid()) 1219 return; 1220 } 1221 1222 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 1223 return; 1224 } 1225 1226 if (ValueKind == VK_PRValue && !DestType->isRecordType() && 1227 !isPlaceholder(BuiltinType::Overload)) { 1228 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 1229 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 1230 return; 1231 } 1232 1233 unsigned msg = diag::err_bad_cxx_cast_generic; 1234 TryCastResult tcr 1235 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 1236 Kind, BasePath, /*ListInitialization=*/false); 1237 if (tcr != TC_Success && msg != 0) { 1238 if (SrcExpr.isInvalid()) 1239 return; 1240 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1241 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 1242 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 1243 << oe->getName() << DestType << OpRange 1244 << oe->getQualifierLoc().getSourceRange(); 1245 Self.NoteAllOverloadCandidates(SrcExpr.get()); 1246 } else { 1247 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, 1248 /*listInitialization=*/false); 1249 } 1250 } 1251 1252 if (isValidCast(tcr)) { 1253 if (Kind == CK_BitCast) 1254 checkCastAlign(); 1255 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 1256 checkObjCConversion(Sema::CCK_OtherCast); 1257 } else { 1258 SrcExpr = ExprError(); 1259 } 1260 } 1261 1262 static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) { 1263 auto *SrcPtrType = SrcType->getAs<PointerType>(); 1264 if (!SrcPtrType) 1265 return false; 1266 auto *DestPtrType = DestType->getAs<PointerType>(); 1267 if (!DestPtrType) 1268 return false; 1269 return SrcPtrType->getPointeeType().getAddressSpace() != 1270 DestPtrType->getPointeeType().getAddressSpace(); 1271 } 1272 1273 /// TryStaticCast - Check if a static cast can be performed, and do so if 1274 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting 1275 /// and casting away constness. 1276 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 1277 QualType DestType, 1278 Sema::CheckedConversionKind CCK, 1279 SourceRange OpRange, unsigned &msg, 1280 CastKind &Kind, CXXCastPath &BasePath, 1281 bool ListInitialization) { 1282 // Determine whether we have the semantics of a C-style cast. 1283 bool CStyle 1284 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1285 1286 // The order the tests is not entirely arbitrary. There is one conversion 1287 // that can be handled in two different ways. Given: 1288 // struct A {}; 1289 // struct B : public A { 1290 // B(); B(const A&); 1291 // }; 1292 // const A &a = B(); 1293 // the cast static_cast<const B&>(a) could be seen as either a static 1294 // reference downcast, or an explicit invocation of the user-defined 1295 // conversion using B's conversion constructor. 1296 // DR 427 specifies that the downcast is to be applied here. 1297 1298 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1299 // Done outside this function. 1300 1301 TryCastResult tcr; 1302 1303 // C++ 5.2.9p5, reference downcast. 1304 // See the function for details. 1305 // DR 427 specifies that this is to be applied before paragraph 2. 1306 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, 1307 OpRange, msg, Kind, BasePath); 1308 if (tcr != TC_NotApplicable) 1309 return tcr; 1310 1311 // C++11 [expr.static.cast]p3: 1312 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 1313 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1314 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 1315 BasePath, msg); 1316 if (tcr != TC_NotApplicable) 1317 return tcr; 1318 1319 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 1320 // [...] if the declaration "T t(e);" is well-formed, [...]. 1321 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 1322 Kind, ListInitialization); 1323 if (SrcExpr.isInvalid()) 1324 return TC_Failed; 1325 if (tcr != TC_NotApplicable) 1326 return tcr; 1327 1328 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 1329 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 1330 // conversions, subject to further restrictions. 1331 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 1332 // of qualification conversions impossible. (In C++20, adding an array bound 1333 // would be the reverse of a qualification conversion, but adding permission 1334 // to add an array bound in a static_cast is a wording oversight.) 1335 // In the CStyle case, the earlier attempt to const_cast should have taken 1336 // care of reverse qualification conversions. 1337 1338 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 1339 1340 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 1341 // converted to an integral type. [...] A value of a scoped enumeration type 1342 // can also be explicitly converted to a floating-point type [...]. 1343 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 1344 if (Enum->getDecl()->isScoped()) { 1345 if (DestType->isBooleanType()) { 1346 Kind = CK_IntegralToBoolean; 1347 return TC_Success; 1348 } else if (DestType->isIntegralType(Self.Context)) { 1349 Kind = CK_IntegralCast; 1350 return TC_Success; 1351 } else if (DestType->isRealFloatingType()) { 1352 Kind = CK_IntegralToFloating; 1353 return TC_Success; 1354 } 1355 } 1356 } 1357 1358 // Reverse integral promotion/conversion. All such conversions are themselves 1359 // again integral promotions or conversions and are thus already handled by 1360 // p2 (TryDirectInitialization above). 1361 // (Note: any data loss warnings should be suppressed.) 1362 // The exception is the reverse of enum->integer, i.e. integer->enum (and 1363 // enum->enum). See also C++ 5.2.9p7. 1364 // The same goes for reverse floating point promotion/conversion and 1365 // floating-integral conversions. Again, only floating->enum is relevant. 1366 if (DestType->isEnumeralType()) { 1367 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1368 diag::err_bad_cast_incomplete)) { 1369 SrcExpr = ExprError(); 1370 return TC_Failed; 1371 } 1372 if (SrcType->isIntegralOrEnumerationType()) { 1373 // [expr.static.cast]p10 If the enumeration type has a fixed underlying 1374 // type, the value is first converted to that type by integral conversion 1375 const EnumType *Enum = DestType->castAs<EnumType>(); 1376 Kind = Enum->getDecl()->isFixed() && 1377 Enum->getDecl()->getIntegerType()->isBooleanType() 1378 ? CK_IntegralToBoolean 1379 : CK_IntegralCast; 1380 return TC_Success; 1381 } else if (SrcType->isRealFloatingType()) { 1382 Kind = CK_FloatingToIntegral; 1383 return TC_Success; 1384 } 1385 } 1386 1387 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 1388 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 1389 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 1390 Kind, BasePath); 1391 if (tcr != TC_NotApplicable) 1392 return tcr; 1393 1394 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 1395 // conversion. C++ 5.2.9p9 has additional information. 1396 // DR54's access restrictions apply here also. 1397 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 1398 OpRange, msg, Kind, BasePath); 1399 if (tcr != TC_NotApplicable) 1400 return tcr; 1401 1402 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 1403 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 1404 // just the usual constness stuff. 1405 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 1406 QualType SrcPointee = SrcPointer->getPointeeType(); 1407 if (SrcPointee->isVoidType()) { 1408 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 1409 QualType DestPointee = DestPointer->getPointeeType(); 1410 if (DestPointee->isIncompleteOrObjectType()) { 1411 // This is definitely the intended conversion, but it might fail due 1412 // to a qualifier violation. Note that we permit Objective-C lifetime 1413 // and GC qualifier mismatches here. 1414 if (!CStyle) { 1415 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 1416 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 1417 DestPointeeQuals.removeObjCGCAttr(); 1418 DestPointeeQuals.removeObjCLifetime(); 1419 SrcPointeeQuals.removeObjCGCAttr(); 1420 SrcPointeeQuals.removeObjCLifetime(); 1421 if (DestPointeeQuals != SrcPointeeQuals && 1422 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 1423 msg = diag::err_bad_cxx_cast_qualifiers_away; 1424 return TC_Failed; 1425 } 1426 } 1427 Kind = IsAddressSpaceConversion(SrcType, DestType) 1428 ? CK_AddressSpaceConversion 1429 : CK_BitCast; 1430 return TC_Success; 1431 } 1432 1433 // Microsoft permits static_cast from 'pointer-to-void' to 1434 // 'pointer-to-function'. 1435 if (!CStyle && Self.getLangOpts().MSVCCompat && 1436 DestPointee->isFunctionType()) { 1437 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; 1438 Kind = CK_BitCast; 1439 return TC_Success; 1440 } 1441 } 1442 else if (DestType->isObjCObjectPointerType()) { 1443 // allow both c-style cast and static_cast of objective-c pointers as 1444 // they are pervasive. 1445 Kind = CK_CPointerToObjCPointerCast; 1446 return TC_Success; 1447 } 1448 else if (CStyle && DestType->isBlockPointerType()) { 1449 // allow c-style cast of void * to block pointers. 1450 Kind = CK_AnyPointerToBlockPointerCast; 1451 return TC_Success; 1452 } 1453 } 1454 } 1455 // Allow arbitrary objective-c pointer conversion with static casts. 1456 if (SrcType->isObjCObjectPointerType() && 1457 DestType->isObjCObjectPointerType()) { 1458 Kind = CK_BitCast; 1459 return TC_Success; 1460 } 1461 // Allow ns-pointer to cf-pointer conversion in either direction 1462 // with static casts. 1463 if (!CStyle && 1464 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) 1465 return TC_Success; 1466 1467 // See if it looks like the user is trying to convert between 1468 // related record types, and select a better diagnostic if so. 1469 if (auto SrcPointer = SrcType->getAs<PointerType>()) 1470 if (auto DestPointer = DestType->getAs<PointerType>()) 1471 if (SrcPointer->getPointeeType()->getAs<RecordType>() && 1472 DestPointer->getPointeeType()->getAs<RecordType>()) 1473 msg = diag::err_bad_cxx_cast_unrelated_class; 1474 1475 if (SrcType->isMatrixType() && DestType->isMatrixType()) { 1476 if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) { 1477 SrcExpr = ExprError(); 1478 return TC_Failed; 1479 } 1480 return TC_Success; 1481 } 1482 1483 // We tried everything. Everything! Nothing works! :-( 1484 return TC_NotApplicable; 1485 } 1486 1487 /// Tests whether a conversion according to N2844 is valid. 1488 TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 1489 QualType DestType, bool CStyle, 1490 CastKind &Kind, CXXCastPath &BasePath, 1491 unsigned &msg) { 1492 // C++11 [expr.static.cast]p3: 1493 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 1494 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1495 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 1496 if (!R) 1497 return TC_NotApplicable; 1498 1499 if (!SrcExpr->isGLValue()) 1500 return TC_NotApplicable; 1501 1502 // Because we try the reference downcast before this function, from now on 1503 // this is the only cast possibility, so we issue an error if we fail now. 1504 // FIXME: Should allow casting away constness if CStyle. 1505 QualType FromType = SrcExpr->getType(); 1506 QualType ToType = R->getPointeeType(); 1507 if (CStyle) { 1508 FromType = FromType.getUnqualifiedType(); 1509 ToType = ToType.getUnqualifiedType(); 1510 } 1511 1512 Sema::ReferenceConversions RefConv; 1513 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship( 1514 SrcExpr->getBeginLoc(), ToType, FromType, &RefConv); 1515 if (RefResult != Sema::Ref_Compatible) { 1516 if (CStyle || RefResult == Sema::Ref_Incompatible) 1517 return TC_NotApplicable; 1518 // Diagnose types which are reference-related but not compatible here since 1519 // we can provide better diagnostics. In these cases forwarding to 1520 // [expr.static.cast]p4 should never result in a well-formed cast. 1521 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast 1522 : diag::err_bad_rvalue_to_rvalue_cast; 1523 return TC_Failed; 1524 } 1525 1526 if (RefConv & Sema::ReferenceConversions::DerivedToBase) { 1527 Kind = CK_DerivedToBase; 1528 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1529 /*DetectVirtual=*/true); 1530 if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(), 1531 R->getPointeeType(), Paths)) 1532 return TC_NotApplicable; 1533 1534 Self.BuildBasePathArray(Paths, BasePath); 1535 } else 1536 Kind = CK_NoOp; 1537 1538 return TC_Success; 1539 } 1540 1541 /// Tests whether a conversion according to C++ 5.2.9p5 is valid. 1542 TryCastResult 1543 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 1544 bool CStyle, SourceRange OpRange, 1545 unsigned &msg, CastKind &Kind, 1546 CXXCastPath &BasePath) { 1547 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 1548 // cast to type "reference to cv2 D", where D is a class derived from B, 1549 // if a valid standard conversion from "pointer to D" to "pointer to B" 1550 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1551 // In addition, DR54 clarifies that the base must be accessible in the 1552 // current context. Although the wording of DR54 only applies to the pointer 1553 // variant of this rule, the intent is clearly for it to apply to the this 1554 // conversion as well. 1555 1556 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1557 if (!DestReference) { 1558 return TC_NotApplicable; 1559 } 1560 bool RValueRef = DestReference->isRValueReferenceType(); 1561 if (!RValueRef && !SrcExpr->isLValue()) { 1562 // We know the left side is an lvalue reference, so we can suggest a reason. 1563 msg = diag::err_bad_cxx_cast_rvalue; 1564 return TC_NotApplicable; 1565 } 1566 1567 QualType DestPointee = DestReference->getPointeeType(); 1568 1569 // FIXME: If the source is a prvalue, we should issue a warning (because the 1570 // cast always has undefined behavior), and for AST consistency, we should 1571 // materialize a temporary. 1572 return TryStaticDowncast(Self, 1573 Self.Context.getCanonicalType(SrcExpr->getType()), 1574 Self.Context.getCanonicalType(DestPointee), CStyle, 1575 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1576 BasePath); 1577 } 1578 1579 /// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1580 TryCastResult 1581 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1582 bool CStyle, SourceRange OpRange, 1583 unsigned &msg, CastKind &Kind, 1584 CXXCastPath &BasePath) { 1585 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1586 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1587 // is a class derived from B, if a valid standard conversion from "pointer 1588 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1589 // class of D. 1590 // In addition, DR54 clarifies that the base must be accessible in the 1591 // current context. 1592 1593 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1594 if (!DestPointer) { 1595 return TC_NotApplicable; 1596 } 1597 1598 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1599 if (!SrcPointer) { 1600 msg = diag::err_bad_static_cast_pointer_nonpointer; 1601 return TC_NotApplicable; 1602 } 1603 1604 return TryStaticDowncast(Self, 1605 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1606 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1607 CStyle, OpRange, SrcType, DestType, msg, Kind, 1608 BasePath); 1609 } 1610 1611 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1612 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1613 /// DestType is possible and allowed. 1614 TryCastResult 1615 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1616 bool CStyle, SourceRange OpRange, QualType OrigSrcType, 1617 QualType OrigDestType, unsigned &msg, 1618 CastKind &Kind, CXXCastPath &BasePath) { 1619 // We can only work with complete types. But don't complain if it doesn't work 1620 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || 1621 !Self.isCompleteType(OpRange.getBegin(), DestType)) 1622 return TC_NotApplicable; 1623 1624 // Downcast can only happen in class hierarchies, so we need classes. 1625 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1626 return TC_NotApplicable; 1627 } 1628 1629 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1630 /*DetectVirtual=*/true); 1631 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { 1632 return TC_NotApplicable; 1633 } 1634 1635 // Target type does derive from source type. Now we're serious. If an error 1636 // appears now, it's not ignored. 1637 // This may not be entirely in line with the standard. Take for example: 1638 // struct A {}; 1639 // struct B : virtual A { 1640 // B(A&); 1641 // }; 1642 // 1643 // void f() 1644 // { 1645 // (void)static_cast<const B&>(*((A*)0)); 1646 // } 1647 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1648 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1649 // However, both GCC and Comeau reject this example, and accepting it would 1650 // mean more complex code if we're to preserve the nice error message. 1651 // FIXME: Being 100% compliant here would be nice to have. 1652 1653 // Must preserve cv, as always, unless we're in C-style mode. 1654 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1655 msg = diag::err_bad_cxx_cast_qualifiers_away; 1656 return TC_Failed; 1657 } 1658 1659 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1660 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1661 // that it builds the paths in reverse order. 1662 // To sum up: record all paths to the base and build a nice string from 1663 // them. Use it to spice up the error message. 1664 if (!Paths.isRecordingPaths()) { 1665 Paths.clear(); 1666 Paths.setRecordingPaths(true); 1667 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); 1668 } 1669 std::string PathDisplayStr; 1670 std::set<unsigned> DisplayedPaths; 1671 for (clang::CXXBasePath &Path : Paths) { 1672 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) { 1673 // We haven't displayed a path to this particular base 1674 // class subobject yet. 1675 PathDisplayStr += "\n "; 1676 for (CXXBasePathElement &PE : llvm::reverse(Path)) 1677 PathDisplayStr += PE.Base->getType().getAsString() + " -> "; 1678 PathDisplayStr += QualType(DestType).getAsString(); 1679 } 1680 } 1681 1682 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1683 << QualType(SrcType).getUnqualifiedType() 1684 << QualType(DestType).getUnqualifiedType() 1685 << PathDisplayStr << OpRange; 1686 msg = 0; 1687 return TC_Failed; 1688 } 1689 1690 if (Paths.getDetectedVirtual() != nullptr) { 1691 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1692 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1693 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1694 msg = 0; 1695 return TC_Failed; 1696 } 1697 1698 if (!CStyle) { 1699 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1700 SrcType, DestType, 1701 Paths.front(), 1702 diag::err_downcast_from_inaccessible_base)) { 1703 case Sema::AR_accessible: 1704 case Sema::AR_delayed: // be optimistic 1705 case Sema::AR_dependent: // be optimistic 1706 break; 1707 1708 case Sema::AR_inaccessible: 1709 msg = 0; 1710 return TC_Failed; 1711 } 1712 } 1713 1714 Self.BuildBasePathArray(Paths, BasePath); 1715 Kind = CK_BaseToDerived; 1716 return TC_Success; 1717 } 1718 1719 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1720 /// C++ 5.2.9p9 is valid: 1721 /// 1722 /// An rvalue of type "pointer to member of D of type cv1 T" can be 1723 /// converted to an rvalue of type "pointer to member of B of type cv2 T", 1724 /// where B is a base class of D [...]. 1725 /// 1726 TryCastResult 1727 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1728 QualType DestType, bool CStyle, 1729 SourceRange OpRange, 1730 unsigned &msg, CastKind &Kind, 1731 CXXCastPath &BasePath) { 1732 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1733 if (!DestMemPtr) 1734 return TC_NotApplicable; 1735 1736 bool WasOverloadedFunction = false; 1737 DeclAccessPair FoundOverload; 1738 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1739 if (FunctionDecl *Fn 1740 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1741 FoundOverload)) { 1742 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1743 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1744 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1745 WasOverloadedFunction = true; 1746 } 1747 } 1748 1749 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1750 if (!SrcMemPtr) { 1751 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1752 return TC_NotApplicable; 1753 } 1754 1755 // Lock down the inheritance model right now in MS ABI, whether or not the 1756 // pointee types are the same. 1757 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1758 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 1759 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 1760 } 1761 1762 // T == T, modulo cv 1763 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1764 DestMemPtr->getPointeeType())) 1765 return TC_NotApplicable; 1766 1767 // B base of D 1768 QualType SrcClass(SrcMemPtr->getClass(), 0); 1769 QualType DestClass(DestMemPtr->getClass(), 0); 1770 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1771 /*DetectVirtual=*/true); 1772 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) 1773 return TC_NotApplicable; 1774 1775 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1776 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1777 Paths.clear(); 1778 Paths.setRecordingPaths(true); 1779 bool StillOkay = 1780 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); 1781 assert(StillOkay); 1782 (void)StillOkay; 1783 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1784 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1785 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1786 msg = 0; 1787 return TC_Failed; 1788 } 1789 1790 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1791 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1792 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1793 msg = 0; 1794 return TC_Failed; 1795 } 1796 1797 if (!CStyle) { 1798 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1799 DestClass, SrcClass, 1800 Paths.front(), 1801 diag::err_upcast_to_inaccessible_base)) { 1802 case Sema::AR_accessible: 1803 case Sema::AR_delayed: 1804 case Sema::AR_dependent: 1805 // Optimistically assume that the delayed and dependent cases 1806 // will work out. 1807 break; 1808 1809 case Sema::AR_inaccessible: 1810 msg = 0; 1811 return TC_Failed; 1812 } 1813 } 1814 1815 if (WasOverloadedFunction) { 1816 // Resolve the address of the overloaded function again, this time 1817 // allowing complaints if something goes wrong. 1818 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1819 DestType, 1820 true, 1821 FoundOverload); 1822 if (!Fn) { 1823 msg = 0; 1824 return TC_Failed; 1825 } 1826 1827 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1828 if (!SrcExpr.isUsable()) { 1829 msg = 0; 1830 return TC_Failed; 1831 } 1832 } 1833 1834 Self.BuildBasePathArray(Paths, BasePath); 1835 Kind = CK_DerivedToBaseMemberPointer; 1836 return TC_Success; 1837 } 1838 1839 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1840 /// is valid: 1841 /// 1842 /// An expression e can be explicitly converted to a type T using a 1843 /// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1844 TryCastResult 1845 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1846 Sema::CheckedConversionKind CCK, 1847 SourceRange OpRange, unsigned &msg, 1848 CastKind &Kind, bool ListInitialization) { 1849 if (DestType->isRecordType()) { 1850 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1851 diag::err_bad_cast_incomplete) || 1852 Self.RequireNonAbstractType(OpRange.getBegin(), DestType, 1853 diag::err_allocation_of_abstract_type)) { 1854 msg = 0; 1855 return TC_Failed; 1856 } 1857 } 1858 1859 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1860 InitializationKind InitKind 1861 = (CCK == Sema::CCK_CStyleCast) 1862 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, 1863 ListInitialization) 1864 : (CCK == Sema::CCK_FunctionalCast) 1865 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) 1866 : InitializationKind::CreateCast(OpRange); 1867 Expr *SrcExprRaw = SrcExpr.get(); 1868 // FIXME: Per DR242, we should check for an implicit conversion sequence 1869 // or for a constructor that could be invoked by direct-initialization 1870 // here, not for an initialization sequence. 1871 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); 1872 1873 // At this point of CheckStaticCast, if the destination is a reference, 1874 // or the expression is an overload expression this has to work. 1875 // There is no other way that works. 1876 // On the other hand, if we're checking a C-style cast, we've still got 1877 // the reinterpret_cast way. 1878 bool CStyle 1879 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1880 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1881 return TC_NotApplicable; 1882 1883 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); 1884 if (Result.isInvalid()) { 1885 msg = 0; 1886 return TC_Failed; 1887 } 1888 1889 if (InitSeq.isConstructorInitialization()) 1890 Kind = CK_ConstructorConversion; 1891 else 1892 Kind = CK_NoOp; 1893 1894 SrcExpr = Result; 1895 return TC_Success; 1896 } 1897 1898 /// TryConstCast - See if a const_cast from source to destination is allowed, 1899 /// and perform it if it is. 1900 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 1901 QualType DestType, bool CStyle, 1902 unsigned &msg) { 1903 DestType = Self.Context.getCanonicalType(DestType); 1904 QualType SrcType = SrcExpr.get()->getType(); 1905 bool NeedToMaterializeTemporary = false; 1906 1907 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1908 // C++11 5.2.11p4: 1909 // if a pointer to T1 can be explicitly converted to the type "pointer to 1910 // T2" using a const_cast, then the following conversions can also be 1911 // made: 1912 // -- an lvalue of type T1 can be explicitly converted to an lvalue of 1913 // type T2 using the cast const_cast<T2&>; 1914 // -- a glvalue of type T1 can be explicitly converted to an xvalue of 1915 // type T2 using the cast const_cast<T2&&>; and 1916 // -- if T1 is a class type, a prvalue of type T1 can be explicitly 1917 // converted to an xvalue of type T2 using the cast const_cast<T2&&>. 1918 1919 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { 1920 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1921 // is C-style, static_cast might find a way, so we simply suggest a 1922 // message and tell the parent to keep searching. 1923 msg = diag::err_bad_cxx_cast_rvalue; 1924 return TC_NotApplicable; 1925 } 1926 1927 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isPRValue()) { 1928 if (!SrcType->isRecordType()) { 1929 // Cannot const_cast non-class prvalue to rvalue reference type. But if 1930 // this is C-style, static_cast can do this. 1931 msg = diag::err_bad_cxx_cast_rvalue; 1932 return TC_NotApplicable; 1933 } 1934 1935 // Materialize the class prvalue so that the const_cast can bind a 1936 // reference to it. 1937 NeedToMaterializeTemporary = true; 1938 } 1939 1940 // It's not completely clear under the standard whether we can 1941 // const_cast bit-field gl-values. Doing so would not be 1942 // intrinsically complicated, but for now, we say no for 1943 // consistency with other compilers and await the word of the 1944 // committee. 1945 if (SrcExpr.get()->refersToBitField()) { 1946 msg = diag::err_bad_cxx_cast_bitfield; 1947 return TC_NotApplicable; 1948 } 1949 1950 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1951 SrcType = Self.Context.getPointerType(SrcType); 1952 } 1953 1954 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1955 // the rules for const_cast are the same as those used for pointers. 1956 1957 if (!DestType->isPointerType() && 1958 !DestType->isMemberPointerType() && 1959 !DestType->isObjCObjectPointerType()) { 1960 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1961 // was a reference type, we converted it to a pointer above. 1962 // The status of rvalue references isn't entirely clear, but it looks like 1963 // conversion to them is simply invalid. 1964 // C++ 5.2.11p3: For two pointer types [...] 1965 if (!CStyle) 1966 msg = diag::err_bad_const_cast_dest; 1967 return TC_NotApplicable; 1968 } 1969 if (DestType->isFunctionPointerType() || 1970 DestType->isMemberFunctionPointerType()) { 1971 // Cannot cast direct function pointers. 1972 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1973 // T is the ultimate pointee of source and target type. 1974 if (!CStyle) 1975 msg = diag::err_bad_const_cast_dest; 1976 return TC_NotApplicable; 1977 } 1978 1979 // C++ [expr.const.cast]p3: 1980 // "For two similar types T1 and T2, [...]" 1981 // 1982 // We only allow a const_cast to change cvr-qualifiers, not other kinds of 1983 // type qualifiers. (Likewise, we ignore other changes when determining 1984 // whether a cast casts away constness.) 1985 if (!Self.Context.hasCvrSimilarType(SrcType, DestType)) 1986 return TC_NotApplicable; 1987 1988 if (NeedToMaterializeTemporary) 1989 // This is a const_cast from a class prvalue to an rvalue reference type. 1990 // Materialize a temporary to store the result of the conversion. 1991 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(), 1992 SrcExpr.get(), 1993 /*IsLValueReference*/ false); 1994 1995 return TC_Success; 1996 } 1997 1998 // Checks for undefined behavior in reinterpret_cast. 1999 // The cases that is checked for is: 2000 // *reinterpret_cast<T*>(&a) 2001 // reinterpret_cast<T&>(a) 2002 // where accessing 'a' as type 'T' will result in undefined behavior. 2003 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 2004 bool IsDereference, 2005 SourceRange Range) { 2006 unsigned DiagID = IsDereference ? 2007 diag::warn_pointer_indirection_from_incompatible_type : 2008 diag::warn_undefined_reinterpret_cast; 2009 2010 if (Diags.isIgnored(DiagID, Range.getBegin())) 2011 return; 2012 2013 QualType SrcTy, DestTy; 2014 if (IsDereference) { 2015 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 2016 return; 2017 } 2018 SrcTy = SrcType->getPointeeType(); 2019 DestTy = DestType->getPointeeType(); 2020 } else { 2021 if (!DestType->getAs<ReferenceType>()) { 2022 return; 2023 } 2024 SrcTy = SrcType; 2025 DestTy = DestType->getPointeeType(); 2026 } 2027 2028 // Cast is compatible if the types are the same. 2029 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 2030 return; 2031 } 2032 // or one of the types is a char or void type 2033 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 2034 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 2035 return; 2036 } 2037 // or one of the types is a tag type. 2038 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 2039 return; 2040 } 2041 2042 // FIXME: Scoped enums? 2043 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 2044 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 2045 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 2046 return; 2047 } 2048 } 2049 2050 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 2051 } 2052 2053 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, 2054 QualType DestType) { 2055 QualType SrcType = SrcExpr.get()->getType(); 2056 if (Self.Context.hasSameType(SrcType, DestType)) 2057 return; 2058 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) 2059 if (SrcPtrTy->isObjCSelType()) { 2060 QualType DT = DestType; 2061 if (isa<PointerType>(DestType)) 2062 DT = DestType->getPointeeType(); 2063 if (!DT.getUnqualifiedType()->isVoidType()) 2064 Self.Diag(SrcExpr.get()->getExprLoc(), 2065 diag::warn_cast_pointer_from_sel) 2066 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2067 } 2068 } 2069 2070 /// Diagnose casts that change the calling convention of a pointer to a function 2071 /// defined in the current TU. 2072 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, 2073 QualType DstType, SourceRange OpRange) { 2074 // Check if this cast would change the calling convention of a function 2075 // pointer type. 2076 QualType SrcType = SrcExpr.get()->getType(); 2077 if (Self.Context.hasSameType(SrcType, DstType) || 2078 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType()) 2079 return; 2080 const auto *SrcFTy = 2081 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); 2082 const auto *DstFTy = 2083 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); 2084 CallingConv SrcCC = SrcFTy->getCallConv(); 2085 CallingConv DstCC = DstFTy->getCallConv(); 2086 if (SrcCC == DstCC) 2087 return; 2088 2089 // We have a calling convention cast. Check if the source is a pointer to a 2090 // known, specific function that has already been defined. 2091 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts(); 2092 if (auto *UO = dyn_cast<UnaryOperator>(Src)) 2093 if (UO->getOpcode() == UO_AddrOf) 2094 Src = UO->getSubExpr()->IgnoreParenImpCasts(); 2095 auto *DRE = dyn_cast<DeclRefExpr>(Src); 2096 if (!DRE) 2097 return; 2098 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 2099 if (!FD) 2100 return; 2101 2102 // Only warn if we are casting from the default convention to a non-default 2103 // convention. This can happen when the programmer forgot to apply the calling 2104 // convention to the function declaration and then inserted this cast to 2105 // satisfy the type system. 2106 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention( 2107 FD->isVariadic(), FD->isCXXInstanceMember()); 2108 if (DstCC == DefaultCC || SrcCC != DefaultCC) 2109 return; 2110 2111 // Diagnose this cast, as it is probably bad. 2112 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC); 2113 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC); 2114 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv) 2115 << SrcCCName << DstCCName << OpRange; 2116 2117 // The checks above are cheaper than checking if the diagnostic is enabled. 2118 // However, it's worth checking if the warning is enabled before we construct 2119 // a fixit. 2120 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin())) 2121 return; 2122 2123 // Try to suggest a fixit to change the calling convention of the function 2124 // whose address was taken. Try to use the latest macro for the convention. 2125 // For example, users probably want to write "WINAPI" instead of "__stdcall" 2126 // to match the Windows header declarations. 2127 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc(); 2128 Preprocessor &PP = Self.getPreprocessor(); 2129 SmallVector<TokenValue, 6> AttrTokens; 2130 SmallString<64> CCAttrText; 2131 llvm::raw_svector_ostream OS(CCAttrText); 2132 if (Self.getLangOpts().MicrosoftExt) { 2133 // __stdcall or __vectorcall 2134 OS << "__" << DstCCName; 2135 IdentifierInfo *II = PP.getIdentifierInfo(OS.str()); 2136 AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) 2137 ? TokenValue(II->getTokenID()) 2138 : TokenValue(II)); 2139 } else { 2140 // __attribute__((stdcall)) or __attribute__((vectorcall)) 2141 OS << "__attribute__((" << DstCCName << "))"; 2142 AttrTokens.push_back(tok::kw___attribute); 2143 AttrTokens.push_back(tok::l_paren); 2144 AttrTokens.push_back(tok::l_paren); 2145 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName); 2146 AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) 2147 ? TokenValue(II->getTokenID()) 2148 : TokenValue(II)); 2149 AttrTokens.push_back(tok::r_paren); 2150 AttrTokens.push_back(tok::r_paren); 2151 } 2152 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens); 2153 if (!AttrSpelling.empty()) 2154 CCAttrText = AttrSpelling; 2155 OS << ' '; 2156 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit) 2157 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText); 2158 } 2159 2160 static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange, 2161 const Expr *SrcExpr, QualType DestType, 2162 Sema &Self) { 2163 QualType SrcType = SrcExpr->getType(); 2164 2165 // Not warning on reinterpret_cast, boolean, constant expressions, etc 2166 // are not explicit design choices, but consistent with GCC's behavior. 2167 // Feel free to modify them if you've reason/evidence for an alternative. 2168 if (CStyle && SrcType->isIntegralType(Self.Context) 2169 && !SrcType->isBooleanType() 2170 && !SrcType->isEnumeralType() 2171 && !SrcExpr->isIntegerConstantExpr(Self.Context) 2172 && Self.Context.getTypeSize(DestType) > 2173 Self.Context.getTypeSize(SrcType)) { 2174 // Separate between casts to void* and non-void* pointers. 2175 // Some APIs use (abuse) void* for something like a user context, 2176 // and often that value is an integer even if it isn't a pointer itself. 2177 // Having a separate warning flag allows users to control the warning 2178 // for their workflow. 2179 unsigned Diag = DestType->isVoidPointerType() ? 2180 diag::warn_int_to_void_pointer_cast 2181 : diag::warn_int_to_pointer_cast; 2182 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; 2183 } 2184 } 2185 2186 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, 2187 ExprResult &Result) { 2188 // We can only fix an overloaded reinterpret_cast if 2189 // - it is a template with explicit arguments that resolves to an lvalue 2190 // unambiguously, or 2191 // - it is the only function in an overload set that may have its address 2192 // taken. 2193 2194 Expr *E = Result.get(); 2195 // TODO: what if this fails because of DiagnoseUseOfDecl or something 2196 // like it? 2197 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2198 Result, 2199 Expr::getValueKindForType(DestType) == 2200 VK_PRValue // Convert Fun to Ptr 2201 ) && 2202 Result.isUsable()) 2203 return true; 2204 2205 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 2206 // preserves Result. 2207 Result = E; 2208 if (!Self.resolveAndFixAddressOfSingleOverloadCandidate( 2209 Result, /*DoFunctionPointerConversion=*/true)) 2210 return false; 2211 return Result.isUsable(); 2212 } 2213 2214 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 2215 QualType DestType, bool CStyle, 2216 SourceRange OpRange, 2217 unsigned &msg, 2218 CastKind &Kind) { 2219 bool IsLValueCast = false; 2220 2221 DestType = Self.Context.getCanonicalType(DestType); 2222 QualType SrcType = SrcExpr.get()->getType(); 2223 2224 // Is the source an overloaded name? (i.e. &foo) 2225 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) 2226 if (SrcType == Self.Context.OverloadTy) { 2227 ExprResult FixedExpr = SrcExpr; 2228 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) 2229 return TC_NotApplicable; 2230 2231 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr"); 2232 SrcExpr = FixedExpr; 2233 SrcType = SrcExpr.get()->getType(); 2234 } 2235 2236 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 2237 if (!SrcExpr.get()->isGLValue()) { 2238 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the 2239 // similar comment in const_cast. 2240 msg = diag::err_bad_cxx_cast_rvalue; 2241 return TC_NotApplicable; 2242 } 2243 2244 if (!CStyle) { 2245 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 2246 /*IsDereference=*/false, OpRange); 2247 } 2248 2249 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 2250 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 2251 // built-in & and * operators. 2252 2253 const char *inappropriate = nullptr; 2254 switch (SrcExpr.get()->getObjectKind()) { 2255 case OK_Ordinary: 2256 break; 2257 case OK_BitField: 2258 msg = diag::err_bad_cxx_cast_bitfield; 2259 return TC_NotApplicable; 2260 // FIXME: Use a specific diagnostic for the rest of these cases. 2261 case OK_VectorComponent: inappropriate = "vector element"; break; 2262 case OK_MatrixComponent: 2263 inappropriate = "matrix element"; 2264 break; 2265 case OK_ObjCProperty: inappropriate = "property expression"; break; 2266 case OK_ObjCSubscript: inappropriate = "container subscripting expression"; 2267 break; 2268 } 2269 if (inappropriate) { 2270 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 2271 << inappropriate << DestType 2272 << OpRange << SrcExpr.get()->getSourceRange(); 2273 msg = 0; SrcExpr = ExprError(); 2274 return TC_NotApplicable; 2275 } 2276 2277 // This code does this transformation for the checked types. 2278 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 2279 SrcType = Self.Context.getPointerType(SrcType); 2280 2281 IsLValueCast = true; 2282 } 2283 2284 // Canonicalize source for comparison. 2285 SrcType = Self.Context.getCanonicalType(SrcType); 2286 2287 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 2288 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 2289 if (DestMemPtr && SrcMemPtr) { 2290 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 2291 // can be explicitly converted to an rvalue of type "pointer to member 2292 // of Y of type T2" if T1 and T2 are both function types or both object 2293 // types. 2294 if (DestMemPtr->isMemberFunctionPointer() != 2295 SrcMemPtr->isMemberFunctionPointer()) 2296 return TC_NotApplicable; 2297 2298 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2299 // We need to determine the inheritance model that the class will use if 2300 // haven't yet. 2301 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 2302 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 2303 } 2304 2305 // Don't allow casting between member pointers of different sizes. 2306 if (Self.Context.getTypeSize(DestMemPtr) != 2307 Self.Context.getTypeSize(SrcMemPtr)) { 2308 msg = diag::err_bad_cxx_cast_member_pointer_size; 2309 return TC_Failed; 2310 } 2311 2312 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 2313 // constness. 2314 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 2315 // we accept it. 2316 if (auto CACK = 2317 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 2318 /*CheckObjCLifetime=*/CStyle)) 2319 return getCastAwayConstnessCastKind(CACK, msg); 2320 2321 // A valid member pointer cast. 2322 assert(!IsLValueCast); 2323 Kind = CK_ReinterpretMemberPointer; 2324 return TC_Success; 2325 } 2326 2327 // See below for the enumeral issue. 2328 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 2329 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 2330 // type large enough to hold it. A value of std::nullptr_t can be 2331 // converted to an integral type; the conversion has the same meaning 2332 // and validity as a conversion of (void*)0 to the integral type. 2333 if (Self.Context.getTypeSize(SrcType) > 2334 Self.Context.getTypeSize(DestType)) { 2335 msg = diag::err_bad_reinterpret_cast_small_int; 2336 return TC_Failed; 2337 } 2338 Kind = CK_PointerToIntegral; 2339 return TC_Success; 2340 } 2341 2342 // Allow reinterpret_casts between vectors of the same size and 2343 // between vectors and integers of the same size. 2344 bool destIsVector = DestType->isVectorType(); 2345 bool srcIsVector = SrcType->isVectorType(); 2346 if (srcIsVector || destIsVector) { 2347 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa. 2348 if (Self.isValidSveBitcast(SrcType, DestType)) { 2349 Kind = CK_BitCast; 2350 return TC_Success; 2351 } 2352 2353 // The non-vector type, if any, must have integral type. This is 2354 // the same rule that C vector casts use; note, however, that enum 2355 // types are not integral in C++. 2356 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) || 2357 (!srcIsVector && !SrcType->isIntegralType(Self.Context))) 2358 return TC_NotApplicable; 2359 2360 // The size we want to consider is eltCount * eltSize. 2361 // That's exactly what the lax-conversion rules will check. 2362 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { 2363 Kind = CK_BitCast; 2364 return TC_Success; 2365 } 2366 2367 if (Self.LangOpts.OpenCL && !CStyle) { 2368 if (DestType->isExtVectorType() || SrcType->isExtVectorType()) { 2369 // FIXME: Allow for reinterpret cast between 3 and 4 element vectors 2370 if (Self.areVectorTypesSameSize(SrcType, DestType)) { 2371 Kind = CK_BitCast; 2372 return TC_Success; 2373 } 2374 } 2375 } 2376 2377 // Otherwise, pick a reasonable diagnostic. 2378 if (!destIsVector) 2379 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 2380 else if (!srcIsVector) 2381 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 2382 else 2383 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 2384 2385 return TC_Failed; 2386 } 2387 2388 if (SrcType == DestType) { 2389 // C++ 5.2.10p2 has a note that mentions that, subject to all other 2390 // restrictions, a cast to the same type is allowed so long as it does not 2391 // cast away constness. In C++98, the intent was not entirely clear here, 2392 // since all other paragraphs explicitly forbid casts to the same type. 2393 // C++11 clarifies this case with p2. 2394 // 2395 // The only allowed types are: integral, enumeration, pointer, or 2396 // pointer-to-member types. We also won't restrict Obj-C pointers either. 2397 Kind = CK_NoOp; 2398 TryCastResult Result = TC_NotApplicable; 2399 if (SrcType->isIntegralOrEnumerationType() || 2400 SrcType->isAnyPointerType() || 2401 SrcType->isMemberPointerType() || 2402 SrcType->isBlockPointerType()) { 2403 Result = TC_Success; 2404 } 2405 return Result; 2406 } 2407 2408 bool destIsPtr = DestType->isAnyPointerType() || 2409 DestType->isBlockPointerType(); 2410 bool srcIsPtr = SrcType->isAnyPointerType() || 2411 SrcType->isBlockPointerType(); 2412 if (!destIsPtr && !srcIsPtr) { 2413 // Except for std::nullptr_t->integer and lvalue->reference, which are 2414 // handled above, at least one of the two arguments must be a pointer. 2415 return TC_NotApplicable; 2416 } 2417 2418 if (DestType->isIntegralType(Self.Context)) { 2419 assert(srcIsPtr && "One type must be a pointer"); 2420 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 2421 // type large enough to hold it; except in Microsoft mode, where the 2422 // integral type size doesn't matter (except we don't allow bool). 2423 if ((Self.Context.getTypeSize(SrcType) > 2424 Self.Context.getTypeSize(DestType))) { 2425 bool MicrosoftException = 2426 Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType(); 2427 if (MicrosoftException) { 2428 unsigned Diag = SrcType->isVoidPointerType() 2429 ? diag::warn_void_pointer_to_int_cast 2430 : diag::warn_pointer_to_int_cast; 2431 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; 2432 } else { 2433 msg = diag::err_bad_reinterpret_cast_small_int; 2434 return TC_Failed; 2435 } 2436 } 2437 Kind = CK_PointerToIntegral; 2438 return TC_Success; 2439 } 2440 2441 if (SrcType->isIntegralOrEnumerationType()) { 2442 assert(destIsPtr && "One type must be a pointer"); 2443 checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self); 2444 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 2445 // converted to a pointer. 2446 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 2447 // necessarily converted to a null pointer value.] 2448 Kind = CK_IntegralToPointer; 2449 return TC_Success; 2450 } 2451 2452 if (!destIsPtr || !srcIsPtr) { 2453 // With the valid non-pointer conversions out of the way, we can be even 2454 // more stringent. 2455 return TC_NotApplicable; 2456 } 2457 2458 // Cannot convert between block pointers and Objective-C object pointers. 2459 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 2460 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 2461 return TC_NotApplicable; 2462 2463 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 2464 // The C-style cast operator can. 2465 TryCastResult SuccessResult = TC_Success; 2466 if (auto CACK = 2467 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 2468 /*CheckObjCLifetime=*/CStyle)) 2469 SuccessResult = getCastAwayConstnessCastKind(CACK, msg); 2470 2471 if (IsAddressSpaceConversion(SrcType, DestType)) { 2472 Kind = CK_AddressSpaceConversion; 2473 assert(SrcType->isPointerType() && DestType->isPointerType()); 2474 if (!CStyle && 2475 !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf( 2476 SrcType->getPointeeType().getQualifiers())) { 2477 SuccessResult = TC_Failed; 2478 } 2479 } else if (IsLValueCast) { 2480 Kind = CK_LValueBitCast; 2481 } else if (DestType->isObjCObjectPointerType()) { 2482 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 2483 } else if (DestType->isBlockPointerType()) { 2484 if (!SrcType->isBlockPointerType()) { 2485 Kind = CK_AnyPointerToBlockPointerCast; 2486 } else { 2487 Kind = CK_BitCast; 2488 } 2489 } else { 2490 Kind = CK_BitCast; 2491 } 2492 2493 // Any pointer can be cast to an Objective-C pointer type with a C-style 2494 // cast. 2495 if (CStyle && DestType->isObjCObjectPointerType()) { 2496 return SuccessResult; 2497 } 2498 if (CStyle) 2499 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2500 2501 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); 2502 2503 // Not casting away constness, so the only remaining check is for compatible 2504 // pointer categories. 2505 2506 if (SrcType->isFunctionPointerType()) { 2507 if (DestType->isFunctionPointerType()) { 2508 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 2509 // a pointer to a function of a different type. 2510 return SuccessResult; 2511 } 2512 2513 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 2514 // an object type or vice versa is conditionally-supported. 2515 // Compilers support it in C++03 too, though, because it's necessary for 2516 // casting the return value of dlsym() and GetProcAddress(). 2517 // FIXME: Conditionally-supported behavior should be configurable in the 2518 // TargetInfo or similar. 2519 Self.Diag(OpRange.getBegin(), 2520 Self.getLangOpts().CPlusPlus11 ? 2521 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2522 << OpRange; 2523 return SuccessResult; 2524 } 2525 2526 if (DestType->isFunctionPointerType()) { 2527 // See above. 2528 Self.Diag(OpRange.getBegin(), 2529 Self.getLangOpts().CPlusPlus11 ? 2530 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2531 << OpRange; 2532 return SuccessResult; 2533 } 2534 2535 // Diagnose address space conversion in nested pointers. 2536 QualType DestPtee = DestType->getPointeeType().isNull() 2537 ? DestType->getPointeeType() 2538 : DestType->getPointeeType()->getPointeeType(); 2539 QualType SrcPtee = SrcType->getPointeeType().isNull() 2540 ? SrcType->getPointeeType() 2541 : SrcType->getPointeeType()->getPointeeType(); 2542 while (!DestPtee.isNull() && !SrcPtee.isNull()) { 2543 if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) { 2544 Self.Diag(OpRange.getBegin(), 2545 diag::warn_bad_cxx_cast_nested_pointer_addr_space) 2546 << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2547 break; 2548 } 2549 DestPtee = DestPtee->getPointeeType(); 2550 SrcPtee = SrcPtee->getPointeeType(); 2551 } 2552 2553 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 2554 // a pointer to an object of different type. 2555 // Void pointers are not specified, but supported by every compiler out there. 2556 // So we finish by allowing everything that remains - it's got to be two 2557 // object pointers. 2558 return SuccessResult; 2559 } 2560 2561 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, 2562 QualType DestType, bool CStyle, 2563 unsigned &msg, CastKind &Kind) { 2564 if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice) 2565 // FIXME: As compiler doesn't have any information about overlapping addr 2566 // spaces at the moment we have to be permissive here. 2567 return TC_NotApplicable; 2568 // Even though the logic below is general enough and can be applied to 2569 // non-OpenCL mode too, we fast-path above because no other languages 2570 // define overlapping address spaces currently. 2571 auto SrcType = SrcExpr.get()->getType(); 2572 // FIXME: Should this be generalized to references? The reference parameter 2573 // however becomes a reference pointee type here and therefore rejected. 2574 // Perhaps this is the right behavior though according to C++. 2575 auto SrcPtrType = SrcType->getAs<PointerType>(); 2576 if (!SrcPtrType) 2577 return TC_NotApplicable; 2578 auto DestPtrType = DestType->getAs<PointerType>(); 2579 if (!DestPtrType) 2580 return TC_NotApplicable; 2581 auto SrcPointeeType = SrcPtrType->getPointeeType(); 2582 auto DestPointeeType = DestPtrType->getPointeeType(); 2583 if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) { 2584 msg = diag::err_bad_cxx_cast_addr_space_mismatch; 2585 return TC_Failed; 2586 } 2587 auto SrcPointeeTypeWithoutAS = 2588 Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType()); 2589 auto DestPointeeTypeWithoutAS = 2590 Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType()); 2591 if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS, 2592 DestPointeeTypeWithoutAS)) { 2593 Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace() 2594 ? CK_NoOp 2595 : CK_AddressSpaceConversion; 2596 return TC_Success; 2597 } else { 2598 return TC_NotApplicable; 2599 } 2600 } 2601 2602 void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) { 2603 // In OpenCL only conversions between pointers to objects in overlapping 2604 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps 2605 // with any named one, except for constant. 2606 2607 // Converting the top level pointee addrspace is permitted for compatible 2608 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but 2609 // if any of the nested pointee addrspaces differ, we emit a warning 2610 // regardless of addrspace compatibility. This makes 2611 // local int ** p; 2612 // return (generic int **) p; 2613 // warn even though local -> generic is permitted. 2614 if (Self.getLangOpts().OpenCL) { 2615 const Type *DestPtr, *SrcPtr; 2616 bool Nested = false; 2617 unsigned DiagID = diag::err_typecheck_incompatible_address_space; 2618 DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()), 2619 SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr()); 2620 2621 while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) { 2622 const PointerType *DestPPtr = cast<PointerType>(DestPtr); 2623 const PointerType *SrcPPtr = cast<PointerType>(SrcPtr); 2624 QualType DestPPointee = DestPPtr->getPointeeType(); 2625 QualType SrcPPointee = SrcPPtr->getPointeeType(); 2626 if (Nested 2627 ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace() 2628 : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) { 2629 Self.Diag(OpRange.getBegin(), DiagID) 2630 << SrcType << DestType << Sema::AA_Casting 2631 << SrcExpr.get()->getSourceRange(); 2632 if (!Nested) 2633 SrcExpr = ExprError(); 2634 return; 2635 } 2636 2637 DestPtr = DestPPtr->getPointeeType().getTypePtr(); 2638 SrcPtr = SrcPPtr->getPointeeType().getTypePtr(); 2639 Nested = true; 2640 DiagID = diag::ext_nested_pointer_qualifier_mismatch; 2641 } 2642 } 2643 } 2644 2645 bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) { 2646 bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() == 2647 LangOptions::AltivecSrcCompatKind::XL; 2648 VectorType::VectorKind VKind = VecTy->getVectorKind(); 2649 2650 if ((VKind == VectorType::AltiVecVector) || 2651 (SrcCompatXL && ((VKind == VectorType::AltiVecBool) || 2652 (VKind == VectorType::AltiVecPixel)))) { 2653 return true; 2654 } 2655 return false; 2656 } 2657 2658 bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, 2659 QualType SrcTy) { 2660 bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() == 2661 LangOptions::AltivecSrcCompatKind::GCC; 2662 if (this->getLangOpts().AltiVec && SrcCompatGCC) { 2663 this->Diag(R.getBegin(), 2664 diag::err_invalid_conversion_between_vector_and_integer) 2665 << VecTy << SrcTy << R; 2666 return true; 2667 } 2668 return false; 2669 } 2670 2671 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, 2672 bool ListInitialization) { 2673 assert(Self.getLangOpts().CPlusPlus); 2674 2675 // Handle placeholders. 2676 if (isPlaceholder()) { 2677 // C-style casts can resolve __unknown_any types. 2678 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2679 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2680 SrcExpr.get(), Kind, 2681 ValueKind, BasePath); 2682 return; 2683 } 2684 2685 checkNonOverloadPlaceholders(); 2686 if (SrcExpr.isInvalid()) 2687 return; 2688 } 2689 2690 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 2691 // This test is outside everything else because it's the only case where 2692 // a non-lvalue-reference target type does not lead to decay. 2693 if (DestType->isVoidType()) { 2694 Kind = CK_ToVoid; 2695 2696 if (claimPlaceholder(BuiltinType::Overload)) { 2697 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2698 SrcExpr, /* Decay Function to ptr */ false, 2699 /* Complain */ true, DestRange, DestType, 2700 diag::err_bad_cstyle_cast_overload); 2701 if (SrcExpr.isInvalid()) 2702 return; 2703 } 2704 2705 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2706 return; 2707 } 2708 2709 // If the type is dependent, we won't do any other semantic analysis now. 2710 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || 2711 SrcExpr.get()->isValueDependent()) { 2712 assert(Kind == CK_Dependent); 2713 return; 2714 } 2715 2716 if (ValueKind == VK_PRValue && !DestType->isRecordType() && 2717 !isPlaceholder(BuiltinType::Overload)) { 2718 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2719 if (SrcExpr.isInvalid()) 2720 return; 2721 } 2722 2723 // AltiVec vector initialization with a single literal. 2724 if (const VectorType *vecTy = DestType->getAs<VectorType>()) { 2725 if (Self.CheckAltivecInitFromScalar(OpRange, DestType, 2726 SrcExpr.get()->getType())) { 2727 SrcExpr = ExprError(); 2728 return; 2729 } 2730 if (Self.ShouldSplatAltivecScalarInCast(vecTy) && 2731 (SrcExpr.get()->getType()->isIntegerType() || 2732 SrcExpr.get()->getType()->isFloatingType())) { 2733 Kind = CK_VectorSplat; 2734 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2735 return; 2736 } 2737 } 2738 2739 // C++ [expr.cast]p5: The conversions performed by 2740 // - a const_cast, 2741 // - a static_cast, 2742 // - a static_cast followed by a const_cast, 2743 // - a reinterpret_cast, or 2744 // - a reinterpret_cast followed by a const_cast, 2745 // can be performed using the cast notation of explicit type conversion. 2746 // [...] If a conversion can be interpreted in more than one of the ways 2747 // listed above, the interpretation that appears first in the list is used, 2748 // even if a cast resulting from that interpretation is ill-formed. 2749 // In plain language, this means trying a const_cast ... 2750 // Note that for address space we check compatibility after const_cast. 2751 unsigned msg = diag::err_bad_cxx_cast_generic; 2752 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, 2753 /*CStyle*/ true, msg); 2754 if (SrcExpr.isInvalid()) 2755 return; 2756 if (isValidCast(tcr)) 2757 Kind = CK_NoOp; 2758 2759 Sema::CheckedConversionKind CCK = 2760 FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast; 2761 if (tcr == TC_NotApplicable) { 2762 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg, 2763 Kind); 2764 if (SrcExpr.isInvalid()) 2765 return; 2766 2767 if (tcr == TC_NotApplicable) { 2768 // ... or if that is not possible, a static_cast, ignoring const and 2769 // addr space, ... 2770 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind, 2771 BasePath, ListInitialization); 2772 if (SrcExpr.isInvalid()) 2773 return; 2774 2775 if (tcr == TC_NotApplicable) { 2776 // ... and finally a reinterpret_cast, ignoring const and addr space. 2777 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true, 2778 OpRange, msg, Kind); 2779 if (SrcExpr.isInvalid()) 2780 return; 2781 } 2782 } 2783 } 2784 2785 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 2786 isValidCast(tcr)) 2787 checkObjCConversion(CCK); 2788 2789 if (tcr != TC_Success && msg != 0) { 2790 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2791 DeclAccessPair Found; 2792 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 2793 DestType, 2794 /*Complain*/ true, 2795 Found); 2796 if (Fn) { 2797 // If DestType is a function type (not to be confused with the function 2798 // pointer type), it will be possible to resolve the function address, 2799 // but the type cast should be considered as failure. 2800 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; 2801 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) 2802 << OE->getName() << DestType << OpRange 2803 << OE->getQualifierLoc().getSourceRange(); 2804 Self.NoteAllOverloadCandidates(SrcExpr.get()); 2805 } 2806 } else { 2807 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 2808 OpRange, SrcExpr.get(), DestType, ListInitialization); 2809 } 2810 } 2811 2812 if (isValidCast(tcr)) { 2813 if (Kind == CK_BitCast) 2814 checkCastAlign(); 2815 2816 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType)) 2817 Self.Diag(OpRange.getBegin(), DiagID) 2818 << SrcExpr.get()->getType() << DestType << OpRange; 2819 2820 } else { 2821 SrcExpr = ExprError(); 2822 } 2823 } 2824 2825 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a 2826 /// non-matching type. Such as enum function call to int, int call to 2827 /// pointer; etc. Cast to 'void' is an exception. 2828 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, 2829 QualType DestType) { 2830 if (Self.Diags.isIgnored(diag::warn_bad_function_cast, 2831 SrcExpr.get()->getExprLoc())) 2832 return; 2833 2834 if (!isa<CallExpr>(SrcExpr.get())) 2835 return; 2836 2837 QualType SrcType = SrcExpr.get()->getType(); 2838 if (DestType.getUnqualifiedType()->isVoidType()) 2839 return; 2840 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) 2841 && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) 2842 return; 2843 if (SrcType->isIntegerType() && DestType->isIntegerType() && 2844 (SrcType->isBooleanType() == DestType->isBooleanType()) && 2845 (SrcType->isEnumeralType() == DestType->isEnumeralType())) 2846 return; 2847 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) 2848 return; 2849 if (SrcType->isEnumeralType() && DestType->isEnumeralType()) 2850 return; 2851 if (SrcType->isComplexType() && DestType->isComplexType()) 2852 return; 2853 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) 2854 return; 2855 if (SrcType->isFixedPointType() && DestType->isFixedPointType()) 2856 return; 2857 2858 Self.Diag(SrcExpr.get()->getExprLoc(), 2859 diag::warn_bad_function_cast) 2860 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2861 } 2862 2863 /// Check the semantics of a C-style cast operation, in C. 2864 void CastOperation::CheckCStyleCast() { 2865 assert(!Self.getLangOpts().CPlusPlus); 2866 2867 // C-style casts can resolve __unknown_any types. 2868 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2869 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2870 SrcExpr.get(), Kind, 2871 ValueKind, BasePath); 2872 return; 2873 } 2874 2875 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2876 // type needs to be scalar. 2877 if (DestType->isVoidType()) { 2878 // We don't necessarily do lvalue-to-rvalue conversions on this. 2879 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2880 if (SrcExpr.isInvalid()) 2881 return; 2882 2883 // Cast to void allows any expr type. 2884 Kind = CK_ToVoid; 2885 return; 2886 } 2887 2888 // If the type is dependent, we won't do any other semantic analysis now. 2889 if (Self.getASTContext().isDependenceAllowed() && 2890 (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || 2891 SrcExpr.get()->isValueDependent())) { 2892 assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() || 2893 SrcExpr.get()->containsErrors()) && 2894 "should only occur in error-recovery path."); 2895 assert(Kind == CK_Dependent); 2896 return; 2897 } 2898 2899 // Overloads are allowed with C extensions, so we need to support them. 2900 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2901 DeclAccessPair DAP; 2902 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( 2903 SrcExpr.get(), DestType, /*Complain=*/true, DAP)) 2904 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); 2905 else 2906 return; 2907 assert(SrcExpr.isUsable()); 2908 } 2909 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2910 if (SrcExpr.isInvalid()) 2911 return; 2912 QualType SrcType = SrcExpr.get()->getType(); 2913 2914 assert(!SrcType->isPlaceholderType()); 2915 2916 checkAddressSpaceCast(SrcType, DestType); 2917 if (SrcExpr.isInvalid()) 2918 return; 2919 2920 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 2921 diag::err_typecheck_cast_to_incomplete)) { 2922 SrcExpr = ExprError(); 2923 return; 2924 } 2925 2926 // Allow casting a sizeless built-in type to itself. 2927 if (DestType->isSizelessBuiltinType() && 2928 Self.Context.hasSameUnqualifiedType(DestType, SrcType)) { 2929 Kind = CK_NoOp; 2930 return; 2931 } 2932 2933 // Allow bitcasting between compatible SVE vector types. 2934 if ((SrcType->isVectorType() || DestType->isVectorType()) && 2935 Self.isValidSveBitcast(SrcType, DestType)) { 2936 Kind = CK_BitCast; 2937 return; 2938 } 2939 2940 if (!DestType->isScalarType() && !DestType->isVectorType() && 2941 !DestType->isMatrixType()) { 2942 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 2943 2944 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 2945 // GCC struct/union extension: allow cast to self. 2946 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 2947 << DestType << SrcExpr.get()->getSourceRange(); 2948 Kind = CK_NoOp; 2949 return; 2950 } 2951 2952 // GCC's cast to union extension. 2953 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 2954 RecordDecl *RD = DestRecordTy->getDecl(); 2955 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) { 2956 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 2957 << SrcExpr.get()->getSourceRange(); 2958 Kind = CK_ToUnion; 2959 return; 2960 } else { 2961 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2962 << SrcType << SrcExpr.get()->getSourceRange(); 2963 SrcExpr = ExprError(); 2964 return; 2965 } 2966 } 2967 2968 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type. 2969 if (Self.getLangOpts().OpenCL && DestType->isEventT()) { 2970 Expr::EvalResult Result; 2971 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) { 2972 llvm::APSInt CastInt = Result.Val.getInt(); 2973 if (0 == CastInt) { 2974 Kind = CK_ZeroToOCLOpaqueType; 2975 return; 2976 } 2977 Self.Diag(OpRange.getBegin(), 2978 diag::err_opencl_cast_non_zero_to_event_t) 2979 << toString(CastInt, 10) << SrcExpr.get()->getSourceRange(); 2980 SrcExpr = ExprError(); 2981 return; 2982 } 2983 } 2984 2985 // Reject any other conversions to non-scalar types. 2986 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 2987 << DestType << SrcExpr.get()->getSourceRange(); 2988 SrcExpr = ExprError(); 2989 return; 2990 } 2991 2992 // The type we're casting to is known to be a scalar, a vector, or a matrix. 2993 2994 // Require the operand to be a scalar, a vector, or a matrix. 2995 if (!SrcType->isScalarType() && !SrcType->isVectorType() && 2996 !SrcType->isMatrixType()) { 2997 Self.Diag(SrcExpr.get()->getExprLoc(), 2998 diag::err_typecheck_expect_scalar_operand) 2999 << SrcType << SrcExpr.get()->getSourceRange(); 3000 SrcExpr = ExprError(); 3001 return; 3002 } 3003 3004 // C2x 6.5.4p4: 3005 // The type nullptr_t shall not be converted to any type other than void, 3006 // bool, or a pointer type. No type other than nullptr_t shall be converted 3007 // to nullptr_t. 3008 if (SrcType->isNullPtrType()) { 3009 // FIXME: 6.3.2.4p2 says that nullptr_t can be converted to itself, but 3010 // 6.5.4p4 is a constraint check and nullptr_t is not void, bool, or a 3011 // pointer type. We're not going to diagnose that as a constraint violation. 3012 if (!DestType->isVoidType() && !DestType->isBooleanType() && 3013 !DestType->isPointerType() && !DestType->isNullPtrType()) { 3014 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_nullptr_cast) 3015 << /*nullptr to type*/ 0 << DestType; 3016 SrcExpr = ExprError(); 3017 return; 3018 } 3019 if (!DestType->isNullPtrType()) { 3020 // Implicitly cast from the null pointer type to the type of the 3021 // destination. 3022 CastKind CK = DestType->isPointerType() ? CK_NullToPointer : CK_BitCast; 3023 SrcExpr = ImplicitCastExpr::Create(Self.Context, DestType, CK, 3024 SrcExpr.get(), nullptr, VK_PRValue, 3025 Self.CurFPFeatureOverrides()); 3026 } 3027 } 3028 if (DestType->isNullPtrType() && !SrcType->isNullPtrType()) { 3029 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_nullptr_cast) 3030 << /*type to nullptr*/ 1 << SrcType; 3031 SrcExpr = ExprError(); 3032 return; 3033 } 3034 3035 if (DestType->isExtVectorType()) { 3036 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); 3037 return; 3038 } 3039 3040 if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) { 3041 if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) 3042 SrcExpr = ExprError(); 3043 return; 3044 } 3045 3046 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 3047 if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) { 3048 SrcExpr = ExprError(); 3049 return; 3050 } 3051 if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) && 3052 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 3053 Kind = CK_VectorSplat; 3054 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 3055 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 3056 SrcExpr = ExprError(); 3057 } 3058 return; 3059 } 3060 3061 if (SrcType->isVectorType()) { 3062 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 3063 SrcExpr = ExprError(); 3064 return; 3065 } 3066 3067 // The source and target types are both scalars, i.e. 3068 // - arithmetic types (fundamental, enum, and complex) 3069 // - all kinds of pointers 3070 // Note that member pointers were filtered out with C++, above. 3071 3072 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 3073 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 3074 SrcExpr = ExprError(); 3075 return; 3076 } 3077 3078 // Can't cast to or from bfloat 3079 if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) { 3080 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16) 3081 << SrcExpr.get()->getSourceRange(); 3082 SrcExpr = ExprError(); 3083 return; 3084 } 3085 if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) { 3086 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16) 3087 << SrcExpr.get()->getSourceRange(); 3088 SrcExpr = ExprError(); 3089 return; 3090 } 3091 3092 // If either type is a pointer, the other type has to be either an 3093 // integer or a pointer. 3094 if (!DestType->isArithmeticType()) { 3095 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 3096 Self.Diag(SrcExpr.get()->getExprLoc(), 3097 diag::err_cast_pointer_from_non_pointer_int) 3098 << SrcType << SrcExpr.get()->getSourceRange(); 3099 SrcExpr = ExprError(); 3100 return; 3101 } 3102 checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType, 3103 Self); 3104 } else if (!SrcType->isArithmeticType()) { 3105 if (!DestType->isIntegralType(Self.Context) && 3106 DestType->isArithmeticType()) { 3107 Self.Diag(SrcExpr.get()->getBeginLoc(), 3108 diag::err_cast_pointer_to_non_pointer_int) 3109 << DestType << SrcExpr.get()->getSourceRange(); 3110 SrcExpr = ExprError(); 3111 return; 3112 } 3113 3114 if ((Self.Context.getTypeSize(SrcType) > 3115 Self.Context.getTypeSize(DestType)) && 3116 !DestType->isBooleanType()) { 3117 // C 6.3.2.3p6: Any pointer type may be converted to an integer type. 3118 // Except as previously specified, the result is implementation-defined. 3119 // If the result cannot be represented in the integer type, the behavior 3120 // is undefined. The result need not be in the range of values of any 3121 // integer type. 3122 unsigned Diag; 3123 if (SrcType->isVoidPointerType()) 3124 Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast 3125 : diag::warn_void_pointer_to_int_cast; 3126 else if (DestType->isEnumeralType()) 3127 Diag = diag::warn_pointer_to_enum_cast; 3128 else 3129 Diag = diag::warn_pointer_to_int_cast; 3130 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; 3131 } 3132 } 3133 3134 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption( 3135 "cl_khr_fp16", Self.getLangOpts())) { 3136 if (DestType->isHalfType()) { 3137 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half) 3138 << DestType << SrcExpr.get()->getSourceRange(); 3139 SrcExpr = ExprError(); 3140 return; 3141 } 3142 } 3143 3144 // ARC imposes extra restrictions on casts. 3145 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) { 3146 checkObjCConversion(Sema::CCK_CStyleCast); 3147 if (SrcExpr.isInvalid()) 3148 return; 3149 3150 const PointerType *CastPtr = DestType->getAs<PointerType>(); 3151 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) { 3152 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 3153 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 3154 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 3155 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 3156 ExprPtr->getPointeeType()->isObjCLifetimeType() && 3157 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 3158 Self.Diag(SrcExpr.get()->getBeginLoc(), 3159 diag::err_typecheck_incompatible_ownership) 3160 << SrcType << DestType << Sema::AA_Casting 3161 << SrcExpr.get()->getSourceRange(); 3162 return; 3163 } 3164 } 3165 } 3166 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 3167 Self.Diag(SrcExpr.get()->getBeginLoc(), 3168 diag::err_arc_convesion_of_weak_unavailable) 3169 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 3170 SrcExpr = ExprError(); 3171 return; 3172 } 3173 } 3174 3175 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType)) 3176 Self.Diag(OpRange.getBegin(), DiagID) << SrcType << DestType << OpRange; 3177 3178 if (isa<PointerType>(SrcType) && isa<PointerType>(DestType)) { 3179 QualType SrcTy = cast<PointerType>(SrcType)->getPointeeType(); 3180 QualType DestTy = cast<PointerType>(DestType)->getPointeeType(); 3181 3182 const RecordDecl *SrcRD = SrcTy->getAsRecordDecl(); 3183 const RecordDecl *DestRD = DestTy->getAsRecordDecl(); 3184 3185 if (SrcRD && DestRD && SrcRD->hasAttr<RandomizeLayoutAttr>() && 3186 SrcRD != DestRD) { 3187 // The struct we are casting the pointer from was randomized. 3188 Self.Diag(OpRange.getBegin(), diag::err_cast_from_randomized_struct) 3189 << SrcType << DestType; 3190 SrcExpr = ExprError(); 3191 return; 3192 } 3193 } 3194 3195 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 3196 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); 3197 DiagnoseBadFunctionCast(Self, SrcExpr, DestType); 3198 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 3199 if (SrcExpr.isInvalid()) 3200 return; 3201 3202 if (Kind == CK_BitCast) 3203 checkCastAlign(); 3204 } 3205 3206 void CastOperation::CheckBuiltinBitCast() { 3207 QualType SrcType = SrcExpr.get()->getType(); 3208 3209 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 3210 diag::err_typecheck_cast_to_incomplete) || 3211 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 3212 diag::err_incomplete_type)) { 3213 SrcExpr = ExprError(); 3214 return; 3215 } 3216 3217 if (SrcExpr.get()->isPRValue()) 3218 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(), 3219 /*IsLValueReference=*/false); 3220 3221 CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType); 3222 CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType); 3223 if (DestSize != SourceSize) { 3224 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch) 3225 << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity(); 3226 SrcExpr = ExprError(); 3227 return; 3228 } 3229 3230 if (!DestType.isTriviallyCopyableType(Self.Context)) { 3231 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) 3232 << 1; 3233 SrcExpr = ExprError(); 3234 return; 3235 } 3236 3237 if (!SrcType.isTriviallyCopyableType(Self.Context)) { 3238 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) 3239 << 0; 3240 SrcExpr = ExprError(); 3241 return; 3242 } 3243 3244 Kind = CK_LValueToRValueBitCast; 3245 } 3246 3247 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either 3248 /// const, volatile or both. 3249 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, 3250 QualType DestType) { 3251 if (SrcExpr.isInvalid()) 3252 return; 3253 3254 QualType SrcType = SrcExpr.get()->getType(); 3255 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) || 3256 DestType->isLValueReferenceType())) 3257 return; 3258 3259 QualType TheOffendingSrcType, TheOffendingDestType; 3260 Qualifiers CastAwayQualifiers; 3261 if (CastsAwayConstness(Self, SrcType, DestType, true, false, 3262 &TheOffendingSrcType, &TheOffendingDestType, 3263 &CastAwayQualifiers) != 3264 CastAwayConstnessKind::CACK_Similar) 3265 return; 3266 3267 // FIXME: 'restrict' is not properly handled here. 3268 int qualifiers = -1; 3269 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { 3270 qualifiers = 0; 3271 } else if (CastAwayQualifiers.hasConst()) { 3272 qualifiers = 1; 3273 } else if (CastAwayQualifiers.hasVolatile()) { 3274 qualifiers = 2; 3275 } 3276 // This is a variant of int **x; const int **y = (const int **)x; 3277 if (qualifiers == -1) 3278 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2) 3279 << SrcType << DestType; 3280 else 3281 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual) 3282 << TheOffendingSrcType << TheOffendingDestType << qualifiers; 3283 } 3284 3285 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 3286 TypeSourceInfo *CastTypeInfo, 3287 SourceLocation RPLoc, 3288 Expr *CastExpr) { 3289 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 3290 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 3291 Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc()); 3292 3293 if (getLangOpts().CPlusPlus) { 3294 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false, 3295 isa<InitListExpr>(CastExpr)); 3296 } else { 3297 Op.CheckCStyleCast(); 3298 } 3299 3300 if (Op.SrcExpr.isInvalid()) 3301 return ExprError(); 3302 3303 // -Wcast-qual 3304 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType); 3305 3306 return Op.complete(CStyleCastExpr::Create( 3307 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 3308 &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc)); 3309 } 3310 3311 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 3312 QualType Type, 3313 SourceLocation LPLoc, 3314 Expr *CastExpr, 3315 SourceLocation RPLoc) { 3316 assert(LPLoc.isValid() && "List-initialization shouldn't get here."); 3317 CastOperation Op(*this, Type, CastExpr); 3318 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 3319 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc()); 3320 3321 Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false); 3322 if (Op.SrcExpr.isInvalid()) 3323 return ExprError(); 3324 3325 auto *SubExpr = Op.SrcExpr.get(); 3326 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 3327 SubExpr = BindExpr->getSubExpr(); 3328 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) 3329 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); 3330 3331 return Op.complete(CXXFunctionalCastExpr::Create( 3332 Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind, 3333 Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc)); 3334 } 3335