Skip to content

Commit

Permalink
Rollup merge of rust-lang#69126 - RalfJung:exact-div, r=oli-obk
Browse files Browse the repository at this point in the history
miri: fix exact_div

Turns out `exact_div` was relying on the broken behavior of `Rem` for `int_min % -1` that was fixed in rust-lang#69002. This PR fixes `exact_div`.

Inside rustc, `exact_div` is only used in a single place where the divisor is always positive (in `ptr_offset_from`), so we cannot test the fix in rustc. The Miri test suite covers this through the `exact_div` intrinsic, though (and it is how I found out).

One step to rust-lang#69117 (then we also need to address build failures introduced by rust-lang#68969)

r? @oli-obk
  • Loading branch information
Dylan-DPC authored Feb 13, 2020
2 parents 8e2772c + 10f342a commit c8343b8
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/librustc_mir/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,8 +384,9 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
) -> InterpResult<'tcx> {
// Performs an exact division, resulting in undefined behavior where
// `x % y != 0` or `y == 0` or `x == T::min_value() && y == -1`.
// First, check x % y != 0.
if self.binary_op(BinOp::Rem, a, b)?.to_bits()? != 0 {
// First, check x % y != 0 (or if that computation overflows).
let (res, overflow, _ty) = self.overflowing_binary_op(BinOp::Rem, a, b)?;
if overflow || res.to_bits(a.layout.size)? != 0 {
// Then, check if `b` is -1, which is the "min_value / -1" case.
let minus1 = Scalar::from_int(-1, dest.layout.size);
let b_scalar = b.to_scalar().unwrap();
Expand All @@ -395,6 +396,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
throw_ub_format!("exact_div: {} cannot be divided by {} without remainder", a, b,)
}
}
// `Rem` says this is all right, so we can let `Div` do its job.
self.binop_ignore_overflow(BinOp::Div, a, b, dest)
}
}

0 comments on commit c8343b8

Please sign in to comment.