Skip to content

Commit cc214ad

Browse files
committed
[Runtime] Improve performance and memory footprint of compatibility overrides
rdar://143401725 Replacing the (non-inlined) call to `swift_once` with a relaxed atomic significantly improves the generated code and reduces the memory footprint. The mechanism itself now does not cause a stack frame to be generated and the expected case (no override) should be perfectly predicted and executed in straight line code. The override case should also be well predicted, with only two branches on the same value.
1 parent 59e07f1 commit cc214ad

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

stdlib/public/CompatibilityOverride/CompatibilityOverride.h

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,10 @@
8282
#define COMPATIBILITY_OVERRIDE_H
8383

8484
#include "../runtime/Private.h"
85+
#include "swift/Runtime/CMakeConfig.h"
8586
#include "swift/Runtime/Concurrency.h"
8687
#include "swift/Runtime/Metadata.h"
87-
#include "swift/Runtime/Once.h"
88-
#include "swift/Runtime/CMakeConfig.h"
88+
#include <atomic>
8989
#include <type_traits>
9090

9191
namespace swift {
@@ -193,14 +193,22 @@ namespace swift {
193193
#define COMPATIBILITY_OVERRIDE(name, ret, attrs, ccAttrs, namespace, \
194194
typedArgs, namedArgs) \
195195
attrs ccAttrs ret namespace swift_##name COMPATIBILITY_PAREN(typedArgs) { \
196-
static Override_##name Override; \
197-
static swift_once_t Predicate; \
198-
swift_once( \
199-
&Predicate, [](void *) { Override = getOverride_##name(); }, nullptr); \
200-
if (Override != nullptr) \
201-
return Override(COMPATIBILITY_UNPAREN_WITH_COMMA(namedArgs) \
202-
swift_##name##Impl); \
203-
return swift_##name##Impl COMPATIBILITY_PAREN(namedArgs); \
196+
constexpr uintptr_t DEFAULT_IMPL_SENTINEL = 0x1; \
197+
static std::atomic<uintptr_t> Override; \
198+
uintptr_t fn = Override.load(std::memory_order::memory_order_relaxed); \
199+
if (SWIFT_LIKELY(fn == DEFAULT_IMPL_SENTINEL)) { \
200+
return swift_##name##Impl COMPATIBILITY_PAREN(namedArgs); \
201+
} else if (SWIFT_UNLIKELY(fn == 0x0)) { \
202+
fn = (uintptr_t)getOverride_##name(); \
203+
if (fn == 0x0) { \
204+
Override.store(DEFAULT_IMPL_SENTINEL, \
205+
std::memory_order::memory_order_relaxed); \
206+
return swift_##name##Impl COMPATIBILITY_PAREN(namedArgs); \
207+
} \
208+
Override.store(fn, std::memory_order::memory_order_relaxed); \
209+
} \
210+
return ((Override_##name)fn)(COMPATIBILITY_UNPAREN_WITH_COMMA(namedArgs) \
211+
swift_##name##Impl); \
204212
}
205213

206214
#endif // #else SWIFT_STDLIB_SUPPORT_BACK_DEPLOYMENT

0 commit comments

Comments
 (0)