move more files to openpower-isa
[soc.git] / src / soc / fu / branch / test / test_pipe_caller.py
index 704cd7f94e1208bdd0b697e6120edbcd5bf9a375..f68374d13f423e02cda9c2d4bc94615b377bc270 100644 (file)
@@ -1,30 +1,26 @@
 from nmigen import Module, Signal
-from nmigen.back.pysim import Simulator, Delay, Settle
-from nmigen.test.utils import FHDLTestCase
+
+# NOTE: to use cxxsim, export NMIGEN_SIM_MODE=cxxsim from the shell
+# Also, check out the cxxsim nmigen branch, and latest yosys from git
+from nmutil.sim_tmp_alternative import Simulator, Settle
+
 from nmigen.cli import rtlil
 import unittest
-from soc.decoder.isa.caller import ISACaller, special_sprs
-from soc.decoder.power_decoder import (create_pdecode)
-from soc.decoder.power_decoder2 import (PowerDecode2)
-from soc.decoder.power_enums import (XER_bits, Function, InternalOp)
-from soc.decoder.selectable_int import SelectableInt
-from soc.simulator.program import Program
-from soc.decoder.isa.all import ISA
+from openpower.decoder.isa.caller import ISACaller, special_sprs
+from openpower.decoder.power_decoder import (create_pdecode)
+from openpower.decoder.power_decoder2 import (PowerDecode2)
+from openpower.decoder.power_enums import (XER_bits, Function, MicrOp)
+from openpower.decoder.selectable_int import SelectableInt
+from openpower.simulator.program import Program
+from openpower.decoder.isa.all import ISA
 from soc.regfile.regfiles import FastRegs
+from soc.config.endian import bigendian
 
+from soc.fu.test.common import TestAccumulatorBase, TestCase, ALUHelpers
 from soc.fu.branch.pipeline import BranchBasePipe
 from soc.fu.branch.pipe_data import BranchPipeSpec
 import random
 
-from soc.regfile.util import fast_reg_to_spr # HACK!
-
-class TestCase:
-    def __init__(self, program, regs, sprs, cr, name):
-        self.program = program
-        self.regs = regs
-        self.sprs = sprs
-        self.name = name
-        self.cr = cr
 
 def get_rec_width(rec):
     recwidth = 0
@@ -35,70 +31,64 @@ def get_rec_width(rec):
     return recwidth
 
 
-# This test bench is a bit different than is usual. Initially when I
-# was writing it, I had all of the tests call a function to create a
-# device under test and simulator, initialize the dut, run the
-# simulation for ~2 cycles, and assert that the dut output what it
-# should have. However, this was really slow, since it needed to
-# create and tear down the dut and simulator for every test case.
+def get_cu_inputs(dec2, sim):
+    """naming (res) must conform to BranchFunctionUnit input regspec
+    """
+    res = {}
+
+    # CIA (PC)
+    #res['cia'] = sim.pc.CIA.value
 
-# Now, instead of doing that, every test case in ALUTestCase puts some
-# data into the test_data list below, describing the instructions to
-# be tested and the initial state. Once all the tests have been run,
-# test_data gets passed to TestRunner which then sets up the DUT and
-# simulator once, runs all the data through it, and asserts that the
-# results match the pseudocode sim at every cycle.
+    yield from ALUHelpers.get_sim_fast_spr1(res, sim, dec2)
+    yield from ALUHelpers.get_sim_fast_spr2(res, sim, dec2)
+    yield from ALUHelpers.get_sim_cr_a(res, sim, dec2)
 
-# By doing this, I've reduced the time it takes to run the test suite
-# massively. Before, it took around 1 minute on my computer, now it
-# takes around 3 seconds
+    print("get inputs", res)
+    return res
 
-test_data = []
 
+class BranchTestCase(TestAccumulatorBase):
 
