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-12427] Pointer stored in C union loses pointee storage when optimised #54866

Closed
swift-ci opened this issue Mar 27, 2020 · 3 comments
Closed
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself

Comments

@swift-ci
Copy link
Collaborator

Previous ID SR-12427
Radar rdar://problem/60983997
Original Reporter nrbrook (JIRA User)
Type Bug
Status Resolved
Resolution Done

Attachment: Download

Environment

Xcode Version 11.4 (11E146), macOS 10.15.4

Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 8c20184c1e5d46cc15863bed3d2ef704

Issue Description:

The attached project demonstrates the issue.

With optimisation enabled, obtaining a pointer using withUnsafePointer and storing the pointer in a union inside a struct which is passed as a pointer to a C function causes the original struct instance to be deallocated before it is used in the C function.

When run without optimisation (debug scheme) the program runs correctly (prints 1, 2, 3). When run with optimisation (release scheme), `str` is released early and the memory read inside the C function is invalid (prints 0, 0, 0). Uncommenting the print statement causes the struct instance to be retained even when optimised.

@CodaFi
Copy link
Member

CodaFi commented Mar 27, 2020

Thanks for the reproducer project, it's just fantastic. It seems like the optimizer is ignoring that taking the address of the temporary counts as a non-removable use and is just erasing everything. In fact, the IR in release just shows everything got inlined into `main` and we're just passing a freshly alloca'd value to your function in C.

Attaching debug and release IR.

@swift-ci create

@swift-ci
Copy link
Collaborator Author

Comment by Nick Brook (JIRA)

Good to know it is a bug and I'm not just misusing swift! For anyone suffering from this until a fix is released, it can be worked around using withExtendedLifetime on the s variable

@eeckstein
Copy link
Member

fixed in #30770

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself
Projects
None yet
Development

No branches or pull requests

3 participants