Why is `rustc_mir_transform::optimized_mir` called twice?

Why is the function rustc_mir_transform::optimized_mir called twice?

To check the number of calls, I inserted the following print statement:

fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
    println!("optimized_mir");
    [...]
}

Result:

$ ./x.py build --stage 1 --keep-stage 1 library
$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc test.rs
optimized_mir
optimized_mir

For completeness, what does test.ts look like?

This is the test.rs I used:

fn foo(_n: i32) {
    let _a = -1;
    let mut _x = 2;
    _x = 5;
    let _y = _x + 3;
    let _z = _x * _y;
    println!("{}", _z);
}

#[allow(dead_code)]
fn bar() {
    let _ = 999;
}

fn main() {
    foo(7);
}

I’ve added some further context into your println

fn optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> &Body<'_> {
    println!("optimized_mir: {:?}", tcx.def_span(did));
    tcx.arena.alloc(inner_optimized_mir(tcx, did))
}

and the result is

optimized_mir: test.rs:15:1: 15:10 (#0)
optimized_mir: test.rs:1:1: 1:16 (#0)

which point to the locations

fn foo(_n: i32) {
^^^^^^^^^^^^^^^ -- here
    let _a = -1;
    let mut _x = 2;
    _x = 5;
    let _y = _x + 3;
    let _z = _x * _y;
    println!("{}", _z);
}

#[allow(dead_code)]
fn bar() {
    let _ = 999;
}

fn main() {
^^^^^^^^^ -- and here
    foo(7);
}

So it looks like the function is called once for foo and once for main.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.