-class BranchTestCase(FHDLTestCase):
-    def __init__(self, name):
-        super().__init__(name)
-        self.test_name = name
-    def run_tst_program(self, prog, initial_regs=[0] * 32,
-                        initial_sprs={}, initial_cr=0):
-        tc = TestCase(prog, initial_regs, initial_sprs, initial_cr,
-                      self.test_name)
-        test_data.append(tc)
+    def case_0_regression_unconditional(self):
+        for i in range(2):
+            imm = random.randrange(-1 << 23, (1 << 23)-1) * 4
+            lst = [f"bl {imm}"]
+            initial_regs = [0] * 32
+            self.add_case(Program(lst, bigendian), initial_regs)
 
-    def test_unconditional(self):
+    def case_unconditional(self):
         choices = ["b", "ba", "bl", "bla"]
         for i in range(20):
             choice = random.choice(choices)
-            imm = random.randrange(-1<<23, (1<<23)-1) * 4
+            imm = random.randrange(-1 << 23, (1 << 23)-1) * 4
             lst = [f"{choice} {imm}"]
             initial_regs = [0] * 32
-            self.run_tst_program(Program(lst), initial_regs)
+            self.add_case(Program(lst, bigendian), initial_regs)
 
-    def test_bc_cr(self):
+    def case_bc_cr(self):
         for i in range(20):
-            bc = random.randrange(-1<<13, (1<<13)-1) * 4
+            bc = random.randrange(-1 << 13, (1 << 13)-1) * 4
             bo = random.choice([0b01100, 0b00100, 0b10100])
             bi = random.randrange(0, 31)
-            cr = random.randrange(0, (1<<32)-1)
+            cr = random.randrange(0, (1 << 32)-1)
             lst = [f"bc {bo}, {bi}, {bc}"]
             initial_regs = [0] * 32
-            self.run_tst_program(Program(lst), initial_cr=cr)
+            self.add_case(Program(lst, bigendian), initial_cr=cr)
 
-    def test_bc_ctr(self):
+    def case_bc_ctr(self):
         for i in range(20):
-            bc = random.randrange(-1<<13, (1<<13)-1) * 4
+            bc = random.randrange(-1 << 13, (1 << 13)-1) * 4
             bo = random.choice([0, 2, 8, 10, 16, 18])
             bi = random.randrange(0, 31)
-            cr = random.randrange(0, (1<<32)-1)
-            ctr = random.randint(0, (1<<32)-1)
+            cr = random.randrange(0, (1 << 32)-1)
+            ctr = random.randint(0, (1 << 32)-1)
             lst = [f"bc {bo}, {bi}, {bc}"]
-            initial_sprs={9: SelectableInt(ctr, 64)}
-            self.run_tst_program(Program(lst),
-                                 initial_sprs=initial_sprs,
-                                 initial_cr=cr)
+            initial_sprs = {9: SelectableInt(ctr, 64)}
+            self.add_case(Program(lst, bigendian),
+                          initial_sprs=initial_sprs,
+                          initial_cr=cr)
 
-    def test_bc_reg(self):
+    def case_bc_reg(self):
         # XXX: bcctr and bcctrl time out (irony: they're counters)
         choices = ["bclr", "bclrl", "bcctr", "bcctrl", "bctar", "bctarl"]
         for insn in choices:
@@ -106,21 +96,43 @@ class BranchTestCase(FHDLTestCase):
                 bh = random.randrange(0, 3)
                 bo = random.choice([4, 12])
                 bi = random.randrange(0, 31)
-                cr = random.randrange(0, (1<<32)-1)
-                ctr = random.randint(0, (1<<32)-1)
-                lr = random.randint(0, (1<<64)-1) & ~3
-                tar = random.randint(0, (1<<64)-1) & ~3
+                cr = random.randrange(0, (1 << 32)-1)
+                ctr = random.randint(0, (1 << 32)-1)
+                lr = random.randint(0, (1 << 64)-1) & ~3
+                tar = random.randint(0, (1 << 64)-1) & ~3
                 lst = [f"{insn} {bo}, {bi}, {bh}"]
