Skip to content
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

[SR-13570] UnsafeMutable*Pointer should stack-promote allocations (like malloc) #56008

Open
belkadan opened this issue Sep 19, 2020 · 1 comment
Labels
compiler The Swift compiler in itself improvement

Comments

@belkadan
Copy link
Contributor

Previous ID SR-13570
Radar rdar://problem/69235379
Original Reporter @belkadan
Type Improvement
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Improvement
Assignee None
Priority Medium

md5: a4eed787067b0f855cb1ab8cd8082a29

relates to:

  • SR-6477 UnsafeBufferPointer should have a stack allocating version (or at least a conditional stack allocation)

Issue Description:

LLVM promotes malloc/free pairs to stack allocations if it can see that the free happens on all paths. The same should happen for UnsafeMutable*Pointer.allocate, as in this code:

public protocol SizedInBytes {
    associatedtype ByteStorage
}

@propertyWrapper
public struct Unaligned<Value: SizedInBytes> {
    private var storage: Value.ByteStorage

    public init(wrappedValue: Value) {
        precondition(MemoryLayout<Value.ByteStorage>.size == MemoryLayout<Value>.size, "byte storage has a different size")
        precondition(MemoryLayout<Value.ByteStorage>.alignment == 1, "byte storage must have byte alignment")
        self.storage = withUnsafeBytes(of: wrappedValue) {
            $0.load(as: Value.ByteStorage.self)
        }
    }

    public var wrappedValue: Value {
        get {
            // This allocation should get stack-promoted but doesn't.
            let result = UnsafeMutablePointer<Value>.allocate(capacity: 1)
            defer { result.deinitialize(count: 1); result.deallocate() }
            result.withMemoryRebound(to: Value.ByteStorage.self, capacity: 1) {
                $0.initialize(to: self.storage)
            }
            return result.pointee
        }
        set {
            self = .init(wrappedValue: newValue)
        }
    }
}

extension Int32: SizedInBytes {
    public typealias ByteStorage = (UInt8, UInt8, UInt8, UInt8)
}

public struct Test {
    @Unaligned public var x: Int32 = 0
}
@typesanitizer
Copy link

@swift-ci create

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
compiler The Swift compiler in itself improvement
Projects
None yet
Development

No branches or pull requests

2 participants