You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Bound check for multiplication in for loops #81237
Bound checking happens when I using x + y * HEIGHT formula to
calculate the coordinate in an array. The generated code is
saved on Godbolt: https://rust.godbolt.org/z/76qEhK.
I tried this code:
constWIDTH:usize = 64;constHEIGHT:usize = 32;constDISPLAY_SIZE:usize = WIDTH*HEIGHT;pubstructDisplay([u8;DISPLAY_SIZE]);implDisplay{pubfndraw(&mutself,(x, y):(u8,u8)) -> bool{letmut collision = false;let(x, y) = (usize::from(x) % WIDTH, usize::from(y) % HEIGHT);for y in y..HEIGHT{let coord = x + y *WIDTH;
collision |= self.0[coord] != 0;}
collision
}}
I expected to see this happen: No bound checks in generated code.
Instead, this happened: There are bound checks.
Note that bound checks doesn't happen if I don't use for loop and just use a immutable y value.
For a more fair comparison you can add the array update in the C code too, to make the two Rust/C versions as close as possible.
The problem for bound checks in Rust is that the compiler couldn't prove that x + y*WIDTH < DISPLAY_SIZE,
while clang/gcc can do that. This godbolt link demonstrates the issue fairer: https://rust.godbolt.org/z/soE8d3
Activity
tesuji commentedon Jan 21, 2021
The code in C with both gcc and clang optimized well but not in Rust ? https://rust.godbolt.org/z/voMWdc.
The code in C:
Gcc and clang just straights to generate
return truefordrawfunction.tesuji commentedon Jan 21, 2021
Comparing llvm-ir outputs between clang and rust: https://rust.godbolt.org/z/soE8d3.
Somehow clang (front-end) just generates
ret i1 true.I wonder if implement the same optimization pass in MIR
@rustbot label A-mir-opt
leonardo-m commentedon Jan 21, 2021
For a more fair comparison you can add the array update in the C code too, to make the two Rust/C versions as close as possible.
leonardo-m commentedon Jan 21, 2021
Something like this (untested):
tesuji commentedon Jan 21, 2021
The problem for bound checks in Rust is that the compiler couldn't prove that
x + y*WIDTH < DISPLAY_SIZE,while clang/gcc can do that. This godbolt link demonstrates the issue fairer: https://rust.godbolt.org/z/soE8d3
oli-obk commentedon Jan 21, 2021
cc @felix91gr I guess this is a good test case for value range analysis on MIR?
felix91gr commentedon Jan 21, 2021
@oli-obk definitely!
... hmm, I'll open an issue on this. We'd better start listing the use, test and edge cases we notice :)
tesuji commentedon Apr 28, 2024
Updating to LLVM 15 in Rust 1.65 fixed the issue: https://rust.godbolt.org/z/55GoEW5df