Skip to content

Reproducible allocation IDs in MIR output with parallel frontend - #166022

Draft
dertin wants to merge 4 commits into
rust-lang:mainfrom
dertin:mir-reproducible-alloc-ids-154278
Draft

dertin wants to merge 4 commits into
rust-lang:mainfrom
dertin:mir-reproducible-alloc-ids-154278

Conversation

@dertin

@dertin dertin commented Nov 16, 2026 •

Copy link
Copy Markdown

View all comments

Fixes #154278

Because the order in which rustc assigns internal allocation IDs can change between runs, compiling the same source again with the same parameters can result in different --emit=mir output when using the parallel frontend.

Allocations are now numbered as the output is written by the MIR printer. Each allocation retains its name throughout the file, including across MIR bodies. The first allocation it prints is called alloc1; the next unique allocation is called alloc2. The compiler keeps using its current internal IDs.

The current dump_mir_cycle test now verifies that two different statics are given different names and that references to a static use the same name as its definition.

I compiled the example from issue #154278 with -Zthreads=60 and --emit=mir 300 times before the fix and 300 times after it. Before the fix, either the static in foo or the one in bar could appear as alloc1, depending on the run. After the fix, all 300 runs produced byte-for-byte identical MIR, which also matched the output from a run with -Zthreads=1

I used an LLM to help me understand MIR output, evaluate possible approaches, assist with parts of the implementation, and generate the tests. I reviewed the changes and test logic, made adjustments, and verified the behavior myself.

@rustbot

rustbot commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri, @RalfJung, @oli-obk, @lcnr

@rustbot rustbot added A-run-make Area: port run-make Makefiles to rmake.rs S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Nov 16, 2026
@rustbot

rustbot commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the pull request, and welcome! The Rust Project has assigned @davidtwco (or someone else) to review your changes, you should hear from them (or someone else) within the next two weeks.

Please see the contribution instructions and our LLM policy for more information.

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler, mir
  • compiler, mir expanded to 79 candidates
  • Random selection from 20 candidates

use rustc_hir_pretty as pprust_hir;
use rustc_hir_pretty::PpAnn;
use rustc_middle::mir::pretty::write_mir_pretty_for_emit;
use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};

@dertin dertin Nov 16, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept the existing write_mir_pretty name to keep the diff smaller. It is used by -Zunpretty=mir and preserves the internal AllocIds without remapping.

Both paths use write_mir_pretty_with_alloc_names:

-Zunpretty=mir calls write_mir_pretty with RawAllocIds. See pretty.rs#L309

--emit=mir calls the new write_mir_pretty_for_emit with AllocationNames.

View changes since the review

@dertin dertin Nov 16, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-Zunpretty=mir:

--emit=mir:

@workingjubilee workingjubilee Nov 21, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is not clear to me why you would have these paths diverge, given that it seems to require making a ton of code generic to uphold this deviation. this seems to make the diff in terms of LOC in the compiler added larger, to... what, exactly? diff less of the test suite? is it really such a huge diff to the test suite?

neither output is part of our stability contract.

@workingjubilee workingjubilee Nov 21, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we were to have this difference in output, it is not clear to me that we would base it off of this, instead of e.g. -Zui-testing.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was unable to see a use case in either output that required the internal allocation IDs of the compiler. To determine whether two references relate to the same allocation and to locate its definition in the MIR, the printed names are sufficient.

There is no need for a -Zui-testing special case because I changed --emit=mir and -Zunpretty=mir to utilize the same printer. We can handle any specific debugging requirements for the internal IDs in a different PR.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These IDs are important when debugging MIR things, where one will add debug output from rustc internals to see IDs in-flight during interpretation.

I don't think it is a good idea for the pretty-printer to do renumbering.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I see why you need the internal AllocIds now. If you see alloc75 in a rustc trace, you want to be able to look up that same alloc75 in the MIR from that run.

As it stands, this PR only renumbers allocations when printing MIR with --emit=mir or -Zunpretty=mir. Both rustc traces and -Zdump-mir dumps still show the internal IDs.