-                initial_sprs={9: SelectableInt(ctr, 64),
-                              8: SelectableInt(lr, 64),
-                              815: SelectableInt(tar, 64)}
-                self.run_tst_program(Program(lst),
-                                     initial_sprs=initial_sprs,
-                                     initial_cr=cr)
-
-        
-
-    def test_ilang(self):
+                initial_sprs = {9: SelectableInt(ctr, 64),
+                                8: SelectableInt(lr, 64),
+                                815: SelectableInt(tar, 64)}
+                self.add_case(Program(lst, bigendian),
+                              initial_sprs=initial_sprs,
+                              initial_cr=cr)
+
+    def case_bc_microwatt_1_regression(self):
+        """bc found to be testing ctr rather than (ctr-1)
+        11fb4:   08 00 49 40     bc      2,4*cr2+gt,0x11fbc
+        cr_file.vhdl:83:13:@136835ns:(report note): Reading CR 33209703
+        """
+        lst = ["bc 2, 9, 8"]
+        initial_regs = [0] * 32
+        cr = 0x33209703
+        self.add_case(Program(lst, bigendian), initial_regs,
+                              initial_cr=cr)
+
+    def case_bc_microwatt_2_regression(self):
+        """modified version, set CTR=1 so that it hits zero in BC
+        """
+        lst = ["bc 2, 9, 8"]
+        initial_regs = [0] * 32
+        cr = 0x33209703
+        ctr = 1
+        initial_sprs = {9: SelectableInt(ctr, 64),
+                        }
+        self.add_case(Program(lst, bigendian), initial_regs,
+                              initial_sprs=initial_sprs,
+                              initial_cr=cr)
+
+    def case_ilang(self):
         pspec = BranchPipeSpec(id_wid=2)
         alu = BranchBasePipe(pspec)
         vl = rtlil.convert(alu, ports=alu.ports())
@@ -128,76 +140,87 @@ class BranchTestCase(FHDLTestCase):
             f.write(vl)
 
 
-class TestRunner(FHDLTestCase):
-    def __init__(self, test_data):
-        super().__init__("run_all")
-        self.test_data = test_data
-
-    def run_all(self):
+class TestRunner(unittest.TestCase):
+    def test_it(self):
+        test_data = BranchTestCase().test_data
         m = Module()
         comb = m.d.comb
         instruction = Signal(32)
 
-        pdecode = create_pdecode()
+        fn_name = "BRANCH"
+        opkls = BranchPipeSpec.opsubsetkls
 
-        m.submodules.pdecode2 = pdecode2 = PowerDecode2(pdecode)
+        m.submodules.pdecode2 = pdecode2 = PowerDecode2(None, opkls, fn_name)
+        pdecode = pdecode2.dec
 
         pspec = BranchPipeSpec(id_wid=2)
         m.submodules.branch = branch = BranchBasePipe(pspec)
 
-        comb += branch.p.data_i.ctx.op.eq_from_execute1(pdecode2.e)
+        comb += branch.p.data_i.ctx.op.eq_from_execute1(pdecode2.do)
         comb += branch.p.valid_i.eq(1)
         comb += branch.n.ready_i.eq(1)
         comb += pdecode2.dec.raw_opcode_in.eq(instruction)
         sim = Simulator(m)
 
         sim.add_clock(1e-6)
+
         def process():
-            for test in self.test_data:
+            for test in test_data:
                 print(test.name)
                 program = test.program
