CastOptimizer: don't assume dynamic casts from ObjectiveC classes to unrelated classes will fail

In case of ObjectiveC classes, the runtime type can differ from its declared type.
Therefore a cast between (compile-time) unrelated classes may succeed at runtime.

rdar://149810124
This commit is contained in:
Erik Eckstein
2025-04-30 16:41:00 +02:00
parent f6a864a188
commit bcc9753288
4 changed files with 19 additions and 18 deletions

View File

@@ -741,7 +741,10 @@ swift::classifyDynamicCast(SILFunction *function,
if (targetClass->isSuperclassOf(sourceClass))
return DynamicCastFeasibility::WillSucceed;
return DynamicCastFeasibility::WillFail;
// In case of ObjectiveC classes, the runtime type can differ from its
// declared type. Therefore a cast between (compile-time) unrelated
// classes may succeed at runtime.
return DynamicCastFeasibility::MaySucceed;
}
}
@@ -750,6 +753,12 @@ swift::classifyDynamicCast(SILFunction *function,
if (hierarchyResult != DynamicCastFeasibility::WillFail)
return hierarchyResult;
// In case of ObjectiveC classes, the runtime type can differ from its
// declared type. Therefore a cast between (compile-time) unrelated
// classes may succeed at runtime.
if (sourceClass->hasClangNode())
return DynamicCastFeasibility::MaySucceed;
// As a backup, consider whether either type is a CF class type
// with an NS bridged equivalent.
CanType bridgedSource = getNSBridgedClassOfCFClass(source);