I also checked what happens with the other outputs when compiling the same code again with the parallel frontend:

  • Per-function, per-pass dumps (-Zdump-mir=foo, also with -Zdump-mir-graphviz). These keep the internal IDs, so if you generate the dumps and the trace in the same run, you can look up the same ID in both.
  • MIR control-flow graph (-Zunpretty=mir-cfg). This uses a different printer. With the same flags, I saw the same instruction refer to alloc1 in one run and alloc2 in another. If it’s worth extending the change, this is where I’d start in a follow-up PR.
  • THIR and Stable MIR (-Zunpretty=thir-tree, -Zunpretty=stable-mir). I saw IDs change between runs here too. The former prints a different compiler representation, and the latter uses the rustc_public printer. I’d leave those for separate PRs if there’s a use case for them.

I’d handle diagnostics on stderr separately too. I compiled forbidden_slices.rs four times with the same flags (-Zthreads=60). I got the same error on line 54 each time, but the ID in the message was alloc75, alloc62, alloc51, and alloc64 across the four runs. Renumbering alone could hide a real difference here. For example, if one run fails when writing to static FOO and another fails when writing to static BAR, both errors could end up saying alloc1. For a follow-up, I’d start by looking at whether the diagnostic could name the static being written to and keep the internal ID so you can still find it in the trace.

Do the internal IDs in -Zdump-mir cover your debugging use case, or do you also need them in the full output from --emit=mir or -Zunpretty=mir? If the dumps cover it, we could keep the change as it is. If you need the internal IDs in the full output too, we could keep them by default and make reproducible names opt-in (for example, with -Zmir-reproducible-alloc-ids).

I used AI to help translate this comment from Spanish.

@rust-log-analyzer

This comment has been minimized.

@RalfJung

Copy link
Copy Markdown
Member

I used an LLM to help me understand MIR output, evaluate possible approaches, assist with parts of the implementation, and generate the tests. I reviewed the changes and test logic, made adjustments, and verified the behavior myself.

Have you read our LLM policy? Please do so, it is linked above.

You need to pre-arrange a reviewer before submitting a PR that contains LLM-generated content. I will mark this as a draft since apparently you did not do that.

@RalfJung
RalfJung marked this pull request as draft November 16, 2026 07:27
@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 16, 2026

@workingjubilee workingjubilee left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems unlikely to me that this approach actually needs 600 lines of new code. There is no justification given for why we uphold a divergence between the two outputs except "to keep the diff smaller", but at a glance this seems to need more code than handling these cases uniformly, whereas lines that should be diffed are not. If there's a particular test that shouldn't be diffed in this way, then it is better to identify that as the reason.

View changes since this review

@workingjubilee workingjubilee Nov 21, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason this is a run-make test? it seems to just be doing string matching on MIR, which seems like something that could be done by our existing infra.

in #156716 we added normalization code inside the test suite to handle this for every single affected test. this PR is kind of weird if it doesn't instead fix this to demonstrate that such outside-rustc normalization isn't necessary anymore.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’ve removed the run-make test for now and updated the existing dump_mir_cycle test. It now checks that each reference uses the same ID as the definition of the static it points to, and that two distinct statics have different IDs within the same MIR file.

For my local check, I compiled the example from #154278 once with -Zthreads=1 and used that MIR file as the reference. I then compiled it 300 times with -Zthreads=60. With the change, all 300 files matched the reference byte for byte.

I still see value in comparing MIR across runs, since dump_mir_cycle could pass even if the numbering changed from one compilation to the next. Do you think it’s worth covering that comparison in CI with a run-make test, or would you prefer to keep it as a local check for now?

I used AI to help translate this comment from Spanish.

use rustc_hir_pretty as pprust_hir;
use rustc_hir_pretty::PpAnn;
use rustc_middle::mir::pretty::write_mir_pretty_for_emit;
use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};