-                self.subTest(test.name)
-                simulator = ISA(pdecode2, test.regs, test.sprs, test.cr)
-                initial_cia = 0x2000
-                simulator.set_pc(initial_cia)
-                gen = program.generate_instructions()
-                instructions = list(zip(gen, program.assembly.splitlines()))
-
-                index = (simulator.pc.CIA.value - initial_cia)//4
-                while index < len(instructions) and index >= 0:
-                    print(index)
-                    ins, code = instructions[index]
-
-                    print("0x{:X}".format(ins & 0xffffffff))
-                    print(code)
-
-                    # ask the decoder to decode this binary data (endian'd)
-                    yield pdecode2.dec.bigendian.eq(0)  # little / big?
-                    yield instruction.eq(ins)          # raw binary instr.
-                    yield branch.p.data_i.cia.eq(simulator.pc.CIA.value)
-                    # note, here, the op will need further decoding in order
-                    # to set the correct SPRs on SPR1/2/3.  op_bc* require
-                    # spr1 to be set to CTR, op_bctar require spr2 to be
-                    # set to TAR, op_bclr* require spr2 to be set to LR.
-                    # if op_sc*, op_rf* and op_hrfid are to be added here
-                    # then additional op-decoding is required, accordingly
-                    yield Settle()
-                    yield from self.set_inputs(branch, pdecode2, simulator)
-                    fn_unit = yield pdecode2.e.fn_unit
-                    self.assertEqual(fn_unit, Function.BRANCH.value, code)
-                    yield
-                    yield
-                    opname = code.split(' ')[0]
-                    prev_nia = simulator.pc.NIA.value
-                    yield from simulator.call(opname)
-                    index = (simulator.pc.CIA.value - initial_cia)//4
-
-                    yield from self.assert_outputs(branch, pdecode2,
-                                                   simulator, prev_nia, code)
+                with self.subTest(test.name):
+                    simulator = ISA(pdecode2, test.regs, test.sprs, test.cr,
+                                    test.mem, test.msr,
+                                    bigendian=bigendian)
+                    initial_cia = 0x2000
+                    simulator.set_pc(initial_cia)
+                    gen = program.generate_instructions()
+                    instructions = list(
+                        zip(gen, program.assembly.splitlines()))
+
+                    pc = simulator.pc.CIA.value
+                    msr = simulator.msr.value
+                    index = (pc - initial_cia)//4
+                    while index < len(instructions) and index >= 0:
+                        print(index)
+                        ins, code = instructions[index]
+
+                        print("0x{:X}".format(ins & 0xffffffff))
+                        print(code)
+
+                        # ask the decoder to decode this binary data (endian'd)
+                        # little / big?
+                        yield pdecode2.dec.bigendian.eq(bigendian)
+                        yield pdecode2.state.msr.eq(msr)  # set MSR in pdecode2
+                        yield pdecode2.state.pc.eq(pc)  # set PC in pdecode2
+                        yield instruction.eq(ins)          # raw binary instr.
+                        # note, here, the op will need further decoding in order
+                        # to set the correct SPRs on SPR1/2/3.  op_bc* require
+                        # spr1 to be set to CTR, op_bctar require spr2 to be
+                        # set to TAR, op_bclr* require spr2 to be set to LR.
+                        # if op_sc*, op_rf* and op_hrfid are to be added here
+                        # then additional op-decoding is required, accordingly
+                        yield Settle()
+                        lk = yield pdecode2.e.do.lk
+                        print("lk:", lk)
+                        yield from self.set_inputs(branch, pdecode2, simulator)
+                        fn_unit = yield pdecode2.e.do.fn_unit
+                        self.assertEqual(fn_unit, Function.BRANCH.value, code)
+                        yield
+                        yield
+                        opname = code.split(' ')[0]
+                        prev_nia = simulator.pc.NIA.value
+                        yield from simulator.call(opname)
+                        pc = simulator.pc.CIA.value
+                        msr = simulator.msr.value
+                        index = (pc - initial_cia)//4
+
+                        yield from self.assert_outputs(branch, pdecode2,
+                                                       simulator, prev_nia,
+                                                       code)
 
         sim.add_sync_process(process)
