Skip to content

[Runtime] Support lazy ObjC realization of Swift classes. #76498

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions stdlib/public/runtime/SwiftObject.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1377,12 +1377,25 @@ id swift_dynamicCastObjCProtocolConditional(id object,
return object;
}

// Check whether the current ObjC runtime supports lazy realization. If it does,
// then we can avoid forcing realization of classes before we use them.
static bool objcSupportsLazyRealization() {
#if OBJC_SUPPORTSLAZYREALIZATION_DEFINED
return SWIFT_LAZY_CONSTANT(_objc_supportsLazyRealization());
#else
return false;
#endif
}

void swift::swift_instantiateObjCClass(const ClassMetadata *_c) {
static const objc_image_info ImageInfo = {0, 0};

// Ensure the superclass is realized.
Class c = class_const_cast(_c);
[class_getSuperclass(c) class];

if (!objcSupportsLazyRealization()) {
// Ensure the superclass is realized.
[class_getSuperclass(c) class];
}

// Register the class.
Class registered = objc_readClassPair(c, &ImageInfo);
Expand All @@ -1392,14 +1405,16 @@ id swift_dynamicCastObjCProtocolConditional(id object,
}

Class swift::swift_getInitializedObjCClass(Class c) {
// Used when we have class metadata and we want to ensure a class has been
// initialized by the Objective-C runtime. We need to do this because the
// class "c" might be valid metadata, but it hasn't been initialized yet.
// Send a message that's likely not to be overridden to minimize potential
// side effects. Ignore the return value in case it is overridden to
// return something different. See
// https://github.com/apple/swift/issues/52863 for an example.
[c self];
if (!objcSupportsLazyRealization()) {
// Used when we have class metadata and we want to ensure a class has been
// initialized by the Objective-C runtime. We need to do this because the
// class "c" might be valid metadata, but it hasn't been initialized yet.
// Send a message that's likely not to be overridden to minimize potential
// side effects. Ignore the return value in case it is overridden to
// return something different. See
// https://github.com/apple/swift/issues/52863 for an example.
[c self];
}
return c;
}

Expand Down