Comment by anonymoushn
2 years ago
This sort of thing is why integer division by 0 is UB in rust on targets where it's not UB, because it's UB in LLVM :)
2 years ago
This sort of thing is why integer division by 0 is UB in rust on targets where it's not UB, because it's UB in LLVM :)
I stared at this really hard, and I eventually couldn't figure out what you mean here.
Obviously naively just dividing integers by zero in Rust will panic, because that's what is defined to happen.
So you have to be thinking about a specific case where it's defined not to panic. But, what case? There isn't an unchecked_div defined on the integers. The wrapping and saturating variants panic for division by zero, as do the various edge cases like div_floor
What case are you thinking of where "integer division by 0 is UB in Rust" ?
The poster is both correct and incorrect. It definitely is true that LLVM only has two instructions to deal with division, udiv and sdiv specifically, and it used to be the case that Rust as a consequence had UB when encountering division by zero as a result as those two instructions consider that operation UB.
But Rust has solved this problem by inserting a check before every division that reasonably could get a division by zero (might even be all operations, I don't know the specifics), which checks for zero and defines the consequences.
So as a result divisions aren't just divisions in Rust, they come with an additional check as overhead, but they aren't UB either.
Oh, I see, yes obviously if you know your value isn't zero, that's what the NonZero types are for, and these of course don't emit a check because it's unnecessary.
3 replies →