-        with sim.write_vcd("simulator.vcd", "simulator.gtkw",
-                            traces=[]):
+        with sim.write_vcd("branch_simulator.vcd"):
             sim.run()
 
     def assert_outputs(self, branch, dec2, sim, prev_nia, code):
@@ -212,79 +235,22 @@ class TestRunner(FHDLTestCase):
         # TODO: check write_fast1 as well (should contain CTR)
 
         # TODO: this should be checking write_fast2
-        lk = yield dec2.e.lk
+        lk = yield dec2.e.do.lk
         branch_lk = yield branch.n.data_o.lr.ok
         self.assertEqual(lk, branch_lk, code)
         if lk:
             branch_lr = yield branch.n.data_o.lr.data
             self.assertEqual(sim.spr['LR'], branch_lr, code)
 
-    def get_inputs(self, dec2, sim):
-        """naming (res) must conform to BranchFunctionUnit input regspec
-        """
-        res = {}
-
-        # CIA (PC)
-        res['cia'] = sim.pc.CIA.value
-
-        # CR A
-        cr1_en = yield dec2.e.read_cr1.ok
-        if cr1_en:
-            cr1_sel = yield dec2.e.read_cr1.data
-            res['cr_a'] = sim.crl[cr1_sel].get_range().value
-
-        # Fast1
-        spr_ok = yield dec2.e.read_fast1.ok
-        spr_num = yield dec2.e.read_fast1.data
-        # HACK
-        spr_num = fast_reg_to_spr(spr_num)
-        if spr_ok:
-            res['spr1'] = sim.spr[spr_dict[spr_num].SPR].value
-
-        # SPR2
-        spr_ok = yield dec2.e.read_fast2.ok
-        spr_num = yield dec2.e.read_fast2.data
-        # HACK
-        spr_num = fast_reg_to_spr(spr_num)
-        if spr_ok:
-            res['spr2'] = sim.spr[spr_dict[spr_num].SPR].value
-
-        print ("get inputs", res)
-        return res
-
     def set_inputs(self, branch, dec2, sim):
-        yield branch.p.data_i.spr1.eq(sim.spr['CTR'].value)
         print(f"cr0: {sim.crl[0].get_range()}")
 
-        # TODO: this needs to now be read_fast1.data and read_fast2.data
-        fast1_en = yield dec2.e.read_fast1.ok
-        if fast1_en:
-            fast1_sel = yield dec2.e.read_fast1.data
-            spr1_sel = fast_reg_to_spr(fast1_sel)
-            spr1_data = sim.spr[spr1_sel].value
-            yield branch.p.data_i.spr1.eq(spr1_data)
-
-        fast2_en = yield dec2.e.read_fast2.ok
-        if fast2_en:
-            fast2_sel = yield dec2.e.read_fast2.data
-            spr2_sel = fast_reg_to_spr(fast2_sel)
-            spr2_data = sim.spr[spr2_sel].value
-            yield branch.p.data_i.spr2.eq(spr2_data)
+        inp = yield from get_cu_inputs(dec2, sim)
 
-
-        cr_en = yield dec2.e.read_cr1.ok
-        if cr_en:
-            cr_sel = yield dec2.e.read_cr1.data
-            cr = sim.crl[cr_sel].get_range().value
-            yield branch.p.data_i.cr.eq(cr)
-            full_cr = sim.cr.get_range().value
-            print(f"full cr: {full_cr:x}, sel: {cr_sel}, cr: {cr:x}")
+        yield from ALUHelpers.set_fast_spr1(branch, dec2, inp)
+        yield from ALUHelpers.set_fast_spr2(branch, dec2, inp)
+        yield from ALUHelpers.set_cr_a(branch, dec2, inp)
 
 
 if __name__ == "__main__":
-    unittest.main(exit=False)
-    suite = unittest.TestSuite()
-    suite.addTest(TestRunner(test_data))
-
-    runner = unittest.TextTestRunner()
-    runner.run(suite)
+    unittest.main()