| 1 |
from rpython.rlib.rarithmetic import LONG_BIT, intmask, r_uint, \ |
| 2 |
uint_mul_high |
| 3 |
|
| 4 |
|
| 5 |
from rpython.jit.metainterp.history import ConstInt |
| 6 |
from rpython.jit.metainterp.resoperation import ResOperation, rop |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
def magic_numbers(m): |
| 14 |
assert m == intmask(m) |
| 15 |
assert m & (m-1) != 0 |
| 16 |
assert m >= 3 |
| 17 |
i = 1 |
| 18 |
while (r_uint(1) << (i+1)) < r_uint(m): |
| 19 |
i += 1 |
| 20 |
|
| 21 |
|
| 22 |
high_word_dividend = r_uint(1) << i |
| 23 |
quotient = r_uint(0) |
| 24 |
for bit in range(LONG_BIT-1, -1, -1): |
| 25 |
t = quotient + (r_uint(1) << bit) |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
if uint_mul_high(t, r_uint(m)) < high_word_dividend: |
| 30 |
quotient = t |
| 31 |
|
| 32 |
|
| 33 |
k = quotient + r_uint(1) |
| 34 |
|
| 35 |
assert k != r_uint(0) |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
assert k > (r_uint(1) << (LONG_BIT-1)) |
| 48 |
|
| 49 |
|
| 50 |
return (k, i) |
| 51 |
|
| 52 |
|
| 53 |
def division_operations(n_box, m, known_nonneg=False): |
| 54 |
kk, ii = magic_numbers(m) |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
if not known_nonneg: |
| 90 |
t_box = ResOperation(rop.INT_RSHIFT, [n_box, ConstInt(LONG_BIT - 1)]) |
| 91 |
nt_box = ResOperation(rop.INT_XOR, [n_box, t_box]) |
| 92 |
else: |
| 93 |
t_box = None |
| 94 |
nt_box = n_box |
| 95 |
mul_box = ResOperation(rop.UINT_MUL_HIGH, [nt_box, ConstInt(intmask(kk))]) |
| 96 |
sh_box = ResOperation(rop.UINT_RSHIFT, [mul_box, ConstInt(ii)]) |
| 97 |
if not known_nonneg: |
| 98 |
final_box = ResOperation(rop.INT_XOR, [sh_box, t_box]) |
| 99 |
return [t_box, nt_box, mul_box, sh_box, final_box] |
| 100 |
else: |
| 101 |
return [mul_box, sh_box] |
| 102 |
|
| 103 |
|
| 104 |
def modulo_operations(n_box, m, known_nonneg=False): |
| 105 |
operations = division_operations(n_box, m, known_nonneg) |
| 106 |
|
| 107 |
mul_box = ResOperation(rop.INT_MUL, [operations[-1], ConstInt(m)]) |
| 108 |
diff_box = ResOperation(rop.INT_SUB, [n_box, mul_box]) |
| 109 |
return operations + [mul_box, diff_box] |
| 110 |
|
| 111 |
|