-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Unnecessary memcpy when returning a struct #57077
Comments
Removing this kind of memcpy is generally the job of call slot optimization. I believe in this case it will fail because Not totally sure whether that restriction needs to apply if the destination is an alloca, as we're just changing one alloca for another. |
Yeah, I think that as-is LLVM is not permitted to optimize away that memcpy. SomeExternFun() func may capture the pointer and println captures the pointer and together they could observe whether or not that memcpy has been optimized away. UItimately the really issue here is the println, which captures the pointer and prevents SROA from working. See #50519 (comment). If you write |
Unfortunately, this is not a solution when we need to pass a pointer again - for example, replacing |
@MSxDOS I'm not totally certain, but I think it's not legal to optimize the memcpy away in this case. Assuming you have code like this:
Then Maybe someone (@rkruppe or @RalfJung?) could comment on whether the result of that pointer comparison might be unspecified behavior? I'm pretty sure it's well defined under LLVM semantics (making elision of this memcpy illegal for LLVM), but possibly in rustc we could have relaxed rules (something akin to RVO)? |
The pointer passed to Cc @eddyb |
Is |
I think this is directly related to the unnecessary memcpy when using You can do unsafe {
let mut fast_box: Box<T> = Box::new(std::mem::uninitialized());
(fast_box.as_mut() as *mut T).write(/* stuff */);
} to write directly to the allocation as when using |
This will probably be solved by #47954 (which will hopefully get revived in the next few months). |
The first example was fixed by #72205 🎉 #57077 (comment) - this still copies stuff. https://rust.godbolt.org/z/PGCmf7 - here |
Fixed on the latest nightly, presumably by #82806 |
Any cases left that still don't optimize, or can we close this? |
This one is still there, but I'm no longer sure it's even related. If not then we can happily close this. |
@MSxDOS Don't think that one is really related. A slightly better example would be https://rust.godbolt.org/z/rxKG4c which uses |
The example was based on code that's used to feed GUIDs to extern functions in Closing this as fixed. |
Returning a newly created struct from a function causes an unnecessary memcpy even if the function is inlined:
Playground
The text was updated successfully, but these errors were encountered: