Rust removes overflow checks when optimization enabled

why does optimization removes overflow checks?
consider below testcase

$cat test.rs
fn fibonacci(n: u32) -> u32 {
    let mut f:u32 = 0;
    let mut s:u32 = 1;
    let mut next: u32 =f+s;    
    for _ in 1..n {
                f = s;
                s= next;
               next=f+s;
    }
    next
}

fn main() {
    println!("{}",fibonacci(100));
}
$rustc test.rs -C opt-level=1
$./test
2425370821

$rustc test.rs -C opt-level=0
$./test
thread 'main' panicked at 'attempt to add with overflow', p11.rs:11:7
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

Basically because no one has found a way to make it fast, and the consequences of overflow are more benign than would be e.g. those of removing array bound checks (panic or logical stupidity vs undefined behavior).

1 Like

You can have your overflow checks with optimization.

Add this to your Cargo.toml

[profile.release]
overflow-checks = true

And build with cargo.

I guess there is a rustc command line option to do the same, I have no idea what it is.

In my limited tests switching on overflow checks had a 15% performance hit. That was for an FFT that is doing a lot of maths using fixed point arithmetic. I wanted overflow flow checks enabled to be sure my fixed point maths was not blowing up.

6 Likes