I'm currently trying to compile some trivial Swift code for bare metal. It utilizes uSwift instead of the standard library, in an attempt to avoid dynamic allocations and expensive calls to Swift runtime. I was hoping I could use UnsafePointer
and other pointer types to bootstrap MMU and eventually get some allocator working on bare metal, unblocking more Swift runtime features for use farther down the line. Unfortunately, looks like use of UnsafePointer
still requires metadata lookups.
Consider this code in StaticString
:
/// A pointer to a null-terminated sequence of UTF-8 code units.
///
/// - Important: Accessing this property when `hasPointerRepresentation` is
/// `false` triggers a runtime error.
@_transparent
public var utf8Start: UnsafePointer<UInt8> {
_precondition(
hasPointerRepresentation,
"StaticString should have pointer representation")
return UnsafePointer(bitPattern: UInt(_startPtrOrData))!
}
Apparently, this property requires metadata lookups to call generic UnsafePointer<UInt8>(bitPattern:)
. I was hoping this call would be specialized, but that doesn't happen for some reason. Generated code adds references to swift_getTypeByMangledNameInContextInMetadataState
and swift_getWitnessTable
symbols. Adding @inlinable @inline(__always)
to the declaration of this initializer doesn't help. I also tried adding @_specialize(exported: true, kind: full, where Pointee == UInt8)
, but apparently it can only be applied to generic functions, and this initializer isn't generic by itself.
Is there any other way to monomorphize/specialize this call to UnsafePointer(bitPattern:)
at compile-time, so that metadata lookups were eliminated, supposedly by the optimizer? The actual need for utf8Start
is irrelevant, I'm interested in a more general question of specializing certain generic functions when using pointer types in Swift. I'm currently not interested in using other generic types, and was hoping that pointer types were low-level enough to be usable on bare metal straight away.
For anyone interested in the actual linker error messages, I shared those on the corresponding uSwift GitHub PR.