add a MultiShift class for generating single-cycle bit-shifters
[ieee754fpu.git] / src / add / test_multishift.py
1 from random import randint
2 from nmigen import Module, Signal
3 from nmigen.compat.sim import run_simulation
4
5 from fpbase import MultiShift
6
7 class MultiShiftModL:
8 def __init__(self, width):
9 self.ms = MultiShift(width)
10 self.a = Signal(width)
11 self.b = Signal(self.ms.smax)
12 self.x = Signal(width)
13
14 def get_fragment(self, platform=None):
15
16 m = Module()
17 m.d.comb += self.x.eq(self.ms.lshift(self.a, self.b))
18
19 return m
20
21 class MultiShiftModR:
22 def __init__(self, width):
23 self.ms = MultiShift(width)
24 self.a = Signal(width)
25 self.b = Signal(self.ms.smax)
26 self.x = Signal(width)
27
28 def get_fragment(self, platform=None):
29
30 m = Module()
31 m.d.comb += self.x.eq(self.ms.rshift(self.a, self.b))
32
33 return m
34
35 def check_case(dut, width, a, b):
36 yield dut.a.eq(a)
37 yield dut.b.eq(b)
38 yield
39
40 x = (a << b) & ((1<<width)-1)
41
42 out_x = yield dut.x
43 assert out_x == x, "Output x 0x%x not equal to expected 0x%x" % (out_x, x)
44
45 def check_caser(dut, width, a, b):
46 yield dut.a.eq(a)
47 yield dut.b.eq(b)
48 yield
49
50 x = (a >> b) & ((1<<width)-1)
51
52 out_x = yield dut.x
53 assert out_x == x, "Output x 0x%x not equal to expected 0x%x" % (out_x, x)
54
55 def testbench(dut):
56 for i in range(32):
57 for j in range(1000):
58 a = randint(0, (1<<32)-1)
59 yield from check_case(dut, 32, a, i)
60
61 def testbenchr(dut):
62 for i in range(32):
63 for j in range(1000):
64 a = randint(0, (1<<32)-1)
65 yield from check_caser(dut, 32, a, i)
66
67 if __name__ == '__main__':
68 dut = MultiShiftModR(width=32)
69 run_simulation(dut, testbenchr(dut), vcd_name="test_multishift.vcd")
70
71 dut = MultiShiftModL(width=32)
72 run_simulation(dut, testbench(dut), vcd_name="test_multishift.vcd")
73