@workingjubilee workingjubilee Nov 21, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is not clear to me why you would have these paths diverge, given that it seems to require making a ton of code generic to uphold this deviation. this seems to make the diff in terms of LOC in the compiler added larger, to... what, exactly? diff less of the test suite? is it really such a huge diff to the test suite?

neither output is part of our stability contract.

@oli-obk oli-obk added the llm-assisted An LLM-assisted PR as defined by the LLM policy. Requires ahead-of-time consent by assignee. label Nov 23, 2026

@workingjubilee workingjubilee left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You didn't change the compiletest logic introduced in ‎src/tools/compiletest/src/runtest.rs.

That's what I meant about the diff having additional code but not affecting the things it should.

Removing that compiletest logic may result in a much larger diff to the test suite, yes, but that's what we want to see! We want to see that it's possible to test rustc and get reproducible results with the parallel frontend.

You may need to look at the rustc-dev-guide on testing if you get lost on what next after removing that logic. I suggest doing so for a minute before jumping to the LLM for an answer.

View changes since this review

write!(f, "<imm>")?;
}
Ok(())
Self::fmt_pointer(ptr, f, ptr.provenance.alloc_id())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there's no real reason to have this single-use helper anymore so the code can be moved back into here.

as mentioned, if we need the original prints of the allocation IDs, we can have the difference be handled without diverging handling between --emit=mir and -Zunpretty=mir

@dertin dertin Nov 24, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

--emit=mir and -Zunpretty=mir now use the same printer. I checked fmt_pointer, and it still has two callers. CtfeProvenance::fmt prints the pointer with rustc’s internal allocation ID, and MirFormat prints it with the name the allocation has in the MIR output. I kept fmt_pointer so both share the code that prints the offset and the <imm> marker.

Comment on lines +1 to +46
use std::num::NonZero;

use rustc_abi::Size;

use super::*;

fn id(value: u64) -> AllocId {
AllocId(NonZero::new(value).unwrap())
}

#[test]
fn names_follow_identity_not_internal_numbers() {
for (a, b) in [(100, 20), (20, 100)] {
let ids = RefCell::default();
let names = AllocationNames(Some(&ids));
assert_eq!(
format!("{:?} {:?} {:?}", names.wrap(id(a)), names.wrap(id(b)), names.wrap(id(a))),
"alloc1 alloc2 alloc1"
);
assert_eq!(format!("{:#?}", names.wrap(id(b))), "a2");
}
}

#[test]
fn pointer_offsets_and_provenance_are_preserved() {
let ids = RefCell::default();
let names = AllocationNames(Some(&ids));
let provenance = CtfeProvenance::from(id(100)).as_immutable();
let first = Pointer::new(provenance, Size::from_bytes(4));
let second = Pointer::new(provenance, Size::from_bytes(8));
assert_eq!(format!("{:?}", names.wrap(first)), "alloc1+0x4<imm>");
assert_eq!(format!("{:#?}", names.wrap(second)), "a1+0x8<imm>");
let other = Pointer::new(CtfeProvenance::from(id(20)), Size::ZERO);
assert_eq!(format!("{:?}", names.wrap(other)), "alloc2");
}

