clang API Documentation
00001 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for cast expressions, including 00011 // 1) C-style casts like '(int) x' 00012 // 2) C++ functional casts like 'int(x)' 00013 // 3) C++ named casts like 'static_cast<int>(x)' 00014 // 00015 //===----------------------------------------------------------------------===// 00016 00017 #include "clang/Sema/SemaInternal.h" 00018 #include "clang/Sema/Initialization.h" 00019 #include "clang/AST/ExprCXX.h" 00020 #include "clang/AST/ExprObjC.h" 00021 #include "clang/AST/ASTContext.h" 00022 #include "clang/AST/CXXInheritance.h" 00023 #include "clang/Basic/PartialDiagnostic.h" 00024 #include "llvm/ADT/SmallVector.h" 00025 #include <set> 00026 using namespace clang; 00027 00028 00029 00030 enum TryCastResult { 00031 TC_NotApplicable, ///< The cast method is not applicable. 00032 TC_Success, ///< The cast method is appropriate and successful. 00033 TC_Failed ///< The cast method is appropriate, but failed. A 00034 ///< diagnostic has been emitted. 00035 }; 00036 00037 enum CastType { 00038 CT_Const, ///< const_cast 00039 CT_Static, ///< static_cast 00040 CT_Reinterpret, ///< reinterpret_cast 00041 CT_Dynamic, ///< dynamic_cast 00042 CT_CStyle, ///< (Type)expr 00043 CT_Functional ///< Type(expr) 00044 }; 00045 00046 namespace { 00047 struct CastOperation { 00048 CastOperation(Sema &S, QualType destType, ExprResult src) 00049 : Self(S), SrcExpr(src), DestType(destType), 00050 ResultType(destType.getNonLValueExprType(S.Context)), 00051 ValueKind(Expr::getValueKindForType(destType)), 00052 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 00053 00054 if (const BuiltinType *placeholder = 00055 src.get()->getType()->getAsPlaceholderType()) { 00056 PlaceholderKind = placeholder->getKind(); 00057 } else { 00058 PlaceholderKind = (BuiltinType::Kind) 0; 00059 } 00060 } 00061 00062 Sema &Self; 00063 ExprResult SrcExpr; 00064 QualType DestType; 00065 QualType ResultType; 00066 ExprValueKind ValueKind; 00067 CastKind Kind; 00068 BuiltinType::Kind PlaceholderKind; 00069 CXXCastPath BasePath; 00070 bool IsARCUnbridgedCast; 00071 00072 SourceRange OpRange; 00073 SourceRange DestRange; 00074 00075 // Top-level semantics-checking routines. 00076 void CheckConstCast(); 00077 void CheckReinterpretCast(); 00078 void CheckStaticCast(); 00079 void CheckDynamicCast(); 00080 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); 00081 void CheckCStyleCast(); 00082 00083 /// Complete an apparently-successful cast operation that yields 00084 /// the given expression. 00085 ExprResult complete(CastExpr *castExpr) { 00086 // If this is an unbridged cast, wrap the result in an implicit 00087 // cast that yields the unbridged-cast placeholder type. 00088 if (IsARCUnbridgedCast) { 00089 castExpr = ImplicitCastExpr::Create(Self.Context, 00090 Self.Context.ARCUnbridgedCastTy, 00091 CK_Dependent, castExpr, 0, 00092 castExpr->getValueKind()); 00093 } 00094 return Self.Owned(castExpr); 00095 } 00096 00097 // Internal convenience methods. 00098 00099 /// Try to handle the given placeholder expression kind. Return 00100 /// true if the source expression has the appropriate placeholder 00101 /// kind. A placeholder can only be claimed once. 00102 bool claimPlaceholder(BuiltinType::Kind K) { 00103 if (PlaceholderKind != K) return false; 00104 00105 PlaceholderKind = (BuiltinType::Kind) 0; 00106 return true; 00107 } 00108 00109 bool isPlaceholder() const { 00110 return PlaceholderKind != 0; 00111 } 00112 bool isPlaceholder(BuiltinType::Kind K) const { 00113 return PlaceholderKind == K; 00114 } 00115 00116 void checkCastAlign() { 00117 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 00118 } 00119 00120 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) { 00121 assert(Self.getLangOpts().ObjCAutoRefCount); 00122 00123 Expr *src = SrcExpr.get(); 00124 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) == 00125 Sema::ACR_unbridged) 00126 IsARCUnbridgedCast = true; 00127 SrcExpr = src; 00128 } 00129 00130 /// Check for and handle non-overload placeholder expressions. 00131 void checkNonOverloadPlaceholders() { 00132 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 00133 return; 00134 00135 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 00136 if (SrcExpr.isInvalid()) 00137 return; 00138 PlaceholderKind = (BuiltinType::Kind) 0; 00139 } 00140 }; 00141 } 00142 00143 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 00144 bool CheckCVR, bool CheckObjCLifetime); 00145 00146 // The Try functions attempt a specific way of casting. If they succeed, they 00147 // return TC_Success. If their way of casting is not appropriate for the given 00148 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 00149 // to emit if no other way succeeds. If their way of casting is appropriate but 00150 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if 00151 // they emit a specialized diagnostic. 00152 // All diagnostics returned by these functions must expect the same three 00153 // arguments: 00154 // %0: Cast Type (a value from the CastType enumeration) 00155 // %1: Source Type 00156 // %2: Destination Type 00157 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 00158 QualType DestType, bool CStyle, 00159 CastKind &Kind, 00160 CXXCastPath &BasePath, 00161 unsigned &msg); 00162 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 00163 QualType DestType, bool CStyle, 00164 const SourceRange &OpRange, 00165 unsigned &msg, 00166 CastKind &Kind, 00167 CXXCastPath &BasePath); 00168 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 00169 QualType DestType, bool CStyle, 00170 const SourceRange &OpRange, 00171 unsigned &msg, 00172 CastKind &Kind, 00173 CXXCastPath &BasePath); 00174 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 00175 CanQualType DestType, bool CStyle, 00176 const SourceRange &OpRange, 00177 QualType OrigSrcType, 00178 QualType OrigDestType, unsigned &msg, 00179 CastKind &Kind, 00180 CXXCastPath &BasePath); 00181 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 00182 QualType SrcType, 00183 QualType DestType,bool CStyle, 00184 const SourceRange &OpRange, 00185 unsigned &msg, 00186 CastKind &Kind, 00187 CXXCastPath &BasePath); 00188 00189 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 00190 QualType DestType, 00191 Sema::CheckedConversionKind CCK, 00192 const SourceRange &OpRange, 00193 unsigned &msg, CastKind &Kind, 00194 bool ListInitialization); 00195 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 00196 QualType DestType, 00197 Sema::CheckedConversionKind CCK, 00198 const SourceRange &OpRange, 00199 unsigned &msg, CastKind &Kind, 00200 CXXCastPath &BasePath, 00201 bool ListInitialization); 00202 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 00203 bool CStyle, unsigned &msg); 00204 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 00205 QualType DestType, bool CStyle, 00206 const SourceRange &OpRange, 00207 unsigned &msg, 00208 CastKind &Kind); 00209 00210 00211 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 00212 ExprResult 00213 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 00214 SourceLocation LAngleBracketLoc, Declarator &D, 00215 SourceLocation RAngleBracketLoc, 00216 SourceLocation LParenLoc, Expr *E, 00217 SourceLocation RParenLoc) { 00218 00219 assert(!D.isInvalidType()); 00220 00221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); 00222 if (D.isInvalidType()) 00223 return ExprError(); 00224 00225 if (getLangOpts().CPlusPlus) { 00226 // Check that there are no default arguments (C++ only). 00227 CheckExtraCXXDefaultArguments(D); 00228 } 00229 00230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E), 00231 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 00232 SourceRange(LParenLoc, RParenLoc)); 00233 } 00234 00235 ExprResult 00236 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 00237 TypeSourceInfo *DestTInfo, Expr *E, 00238 SourceRange AngleBrackets, SourceRange Parens) { 00239 ExprResult Ex = Owned(E); 00240 QualType DestType = DestTInfo->getType(); 00241 00242 // If the type is dependent, we won't do the semantic analysis now. 00243 // FIXME: should we check this in a more fine-grained manner? 00244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent(); 00245 00246 CastOperation Op(*this, DestType, E); 00247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 00248 Op.DestRange = AngleBrackets; 00249 00250 switch (Kind) { 00251 default: llvm_unreachable("Unknown C++ cast!"); 00252 00253 case tok::kw_const_cast: 00254 if (!TypeDependent) { 00255 Op.CheckConstCast(); 00256 if (Op.SrcExpr.isInvalid()) 00257 return ExprError(); 00258 } 00259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, 00260 Op.ValueKind, Op.SrcExpr.take(), DestTInfo, 00261 OpLoc, Parens.getEnd())); 00262 00263 case tok::kw_dynamic_cast: { 00264 if (!TypeDependent) { 00265 Op.CheckDynamicCast(); 00266 if (Op.SrcExpr.isInvalid()) 00267 return ExprError(); 00268 } 00269 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 00270 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 00271 &Op.BasePath, DestTInfo, 00272 OpLoc, Parens.getEnd())); 00273 } 00274 case tok::kw_reinterpret_cast: { 00275 if (!TypeDependent) { 00276 Op.CheckReinterpretCast(); 00277 if (Op.SrcExpr.isInvalid()) 00278 return ExprError(); 00279 } 00280 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 00281 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 00282 0, DestTInfo, OpLoc, 00283 Parens.getEnd())); 00284 } 00285 case tok::kw_static_cast: { 00286 if (!TypeDependent) { 00287 Op.CheckStaticCast(); 00288 if (Op.SrcExpr.isInvalid()) 00289 return ExprError(); 00290 } 00291 00292 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, 00293 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 00294 &Op.BasePath, DestTInfo, 00295 OpLoc, Parens.getEnd())); 00296 } 00297 } 00298 } 00299 00300 /// Try to diagnose a failed overloaded cast. Returns true if 00301 /// diagnostics were emitted. 00302 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 00303 SourceRange range, Expr *src, 00304 QualType destType, 00305 bool listInitialization) { 00306 switch (CT) { 00307 // These cast kinds don't consider user-defined conversions. 00308 case CT_Const: 00309 case CT_Reinterpret: 00310 case CT_Dynamic: 00311 return false; 00312 00313 // These do. 00314 case CT_Static: 00315 case CT_CStyle: 00316 case CT_Functional: 00317 break; 00318 } 00319 00320 QualType srcType = src->getType(); 00321 if (!destType->isRecordType() && !srcType->isRecordType()) 00322 return false; 00323 00324 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 00325 InitializationKind initKind 00326 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 00327 range, listInitialization) 00328 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, 00329 listInitialization) 00330 : InitializationKind::CreateCast(/*type range?*/ range); 00331 InitializationSequence sequence(S, entity, initKind, &src, 1); 00332 00333 assert(sequence.Failed() && "initialization succeeded on second try?"); 00334 switch (sequence.getFailureKind()) { 00335 default: return false; 00336 00337 case InitializationSequence::FK_ConstructorOverloadFailed: 00338 case InitializationSequence::FK_UserConversionOverloadFailed: 00339 break; 00340 } 00341 00342 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 00343 00344 unsigned msg = 0; 00345 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 00346 00347 switch (sequence.getFailedOverloadResult()) { 00348 case OR_Success: llvm_unreachable("successful failed overload"); 00349 case OR_No_Viable_Function: 00350 if (candidates.empty()) 00351 msg = diag::err_ovl_no_conversion_in_cast; 00352 else 00353 msg = diag::err_ovl_no_viable_conversion_in_cast; 00354 howManyCandidates = OCD_AllCandidates; 00355 break; 00356 00357 case OR_Ambiguous: 00358 msg = diag::err_ovl_ambiguous_conversion_in_cast; 00359 howManyCandidates = OCD_ViableCandidates; 00360 break; 00361 00362 case OR_Deleted: 00363 msg = diag::err_ovl_deleted_conversion_in_cast; 00364 howManyCandidates = OCD_ViableCandidates; 00365 break; 00366 } 00367 00368 S.Diag(range.getBegin(), msg) 00369 << CT << srcType << destType 00370 << range << src->getSourceRange(); 00371 00372 candidates.NoteCandidates(S, howManyCandidates, src); 00373 00374 return true; 00375 } 00376 00377 /// Diagnose a failed cast. 00378 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 00379 SourceRange opRange, Expr *src, QualType destType, 00380 bool listInitialization) { 00381 if (src->getType() == S.Context.BoundMemberTy) { 00382 (void) S.CheckPlaceholderExpr(src); // will always fail 00383 return; 00384 } 00385 00386 if (msg == diag::err_bad_cxx_cast_generic && 00387 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, 00388 listInitialization)) 00389 return; 00390 00391 S.Diag(opRange.getBegin(), msg) << castType 00392 << src->getType() << destType << opRange << src->getSourceRange(); 00393 } 00394 00395 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes, 00396 /// this removes one level of indirection from both types, provided that they're 00397 /// the same kind of pointer (plain or to-member). Unlike the Sema function, 00398 /// this one doesn't care if the two pointers-to-member don't point into the 00399 /// same class. This is because CastsAwayConstness doesn't care. 00400 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) { 00401 const PointerType *T1PtrType = T1->getAs<PointerType>(), 00402 *T2PtrType = T2->getAs<PointerType>(); 00403 if (T1PtrType && T2PtrType) { 00404 T1 = T1PtrType->getPointeeType(); 00405 T2 = T2PtrType->getPointeeType(); 00406 return true; 00407 } 00408 const ObjCObjectPointerType *T1ObjCPtrType = 00409 T1->getAs<ObjCObjectPointerType>(), 00410 *T2ObjCPtrType = 00411 T2->getAs<ObjCObjectPointerType>(); 00412 if (T1ObjCPtrType) { 00413 if (T2ObjCPtrType) { 00414 T1 = T1ObjCPtrType->getPointeeType(); 00415 T2 = T2ObjCPtrType->getPointeeType(); 00416 return true; 00417 } 00418 else if (T2PtrType) { 00419 T1 = T1ObjCPtrType->getPointeeType(); 00420 T2 = T2PtrType->getPointeeType(); 00421 return true; 00422 } 00423 } 00424 else if (T2ObjCPtrType) { 00425 if (T1PtrType) { 00426 T2 = T2ObjCPtrType->getPointeeType(); 00427 T1 = T1PtrType->getPointeeType(); 00428 return true; 00429 } 00430 } 00431 00432 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 00433 *T2MPType = T2->getAs<MemberPointerType>(); 00434 if (T1MPType && T2MPType) { 00435 T1 = T1MPType->getPointeeType(); 00436 T2 = T2MPType->getPointeeType(); 00437 return true; 00438 } 00439 00440 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(), 00441 *T2BPType = T2->getAs<BlockPointerType>(); 00442 if (T1BPType && T2BPType) { 00443 T1 = T1BPType->getPointeeType(); 00444 T2 = T2BPType->getPointeeType(); 00445 return true; 00446 } 00447 00448 return false; 00449 } 00450 00451 /// CastsAwayConstness - Check if the pointer conversion from SrcType to 00452 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by 00453 /// the cast checkers. Both arguments must denote pointer (possibly to member) 00454 /// types. 00455 /// 00456 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 00457 /// 00458 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 00459 static bool 00460 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 00461 bool CheckCVR, bool CheckObjCLifetime) { 00462 // If the only checking we care about is for Objective-C lifetime qualifiers, 00463 // and we're not in ARC mode, there's nothing to check. 00464 if (!CheckCVR && CheckObjCLifetime && 00465 !Self.Context.getLangOpts().ObjCAutoRefCount) 00466 return false; 00467 00468 // Casting away constness is defined in C++ 5.2.11p8 with reference to 00469 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since 00470 // the rules are non-trivial. So first we construct Tcv *...cv* as described 00471 // in C++ 5.2.11p8. 00472 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 00473 SrcType->isBlockPointerType()) && 00474 "Source type is not pointer or pointer to member."); 00475 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 00476 DestType->isBlockPointerType()) && 00477 "Destination type is not pointer or pointer to member."); 00478 00479 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 00480 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 00481 SmallVector<Qualifiers, 8> cv1, cv2; 00482 00483 // Find the qualifiers. We only care about cvr-qualifiers for the 00484 // purpose of this check, because other qualifiers (address spaces, 00485 // Objective-C GC, etc.) are part of the type's identity. 00486 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 00487 // Determine the relevant qualifiers at this level. 00488 Qualifiers SrcQuals, DestQuals; 00489 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 00490 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 00491 00492 Qualifiers RetainedSrcQuals, RetainedDestQuals; 00493 if (CheckCVR) { 00494 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers()); 00495 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers()); 00496 } 00497 00498 if (CheckObjCLifetime && 00499 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 00500 return true; 00501 00502 cv1.push_back(RetainedSrcQuals); 00503 cv2.push_back(RetainedDestQuals); 00504 } 00505 if (cv1.empty()) 00506 return false; 00507 00508 // Construct void pointers with those qualifiers (in reverse order of 00509 // unwrapping, of course). 00510 QualType SrcConstruct = Self.Context.VoidTy; 00511 QualType DestConstruct = Self.Context.VoidTy; 00512 ASTContext &Context = Self.Context; 00513 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(), 00514 i2 = cv2.rbegin(); 00515 i1 != cv1.rend(); ++i1, ++i2) { 00516 SrcConstruct 00517 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1)); 00518 DestConstruct 00519 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2)); 00520 } 00521 00522 // Test if they're compatible. 00523 bool ObjCLifetimeConversion; 00524 return SrcConstruct != DestConstruct && 00525 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false, 00526 ObjCLifetimeConversion); 00527 } 00528 00529 /// CheckDynamicCast - Check that a dynamic_cast<DestType>(SrcExpr) is valid. 00530 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 00531 /// checked downcasts in class hierarchies. 00532 void CastOperation::CheckDynamicCast() { 00533 if (ValueKind == VK_RValue) 00534 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00535 else if (isPlaceholder()) 00536 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 00537 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00538 return; 00539 00540 QualType OrigSrcType = SrcExpr.get()->getType(); 00541 QualType DestType = Self.Context.getCanonicalType(this->DestType); 00542 00543 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 00544 // or "pointer to cv void". 00545 00546 QualType DestPointee; 00547 const PointerType *DestPointer = DestType->getAs<PointerType>(); 00548 const ReferenceType *DestReference = 0; 00549 if (DestPointer) { 00550 DestPointee = DestPointer->getPointeeType(); 00551 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 00552 DestPointee = DestReference->getPointeeType(); 00553 } else { 00554 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 00555 << this->DestType << DestRange; 00556 return; 00557 } 00558 00559 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 00560 if (DestPointee->isVoidType()) { 00561 assert(DestPointer && "Reference to void is not possible"); 00562 } else if (DestRecord) { 00563 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 00564 diag::err_bad_dynamic_cast_incomplete, 00565 DestRange)) 00566 return; 00567 } else { 00568 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 00569 << DestPointee.getUnqualifiedType() << DestRange; 00570 return; 00571 } 00572 00573 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 00574 // complete class type, [...]. If T is an lvalue reference type, v shall be 00575 // an lvalue of a complete class type, [...]. If T is an rvalue reference 00576 // type, v shall be an expression having a complete class type, [...] 00577 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 00578 QualType SrcPointee; 00579 if (DestPointer) { 00580 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 00581 SrcPointee = SrcPointer->getPointeeType(); 00582 } else { 00583 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 00584 << OrigSrcType << SrcExpr.get()->getSourceRange(); 00585 return; 00586 } 00587 } else if (DestReference->isLValueReferenceType()) { 00588 if (!SrcExpr.get()->isLValue()) { 00589 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 00590 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 00591 } 00592 SrcPointee = SrcType; 00593 } else { 00594 SrcPointee = SrcType; 00595 } 00596 00597 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 00598 if (SrcRecord) { 00599 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 00600 diag::err_bad_dynamic_cast_incomplete, 00601 SrcExpr.get())) 00602 return; 00603 } else { 00604 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 00605 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 00606 return; 00607 } 00608 00609 assert((DestPointer || DestReference) && 00610 "Bad destination non-ptr/ref slipped through."); 00611 assert((DestRecord || DestPointee->isVoidType()) && 00612 "Bad destination pointee slipped through."); 00613 assert(SrcRecord && "Bad source pointee slipped through."); 00614 00615 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 00616 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 00617 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 00618 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 00619 return; 00620 } 00621 00622 // C++ 5.2.7p3: If the type of v is the same as the required result type, 00623 // [except for cv]. 00624 if (DestRecord == SrcRecord) { 00625 Kind = CK_NoOp; 00626 return; 00627 } 00628 00629 // C++ 5.2.7p5 00630 // Upcasts are resolved statically. 00631 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) { 00632 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 00633 OpRange.getBegin(), OpRange, 00634 &BasePath)) 00635 return; 00636 00637 Kind = CK_DerivedToBase; 00638 00639 // If we are casting to or through a virtual base class, we need a 00640 // vtable. 00641 if (Self.BasePathInvolvesVirtualBase(BasePath)) 00642 Self.MarkVTableUsed(OpRange.getBegin(), 00643 cast<CXXRecordDecl>(SrcRecord->getDecl())); 00644 return; 00645 } 00646 00647 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 00648 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 00649 assert(SrcDecl && "Definition missing"); 00650 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 00651 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 00652 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 00653 } 00654 Self.MarkVTableUsed(OpRange.getBegin(), 00655 cast<CXXRecordDecl>(SrcRecord->getDecl())); 00656 00657 // Done. Everything else is run-time checks. 00658 Kind = CK_Dynamic; 00659 } 00660 00661 /// CheckConstCast - Check that a const_cast<DestType>(SrcExpr) is valid. 00662 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code 00663 /// like this: 00664 /// const char *str = "literal"; 00665 /// legacy_function(const_cast<char*>(str)); 00666 void CastOperation::CheckConstCast() { 00667 if (ValueKind == VK_RValue) 00668 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00669 else if (isPlaceholder()) 00670 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 00671 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00672 return; 00673 00674 unsigned msg = diag::err_bad_cxx_cast_generic; 00675 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success 00676 && msg != 0) 00677 Self.Diag(OpRange.getBegin(), msg) << CT_Const 00678 << SrcExpr.get()->getType() << DestType << OpRange; 00679 } 00680 00681 /// CheckReinterpretCast - Check that a reinterpret_cast<DestType>(SrcExpr) is 00682 /// valid. 00683 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 00684 /// like this: 00685 /// char *bytes = reinterpret_cast<char*>(int_ptr); 00686 void CastOperation::CheckReinterpretCast() { 00687 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) 00688 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00689 else 00690 checkNonOverloadPlaceholders(); 00691 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00692 return; 00693 00694 unsigned msg = diag::err_bad_cxx_cast_generic; 00695 TryCastResult tcr = 00696 TryReinterpretCast(Self, SrcExpr, DestType, 00697 /*CStyle*/false, OpRange, msg, Kind); 00698 if (tcr != TC_Success && msg != 0) 00699 { 00700 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00701 return; 00702 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 00703 //FIXME: &f<int>; is overloaded and resolvable 00704 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 00705 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 00706 << DestType << OpRange; 00707 Self.NoteAllOverloadCandidates(SrcExpr.get()); 00708 00709 } else { 00710 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), 00711 DestType, /*listInitialization=*/false); 00712 } 00713 } else if (tcr == TC_Success && Self.getLangOpts().ObjCAutoRefCount) { 00714 checkObjCARCConversion(Sema::CCK_OtherCast); 00715 } 00716 } 00717 00718 00719 /// CheckStaticCast - Check that a static_cast<DestType>(SrcExpr) is valid. 00720 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 00721 /// implicit conversions explicit and getting rid of data loss warnings. 00722 void CastOperation::CheckStaticCast() { 00723 if (isPlaceholder()) { 00724 checkNonOverloadPlaceholders(); 00725 if (SrcExpr.isInvalid()) 00726 return; 00727 } 00728 00729 // This test is outside everything else because it's the only case where 00730 // a non-lvalue-reference target type does not lead to decay. 00731 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 00732 if (DestType->isVoidType()) { 00733 Kind = CK_ToVoid; 00734 00735 if (claimPlaceholder(BuiltinType::Overload)) { 00736 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 00737 false, // Decay Function to ptr 00738 true, // Complain 00739 OpRange, DestType, diag::err_bad_static_cast_overload); 00740 if (SrcExpr.isInvalid()) 00741 return; 00742 } 00743 00744 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 00745 return; 00746 } 00747 00748 if (ValueKind == VK_RValue && !DestType->isRecordType() && 00749 !isPlaceholder(BuiltinType::Overload)) { 00750 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00751 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00752 return; 00753 } 00754 00755 unsigned msg = diag::err_bad_cxx_cast_generic; 00756 TryCastResult tcr 00757 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 00758 Kind, BasePath, /*ListInitialization=*/false); 00759 if (tcr != TC_Success && msg != 0) { 00760 if (SrcExpr.isInvalid()) 00761 return; 00762 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 00763 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 00764 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 00765 << oe->getName() << DestType << OpRange 00766 << oe->getQualifierLoc().getSourceRange(); 00767 Self.NoteAllOverloadCandidates(SrcExpr.get()); 00768 } else { 00769 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, 00770 /*listInitialization=*/false); 00771 } 00772 } else if (tcr == TC_Success) { 00773 if (Kind == CK_BitCast) 00774 checkCastAlign(); 00775 if (Self.getLangOpts().ObjCAutoRefCount) 00776 checkObjCARCConversion(Sema::CCK_OtherCast); 00777 } else if (Kind == CK_BitCast) { 00778 checkCastAlign(); 00779 } 00780 } 00781 00782 /// TryStaticCast - Check if a static cast can be performed, and do so if 00783 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting 00784 /// and casting away constness. 00785 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 00786 QualType DestType, 00787 Sema::CheckedConversionKind CCK, 00788 const SourceRange &OpRange, unsigned &msg, 00789 CastKind &Kind, CXXCastPath &BasePath, 00790 bool ListInitialization) { 00791 // Determine whether we have the semantics of a C-style cast. 00792 bool CStyle 00793 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 00794 00795 // The order the tests is not entirely arbitrary. There is one conversion 00796 // that can be handled in two different ways. Given: 00797 // struct A {}; 00798 // struct B : public A { 00799 // B(); B(const A&); 00800 // }; 00801 // const A &a = B(); 00802 // the cast static_cast<const B&>(a) could be seen as either a static 00803 // reference downcast, or an explicit invocation of the user-defined 00804 // conversion using B's conversion constructor. 00805 // DR 427 specifies that the downcast is to be applied here. 00806 00807 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 00808 // Done outside this function. 00809 00810 TryCastResult tcr; 00811 00812 // C++ 5.2.9p5, reference downcast. 00813 // See the function for details. 00814 // DR 427 specifies that this is to be applied before paragraph 2. 00815 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, 00816 OpRange, msg, Kind, BasePath); 00817 if (tcr != TC_NotApplicable) 00818 return tcr; 00819 00820 // C++0x [expr.static.cast]p3: 00821 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 00822 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 00823 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 00824 BasePath, msg); 00825 if (tcr != TC_NotApplicable) 00826 return tcr; 00827 00828 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 00829 // [...] if the declaration "T t(e);" is well-formed, [...]. 00830 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 00831 Kind, ListInitialization); 00832 if (SrcExpr.isInvalid()) 00833 return TC_Failed; 00834 if (tcr != TC_NotApplicable) 00835 return tcr; 00836 00837 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 00838 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 00839 // conversions, subject to further restrictions. 00840 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 00841 // of qualification conversions impossible. 00842 // In the CStyle case, the earlier attempt to const_cast should have taken 00843 // care of reverse qualification conversions. 00844 00845 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 00846 00847 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 00848 // converted to an integral type. [...] A value of a scoped enumeration type 00849 // can also be explicitly converted to a floating-point type [...]. 00850 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 00851 if (Enum->getDecl()->isScoped()) { 00852 if (DestType->isBooleanType()) { 00853 Kind = CK_IntegralToBoolean; 00854 return TC_Success; 00855 } else if (DestType->isIntegralType(Self.Context)) { 00856 Kind = CK_IntegralCast; 00857 return TC_Success; 00858 } else if (DestType->isRealFloatingType()) { 00859 Kind = CK_IntegralToFloating; 00860 return TC_Success; 00861 } 00862 } 00863 } 00864 00865 // Reverse integral promotion/conversion. All such conversions are themselves 00866 // again integral promotions or conversions and are thus already handled by 00867 // p2 (TryDirectInitialization above). 00868 // (Note: any data loss warnings should be suppressed.) 00869 // The exception is the reverse of enum->integer, i.e. integer->enum (and 00870 // enum->enum). See also C++ 5.2.9p7. 00871 // The same goes for reverse floating point promotion/conversion and 00872 // floating-integral conversions. Again, only floating->enum is relevant. 00873 if (DestType->isEnumeralType()) { 00874 if (SrcType->isIntegralOrEnumerationType()) { 00875 Kind = CK_IntegralCast; 00876 return TC_Success; 00877 } else if (SrcType->isRealFloatingType()) { 00878 Kind = CK_FloatingToIntegral; 00879 return TC_Success; 00880 } 00881 } 00882 00883 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 00884 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 00885 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 00886 Kind, BasePath); 00887 if (tcr != TC_NotApplicable) 00888 return tcr; 00889 00890 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 00891 // conversion. C++ 5.2.9p9 has additional information. 00892 // DR54's access restrictions apply here also. 00893 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 00894 OpRange, msg, Kind, BasePath); 00895 if (tcr != TC_NotApplicable) 00896 return tcr; 00897 00898 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 00899 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 00900 // just the usual constness stuff. 00901 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 00902 QualType SrcPointee = SrcPointer->getPointeeType(); 00903 if (SrcPointee->isVoidType()) { 00904 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 00905 QualType DestPointee = DestPointer->getPointeeType(); 00906 if (DestPointee->isIncompleteOrObjectType()) { 00907 // This is definitely the intended conversion, but it might fail due 00908 // to a qualifier violation. Note that we permit Objective-C lifetime 00909 // and GC qualifier mismatches here. 00910 if (!CStyle) { 00911 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 00912 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 00913 DestPointeeQuals.removeObjCGCAttr(); 00914 DestPointeeQuals.removeObjCLifetime(); 00915 SrcPointeeQuals.removeObjCGCAttr(); 00916 SrcPointeeQuals.removeObjCLifetime(); 00917 if (DestPointeeQuals != SrcPointeeQuals && 00918 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 00919 msg = diag::err_bad_cxx_cast_qualifiers_away; 00920 return TC_Failed; 00921 } 00922 } 00923 Kind = CK_BitCast; 00924 return TC_Success; 00925 } 00926 } 00927 else if (DestType->isObjCObjectPointerType()) { 00928 // allow both c-style cast and static_cast of objective-c pointers as 00929 // they are pervasive. 00930 Kind = CK_CPointerToObjCPointerCast; 00931 return TC_Success; 00932 } 00933 else if (CStyle && DestType->isBlockPointerType()) { 00934 // allow c-style cast of void * to block pointers. 00935 Kind = CK_AnyPointerToBlockPointerCast; 00936 return TC_Success; 00937 } 00938 } 00939 } 00940 // Allow arbitray objective-c pointer conversion with static casts. 00941 if (SrcType->isObjCObjectPointerType() && 00942 DestType->isObjCObjectPointerType()) { 00943 Kind = CK_BitCast; 00944 return TC_Success; 00945 } 00946 00947 // We tried everything. Everything! Nothing works! :-( 00948 return TC_NotApplicable; 00949 } 00950 00951 /// Tests whether a conversion according to N2844 is valid. 00952 TryCastResult 00953 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, 00954 bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 00955 unsigned &msg) { 00956 // C++0x [expr.static.cast]p3: 00957 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 00958 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 00959 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 00960 if (!R) 00961 return TC_NotApplicable; 00962 00963 if (!SrcExpr->isGLValue()) 00964 return TC_NotApplicable; 00965 00966 // Because we try the reference downcast before this function, from now on 00967 // this is the only cast possibility, so we issue an error if we fail now. 00968 // FIXME: Should allow casting away constness if CStyle. 00969 bool DerivedToBase; 00970 bool ObjCConversion; 00971 bool ObjCLifetimeConversion; 00972 QualType FromType = SrcExpr->getType(); 00973 QualType ToType = R->getPointeeType(); 00974 if (CStyle) { 00975 FromType = FromType.getUnqualifiedType(); 00976 ToType = ToType.getUnqualifiedType(); 00977 } 00978 00979 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(), 00980 ToType, FromType, 00981 DerivedToBase, ObjCConversion, 00982 ObjCLifetimeConversion) 00983 < Sema::Ref_Compatible_With_Added_Qualification) { 00984 msg = diag::err_bad_lvalue_to_rvalue_cast; 00985 return TC_Failed; 00986 } 00987 00988 if (DerivedToBase) { 00989 Kind = CK_DerivedToBase; 00990 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 00991 /*DetectVirtual=*/true); 00992 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths)) 00993 return TC_NotApplicable; 00994 00995 Self.BuildBasePathArray(Paths, BasePath); 00996 } else 00997 Kind = CK_NoOp; 00998 00999 return TC_Success; 01000 } 01001 01002 /// Tests whether a conversion according to C++ 5.2.9p5 is valid. 01003 TryCastResult 01004 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 01005 bool CStyle, const SourceRange &OpRange, 01006 unsigned &msg, CastKind &Kind, 01007 CXXCastPath &BasePath) { 01008 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 01009 // cast to type "reference to cv2 D", where D is a class derived from B, 01010 // if a valid standard conversion from "pointer to D" to "pointer to B" 01011 // exists, cv2 >= cv1, and B is not a virtual base class of D. 01012 // In addition, DR54 clarifies that the base must be accessible in the 01013 // current context. Although the wording of DR54 only applies to the pointer 01014 // variant of this rule, the intent is clearly for it to apply to the this 01015 // conversion as well. 01016 01017 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 01018 if (!DestReference) { 01019 return TC_NotApplicable; 01020 } 01021 bool RValueRef = DestReference->isRValueReferenceType(); 01022 if (!RValueRef && !SrcExpr->isLValue()) { 01023 // We know the left side is an lvalue reference, so we can suggest a reason. 01024 msg = diag::err_bad_cxx_cast_rvalue; 01025 return TC_NotApplicable; 01026 } 01027 01028 QualType DestPointee = DestReference->getPointeeType(); 01029 01030 return TryStaticDowncast(Self, 01031 Self.Context.getCanonicalType(SrcExpr->getType()), 01032 Self.Context.getCanonicalType(DestPointee), CStyle, 01033 OpRange, SrcExpr->getType(), DestType, msg, Kind, 01034 BasePath); 01035 } 01036 01037 /// Tests whether a conversion according to C++ 5.2.9p8 is valid. 01038 TryCastResult 01039 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 01040 bool CStyle, const SourceRange &OpRange, 01041 unsigned &msg, CastKind &Kind, 01042 CXXCastPath &BasePath) { 01043 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 01044 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 01045 // is a class derived from B, if a valid standard conversion from "pointer 01046 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 01047 // class of D. 01048 // In addition, DR54 clarifies that the base must be accessible in the 01049 // current context. 01050 01051 const PointerType *DestPointer = DestType->getAs<PointerType>(); 01052 if (!DestPointer) { 01053 return TC_NotApplicable; 01054 } 01055 01056 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 01057 if (!SrcPointer) { 01058 msg = diag::err_bad_static_cast_pointer_nonpointer; 01059 return TC_NotApplicable; 01060 } 01061 01062 return TryStaticDowncast(Self, 01063 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 01064 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 01065 CStyle, OpRange, SrcType, DestType, msg, Kind, 01066 BasePath); 01067 } 01068 01069 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 01070 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 01071 /// DestType is possible and allowed. 01072 TryCastResult 01073 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 01074 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType, 01075 QualType OrigDestType, unsigned &msg, 01076 CastKind &Kind, CXXCastPath &BasePath) { 01077 // We can only work with complete types. But don't complain if it doesn't work 01078 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) || 01079 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0)) 01080 return TC_NotApplicable; 01081 01082 // Downcast can only happen in class hierarchies, so we need classes. 01083 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 01084 return TC_NotApplicable; 01085 } 01086 01087 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 01088 /*DetectVirtual=*/true); 01089 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) { 01090 return TC_NotApplicable; 01091 } 01092 01093 // Target type does derive from source type. Now we're serious. If an error 01094 // appears now, it's not ignored. 01095 // This may not be entirely in line with the standard. Take for example: 01096 // struct A {}; 01097 // struct B : virtual A { 01098 // B(A&); 01099 // }; 01100 // 01101 // void f() 01102 // { 01103 // (void)static_cast<const B&>(*((A*)0)); 01104 // } 01105 // As far as the standard is concerned, p5 does not apply (A is virtual), so 01106 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 01107 // However, both GCC and Comeau reject this example, and accepting it would 01108 // mean more complex code if we're to preserve the nice error message. 01109 // FIXME: Being 100% compliant here would be nice to have. 01110 01111 // Must preserve cv, as always, unless we're in C-style mode. 01112 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 01113 msg = diag::err_bad_cxx_cast_qualifiers_away; 01114 return TC_Failed; 01115 } 01116 01117 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 01118 // This code is analoguous to that in CheckDerivedToBaseConversion, except 01119 // that it builds the paths in reverse order. 01120 // To sum up: record all paths to the base and build a nice string from 01121 // them. Use it to spice up the error message. 01122 if (!Paths.isRecordingPaths()) { 01123 Paths.clear(); 01124 Paths.setRecordingPaths(true); 01125 Self.IsDerivedFrom(DestType, SrcType, Paths); 01126 } 01127 std::string PathDisplayStr; 01128 std::set<unsigned> DisplayedPaths; 01129 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end(); 01130 PI != PE; ++PI) { 01131 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) { 01132 // We haven't displayed a path to this particular base 01133 // class subobject yet. 01134 PathDisplayStr += "\n "; 01135 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(), 01136 EE = PI->rend(); 01137 EI != EE; ++EI) 01138 PathDisplayStr += EI->Base->getType().getAsString() + " -> "; 01139 PathDisplayStr += QualType(DestType).getAsString(); 01140 } 01141 } 01142 01143 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 01144 << QualType(SrcType).getUnqualifiedType() 01145 << QualType(DestType).getUnqualifiedType() 01146 << PathDisplayStr << OpRange; 01147 msg = 0; 01148 return TC_Failed; 01149 } 01150 01151 if (Paths.getDetectedVirtual() != 0) { 01152 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 01153 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 01154 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 01155 msg = 0; 01156 return TC_Failed; 01157 } 01158 01159 if (!CStyle) { 01160 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 01161 SrcType, DestType, 01162 Paths.front(), 01163 diag::err_downcast_from_inaccessible_base)) { 01164 case Sema::AR_accessible: 01165 case Sema::AR_delayed: // be optimistic 01166 case Sema::AR_dependent: // be optimistic 01167 break; 01168 01169 case Sema::AR_inaccessible: 01170 msg = 0; 01171 return TC_Failed; 01172 } 01173 } 01174 01175 Self.BuildBasePathArray(Paths, BasePath); 01176 Kind = CK_BaseToDerived; 01177 return TC_Success; 01178 } 01179 01180 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to 01181 /// C++ 5.2.9p9 is valid: 01182 /// 01183 /// An rvalue of type "pointer to member of D of type cv1 T" can be 01184 /// converted to an rvalue of type "pointer to member of B of type cv2 T", 01185 /// where B is a base class of D [...]. 01186 /// 01187 TryCastResult 01188 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 01189 QualType DestType, bool CStyle, 01190 const SourceRange &OpRange, 01191 unsigned &msg, CastKind &Kind, 01192 CXXCastPath &BasePath) { 01193 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 01194 if (!DestMemPtr) 01195 return TC_NotApplicable; 01196 01197 bool WasOverloadedFunction = false; 01198 DeclAccessPair FoundOverload; 01199 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 01200 if (FunctionDecl *Fn 01201 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 01202 FoundOverload)) { 01203 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 01204 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 01205 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 01206 WasOverloadedFunction = true; 01207 } 01208 } 01209 01210 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 01211 if (!SrcMemPtr) { 01212 msg = diag::err_bad_static_cast_member_pointer_nonmp; 01213 return TC_NotApplicable; 01214 } 01215 01216 // T == T, modulo cv 01217 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 01218 DestMemPtr->getPointeeType())) 01219 return TC_NotApplicable; 01220 01221 // B base of D 01222 QualType SrcClass(SrcMemPtr->getClass(), 0); 01223 QualType DestClass(DestMemPtr->getClass(), 0); 01224 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 01225 /*DetectVirtual=*/true); 01226 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) { 01227 return TC_NotApplicable; 01228 } 01229 01230 // B is a base of D. But is it an allowed base? If not, it's a hard error. 01231 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 01232 Paths.clear(); 01233 Paths.setRecordingPaths(true); 01234 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths); 01235 assert(StillOkay); 01236 (void)StillOkay; 01237 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 01238 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 01239 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 01240 msg = 0; 01241 return TC_Failed; 01242 } 01243 01244 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 01245 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 01246 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 01247 msg = 0; 01248 return TC_Failed; 01249 } 01250 01251 if (!CStyle) { 01252 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 01253 DestClass, SrcClass, 01254 Paths.front(), 01255 diag::err_upcast_to_inaccessible_base)) { 01256 case Sema::AR_accessible: 01257 case Sema::AR_delayed: 01258 case Sema::AR_dependent: 01259 // Optimistically assume that the delayed and dependent cases 01260 // will work out. 01261 break; 01262 01263 case Sema::AR_inaccessible: 01264 msg = 0; 01265 return TC_Failed; 01266 } 01267 } 01268 01269 if (WasOverloadedFunction) { 01270 // Resolve the address of the overloaded function again, this time 01271 // allowing complaints if something goes wrong. 01272 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 01273 DestType, 01274 true, 01275 FoundOverload); 01276 if (!Fn) { 01277 msg = 0; 01278 return TC_Failed; 01279 } 01280 01281 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 01282 if (!SrcExpr.isUsable()) { 01283 msg = 0; 01284 return TC_Failed; 01285 } 01286 } 01287 01288 Self.BuildBasePathArray(Paths, BasePath); 01289 Kind = CK_DerivedToBaseMemberPointer; 01290 return TC_Success; 01291 } 01292 01293 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 01294 /// is valid: 01295 /// 01296 /// An expression e can be explicitly converted to a type T using a 01297 /// @c static_cast if the declaration "T t(e);" is well-formed [...]. 01298 TryCastResult 01299 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 01300 Sema::CheckedConversionKind CCK, 01301 const SourceRange &OpRange, unsigned &msg, 01302 CastKind &Kind, bool ListInitialization) { 01303 if (DestType->isRecordType()) { 01304 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 01305 diag::err_bad_dynamic_cast_incomplete) || 01306 Self.RequireNonAbstractType(OpRange.getBegin(), DestType, 01307 diag::err_allocation_of_abstract_type)) { 01308 msg = 0; 01309 return TC_Failed; 01310 } 01311 } 01312 01313 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 01314 InitializationKind InitKind 01315 = (CCK == Sema::CCK_CStyleCast) 01316 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, 01317 ListInitialization) 01318 : (CCK == Sema::CCK_FunctionalCast) 01319 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) 01320 : InitializationKind::CreateCast(OpRange); 01321 Expr *SrcExprRaw = SrcExpr.get(); 01322 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1); 01323 01324 // At this point of CheckStaticCast, if the destination is a reference, 01325 // or the expression is an overload expression this has to work. 01326 // There is no other way that works. 01327 // On the other hand, if we're checking a C-style cast, we've still got 01328 // the reinterpret_cast way. 01329 bool CStyle 01330 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 01331 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 01332 return TC_NotApplicable; 01333 01334 ExprResult Result 01335 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1)); 01336 if (Result.isInvalid()) { 01337 msg = 0; 01338 return TC_Failed; 01339 } 01340 01341 if (InitSeq.isConstructorInitialization()) 01342 Kind = CK_ConstructorConversion; 01343 else 01344 Kind = CK_NoOp; 01345 01346 SrcExpr = move(Result); 01347 return TC_Success; 01348 } 01349 01350 /// TryConstCast - See if a const_cast from source to destination is allowed, 01351 /// and perform it if it is. 01352 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 01353 bool CStyle, unsigned &msg) { 01354 DestType = Self.Context.getCanonicalType(DestType); 01355 QualType SrcType = SrcExpr->getType(); 01356 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 01357 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) { 01358 // Cannot const_cast non-lvalue to lvalue reference type. But if this 01359 // is C-style, static_cast might find a way, so we simply suggest a 01360 // message and tell the parent to keep searching. 01361 msg = diag::err_bad_cxx_cast_rvalue; 01362 return TC_NotApplicable; 01363 } 01364 01365 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2 01366 // [...] if a pointer to T1 can be [cast] to the type pointer to T2. 01367 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 01368 SrcType = Self.Context.getPointerType(SrcType); 01369 } 01370 01371 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 01372 // the rules for const_cast are the same as those used for pointers. 01373 01374 if (!DestType->isPointerType() && 01375 !DestType->isMemberPointerType() && 01376 !DestType->isObjCObjectPointerType()) { 01377 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 01378 // was a reference type, we converted it to a pointer above. 01379 // The status of rvalue references isn't entirely clear, but it looks like 01380 // conversion to them is simply invalid. 01381 // C++ 5.2.11p3: For two pointer types [...] 01382 if (!CStyle) 01383 msg = diag::err_bad_const_cast_dest; 01384 return TC_NotApplicable; 01385 } 01386 if (DestType->isFunctionPointerType() || 01387 DestType->isMemberFunctionPointerType()) { 01388 // Cannot cast direct function pointers. 01389 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 01390 // T is the ultimate pointee of source and target type. 01391 if (!CStyle) 01392 msg = diag::err_bad_const_cast_dest; 01393 return TC_NotApplicable; 01394 } 01395 SrcType = Self.Context.getCanonicalType(SrcType); 01396 01397 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 01398 // completely equal. 01399 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 01400 // in multi-level pointers may change, but the level count must be the same, 01401 // as must be the final pointee type. 01402 while (SrcType != DestType && 01403 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 01404 Qualifiers SrcQuals, DestQuals; 01405 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 01406 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 01407 01408 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 01409 // the other qualifiers (e.g., address spaces) are identical. 01410 SrcQuals.removeCVRQualifiers(); 01411 DestQuals.removeCVRQualifiers(); 01412 if (SrcQuals != DestQuals) 01413 return TC_NotApplicable; 01414 } 01415 01416 // Since we're dealing in canonical types, the remainder must be the same. 01417 if (SrcType != DestType) 01418 return TC_NotApplicable; 01419 01420 return TC_Success; 01421 } 01422 01423 // Checks for undefined behavior in reinterpret_cast. 01424 // The cases that is checked for is: 01425 // *reinterpret_cast<T*>(&a) 01426 // reinterpret_cast<T&>(a) 01427 // where accessing 'a' as type 'T' will result in undefined behavior. 01428 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 01429 bool IsDereference, 01430 SourceRange Range) { 01431 unsigned DiagID = IsDereference ? 01432 diag::warn_pointer_indirection_from_incompatible_type : 01433 diag::warn_undefined_reinterpret_cast; 01434 01435 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) == 01436 DiagnosticsEngine::Ignored) { 01437 return; 01438 } 01439 01440 QualType SrcTy, DestTy; 01441 if (IsDereference) { 01442 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 01443 return; 01444 } 01445 SrcTy = SrcType->getPointeeType(); 01446 DestTy = DestType->getPointeeType(); 01447 } else { 01448 if (!DestType->getAs<ReferenceType>()) { 01449 return; 01450 } 01451 SrcTy = SrcType; 01452 DestTy = DestType->getPointeeType(); 01453 } 01454 01455 // Cast is compatible if the types are the same. 01456 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 01457 return; 01458 } 01459 // or one of the types is a char or void type 01460 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 01461 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 01462 return; 01463 } 01464 // or one of the types is a tag type. 01465 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 01466 return; 01467 } 01468 01469 // FIXME: Scoped enums? 01470 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 01471 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 01472 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 01473 return; 01474 } 01475 } 01476 01477 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 01478 } 01479 01480 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 01481 QualType DestType, bool CStyle, 01482 const SourceRange &OpRange, 01483 unsigned &msg, 01484 CastKind &Kind) { 01485 bool IsLValueCast = false; 01486 01487 DestType = Self.Context.getCanonicalType(DestType); 01488 QualType SrcType = SrcExpr.get()->getType(); 01489 01490 // Is the source an overloaded name? (i.e. &foo) 01491 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ... 01492 if (SrcType == Self.Context.OverloadTy) { 01493 // ... unless foo<int> resolves to an lvalue unambiguously. 01494 // TODO: what if this fails because of DiagnoseUseOfDecl or something 01495 // like it? 01496 ExprResult SingleFunctionExpr = SrcExpr; 01497 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 01498 SingleFunctionExpr, 01499 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 01500 ) && SingleFunctionExpr.isUsable()) { 01501 SrcExpr = move(SingleFunctionExpr); 01502 SrcType = SrcExpr.get()->getType(); 01503 } else { 01504 return TC_NotApplicable; 01505 } 01506 } 01507 01508 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 01509 if (!SrcExpr.get()->isGLValue()) { 01510 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the 01511 // similar comment in const_cast. 01512 msg = diag::err_bad_cxx_cast_rvalue; 01513 return TC_NotApplicable; 01514 } 01515 01516 if (!CStyle) { 01517 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 01518 /*isDereference=*/false, OpRange); 01519 } 01520 01521 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 01522 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 01523 // built-in & and * operators. 01524 01525 const char *inappropriate = 0; 01526 switch (SrcExpr.get()->getObjectKind()) { 01527 case OK_Ordinary: 01528 break; 01529 case OK_BitField: inappropriate = "bit-field"; break; 01530 case OK_VectorComponent: inappropriate = "vector element"; break; 01531 case OK_ObjCProperty: inappropriate = "property expression"; break; 01532 case OK_ObjCSubscript: inappropriate = "container subscripting expression"; 01533 break; 01534 } 01535 if (inappropriate) { 01536 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 01537 << inappropriate << DestType 01538 << OpRange << SrcExpr.get()->getSourceRange(); 01539 msg = 0; SrcExpr = ExprError(); 01540 return TC_NotApplicable; 01541 } 01542 01543 // This code does this transformation for the checked types. 01544 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 01545 SrcType = Self.Context.getPointerType(SrcType); 01546 01547 IsLValueCast = true; 01548 } 01549 01550 // Canonicalize source for comparison. 01551 SrcType = Self.Context.getCanonicalType(SrcType); 01552 01553 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 01554 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 01555 if (DestMemPtr && SrcMemPtr) { 01556 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 01557 // can be explicitly converted to an rvalue of type "pointer to member 01558 // of Y of type T2" if T1 and T2 are both function types or both object 01559 // types. 01560 if (DestMemPtr->getPointeeType()->isFunctionType() != 01561 SrcMemPtr->getPointeeType()->isFunctionType()) 01562 return TC_NotApplicable; 01563 01564 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 01565 // constness. 01566 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 01567 // we accept it. 01568 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 01569 /*CheckObjCLifetime=*/CStyle)) { 01570 msg = diag::err_bad_cxx_cast_qualifiers_away; 01571 return TC_Failed; 01572 } 01573 01574 // Don't allow casting between member pointers of different sizes. 01575 if (Self.Context.getTypeSize(DestMemPtr) != 01576 Self.Context.getTypeSize(SrcMemPtr)) { 01577 msg = diag::err_bad_cxx_cast_member_pointer_size; 01578 return TC_Failed; 01579 } 01580 01581 // A valid member pointer cast. 01582 assert(!IsLValueCast); 01583 Kind = CK_ReinterpretMemberPointer; 01584 return TC_Success; 01585 } 01586 01587 // See below for the enumeral issue. 01588 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 01589 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 01590 // type large enough to hold it. A value of std::nullptr_t can be 01591 // converted to an integral type; the conversion has the same meaning 01592 // and validity as a conversion of (void*)0 to the integral type. 01593 if (Self.Context.getTypeSize(SrcType) > 01594 Self.Context.getTypeSize(DestType)) { 01595 msg = diag::err_bad_reinterpret_cast_small_int; 01596 return TC_Failed; 01597 } 01598 Kind = CK_PointerToIntegral; 01599 return TC_Success; 01600 } 01601 01602 bool destIsVector = DestType->isVectorType(); 01603 bool srcIsVector = SrcType->isVectorType(); 01604 if (srcIsVector || destIsVector) { 01605 // FIXME: Should this also apply to floating point types? 01606 bool srcIsScalar = SrcType->isIntegralType(Self.Context); 01607 bool destIsScalar = DestType->isIntegralType(Self.Context); 01608 01609 // Check if this is a cast between a vector and something else. 01610 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) && 01611 !(srcIsVector && destIsVector)) 01612 return TC_NotApplicable; 01613 01614 // If both types have the same size, we can successfully cast. 01615 if (Self.Context.getTypeSize(SrcType) 01616 == Self.Context.getTypeSize(DestType)) { 01617 Kind = CK_BitCast; 01618 return TC_Success; 01619 } 01620 01621 if (destIsScalar) 01622 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 01623 else if (srcIsScalar) 01624 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 01625 else 01626 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 01627 01628 return TC_Failed; 01629 } 01630 01631 if (SrcType == DestType) { 01632 // C++ 5.2.10p2 has a note that mentions that, subject to all other 01633 // restrictions, a cast to the same type is allowed so long as it does not 01634 // cast away constness. In C++98, the intent was not entirely clear here, 01635 // since all other paragraphs explicitly forbid casts to the same type. 01636 // C++11 clarifies this case with p2. 01637 // 01638 // The only allowed types are: integral, enumeration, pointer, or 01639 // pointer-to-member types. We also won't restrict Obj-C pointers either. 01640 Kind = CK_NoOp; 01641 TryCastResult Result = TC_NotApplicable; 01642 if (SrcType->isIntegralOrEnumerationType() || 01643 SrcType->isAnyPointerType() || 01644 SrcType->isMemberPointerType() || 01645 SrcType->isBlockPointerType()) { 01646 Result = TC_Success; 01647 } 01648 return Result; 01649 } 01650 01651 bool destIsPtr = DestType->isAnyPointerType() || 01652 DestType->isBlockPointerType(); 01653 bool srcIsPtr = SrcType->isAnyPointerType() || 01654 SrcType->isBlockPointerType(); 01655 if (!destIsPtr && !srcIsPtr) { 01656 // Except for std::nullptr_t->integer and lvalue->reference, which are 01657 // handled above, at least one of the two arguments must be a pointer. 01658 return TC_NotApplicable; 01659 } 01660 01661 if (DestType->isIntegralType(Self.Context)) { 01662 assert(srcIsPtr && "One type must be a pointer"); 01663 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 01664 // type large enough to hold it; except in Microsoft mode, where the 01665 // integral type size doesn't matter. 01666 if ((Self.Context.getTypeSize(SrcType) > 01667 Self.Context.getTypeSize(DestType)) && 01668 !Self.getLangOpts().MicrosoftExt) { 01669 msg = diag::err_bad_reinterpret_cast_small_int; 01670 return TC_Failed; 01671 } 01672 Kind = CK_PointerToIntegral; 01673 return TC_Success; 01674 } 01675 01676 if (SrcType->isIntegralOrEnumerationType()) { 01677 assert(destIsPtr && "One type must be a pointer"); 01678 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 01679 // converted to a pointer. 01680 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 01681 // necessarily converted to a null pointer value.] 01682 Kind = CK_IntegralToPointer; 01683 return TC_Success; 01684 } 01685 01686 if (!destIsPtr || !srcIsPtr) { 01687 // With the valid non-pointer conversions out of the way, we can be even 01688 // more stringent. 01689 return TC_NotApplicable; 01690 } 01691 01692 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 01693 // The C-style cast operator can. 01694 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 01695 /*CheckObjCLifetime=*/CStyle)) { 01696 msg = diag::err_bad_cxx_cast_qualifiers_away; 01697 return TC_Failed; 01698 } 01699 01700 // Cannot convert between block pointers and Objective-C object pointers. 01701 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 01702 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 01703 return TC_NotApplicable; 01704 01705 if (IsLValueCast) { 01706 Kind = CK_LValueBitCast; 01707 } else if (DestType->isObjCObjectPointerType()) { 01708 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 01709 } else if (DestType->isBlockPointerType()) { 01710 if (!SrcType->isBlockPointerType()) { 01711 Kind = CK_AnyPointerToBlockPointerCast; 01712 } else { 01713 Kind = CK_BitCast; 01714 } 01715 } else { 01716 Kind = CK_BitCast; 01717 } 01718 01719 // Any pointer can be cast to an Objective-C pointer type with a C-style 01720 // cast. 01721 if (CStyle && DestType->isObjCObjectPointerType()) { 01722 return TC_Success; 01723 } 01724 01725 // Not casting away constness, so the only remaining check is for compatible 01726 // pointer categories. 01727 01728 if (SrcType->isFunctionPointerType()) { 01729 if (DestType->isFunctionPointerType()) { 01730 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 01731 // a pointer to a function of a different type. 01732 return TC_Success; 01733 } 01734 01735 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 01736 // an object type or vice versa is conditionally-supported. 01737 // Compilers support it in C++03 too, though, because it's necessary for 01738 // casting the return value of dlsym() and GetProcAddress(). 01739 // FIXME: Conditionally-supported behavior should be configurable in the 01740 // TargetInfo or similar. 01741 Self.Diag(OpRange.getBegin(), 01742 Self.getLangOpts().CPlusPlus0x ? 01743 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 01744 << OpRange; 01745 return TC_Success; 01746 } 01747 01748 if (DestType->isFunctionPointerType()) { 01749 // See above. 01750 Self.Diag(OpRange.getBegin(), 01751 Self.getLangOpts().CPlusPlus0x ? 01752 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 01753 << OpRange; 01754 return TC_Success; 01755 } 01756 01757 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 01758 // a pointer to an object of different type. 01759 // Void pointers are not specified, but supported by every compiler out there. 01760 // So we finish by allowing everything that remains - it's got to be two 01761 // object pointers. 01762 return TC_Success; 01763 } 01764 01765 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, 01766 bool ListInitialization) { 01767 // Handle placeholders. 01768 if (isPlaceholder()) { 01769 // C-style casts can resolve __unknown_any types. 01770 if (claimPlaceholder(BuiltinType::UnknownAny)) { 01771 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 01772 SrcExpr.get(), Kind, 01773 ValueKind, BasePath); 01774 return; 01775 } 01776 01777 checkNonOverloadPlaceholders(); 01778 if (SrcExpr.isInvalid()) 01779 return; 01780 } 01781 01782 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 01783 // This test is outside everything else because it's the only case where 01784 // a non-lvalue-reference target type does not lead to decay. 01785 if (DestType->isVoidType()) { 01786 Kind = CK_ToVoid; 01787 01788 if (claimPlaceholder(BuiltinType::Overload)) { 01789 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 01790 SrcExpr, /* Decay Function to ptr */ false, 01791 /* Complain */ true, DestRange, DestType, 01792 diag::err_bad_cstyle_cast_overload); 01793 if (SrcExpr.isInvalid()) 01794 return; 01795 } 01796 01797 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 01798 if (SrcExpr.isInvalid()) 01799 return; 01800 01801 return; 01802 } 01803 01804 // If the type is dependent, we won't do any other semantic analysis now. 01805 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) { 01806 assert(Kind == CK_Dependent); 01807 return; 01808 } 01809 01810 if (ValueKind == VK_RValue && !DestType->isRecordType() && 01811 !isPlaceholder(BuiltinType::Overload)) { 01812 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 01813 if (SrcExpr.isInvalid()) 01814 return; 01815 } 01816 01817 // AltiVec vector initialization with a single literal. 01818 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 01819 if (vecTy->getVectorKind() == VectorType::AltiVecVector 01820 && (SrcExpr.get()->getType()->isIntegerType() 01821 || SrcExpr.get()->getType()->isFloatingType())) { 01822 Kind = CK_VectorSplat; 01823 return; 01824 } 01825 01826 // C++ [expr.cast]p5: The conversions performed by 01827 // - a const_cast, 01828 // - a static_cast, 01829 // - a static_cast followed by a const_cast, 01830 // - a reinterpret_cast, or 01831 // - a reinterpret_cast followed by a const_cast, 01832 // can be performed using the cast notation of explicit type conversion. 01833 // [...] If a conversion can be interpreted in more than one of the ways 01834 // listed above, the interpretation that appears first in the list is used, 01835 // even if a cast resulting from that interpretation is ill-formed. 01836 // In plain language, this means trying a const_cast ... 01837 unsigned msg = diag::err_bad_cxx_cast_generic; 01838 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType, 01839 /*CStyle*/true, msg); 01840 if (tcr == TC_Success) 01841 Kind = CK_NoOp; 01842 01843 Sema::CheckedConversionKind CCK 01844 = FunctionalStyle? Sema::CCK_FunctionalCast 01845 : Sema::CCK_CStyleCast; 01846 if (tcr == TC_NotApplicable) { 01847 // ... or if that is not possible, a static_cast, ignoring const, ... 01848 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 01849 msg, Kind, BasePath, ListInitialization); 01850 if (SrcExpr.isInvalid()) 01851 return; 01852 01853 if (tcr == TC_NotApplicable) { 01854 // ... and finally a reinterpret_cast, ignoring const. 01855 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 01856 OpRange, msg, Kind); 01857 if (SrcExpr.isInvalid()) 01858 return; 01859 } 01860 } 01861 01862 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success) 01863 checkObjCARCConversion(CCK); 01864 01865 if (tcr != TC_Success && msg != 0) { 01866 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 01867 DeclAccessPair Found; 01868 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 01869 DestType, 01870 /*Complain*/ true, 01871 Found); 01872 01873 assert(!Fn && "cast failed but able to resolve overload expression!!"); 01874 (void)Fn; 01875 01876 } else { 01877 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 01878 OpRange, SrcExpr.get(), DestType, ListInitialization); 01879 } 01880 } else if (Kind == CK_BitCast) { 01881 checkCastAlign(); 01882 } 01883 01884 // Clear out SrcExpr if there was a fatal error. 01885 if (tcr != TC_Success) 01886 SrcExpr = ExprError(); 01887 } 01888 01889 /// Check the semantics of a C-style cast operation, in C. 01890 void CastOperation::CheckCStyleCast() { 01891 assert(!Self.getLangOpts().CPlusPlus); 01892 01893 // C-style casts can resolve __unknown_any types. 01894 if (claimPlaceholder(BuiltinType::UnknownAny)) { 01895 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 01896 SrcExpr.get(), Kind, 01897 ValueKind, BasePath); 01898 return; 01899 } 01900 01901 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 01902 // type needs to be scalar. 01903 if (DestType->isVoidType()) { 01904 // We don't necessarily do lvalue-to-rvalue conversions on this. 01905 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 01906 if (SrcExpr.isInvalid()) 01907 return; 01908 01909 // Cast to void allows any expr type. 01910 Kind = CK_ToVoid; 01911 return; 01912 } 01913 01914 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 01915 if (SrcExpr.isInvalid()) 01916 return; 01917 QualType SrcType = SrcExpr.get()->getType(); 01918 01919 // You can cast an _Atomic(T) to anything you can cast a T to. 01920 if (const AtomicType *AtomicSrcType = SrcType->getAs<AtomicType>()) 01921 SrcType = AtomicSrcType->getValueType(); 01922 01923 assert(!SrcType->isPlaceholderType()); 01924 01925 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 01926 diag::err_typecheck_cast_to_incomplete)) { 01927 SrcExpr = ExprError(); 01928 return; 01929 } 01930 01931 if (!DestType->isScalarType() && !DestType->isVectorType()) { 01932 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 01933 01934 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 01935 // GCC struct/union extension: allow cast to self. 01936 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 01937 << DestType << SrcExpr.get()->getSourceRange(); 01938 Kind = CK_NoOp; 01939 return; 01940 } 01941 01942 // GCC's cast to union extension. 01943 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 01944 RecordDecl *RD = DestRecordTy->getDecl(); 01945 RecordDecl::field_iterator Field, FieldEnd; 01946 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 01947 Field != FieldEnd; ++Field) { 01948 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 01949 !Field->isUnnamedBitfield()) { 01950 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 01951 << SrcExpr.get()->getSourceRange(); 01952 break; 01953 } 01954 } 01955 if (Field == FieldEnd) { 01956 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 01957 << SrcType << SrcExpr.get()->getSourceRange(); 01958 SrcExpr = ExprError(); 01959 return; 01960 } 01961 Kind = CK_ToUnion; 01962 return; 01963 } 01964 01965 // Reject any other conversions to non-scalar types. 01966 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 01967 << DestType << SrcExpr.get()->getSourceRange(); 01968 SrcExpr = ExprError(); 01969 return; 01970 } 01971 01972 // The type we're casting to is known to be a scalar or vector. 01973 01974 // Require the operand to be a scalar or vector. 01975 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 01976 Self.Diag(SrcExpr.get()->getExprLoc(), 01977 diag::err_typecheck_expect_scalar_operand) 01978 << SrcType << SrcExpr.get()->getSourceRange(); 01979 SrcExpr = ExprError(); 01980 return; 01981 } 01982 01983 if (DestType->isExtVectorType()) { 01984 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind); 01985 return; 01986 } 01987 01988 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 01989 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 01990 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 01991 Kind = CK_VectorSplat; 01992 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 01993 SrcExpr = ExprError(); 01994 } 01995 return; 01996 } 01997 01998 if (SrcType->isVectorType()) { 01999 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 02000 SrcExpr = ExprError(); 02001 return; 02002 } 02003 02004 // The source and target types are both scalars, i.e. 02005 // - arithmetic types (fundamental, enum, and complex) 02006 // - all kinds of pointers 02007 // Note that member pointers were filtered out with C++, above. 02008 02009 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 02010 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 02011 SrcExpr = ExprError(); 02012 return; 02013 } 02014 02015 // If either type is a pointer, the other type has to be either an 02016 // integer or a pointer. 02017 if (!DestType->isArithmeticType()) { 02018 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 02019 Self.Diag(SrcExpr.get()->getExprLoc(), 02020 diag::err_cast_pointer_from_non_pointer_int) 02021 << SrcType << SrcExpr.get()->getSourceRange(); 02022 SrcExpr = ExprError(); 02023 return; 02024 } 02025 } else if (!SrcType->isArithmeticType()) { 02026 if (!DestType->isIntegralType(Self.Context) && 02027 DestType->isArithmeticType()) { 02028 Self.Diag(SrcExpr.get()->getLocStart(), 02029 diag::err_cast_pointer_to_non_pointer_int) 02030 << DestType << SrcExpr.get()->getSourceRange(); 02031 SrcExpr = ExprError(); 02032 return; 02033 } 02034 } 02035 02036 // ARC imposes extra restrictions on casts. 02037 if (Self.getLangOpts().ObjCAutoRefCount) { 02038 checkObjCARCConversion(Sema::CCK_CStyleCast); 02039 if (SrcExpr.isInvalid()) 02040 return; 02041 02042 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) { 02043 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 02044 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 02045 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 02046 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 02047 ExprPtr->getPointeeType()->isObjCLifetimeType() && 02048 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 02049 Self.Diag(SrcExpr.get()->getLocStart(), 02050 diag::err_typecheck_incompatible_ownership) 02051 << SrcType << DestType << Sema::AA_Casting 02052 << SrcExpr.get()->getSourceRange(); 02053 return; 02054 } 02055 } 02056 } 02057 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 02058 Self.Diag(SrcExpr.get()->getLocStart(), 02059 diag::err_arc_convesion_of_weak_unavailable) 02060 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 02061 SrcExpr = ExprError(); 02062 return; 02063 } 02064 } 02065 02066 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 02067 if (SrcExpr.isInvalid()) 02068 return; 02069 02070 if (Kind == CK_BitCast) 02071 checkCastAlign(); 02072 } 02073 02074 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 02075 TypeSourceInfo *CastTypeInfo, 02076 SourceLocation RPLoc, 02077 Expr *CastExpr) { 02078 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 02079 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 02080 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 02081 02082 if (getLangOpts().CPlusPlus) { 02083 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false, 02084 isa<InitListExpr>(CastExpr)); 02085 } else { 02086 Op.CheckCStyleCast(); 02087 } 02088 02089 if (Op.SrcExpr.isInvalid()) 02090 return ExprError(); 02091 02092 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 02093 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 02094 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 02095 } 02096 02097 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 02098 SourceLocation LPLoc, 02099 Expr *CastExpr, 02100 SourceLocation RPLoc) { 02101 assert(LPLoc.isValid() && "List-initialization shouldn't get here."); 02102 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 02103 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 02104 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 02105 02106 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false); 02107 if (Op.SrcExpr.isInvalid()) 02108 return ExprError(); 02109 02110 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 02111 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(), 02112 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc)); 02113 }