• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


29 Nov, 2024

Updated at 14 Dec, 2024

How to generate the `DIV` assembly instruction?

I want to do exactly what the x86-64 DIV instruction does: calculate (a / b, a % b) where a is u128, b is u64 and I know that the quotient a / b fits in u64:

pub fn div_mod(a: u128, b: u64) -> (u64, u64) {
    let b = u128::from(b);
    assert!(b != 0 && a < b << 64);
    ((a / b) as u64, (a % b) as u64)
}

So this could generate the DIV instruction that calculates both, but it doesn't : it instead calls into a software u128 by u128 division function (__udivti3) to calculate q = a / b and then calculates the modulo by a - q * b (compiler explorer), which is much more work.

  1. Is there a reason this doesn't optimize to DIV?
  2. Even if it doesn't realize it can do DIV, shouldn't there be a software u128 / u64 function which, while still more work than DIV (because the quotient is u128 rather than u64), is a lot simpler than calculating u128 / u128?
  3. Is there an intrinsic I can use to call DIV?

6 posts - 4 participants

Read full topic