#[test]
fn indirect_constants_keep_their_offset() {
let ids = RefCell::default();
let names = AllocationNames(Some(&ids));
let value = ConstValue::Indirect { alloc_id: id(100), offset: Size::from_bytes(4) };
assert_eq!(
format!("{:?}", names.wrap(&value)),
"Indirect { alloc_id: alloc1, offset: Size(4 bytes) }"
);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is another case of "not better than a UI test" afaict?

we want such tests when we can test internal logic, but printing like this is externally visible so it should use the same kind of thing. our UI tests can automatically be updated using --bless

Suggested change
use std::num::NonZero;
use rustc_abi::Size;
use super::*;
fn id(value: u64) -> AllocId {
AllocId(NonZero::new(value).unwrap())
}
#[test]
fn names_follow_identity_not_internal_numbers() {
for (a, b) in [(100, 20), (20, 100)] {
let ids = RefCell::default();
let names = AllocationNames(Some(&ids));
assert_eq!(
format!("{:?} {:?} {:?}", names.wrap(id(a)), names.wrap(id(b)), names.wrap(id(a))),
"alloc1 alloc2 alloc1"
);
assert_eq!(format!("{:#?}", names.wrap(id(b))), "a2");
}
}
#[test]
fn pointer_offsets_and_provenance_are_preserved() {
let ids = RefCell::default();
let names = AllocationNames(Some(&ids));
let provenance = CtfeProvenance::from(id(100)).as_immutable();
let first = Pointer::new(provenance, Size::from_bytes(4));
let second = Pointer::new(provenance, Size::from_bytes(8));
assert_eq!(format!("{:?}", names.wrap(first)), "alloc1+0x4<imm>");
assert_eq!(format!("{:#?}", names.wrap(second)), "a1+0x8<imm>");
let other = Pointer::new(CtfeProvenance::from(id(20)), Size::ZERO);
assert_eq!(format!("{:?}", names.wrap(other)), "alloc2");
}
#[test]
fn indirect_constants_keep_their_offset() {
let ids = RefCell::default();
let names = AllocationNames(Some(&ids));
let value = ConstValue::Indirect { alloc_id: id(100), offset: Size::from_bytes(4) };
assert_eq!(
format!("{:?}", names.wrap(&value)),
"Indirect { alloc_id: alloc1, offset: Size(4 bytes) }"
);
}

@dertin dertin Nov 24, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense. I’ll drop these unit tests and check what rustc actually prints.

I’d like to settle the default before deciding what the test should expect. Should the MIR show reproducible allocation names by default, or should it keep showing rustc’s internal AllocIds and let people opt in to reproducible names with a -Z flag?

For this PR I’m looking at the .mir file from --emit=mir and the MIR that -Zunpretty=mir writes to stdout. Diagnostics on stderr also show allocation IDs. Would you like me to look at those in this PR too, or would you prefer a follow-up?

Comment thread compiler/rustc_middle/src/mir/pretty.rs Resolved
Comment thread compiler/rustc_middle/src/mir/pretty.rs Resolved
@rustbot

rustbot commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@RalfJung

RalfJung commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

You didn't change the compiletest logic introduced in ‎src/tools/compiletest/src/runtest.rs.

Indeed, compiletest already has allocation renumbering.
The PR currently does not explain why that is not enough.

@dertin

dertin commented Nov 24, 2026

Copy link
Copy Markdown
Author

The PR currently does not explain why that is not enough.

I understand that compiletest can already renumber allocation IDs when it compares test output. But #154278 shows up when you compile the same program several times with the parallel frontend and compare the .mir files on disk. I used rustc --emit=mir -Zthreads=60 for my test. In this PR, --emit=mir and -Zunpretty=mir use the same MIR pretty-printer, so the change also applies when rustc writes MIR to stdout. When you run rustc directly, neither output goes through compiletest.

I also tried removing the ALLOC$ID rule, as @workingjubilee suggested. In UI tests, that rule replaces each allocation ID with the same placeholder. If two references used to point to the same allocation and one now points somewhere else, the IDs in the test output still look the same. Removing the rule brought back the earlier behavior: distinct allocations get distinct numbers, but those numbers depend on the order in which the IDs appear in the output.

I saw this in forbidden_slices.rs. The error in R2 says the pointer is four bytes from the end of its allocation, and the one in R8 says it’s seven bytes from the end. With 60 threads, either diagnostic can arrive first, so the four-byte error sometimes showed ALLOC10 and sometimes ALLOC11.

What worked locally for that test was sorting the diagnostics by source location before renumbering the IDs, keeping each error together with its notes. The four-byte error then kept the same number regardless of which diagnostic arrived first. All six runs with 60 threads produced the same normalized stderr as the single-threaded run.

I then tried the change on the 47 existing UI tests affected by #156716, which introduced the ALLOC$ID rule. The full normalized stderr matched between one thread and 60 threads in 45 of them. In the other two, the IDs matched too, but a warning listed the same help messages in a different order. What’s still open for compiletest is how to allow for that difference while still catching a note attached to the wrong error. I tried moving a note to a different error in the expected output, and the comparison that ignores line order still passed. These compiletest changes are local and aren’t in the PR.

Do you think it makes sense to keep this PR focused on making allocation names reproducible across parallel runs, both in .mir files and on stdout, and handle the compiletest work separately?

I used AI to help translate this comment from Spanish.

@rust-bors

This comment has been minimized.

@dertin
dertin force-pushed the mir-reproducible-alloc-ids-154278 branch from a320b6c to 4772a3d Compare November 26, 2026 21:27
@workingjubilee

Copy link
Copy Markdown
Member

@dertin que es en espanol?

@dertin

dertin commented Nov 26, 2026

Copy link
Copy Markdown
Author

@workingjubilee @RalfJung, to bring the different threads together, here are the options I see for moving forward with this PR:

  1. Use reproducible allocation names by default, as the PR does today for --emit=mir and -Zunpretty=mir. Is it enough to look up internal IDs in the -Zdump-mir dumps, or do you need them in the full MIR output too?

  2. Keep internal IDs by default and add a new optional -Z flag for reproducible names. When debugging rustc, you’d still see the same ID in the trace and in the full MIR output. To compare the MIR from two runs with the parallel frontend, you’d enable the flag for both runs.

  3. Add a new optional -Z flag to write a mapping file in mir_dump/. When emitting MIR with reproducible names, you could also ask for the mapping to see which internal AllocId each name corresponds to in that run. Keeping the mapping in a separate file would let you compare the entire .mir file or stdout.

I’d go with option 2 for this PR and consider option 3 in a follow-up. The two could work together if you need to cross-reference reproducible MIR with a trace from the same run. Would that work for you, or would you prefer another approach?

On compiletest, would you like me to change the rule that replaces distinct IDs with ALLOC$ID in UI tests as part of this PR, or handle it in a separate PR? Changing compiletest alone wouldn’t fix #154278. The issue shows up when you run rustc --emit=mir -Zthreads=60 several times with the same flags and compare the .mir files on disk. Those runs don’t go through compiletest.

@dertin

dertin commented Nov 26, 2026 •

Copy link
Copy Markdown
Author

@dertin que es en espanol?

@workingjubilee, escribo mis comentarios primero en español. Las ideas y propuestas son mías. Uso ChatGPT para expresarlas en inglés porque me cuesta escribir en inglés. Disculpá si eso generó confusión.

La única persona de acá que conozco que habla español es @spastorino. que lo he cruzado en alguna meetup. Podemos seguir en inglés, sin problema.


@workingjubilee, I write my comments in Spanish first. The ideas and proposals are mine. I use ChatGPT to express them in English because writing in English is harder for me. Sorry if that caused any confusion.

The only person I know here who speaks Spanish is @spastorino. I’ve run into him at a meetup. We can keep going in English, no problem

@workingjubilee

Copy link
Copy Markdown
Member

...original en espanol tambien contiene gran Markdown?

There is a tendency when people ask for an LLM-based translation to also say, "Please fix a few sentences and make it sound nicer". Sometimes, a model "helpfully" volunteers this edit. This is why the LLM policy suggests presenting the original text alongside the offered translation. Text "upgraded" by LLMs in this manner looks impressive at a glance but is more tedious to actually read.

I have carefully held this comment for many minutes, rereading this entire thread, and revising it repeatedly to keep it short and easy to read, without repeating anything I have already said, yet still saying everything I want to say.

@rust-bors

rust-bors Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

☔ The latest upstream changes (presumably #166674) made this pull request unmergeable. Please resolve the merge conflicts by rebasing.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-run-make Area: port run-make Makefiles to rmake.rs llm-assisted An LLM-assisted PR as defined by the LLM policy. Requires ahead-of-time consent by assignee. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

parallel: --emit=mir not reproducible (alloc ids)

7 participants