Hi,
When playing with some of my code on compiler explorer, I found a case where rust would not compute the result of some functions at compile time. I managed to reduce the code to the following:
pub fn test() -> i32 {
let mut s = 0;
for i in 0..102 {
if i == 0 {
s = i;
}
s += 1;
}
s
}
pub fn test2() -> i32 {
let mut s = 0;
for i in 0..101 {
if i == 0 {
s = i;
}
s += 1;
}
s
}
pub fn test3() -> i32 {
let mut s = 0;
for _ in 0..102 {
s += 1;
}
s
}
compiler explorer link
Both test2 and test3 are completely optimized and are compiled down to a singled "mov constant + ret" combo. But the test function generates something quite convoluted: the compiler loads the result (102) and removes 6 from it until it reaches 0, at which point it returns the value of another register to which 6s have been added at each step.
I tried a few versions of rustc but couldn't find any which completely optimized away the first function. Using mir-opt-level didn't help.
Hi,
When playing with some of my code on compiler explorer, I found a case where rust would not compute the result of some functions at compile time. I managed to reduce the code to the following:
compiler explorer link
Both
test2andtest3are completely optimized and are compiled down to a singled "mov constant + ret" combo. But thetestfunction generates something quite convoluted: the compiler loads the result (102) and removes6from it until it reaches0, at which point it returns the value of another register to which6s have been added at each step.I tried a few versions of rustc but couldn't find any which completely optimized away the first function. Using
mir-opt-leveldidn't help.