/// DIVU's internal clocks, from the microcode's shift-and-subtract loop. /// /// The manual gives only a maximum (UM Table 8-4). The loop: overflow is /// detected first; otherwise 15 steps each shift the dividend left, and a /// step whose shifted-out bit was 0 costs 2 more clocks, less 1 if the /// trial subtraction succeeded. Jorge Cwik's analysis (2005, carried in /// WinUAE, T2) states the same count; SST DIVU checks it on every case (T3). pub fn divide_unsigned_clocks(dividend: u32, divisor: u32) -> u32 { if dividend >> 16 >= divisor { return 10; } let mut dividend = u64::from(dividend); let mut half_clocks = 38; let shifted_divisor = u64::from(divisor) << 16; for _ in 0..15 { let carry = dividend & 0x8000_0000; dividend = (dividend << 1) & 0xFFFF_FFFF; if carry != 0 { dividend = dividend.wrapping_sub(shifted_divisor) & 0xFFFF_FFFF; } else { half_clocks += 2; if dividend >= shifted_divisor { dividend -= shifted_divisor; half_clocks -= 1; } } } half_clocks * 2 } /// DIVS's internal clocks: sign handling, then one step per quotient bit. /// /// `dividend` and `divisor` are signed. Absolute overflow /// (`|dividend| >> 16 >= |divisor|`) is found early; otherwise the unsigned loop runs on the /// magnitudes and each of the 15 high quotient bits that is 0 costs 2 /// clocks (Cwik 2005, T2; checked against the corpus, T3). pub fn divide_signed_clocks(dividend: i64, divisor: i64) -> u32 { let mut half_clocks: i64 = 6; if dividend < 0 { half_clocks += 1; } if dividend.abs() >> 16 >= divisor.abs() { return ((half_clocks + 2) * 2) as u32; } let quotient = dividend.abs() / divisor.abs(); half_clocks += 55; if divisor >= 0 { half_clocks += if dividend >= 0 { -1 } else { 1 }; } for bit in 0..15 { if quotient & (0x8000 >> bit) == 0 { half_clocks += 1; } } (half_clocks * 2) as u32 }