Intel supports the carry and overflow flags. It's nearly free to detect wrapping.
Even if they didn't, modern CPU performance is dictated by memory latency. Any extra computation that doesn't do extra fetches is close to free.
Conversation
That's not the kind of hardware support I'm talking about. You can enable overflow checking and see for yourself that it has a significant performance and code size cost despite using the available intrinsics / hardware support.
1
Having overflow checks for all arithmetic operation blocks many other optimizations which hurts much more in idiomatic Rust than C. Branches and larger code size hurt overall performance by wasting global resources. The bounds checks are already expensive but not quite as bad.
1
The decision involved a lot of people reviewing potential compromises and data on performance. It was a frequent topic and the unfortunate reality is the current compiler and hardware support is very inadequate for the performance tier Rust wants to compete in by default.
1
Unfortunate indeed. I hope feedback has been given to hardware vendors. Thanks for the explanation!
1
MIPS has trapping versions of the arithmetic instructions so it avoids extra code size but that would likely still have a fair bit of overhead in a modern CPU and the compiler would still miss optimizations. A lot of work needs to be done to eliminate the overhead.
2
Maybe the RISC-V community would be open for suggestions. Also, would you happen to have pointers to the performance analysis that has been done? Just out of curiosity.
1
It's spread out over a lot of threads, issues, etc. and it was a couple years ago so I don't have links handy. The overhead at the hardware level ends up being 3-10% in most cases, but missed optimizations like loop unrolling, vectorization, etc. can make it far larger.
1
I haven't read huonw.github.io/blog/2016/04/m for a long time but I think it's probably a good overview.
1
1
Integer overflows are also much more dangerous in C (and unsafe Rust) where it instantly turns into a buffer overflow vs. normal Rust code where that can't happen. It makes it harder to justify a significant cost (i.e. in the ballpark of 10%, but varying a huge amount).
1
Logic errors involving integer overflow are definitely a problem, but not quite the same as pervasive heap overflows, etc. caused by them. That part is at least contained to unsafe code in Rust. Lots of that is for data structures where int overflow -> heap overflow is common.
Google adopted -fsanitize=integer -fsanitize-trap=integer for hardening C and C++ code in Android and the performance cost is definitely constraining / guiding their usage. That's a bit lighter than the checks in Rust since there's no unique error and it doesn't unwind.
1
Microsoft started using a SafeInt class internally for their C++ code, which detects overflow. They just paid the performance price.

