Move coroutine upvars into locals for better memory economy#135527
Move coroutine upvars into locals for better memory economy#135527dingxiangfei2009 wants to merge 2 commits intorust-lang:mainfrom
Conversation
|
Some changes occurred in compiler/rustc_codegen_cranelift cc @bjorn3 Some changes occurred to the CTFE / Miri interpreter cc @rust-lang/miri Some changes occurred to MIR optimizations cc @rust-lang/wg-mir-opt Some changes occurred to the CTFE machinery cc @rust-lang/wg-const-eval |
This comment has been minimized.
This comment has been minimized.
|
☔ The latest upstream changes (presumably #135715) made this pull request unmergeable. Please resolve the merge conflicts. |
|
I don't think this needs a reviewer? |
3e6a399 to
9603ad6
Compare
|
cc @Darksonn @tmandry @eholk @rust-lang/wg-async Ding here is reworking the layout of coroutines to try to reduce their memory footprint (and that of What do people think? |
This comment has been minimized.
This comment has been minimized.
|
For anyone searching for a description of what this PR changes, it's summarized at the top of compiler/rustc_mir_transform/src/coroutine/relocate_upvars.rs. |
| //! The reason is that it is possible that coroutine layout may change and the source memory location of | ||
| //! an upvar may not necessarily be mapped exactly to the same place as in the `Unresumed` state. |
There was a problem hiding this comment.
Don't we decide the offsets of upvars in Unresumed in the same place as we decide the offset of saved locals? Couldn't we then "backpropagate" the field offsets for each upvar's local as the offset for the corresponding upvar?
There was a problem hiding this comment.
Thank you for reviewing! I had a backlog of things due to sickness.
True indeed. This statement is completely voided by the work in the second commit. I will reword this section in the following way.
By enabling the feature gate coroutine_new_layout the field offsets of the upvars in Unresumed state are further exactly placed in the same place as their corresponding saved locals, which is guaranteed by the alternative coroutine layout calculator that enters in effect. <... quote the relevant comment/file/etc. ...>
|
I don't personally have any means of performance testing this at the moment. It would be much easier if it landed behind a feature gate. |
|
☔ The latest upstream changes (presumably #135318) made this pull request unmergeable. Please resolve the merge conflicts. |
|
Cc @arielb1 who was also investigated this
…On Wed, Jan 29, 2025, at 7:56 PM, Tyler Mandry wrote:
***@***.**** commented on this pull request.
In compiler/rustc_mir_transform/src/coroutine/relocate_upvars.rs <#135527 (comment)>:
> +//! The reason is that it is possible that coroutine layout may change and the source memory location of
+//! an upvar may not necessarily be mapped exactly to the same place as in the `Unresumed` state.
Don't we decide the offsets of upvars in `Unresumed` in the same place as we decide the offset of saved locals? Couldn't we then "backpropagate" the field offsets for each upvar's local as the offset for the corresponding upvar?
—
Reply to this email directly, view it on GitHub <#135527 (review)>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AABF4ZTFDPQDUNGH5L6MGSL2NF2CHAVCNFSM6AAAAABVG4UUZ2VHI2DSMVQWIX3LMV43YUDVNRWFEZLROVSXG5CSMV3GSZLXHMZDKOBSGY4TKMZUHA>.
You are receiving this because you are on a team that was mentioned.Message ID: ***@***.***>
|
I think it is fair to land with a feature gate so that we can get to play with it. The PR has temporarily disabled the check on the feature gate. However, given that coroutine layout data is keyed individually by their |
9603ad6 to
3a1e04a
Compare
This comment has been minimized.
This comment has been minimized.
3a1e04a to
61d4bbd
Compare
This comment has been minimized.
This comment has been minimized.
Would this be better as a |
|
Are there any issues if only one crate activates it but others do not? if there are no issues, a feature gate seems ok (and easier to use ^^) |
|
☔ The latest upstream changes (presumably #137030) made this pull request unmergeable. Please resolve the merge conflicts. |
|
A feature doesn't allow turning it on for the whole build, you'd have to fork every single crate that uses async. A -Z flag would be better IMO. |
|
Agreed on a If my understanding is correct, we shouldn't expect any regression from this approach (only upside), but since we currently rely on later passes eliding copies there might be some regression. We could be more aggressive in eliding the copies ourselves, but maybe this is hard. |
|
Thanks for looking into this! I will have time this week to clean this up a bit and I will ask rustbot to set it to ready-for-review. |
61d4bbd to
0ff7e65
Compare
|
Some changes occurred in compiler/rustc_codegen_ssa |
|
Replying to @ywxt
I posted a patch to fix it up. It is still not perfect because it does not report prefix alignment value. And good catch on the mysterious padding! @ywxt posted an example where prefix alignment can lead to unnecessary padding. To quote: async fn bar1(_: [u32; 3] ) {}
async fn bar2(_: [u8; 2]) {}
let a = [1, 2];
let b = [1, 2, 3,];
let c = async move {
bar2(a).await;
bar1(b).await;
};With or without
Now the fix is apparently set the prefix alignment to For this matter, is there anyone who can approve or reject my suggestion? |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Is it possible to make the discriminant postposed to the last so that we can remove paddings? |
fn main() {
struct Pointer{
p: Box<i32>,
}
async fn inc(pointer: &mut Pointer) {
*pointer.p += 1;
}
async fn task(mut pointer: Pointer) {
inc(&mut pointer).await;
inc(&mut pointer).await;
}
let pointer = Pointer { p: Box::new(0) };
let task = task(pointer);
println!("size of future: {}", std::mem::size_of_val(&task));
}I think we can eliminate paddings in |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
Replying to @ywxt
Yes, I agree. To the extreme we could even slot it in some padding location in the middle, in case some types demand big alignment and leave a huge gap in between. I would like to land the current patch as-is. This enhancement can go with a second packing scheme that actually depends on this. |
|
Oh can anyone explain why this is considered a trait system refactor? This PR does not affect trait solver at all. 😕 |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This function hints at an early commitment to coroutine memory layout. We should not give promises on how upvars are allocated. Signed-off-by: Xiangfei Ding <dingxiangfei2009@protonmail.ch>
... and treat coroutine upvar captures as saved locals as well. This allows the liveness analysis to determine which captures are truly saved across a yield point and which are initially used but discarded at first yield points. In the event that upvar captures are promoted, most certainly because a coroutine suspends at least once, the slots in the promotion prefix shall be reused. This means that the copies emitted in the upvar relocation MIR pass will eventually elided and eliminated in the codegen phase, hence no additional runtime cost is realised. Additional MIR dumps are inserted so that it is easier to inspect the bodies of async closures, including those that captures the state by-value. Debug information is updated to point at the correct location for upvars in borrow checking errors and final debuginfo. A language change that this patch enables is now actually reverted, so that lifetimes on relocated upvars are invariant with the upvars outside of the coroutine body. We are deferring the language change to a later discussion. Co-authored-by: Dario Nieuwenhuis <dirbaio@dirbaio.net> Signed-off-by: Xiangfei Ding <dingxiangfei2009@protonmail.ch>
|
This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed. Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers. |
|
☔ The latest upstream changes (presumably #151842) made this pull request unmergeable. Please resolve the merge conflicts. |
|
Sorry, Anyone can explain what's the status of this pr right now? |
|
I will be actively maintaining it, but I do not know anyone who can make the decision for go/no-go. cc @traviscross what should we do about it? Do we still need more reviews? Who else can give us the verdict? |
|
If there are concerns that would trigger immediate regressions in correctness, regressions in MIR semantics or regressions in performance with major async crates, we should fix it in this PR and I will be in charge. If there are only minor concerns such as technicality, we could resolve it progressively in the later patch series. I will take the responsibility for further improvements. This PR has unfortunately turned into a head-of-line block on a few other works at the moment. I hope the situation could be improved. |
|
Looking at the history, we had signaled lang approval for this to land under a nightly feature flag, and we had said that to later stabilize this would need lang FCP. Do you want to land this under a feature flag, or would you prefer to propose stabilization at this point? If the latter, then please draft a summary of what's happened and changed over the course of this long thread, and please ensure that the PR description is the complete stabilization report you want the lang team to review, and then we'll nominate and discuss this for stabilization. Have a look at the dev guide stabilization report template. The checklist items regarding test coverage and implementation maturity might be helpful in this case. Beyond everyone on lang feeling comfortable, it will of course need someone on compiler to r+ it, and these items would likely be helpful there. |
|
@traviscross thanks for weighing in. I should be clearer. I would still prefer to land it behind the nightly compiler flag There are interested parties who would like to try out the flag on nightly first because the build system does not really allow building a custom |
|
Thanks for your explanation! @traviscross @dingxiangfei2009 Landing on nightly first is absolutely an appropriate way to enables the current solution to be widely validated. I was wondering if there’s a way we could help move this PR forward more smoothly, as it’s been ongoing for a while now (including the previous PRs). |
|
@traviscross I have updated the PR front cover on how test coverage has been. One question is, should we also update the dev-guide? Anyway, I will try... r? compiler |
View all comments
Replace #127522
Related to #62958
The problem statement
#62958 demonstrates two problems. One is that upvars are always unconditionally promoted to prefix data fields of the state machine; the other is that the opportunity to achieve a more compact data layout is lost because captured upvars are not subjected to liveness analysis, in the sense that the memory space at one point occupied by upvars is never reclaimed and made available for other saved data across certain yield points, even when they are dead at those suspension locations.
The second problem is better demonstrated with this code snippet.
The difficulty lies with the fact that captured upvars do not receive their own locals inside a coroutine body. If we can assign locals to them somehow, we can run the layout scheme as usual and the optimisation on the data layout comes into effect out of the box in most cases.
Proposed changes
This is an initial work to improve memory economy of coroutine and
asyncfutures, by reducing the unnecessary of promotion of captured upvars into state prefix. In a nutshell, this patch works along the idea in this comment and this comment.The patch contains the following changes.
RelocateUpvarMIR pass that inserts a MIR gadget, through which captured values by coroutine orasyncbodies or closures are moved into the inner MIR locals. This opens opportunities to subject the captured upvars to the same liveness analysis right before theStateTransformrewrites and determine which are the necessary ones to be stored in the coroutine state during suspension.prefixdata regions of coroutine states. Instead, they are moved into theUnresumedstate, or by convention the first variants of the state ADTs.prefixafter all, we further arrange the coroutine state data layout, so that their offsets in theUnresumedstate coincide with their memory slots after promotion. This means that during codegen, the additional moves introduced by theRelocateUpvargadget are actually elided. The relevant change is implemented inrustc_abi.Unresumedvariant.-Z pack-coroutine-layout=captures-only. The default ispack-coroutine-layout=no, so that we keep the layout aligned with the stable.Other than upvars, the coroutine state data layout scheme remains largely the same.
Test coverage
We have added the following tests.
run-passtests, which switch on this new layout calculation.Further optimisation to be implemented behind a feature gate
Point 4 mentions that any local to be saved across suspensions will be promoted whenever they are alive across two or more yield locations. We would like to run an experiment behind a feature gate on improvements of the layout scheme. For ease of reviewing, it is better to drop this part of work from this PR. Nevertheless, the idea runs along the implementation in #127522 and we intend to propose a second PR just for that.
Old PR description
Good day, this PR is related to #127522 and it is made easier to the public to test out a new coroutine/`async` state machine directly.Prepare the compiler for tests
For starter, you may build the compiler as prescribed in the
rustc-dev-guideinstruction. If a test in the docker container is desirable, you may build this compiler withsrc/ci/docker/run.sh dist-x86_64-linux --devforx86_64and package the compiler with../x distto produce the artifacts inobj/dist-x86_64-linux/build/dist. This Dockerfile gets you a working Rust builder image which allows you to build your Rust applications inbookworm.The state of performance
So far with this patch, I have been studying the performance impact on the cases of
tokio's single- and multi-threaded runtime, as well as a simpleaxumHTTP service. As far as I can see, I can find a change in performance characteristics that are statistically significant, one-sidedp = 0.05.This time, I would like to call for pooling in your valuable assessments and thoughts on this patch. I kindly request experiments from you and hopefully you can provide regression cases with
perf record -e cycles:u,instructions:u,cache-misses:ureports.Thank you all so much! 🙇