sorting out div/mod routines, bug in simulator
[nmutil.git] / src / nmutil / divmod.py
1 from copy import copy
2 # this is a POWER ISA 3.0B compatible *signed* div function
3 # however it is also the c, c++, rust, java *and* x86 way of doing things
4 def trunc_divs(n, d):
5 abs_n = abs(n.to_signed_int())
6 abs_d = abs(d.to_signed_int())
7 print("trunc_div n", abs_n, n.to_signed_int())
8 print("trunc_div d", abs_d, d.to_signed_int())
9 abs_q = abs_n // abs_d
10 sign_n = n.value & (1 << (n.bits - 1)) != 0
11 sign_d = d.value & (1 << (d.bits - 1)) != 0
12 print ("trunc_div", hex(n.value), hex(d.value),
13 hex(abs_n), hex(abs_d), hex(abs_q),
14 sign_n, sign_d)
15 res = copy(n)
16 if (sign_n == sign_d):
17 res.value = abs_q
18 return res
19 mask = (1 << res.bits) - 1
20 res.value = (-abs_q) & mask
21
22 return res
23
24
25 # this is a POWER ISA 3.0B compatible *signed* mod / remainder function
26 # however it is also the c, c++, rust, java *and* x86 way of doing things
27 def trunc_rems(n, d):
28 m = d * trunc_divs(n, d)
29 m.bits = n.bits # cheat - really shouldn't do this. mul returns full length
30 return n - m
31
32