Merge branch 'master' of ssh://git.libre-riscv.org:922/rv32
authorJacob Lifshay <programmerjake@gmail.com>
Wed, 28 Nov 2018 07:57:25 +0000 (23:57 -0800)
committerJacob Lifshay <programmerjake@gmail.com>
Wed, 28 Nov 2018 07:57:25 +0000 (23:57 -0800)
15 files changed:
README.txt [new file with mode: 0644]
cpu.py [new file with mode: 0644]
cpu_decoder.py [new file with mode: 0644]
cpu_fetch_action.py [new file with mode: 0644]
cpu_fetch_stage.py [new file with mode: 0644]
cpu_handle_csr.py [new file with mode: 0644]
cpu_handle_trap.py [new file with mode: 0644]
cpu_loadstore_calc.py [new file with mode: 0644]
cpu_mie.py [new file with mode: 0644]
cpu_mip.py [new file with mode: 0644]
cpu_mstatus.py [new file with mode: 0644]
cpudefs.py [new file with mode: 0644]
pipestage.py [new file with mode: 0644]
regfile.py [new file with mode: 0644]
riscvdefs.py [new file with mode: 0644]

diff --git a/README.txt b/README.txt
new file mode 100644 (file)
index 0000000..ca3ba1a
--- /dev/null
@@ -0,0 +1,9 @@
+# Limitations
+
+* there is no << or >> operator, only <<< and >>> (arithmetic shift)
+  _Operator("<<", [lhs, rhs]) will generate verilog however simulation
+  will fail, and value_bits_sign will not correctly recognise it
+* it is not possible to declare parameters
+* an input of [31:2] is not possible, only a parameter of [N:0]
+* tasks are not supported.
+* Clock Domains: https://gist.github.com/cr1901/5de5b276fca539b66fe7f4493a5bfe7d
diff --git a/cpu.py b/cpu.py
new file mode 100644 (file)
index 0000000..29cbe57
--- /dev/null
+++ b/cpu.py
@@ -0,0 +1,664 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+class MemoryInterface:
+    fetch_address = Signal(32, name="memory_interface_fetch_address") # XXX [2:]
+    fetch_data = Signal(32, name="memory_interface_fetch_data")
+    fetch_valid = Signal(name="memory_interface_fetch_valid")
+    rw_address= Signal(32, name="memory_interface_rw_address") # XXX [2:]
+    rw_byte_mask = Signal(4, name="memory_interface_rw_byte_mask")
+    rw_read_not_write = Signal(name="memory_interface_rw_read_not_write")
+    rw_active = Signal(name="memory_interface_rw_active")
+    rw_data_in = Signal(32, name="memory_interface_rw_data_in")
+    rw_data_out = Signal(32, name="memory_interface_rw_data_out")
+    rw_address_valid = Signal(name="memory_interface_rw_address_valid")
+    rw_wait = Signal(name="memory_interface_rw_wait")
+
+
+class Decoder:
+    funct7 = Signal(7, name="decoder_funct7")
+    funct3 = Signal(3, name="decoder_funct3")
+    rd = Signal(5, name="decoder_rd")
+    rs1 = Signal(5, name="decoder_rs1")
+    rs2 = Signal(5, name="decoder_rs2")
+    immediate = Signal(32, name="decoder_immediate")
+    opcode = Signal(7, name="decoder_opcode")
+    act = Signal(decode_action, name="decoder_action")
+
+
+class MStatus:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.mpie = Signal(name="mstatus_mpie")
+        self.mie = Signal(name="mstatus_mie")
+        self.mstatus = Signal(32, name="mstatus")
+
+        self.sync += self.mie.eq(0)
+        self.sync += self.mpie.eq(0)
+        self.sync += self.mstatus.eq(0)
+
+
+class MIE:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.meie = Signal(name="mie_meie")
+        self.mtie = Signal(name="mie_mtie")
+        self.msie = Signal(name="mie_msie")
+        self.mie = Signal(32)
+
+
+class MIP:
+    def __init__(self):
+        self.mip = Signal(32)
+
+
+class M:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.mcause = Signal(32)
+        self.mepc = Signal(32)
+        self.mscratch = Signal(32)
+        self.sync += self.mcause.eq(0)
+        self.sync += self.mepc.eq(0) # 32'hXXXXXXXX;
+        self.sync += self.mscratch.eq(0) # 32'hXXXXXXXX;
+
+
+class Misa:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.misa = Signal(32)
+        cl = []
+        for l in list(string.ascii_lowercase):
+            value = 1 if l == 'i' else 0
+            cl.append(Constant(value))
+        cl.append(Constant(0, 4))
+        cl.append(Constant(0b01, 2))
+        self.comb += self.misa.eq(Cat(cl))
+
+
+class Fetch:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.action = Signal(fetch_action, name="fetch_action")
+        self.target_pc = Signal(32, name="fetch_target_pc")
+        self.output_pc = Signal(32, name="fetch_output_pc")
+        self.output_instruction = Signal(32, name="fetch_ouutput_instruction")
+        self.output_state = Signal(fetch_output_state,name="fetch_output_state")
+
+class CSR:
+    def __init__(self, comb, sync, dc, register_rs1):
+        self.comb = comb
+        self.sync = sync
+        self.number = Signal(12, name="csr_number")
+        self.input_value = Signal(32, name="csr_input_value")
+        self.reads = Signal(name="csr_reads")
+        self.writes = Signal(name="csr_writes")
+        self.op_is_valid = Signal(name="csr_op_is_valid")
+
+        self.comb += self.number.eq(dc.immediate)
+        self.comb += self.input_value.eq(Mux(dc.funct3[2],
+                                            dc.rs1,
+                                            register_rs1))
+        self.comb += self.reads.eq(dc.funct3[1] | (dc.rd != 0))
+        self.comb += self.writes.eq(~dc.funct3[1] | (dc.rs1 != 0))
+
+        self.comb += self.get_csr_op_is_valid()
+
+    def get_csr_op_is_valid(self):
+        """ determines if a CSR is valid
+        """
+        c = {}
+        # invalid csrs
+        for f in [csr_ustatus, csr_fflags, csr_frm, csr_fcsr,
+                  csr_uie, csr_utvec, csr_uscratch, csr_uepc,
+                  csr_ucause, csr_utval, csr_uip, csr_sstatus,
+                  csr_sedeleg, csr_sideleg, csr_sie, csr_stvec,
+                  csr_scounteren, csr_sscratch, csr_sepc, csr_scause,
+                  csr_stval, csr_sip, csr_satp, csr_medeleg,
+                  csr_mideleg, csr_dcsr, csr_dpc, csr_dscratch]:
+            c[f] = self.op_is_valid.eq(0)
+
+        # not-writeable -> ok
+        for f in [csr_cycle, csr_time, csr_instret, csr_cycleh,
+                  csr_timeh, csr_instreth, csr_mvendorid, csr_marchid,
+                  csr_mimpid, csr_mhartid]:
+            c[f] = self.op_is_valid.eq(~self.writes)
+
+        # valid csrs
+        for f in [csr_misa, csr_mstatus, csr_mie, csr_mtvec,
+                  csr_mscratch, csr_mepc, csr_mcause, csr_mip]:
+            c[f] = self.op_is_valid.eq(1)
+
+        # not implemented / default
+        for f in [csr_mcounteren, csr_mtval, csr_mcycle, csr_minstret,
+                  csr_mcycleh, csr_minstreth, "default"]:
+            c[f] = self.op_is_valid.eq(0)
+
+        return Case(self.number, c)
+
+    def evaluate_csr_funct3_op(self, funct3, previous, written):
+        c = { "default": written.eq(Constant(0, 32))}
+        for f in [F3.csrrw, F3.csrrwi]:
+            c[f] = written.eq(self.input_value)
+        for f in [F3.csrrs, F3.csrrsi]:
+            c[f] = written.eq(self.input_value | previous)
+        for f in [F3.csrrc, F3.csrrci]:
+            c[f] = written.eq(~self.input_value & previous)
+        return Case(funct3, c)
+
+
+class MInfo:
+    def __init__(self, comb):
+        self.comb = comb
+        # TODO
+        self.cycle_counter   = Signal(64); # TODO: implement cycle_counter
+        self.time_counter    = Signal(64); # TODO: implement time_counter
+        self.instret_counter = Signal(64); # TODO: implement instret_counter
+
+        self.mvendorid = Signal(32)
+        self.marchid = Signal(32)
+        self.mimpid = Signal(32)
+        self.mhartid = Signal(32)
+        self.comb += self.mvendorid.eq(Constant(0, 32))
+        self.comb += self.marchid.eq(Constant(0, 32))
+        self.comb += self.mimpid.eq(Constant(0, 32))
+        self.comb += self.mhartid.eq(Constant(0, 32))
+
+class Regs:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+
+        self.ra_en = Signal(reset=1, name="regfile_ra_en") # TODO: ondemand en
+        self.rs1 = Signal(32, name="regfile_rs1")
+        self.rs_a = Signal(5, name="regfile_rs_a")
+
+        self.rb_en = Signal(reset=1, name="regfile_rb_en") # TODO: ondemand en
+        self.rs2 = Signal(32, name="regfile_rs2")
+        self.rs_b = Signal(5, name="regfile_rs_b")
+
+        self.w_en = Signal(name="regfile_w_en")
+        self.wval = Signal(32, name="regfile_wval")
+        self.rd = Signal(32, name="regfile_rd")
+
+class CPU(Module):
+    """
+    """
+
+    def get_lsbm(self, dc):
+        return Cat(Constant(1),
+                   Mux((dc.funct3[1] | dc.funct3[0]),
+                       Constant(1), Constant(0)),
+                   Mux((dc.funct3[1]),
+                       Constant(0b11, 2), Constant(0, 2)))
+
+    # XXX this happens to get done by various self.sync actions
+    #def reset_to_initial(self, m, mstatus, mie, registers):
+    #    return [m.mcause.eq(0),
+    #            ]
+
+    def handle_trap(self, mcause, mepc, mie, mpie):
+        s = [mcause.eq(self.new_mcause),
+             mepc.eq(self.new_mepc),
+             mpie.eq(self.new_mpie),
+             mie.eq(self.new_mie)]
+        return s
+
+    def main_block(self, mtvec, mip, minfo, misa, csr, mi, m, mstatus, mie,
+                         ft, dc,
+                         load_store_misaligned,
+                         loaded_value, alu_result,
+                         lui_auipc_result):
+        c = {}
+        c[FOS.empty] = []
+        c[FOS.trap] = self.handle_trap(m.mcause, m.mepc,
+                                       mstatus.mie, mstatus.mpie)
+        c[FOS.valid] = self.handle_valid(mtvec, mip, minfo, misa, csr, mi, m,
+                                       mstatus, mie, ft, dc,
+                                       load_store_misaligned,
+                                       loaded_value,
+                                       alu_result,
+                                       lui_auipc_result)
+        return [self.regs.w_en.eq(0),
+                Case(ft.output_state, c),
+                self.regs.w_en.eq(0)]
+
+    def write_register(self, rd, val):
+        return [self.regs.rd.eq(rd),
+                self.regs.wval.eq(val),
+                self.regs.w_en.eq(1)
+               ]
+
+    def handle_valid(self, mtvec, mip, minfo, misa, csr, mi, m, mstatus, mie,
+                           ft, dc,
+                           load_store_misaligned,
+                           loaded_value, alu_result,
+                           lui_auipc_result):
+        # fetch action ack trap
+        i = If((ft.action == FA.ack_trap) | (ft.action == FA.noerror_trap),
+                self.handle_trap(m.mcause, m.mepc, mstatus.mie, mstatus.mpie)
+              )
+
+        # load
+        i = i.Elif((dc.act & DA.load) != 0,
+                If(~mi.rw_wait,
+                    self.write_register(dc.rd, loaded_value)
+                )
+              )
+
+        # op or op_immediate
+        i = i.Elif((dc.act & DA.op_op_imm) != 0,
+                self.write_register(dc.rd, alu_result)
+              )
+
+        # lui or auipc
+        i = i.Elif((dc.act & DA.lui_auipc) != 0,
+                self.write_register(dc.rd, lui_auipc_result)
+              )
+
+        # jal/jalr
+        i = i.Elif((dc.act & (DA.jal | DA.jalr)) != 0,
+                self.write_register(dc.rd, ft.output_pc + 4)
+              )
+
+        i = i.Elif((dc.act & DA.csr) != 0,
+                self.handle_csr(mtvec, mip, minfo, misa, mstatus, mie, m,
+                                dc, csr)
+              )
+
+        # fence, store, branch
+        i = i.Elif((dc.act & (DA.fence | DA.fence_i |
+                              DA.store | DA.branch)) != 0,
+                # do nothing
+              )
+
+        return i
+
+    def handle_csr(self, mtvec, mip, minfo, misa, mstatus, mie, m, dc, csr):
+        csr_output_value = Signal(32)
+        csr_written_value = Signal(32)
+        c = {}
+
+        # cycle
+        c[csr_cycle]  = csr_output_value.eq(minfo.cycle_counter[0:32])
+        c[csr_cycleh] = csr_output_value.eq(minfo.cycle_counter[32:64])
+        # time
+        c[csr_time]  = csr_output_value.eq(minfo.time_counter[0:32])
+        c[csr_timeh] = csr_output_value.eq(minfo.time_counter[32:64])
+        # instret
+        c[csr_instret]  = csr_output_value.eq(minfo.instret_counter[0:32])
+        c[csr_instreth] = csr_output_value.eq(minfo.instret_counter[32:64])
+        # mvendorid/march/mimpl/mhart
+        c[csr_mvendorid] = csr_output_value.eq(minfo.mvendorid)
+        c[csr_marchid  ] = csr_output_value.eq(minfo.marchid  )
+        c[csr_mimpid   ] = csr_output_value.eq(minfo.mimpid   )
+        c[csr_mhartid  ] = csr_output_value.eq(minfo.mhartid  )
+        # misa
+        c[csr_misa     ] = csr_output_value.eq(misa.misa)
+        # mstatus
+        c[csr_mstatus  ] = [
+            csr_output_value.eq(mstatus.mstatus),
+            csr.evaluate_csr_funct3_op(dc.funct3, csr_output_value,
+                                                  csr_written_value),
+            mstatus.mpie.eq(csr_written_value[7]),
+            mstatus.mie.eq(csr_written_value[3])
+        ]
+        # mie
+        c[csr_mie      ] = [
+            csr_output_value.eq(mie.mie),
+            csr.evaluate_csr_funct3_op(dc.funct3, csr_output_value,
+                                                  csr_written_value),
+            mie.meie.eq(csr_written_value[11]),
+            mie.mtie.eq(csr_written_value[7]),
+            mie.msie.eq(csr_written_value[3]),
+        ]
+        # mtvec
+        c[csr_mtvec    ] = csr_output_value.eq(mtvec)
+        # mscratch
+        c[csr_mscratch ] = [
+            csr_output_value.eq(m.mscratch),
+            csr.evaluate_csr_funct3_op(dc.funct3, csr_output_value,
+                                                  csr_written_value),
+            If(csr.writes,
+                m.mscratch.eq(csr_written_value),
+            )
+        ]
+        # mepc
+        c[csr_mepc ] = [
+            csr_output_value.eq(m.mepc),
+            csr.evaluate_csr_funct3_op(dc.funct3, csr_output_value,
+                                                  csr_written_value),
+            If(csr.writes,
+                m.mepc.eq(csr_written_value),
+            )
+        ]
+
+        # mcause
+        c[csr_mcause ] = [
+            csr_output_value.eq(m.mcause),
+            csr.evaluate_csr_funct3_op(dc.funct3, csr_output_value,
+                                                  csr_written_value),
+            If(csr.writes,
+                m.mcause.eq(csr_written_value),
+            )
+        ]
+
+        # mip
+        c[csr_mip  ] = [
+            csr_output_value.eq(mip.mip),
+            csr.evaluate_csr_funct3_op(dc.funct3, csr_output_value,
+                                                  csr_written_value),
+        ]
+
+        return [Case(csr.number, c),
+                If(csr.reads,
+                    self.write_register(dc.rd, csr_output_value)
+                )]
+
+    def __init__(self):
+        Module.__init__(self)
+        self.clk = ClockSignal()
+        self.reset = ResetSignal()
+        self.tty_write = Signal()
+        self.tty_write_data = Signal(8)
+        self.tty_write_busy = Signal()
+        self.switch_2 = Signal()
+        self.switch_3 = Signal()
+        self.led_1 = Signal()
+        self.led_3 = Signal()
+
+        ram_size = Constant(0x8000)
+        ram_start = Constant(0x10000, 32)
+        reset_vector = Signal(32)
+        mtvec = Signal(32)
+
+        reset_vector.eq(ram_start)
+        mtvec.eq(ram_start + 0x40)
+
+        self.regs = Regs(self.comb, self.sync)
+
+        rf = Instance("RegFile", name="regfile",
+           i_ra_en = self.regs.ra_en,
+           i_rb_en = self.regs.rb_en,
+           i_w_en = self.regs.w_en,
+           o_read_a = self.regs.rs1,
+           o_read_b = self.regs.rs2,
+           i_writeval = self.regs.wval,
+           i_rs_a = self.regs.rs_a,
+           i_rs_b = self.regs.rs_b,
+           i_rd = self.regs.rd)
+
+        self.specials += rf
+
+        mi = MemoryInterface()
+
+        mii = Instance("cpu_memory_interface", name="memory_instance",
+                    p_ram_size = ram_size,
+                    p_ram_start = ram_start,
+                    i_clk=ClockSignal(),
+                    i_rst=ResetSignal(),
+                    i_fetch_address = mi.fetch_address,
+                    o_fetch_data = mi.fetch_data,
+                    o_fetch_valid = mi.fetch_valid,
+                    i_rw_address = mi.rw_address,
+                    i_rw_byte_mask = mi.rw_byte_mask,
+                    i_rw_read_not_write = mi.rw_read_not_write,
+                    i_rw_active = mi.rw_active,
+                    i_rw_data_in = mi.rw_data_in,
+                    o_rw_data_out = mi.rw_data_out,
+                    o_rw_address_valid = mi.rw_address_valid,
+                    o_rw_wait = mi.rw_wait,
+                    o_tty_write = self.tty_write,
+                    o_tty_write_data = self.tty_write_data,
+                    i_tty_write_busy = self.tty_write_busy,
+                    i_switch_2 = self.switch_2,
+                    i_switch_3 = self.switch_3,
+                    o_led_1 = self.led_1,
+                    o_led_3 = self.led_3
+                  )
+        self.specials += mii
+
+        ft = Fetch(self.comb, self.sync)
+
+        fs = Instance("CPUFetchStage", name="fetch_stage",
+            i_clk=ClockSignal(),
+            i_rst=ResetSignal(),
+            o_memory_interface_fetch_address = mi.fetch_address,
+            i_memory_interface_fetch_data = mi.fetch_data,
+            i_memory_interface_fetch_valid = mi.fetch_valid,
+            i_fetch_action = ft.action,
+            i_target_pc = ft.target_pc,
+            o_output_pc = ft.output_pc,
+            o_output_instruction = ft.output_instruction,
+            o_output_state = ft.output_state,
+            i_reset_vector = reset_vector,
+            i_mtvec = mtvec,
+        )
+        self.specials += fs
+
+        dc = Decoder()
+
+        cd = Instance("CPUDecoder", name="decoder",
+            i_instruction = ft.output_instruction,
+            o_funct7 = dc.funct7,
+            o_funct3 = dc.funct3,
+            o_rd = dc.rd,
+            o_rs1 = dc.rs1,
+            o_rs2 = dc.rs2,
+            o_immediate = dc.immediate,
+            o_opcode = dc.opcode,
+            o_decode_action = dc.act
+        )
+        self.specials += cd
+
+        self.comb += self.regs.rs_a.eq(dc.rs1)
+        self.comb += self.regs.rs_b.eq(dc.rs2)
+
+        load_store_address = Signal(32)
+        load_store_address_low_2 = Signal(2)
+        load_store_misaligned = Signal()
+        unmasked_loaded_value = Signal(32)
+        loaded_value = Signal(32)
+
+        lsc = Instance("CPULoadStoreCalc", name="cpu_loadstore_calc",
+            i_dc_immediate = dc.immediate,
+            i_dc_funct3 = dc.funct3,
+            i_rs1 = self.regs.rs1,
+            i_rs2 = self.regs.rs2,
+            i_rw_data_in = mi.rw_data_in,
+            i_rw_data_out = mi.rw_data_out,
+            o_load_store_address = load_store_address,
+            o_load_store_address_low_2 = load_store_address_low_2,
+            o_load_store_misaligned = load_store_misaligned,
+            o_loaded_value = loaded_value)
+
+        self.specials += lsc
+
+        # XXX rwaddr not 31:2 any more
+        self.comb += mi.rw_address.eq(load_store_address[2:])
+
+        unshifted_load_store_byte_mask = Signal(4)
+
+        self.comb += unshifted_load_store_byte_mask.eq(self.get_lsbm(dc))
+
+        # XXX yuck.  this will cause migen simulation to fail
+        # (however conversion to verilog works)
+        self.comb += mi.rw_byte_mask.eq(
+                _Operator("<<", [unshifted_load_store_byte_mask,
+                                        load_store_address_low_2]))
+
+        self.comb += mi.rw_active.eq(~self.reset
+                        & (ft.output_state == FOS.valid)
+                        & ~load_store_misaligned
+                        & ((dc.act & (DA.load | DA.store)) != 0))
+
+        self.comb += mi.rw_read_not_write.eq(~dc.opcode[5])
+
+        # alu
+        alu_a = Signal(32)
+        alu_b = Signal(32)
+        alu_result = Signal(32)
+
+        self.comb += alu_a.eq(self.regs.rs1)
+        self.comb += alu_b.eq(Mux(dc.opcode[5],
+                                  self.regs.rs2,
+                                  dc.immediate))
+
+        ali = Instance("cpu_alu", name="alu",
+            i_funct7 = dc.funct7,
+            i_funct3 = dc.funct3,
+            i_opcode = dc.opcode,
+            i_a = alu_a,
+            i_b = alu_b,
+            o_result = alu_result
+        )
+        self.specials += ali
+
+        lui_auipc_result = Signal(32)
+        self.comb += lui_auipc_result.eq(Mux(dc.opcode[5],
+                                             dc.immediate,
+                                             dc.immediate + ft.output_pc))
+
+        self.comb += ft.target_pc.eq(Cat(0,
+                    Mux(dc.opcode != OP.jalr,
+                                ft.output_pc[1:32],
+                                self.regs.rs1[1:32] + dc.immediate[1:32])))
+
+        misaligned_jump_target = Signal()
+        self.comb += misaligned_jump_target.eq(ft.target_pc[1])
+        branch_arg_a = Signal(32)
+        branch_arg_b = Signal(32)
+        self.comb += branch_arg_a.eq(Cat( self.regs.rs1[0:31],
+                                          self.regs.rs1[31] ^ ~dc.funct3[1]))
+        self.comb += branch_arg_b.eq(Cat( self.regs.rs2[0:31],
+                                          self.regs.rs2[31] ^ ~dc.funct3[1]))
+
+        branch_taken = Signal()
+        self.comb += branch_taken.eq(dc.funct3[0] ^
+                                     Mux(dc.funct3[2],
+                                         branch_arg_a < branch_arg_b,
+                                         branch_arg_a == branch_arg_b))
+
+        m = M(self.comb, self.sync)
+        mstatus = MStatus(self.comb, self.sync)
+        mie = MIE(self.comb, self.sync)
+        misa = Misa(self.comb, self.sync)
+        mip = MIP()
+
+        mp = Instance("CPUMIP", name="cpu_mip",
+            o_mip = mip.mip)
+
+        self.specials += mp
+
+        mii = Instance("CPUMIE", name="cpu_mie",
+            o_mie = mie.mie,
+            i_meie = mie.meie,
+            i_mtie = mie.mtie,
+            i_msie = mie.msie)
+
+        self.specials += mii
+
+        ms = Instance("CPUMStatus", name="cpu_mstatus",
+            o_mstatus = mstatus.mstatus,
+            i_mpie = mstatus.mpie,
+            i_mie = mstatus.mie)
+
+        self.specials += ms
+
+        # CSR decoding
+        csr = CSR(self.comb, self.sync, dc, self.regs.rs1)
+
+        fi = Instance("CPUFetchAction", name="cpu_fetch_action",
+            o_fetch_action = ft.action,
+            i_output_state = ft.output_state,
+            i_dc_act = dc.act,
+            i_load_store_misaligned = load_store_misaligned,
+            i_mi_rw_wait = mi.rw_wait,
+            i_mi_rw_address_valid = mi.rw_address_valid,
+            i_branch_taken = branch_taken,
+            i_misaligned_jump_target = misaligned_jump_target,
+            i_csr_op_is_valid = csr.op_is_valid)
+
+        self.specials += fi
+
+        minfo = MInfo(self.comb)
+
+        self.new_mcause = Signal(32)
+        self.new_mepc = Signal(32)
+        self.new_mpie = Signal()
+        self.new_mie = Signal()
+
+        ht = Instance("CPUHandleTrap", "cpu_handle_trap",
+                      i_ft_action = ft.action,
+                      i_ft_output_pc = ft.output_pc,
+                      i_dc_action = dc.act,
+                      i_dc_immediate = dc.immediate,
+                      i_load_store_misaligned = load_store_misaligned,
+                      i_mie = mstatus.mie,
+                      o_mcause = self.new_mcause,
+                      o_mepc = self.new_mepc,
+                      o_mpie = self.new_mpie,
+                      o_mie = self.new_mie)
+
+        self.specials += ht
+
+        self.sync += If(~self.reset,
+                        self.main_block(mtvec, mip, minfo, misa, csr, mi, m,
+                                        mstatus, mie, ft, dc,
+                                        load_store_misaligned,
+                                        loaded_value,
+                                       alu_result,
+                                       lui_auipc_result)
+                     )
+
+if __name__ == "__main__":
+    example = CPU()
+    print(verilog.convert(example,
+         {
+           example.tty_write,
+           example.tty_write_data,
+           example.tty_write_busy,
+           example.switch_2,
+           example.switch_3,
+           example.led_1,
+           example.led_3,
+           }))
diff --git a/cpu_decoder.py b/cpu_decoder.py
new file mode 100644 (file)
index 0000000..c92fb88
--- /dev/null
@@ -0,0 +1,273 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 100ps
+"""
+from migen import *
+from migen.fhdl import verilog
+
+from riscvdefs import *
+from cpudefs import *
+
+class CPUDecoder(Module):
+    """ decodes a 32-bit instruction into an immediate and other constituent
+        parts, including the opcode and funct3 and funct7, followed by
+        a further (hierarchical) breakdown of the action required to be taken.
+        unidentified actions are decoded as an illegal instruction trap.
+    """
+
+    def __init__(self):
+        self.instruction = Signal(32)
+        self.funct7 = Signal(7)
+        self.funct3 = Signal(3)
+        self.rd = Signal(5)
+        self.rs1 = Signal(5)
+        self.rs2 = Signal(5)
+        self.immediate = Signal(32)
+        self.opcode = Signal(7)
+        self.decode_action = Signal(decode_action)
+
+        # decode bits of instruction
+        self.comb += self.funct7.eq(self.instruction[25:32])
+        self.comb += self.funct3.eq(self.instruction[12:15])
+        self.comb += self.rd.eq    (self.instruction[7:12])
+        self.comb += self.rs1.eq   (self.instruction[15:20])
+        self.comb += self.rs2.eq   (self.instruction[20:25])
+        self.comb += self.opcode.eq(self.instruction[0:7])
+
+        # add combinatorial decode opcode case statements for immed and action
+        self.comb += self.calculate_immediate()
+        self.comb += self.calculate_action()
+
+    def calculate_immediate(self):
+        """ calculate immediate
+        """
+        ci = {}
+        no_imm = Constant(0x0, 32)
+
+        # R-type: no immediate
+        for op in [OP.amo, OP.op, OP.op_32, OP.op_fp]:
+            ci[op] = self.immediate.eq(no_imm)
+
+        # I-type: sign-extended bits 20-31
+        im = Cat(self.instruction[20:], Replicate(self.instruction[31], 20))
+        for op in [OP.load, OP.load_fp, OP.misc_mem,
+                   OP.op_imm, OP.op_imm_32, OP.jalr,
+                   OP.system]:
+            ci[op] = self.immediate.eq(im)
+
+        # S-type
+        im = Cat(self.instruction[7:12], self.instruction[25:31],
+                 Replicate(self.instruction[31], 21))
+        for op in [OP.store, OP.store_fp]:
+            ci[op] = self.immediate.eq(im)
+
+        # B-type
+        im = Cat(Constant(0, 1),
+                 self.instruction[8:12], self.instruction[25:31],
+                 self.instruction[7], Replicate(self.instruction[31], 20))
+        for op in [OP.branch, ]:
+            ci[op] = self.immediate.eq(im)
+
+        # U-type
+        im = Cat(Constant(0, 1), self.instruction[12:], )
+        for op in [OP.auipc, OP.lui]:
+            ci[op] = self.immediate.eq(im)
+
+        # J-type
+        im = Cat(Constant(0, 1),
+                 self.instruction[21:25], self.instruction[25:31],
+                 self.instruction[20], self.instruction[12:20],
+                 Replicate(self.instruction[31], 12))
+        for op in [OP.jal, ]:
+            ci[op] = self.immediate.eq(im)
+
+        # R4-type: no immediate
+        for op in [OP.madd, OP.msub, OP.nmsub, OP.nmadd]:
+            ci[op] = self.immediate.eq(no_imm)
+
+        # unknown
+        for op in [ OP.custom_0, OP.op_48b_escape_0, OP.custom_1,
+                    OP.op_64b_escape, OP.reserved_10101, OP.rv128_0,
+                    OP.op_48b_escape_1, OP.reserved_11010,
+                    OP.reserved_11101, OP.rv128_1, OP.op_80b_escape]:
+            ci[op] = self.immediate.eq(no_imm)
+
+        # default
+        for op in [ "default", ]:
+            ci[op] = self.immediate.eq(no_imm)
+
+        return Case(self.opcode, ci)
+
+    def _decode_funct3(self, action, options):
+        """ decode by list of cases
+        """
+        c = {}
+        # load opcode
+        for op in options:
+            c[op] = self.decode_action.eq(action)
+        # default
+        c["default"] = self.decode_action.eq(DA.trap_illegal_instruction)
+
+        return Case(self.funct3, c)
+
+    def calculate_store_action(self):
+        """ decode store action
+        """
+        return self._decode_funct3(DA.store, [F3.sb, F3.sh, F3.sw, ])
+
+    def calculate_load_action(self):
+        """ decode load action
+        """
+        return self._decode_funct3(DA.load, [F3.lb, F3.lbu, F3.lh,
+                                             F3.lhu, F3.lw, ])
+
+    def calculate_branch_action(self):
+        """ decode branch action
+        """
+        return self._decode_funct3(DA.branch, [F3.beq, F3.bne, F3.blt,
+                                               F3.bge, F3.bltu, F3.bgeu ])
+
+    def calculate_jalr_action(self):
+        """ decode jalr action
+        """
+        return self._decode_funct3(DA.jalr, [F3.jalr, ])
+
+    def calculate_op_action(self):
+        """ decode op action: the arith ops, and, or, add, xor, sr/sl etc.
+        """
+        c = {}
+        immz = Constant(0, 12)
+        regz = Constant(0, 5)
+        # slli
+        c[F3.slli] = \
+            If((self.funct7 == Constant(0, 7)),
+                self.decode_action.eq(DA.op_op_imm)
+            ).Else(
+                self.decode_action.eq(DA.trap_illegal_instruction))
+        # srli/srai
+        c[F3.srli_srai] = \
+            If((self.funct7 == Constant(0, 7) | \
+               (self.funct7 == Constant(0x20, 7))),
+                self.decode_action.eq(DA.op_op_imm)
+            ).Else(
+                self.decode_action.eq(DA.trap_illegal_instruction))
+        # default
+        c["default"] = self.decode_action.eq(DA.op_op_imm)
+
+        return Case(self.funct3, c)
+
+    def calculate_misc_action(self):
+        """ decode misc mem action: fence and fence_i
+        """
+        c = {}
+        immz = Constant(0, 12)
+        regz = Constant(0, 5)
+        # fence
+        c[F3.fence] = \
+            If((self.immediate[8:12] == immz) & (self.rs1 == regz) & \
+                                                (self.rd == regz),
+                self.decode_action.eq(DA.fence)
+            ).Else(
+                self.decode_action.eq(DA.trap_illegal_instruction))
+        # fence.i
+        c[F3.fence_i] = \
+            If((self.immediate[0:12] == immz) & (self.rs1 == regz) & \
+                                                (self.rd == regz),
+                self.decode_action.eq(DA.fence_i)
+            ).Else(
+                self.decode_action.eq(DA.trap_illegal_instruction))
+        # default
+        c["default"] = self.decode_action.eq(DA.trap_illegal_instruction)
+
+        return Case(self.funct3, c)
+
+    def calculate_system_action(self):
+        """ decode opcode system: ebreak and csrs
+        """
+        c = {}
+        b1 = Constant(1, 32)
+        regz = Constant(0, 5)
+        # ebreak
+        c[F3.ecall_ebreak] = \
+            If((self.immediate == ~b1) & (self.rs1 == regz) & \
+                                         (self.rd == regz),
+                self.decode_action.eq(DA.trap_ecall_ebreak)
+            ).Else(
+                self.decode_action.eq(DA.trap_illegal_instruction))
+        # csrs
+        for op in [ F3.csrrw, F3.csrrs, F3.csrrc,
+                    F3.csrrwi, F3.csrrsi, F3.csrrci]:
+            c[op] = self.decode_action.eq(DA.csr)
+        # default
+        c["default"] = self.decode_action.eq(DA.trap_illegal_instruction)
+
+        return Case(self.funct3, c)
+
+    def calculate_action(self):
+        """ calculate action based on opcode.
+
+            this is a first level case statement that calls down to 2nd
+            level case (and in some cases if logic) mostly using funct3
+            (funct7 in the case of arith ops).
+        """
+        c = {}
+        c[OP.load    ] = self.calculate_load_action()
+        c[OP.misc_mem] = self.calculate_misc_action()
+        c[OP.op_imm  ] = self.calculate_op_action()
+        c[OP.op      ] = self.calculate_op_action()
+        c[OP.lui     ] = self.decode_action.eq(DA.lui_auipc)
+        c[OP.auipc   ] = self.decode_action.eq(DA.lui_auipc)
+        c[OP.store   ] = self.calculate_store_action()
+        c[OP.branch  ] = self.calculate_branch_action()
+        c[OP.jalr    ] = self.calculate_jalr_action()
+        c[OP.jal     ] = self.decode_action.eq(DA.jal)
+        c[OP.system  ] = self.calculate_system_action()
+
+        # big batch of unrecognised opcodes: throw trap.
+        for o in [ OP.load_fp, OP.custom_0, OP.op_imm_32,
+                    OP.op_48b_escape_0, OP.store_fp, OP.custom_1,
+                    OP.amo, OP.op_32, OP.op_64b_escape,
+                    OP.madd, OP.msub, OP.nmsub,
+                    OP.nmadd, OP.op_fp, OP.reserved_10101,
+                    OP.rv128_0, OP.op_48b_escape_1, OP.reserved_11010,
+                    OP.reserved_11101, OP.rv128_1, OP.op_80b_escape,
+                    "default", ]:
+            c[o] = self.decode_action.eq(DA.trap_illegal_instruction)
+
+        return Case(self.opcode, c)
+
+if __name__ == "__main__":
+    example = CPUDecoder()
+    print(verilog.convert(example,
+         {
+           example.instruction,
+           example.funct7,
+           example.funct3,
+           example.rd,
+           example.rs1,
+           example.rs2,
+           example.immediate,
+           example.opcode,
+           example.decode_action,
+           }))
diff --git a/cpu_fetch_action.py b/cpu_fetch_action.py
new file mode 100644 (file)
index 0000000..3b6d7b8
--- /dev/null
@@ -0,0 +1,128 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+class CPUFetchAction(Module):
+    def __init__(self):
+        Module.__init__(self)
+        self.action = Signal(fetch_action)
+        self.output_state = Signal()
+        self.dc_act = Signal(decode_action)
+        self.load_store_misaligned = Signal()
+        self.mi_rw_wait = Signal()
+        self.mi_rw_address_valid = Signal()
+        self.branch_taken = Signal()
+        self.misaligned_jump_target = Signal()
+        self.csr_op_is_valid = Signal()
+
+        c = {}
+        c["default"] = self.action.eq(FA.default) # XXX should be 32'XXXXXXXX?
+        c[FOS.empty] = self.action.eq(FA.default)
+        c[FOS.trap] = self.action.eq(FA.ack_trap)
+
+        # illegal instruction -> error trap
+        i= If((self.dc_act & DA.trap_illegal_instruction) != 0,
+                 self.action.eq(FA.error_trap)
+              )
+
+        # ecall / ebreak -> noerror trap
+        i = i.Elif((self.dc_act & DA.trap_ecall_ebreak) != 0,
+                 self.action.eq(FA.noerror_trap))
+
+        # load/store: check alignment, check wait
+        i = i.Elif((self.dc_act & (DA.load | DA.store)) != 0,
+                If((self.load_store_misaligned | ~self.mi_rw_address_valid),
+                    self.action.eq(FA.error_trap) # misaligned or invalid addr
+                ).Elif(self.mi_rw_wait,
+                    self.action.eq(FA.wait) # wait
+                ).Else(
+                    self.action.eq(FA.default) # ok
+                )
+              )
+
+        # fence
+        i = i.Elif((self.dc_act & DA.fence) != 0,
+                 self.action.eq(FA.fence))
+
+        # branch -> misaligned=error, otherwise jump
+        i = i.Elif((self.dc_act & DA.branch) != 0,
+                If(self.branch_taken,
+                    If(self.misaligned_jump_target,
+                        self.action.eq(FA.error_trap)
+                    ).Else(
+                        self.action.eq(FA.jump)
+                    )
+                 ).Else(
+                        self.action.eq(FA.default)
+                 )
+              )
+
+        # jal/jalr -> misaligned=error, otherwise jump
+        i = i.Elif((self.dc_act & (DA.jal | DA.jalr)) != 0,
+                If(self.misaligned_jump_target,
+                    self.action.eq(FA.error_trap)
+                ).Else(
+                    self.action.eq(FA.jump)
+                )
+              )
+
+        # csr -> opvalid=ok, else error trap
+        i = i.Elif((self.dc_act & DA.csr) != 0,
+                If(self.csr_op_is_valid,
+                    self.action.eq(FA.default)
+                ).Else(
+                    self.action.eq(FA.error_trap)
+                )
+              )
+
+        c[FOS.valid] = i
+
+        self.comb += Case(self.output_state, c)
+
+
+if __name__ == "__main__":
+    example = CPUFetchAction()
+    print(verilog.convert(example,
+         {
+            example.action,
+            example.output_state,
+            example.dc_act,
+            example.load_store_misaligned,
+            example.mi_rw_wait,
+            example.mi_rw_address_valid,
+            example.branch_taken,
+            example.misaligned_jump_target,
+            example.csr_op_is_valid,
+           }))
diff --git a/cpu_fetch_stage.py b/cpu_fetch_stage.py
new file mode 100644 (file)
index 0000000..e3a3467
--- /dev/null
@@ -0,0 +1,127 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+"""
+
+from migen import *
+from migen.fhdl import verilog
+
+#from riscvdefs import *
+from cpudefs import *
+
+
+class CPUFetchStage(Module):
+    def __init__(self):
+        self.clk = ClockSignal()
+        self.reset = ResetSignal()
+        self.reset_vector = Signal(32) #32'hXXXXXXXX; - parameter
+        self.mtvec = Signal(32) # 32'hXXXXXXXX; - parameter
+        #output [31:2] memory_interface_fetch_address,
+        self.memory_interface_fetch_address = Signal(32)
+        #input [31:0] memory_interface_fetch_data,
+        self.memory_interface_fetch_data = Signal(32)
+        self.memory_interface_fetch_valid = Signal()
+        self.fetch_action = Signal(fetch_action)
+        self.target_pc = Signal(32)
+        self.output_pc = Signal(32, reset=self.reset_vector)
+        self.output_instruction = Signal(32)
+        self.output_state = Signal(fetch_output_state,
+                                   reset=FOS.empty)
+
+        #self.comb += [
+        #    self.cd_sys.clk.eq(self.clk),
+        #    self.cd_sys.rst.eq(self.reset)
+        #]
+
+        fetch_pc = Signal(32, reset=self.reset_vector)
+
+        self.sync += If(self.fetch_action != FA.wait,
+                        self.output_pc.eq(fetch_pc))
+
+        self.comb += self.memory_interface_fetch_address.eq(fetch_pc[2:])
+
+        #initial output_pc <= self.reset_vector;
+        #initial output_state <= `FOS.empty;
+
+        delayed_instruction = Signal(32, reset=0)
+        delayed_instruction_valid = Signal(reset=0)
+
+        self.sync += delayed_instruction.eq(self.output_instruction)
+
+        self.comb += If(delayed_instruction_valid,
+                    self.output_instruction.eq(delayed_instruction)
+                ).Else(
+                    self.output_instruction.eq(self.memory_interface_fetch_data)
+                )
+
+        self.sync += delayed_instruction_valid.eq(self.fetch_action ==
+                                                  FA.wait)
+
+        fc = {
+            FA.ack_trap:
+                If(self.memory_interface_fetch_valid,
+                   [fetch_pc.eq(fetch_pc + 4),
+                    self.output_state.eq(FOS.valid)]
+                ).Else(
+                   [fetch_pc.eq(self.mtvec),
+                    self.output_state.eq(FOS.trap)]
+                ),
+            FA.fence:
+                [ fetch_pc.eq(self.output_pc + 4),
+                  self.output_state.eq(FOS.empty)
+                ],
+            FA.jump:
+                [ fetch_pc.eq(self.target_pc),
+                  self.output_state.eq(FOS.empty)
+                ],
+            FA.error_trap:
+                   [fetch_pc.eq(self.mtvec),
+                    self.output_state.eq(FOS.empty)
+                ],
+            FA.wait:
+                   [fetch_pc.eq(fetch_pc),
+                    self.output_state.eq(FOS.valid)
+                ]
+        }
+        fc[FA.default] = fc[FA.ack_trap]
+        fc[FA.noerror_trap] = fc[FA.error_trap]
+        self.sync += Case(self.fetch_action,
+                          fc).makedefault(FA.default)
+
+if __name__ == "__main__":
+    example = CPUFetchStage()
+    #memory_interface_fetch_address = Signal(32)
+    print(verilog.convert(example,
+         { #example.clk,
+           #example.reset,
+           example.memory_interface_fetch_address,
+           example.memory_interface_fetch_data,
+           example.memory_interface_fetch_valid,
+           example.fetch_action,
+           example.target_pc,
+           example.output_pc,
+           example.output_instruction,
+           example.output_state,
+           example.reset_vector,
+           example.mtvec
+            }))
diff --git a/cpu_handle_csr.py b/cpu_handle_csr.py
new file mode 100644 (file)
index 0000000..f2f5788
--- /dev/null
@@ -0,0 +1,259 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+
+class Misa:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.misa = Signal(32)
+        cl = []
+        for l in list(string.ascii_lowercase):
+            value = 1 if l == 'i' else 0
+            cl.append(Constant(value))
+        cl.append(Constant(0, 4))
+        cl.append(Constant(0b01, 2))
+        self.comb += self.misa.eq(Cat(cl))
+
+class MStatus:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.mpie = Signal(name="mstatus_mpie")
+        self.mie = Signal(name="mstatus_mie")
+        self.mstatus = Signal(32, name="mstatus")
+
+        self.sync += self.mie.eq(0)
+        self.sync += self.mpie.eq(0)
+        self.sync += self.mstatus.eq(0)
+
+
+class M:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.mcause = Signal(32)
+        self.mepc = Signal(32)
+        self.mscratch = Signal(32)
+        self.sync += self.mcause.eq(0)
+        self.sync += self.mepc.eq(0) # 32'hXXXXXXXX;
+        self.sync += self.mscratch.eq(0) # 32'hXXXXXXXX;
+
+
+class MIE:
+    def __init__(self, comb, sync):
+        self.comb = comb
+        self.sync = sync
+        self.meie = Signal(name="mie_meie")
+        self.mtie = Signal(name="mie_mtie")
+        self.msie = Signal(name="mie_msie")
+        self.mie = Signal(32)
+
+
+class MIP:
+    def __init__(self):
+        self.mip = Signal(32)
+
+
+
+class MInfo:
+    def __init__(self, comb):
+        self.comb = comb
+        # TODO
+        self.cycle_counter   = Signal(64); # TODO: implement cycle_counter
+        self.time_counter    = Signal(64); # TODO: implement time_counter
+        self.instret_counter = Signal(64); # TODO: implement instret_counter
+
+        self.mvendorid = Signal(32)
+        self.marchid = Signal(32)
+        self.mimpid = Signal(32)
+        self.mhartid = Signal(32)
+        self.comb += self.mvendorid.eq(Constant(0, 32))
+        self.comb += self.marchid.eq(Constant(0, 32))
+        self.comb += self.mimpid.eq(Constant(0, 32))
+        self.comb += self.mhartid.eq(Constant(0, 32))
+
+
+class CPUHandleCSR(Module):
+    """
+    """
+
+    def __init__(self):
+        Module.__init__(self)
+        self.clk = ClockSignal()
+        self.reset = ResetSignal()
+
+        self.dc_funct3 = Signal(3)
+        self.mtvec = Signal(32)
+        self.csr_number = Signal(12)
+        self.csr_writes = Signal()
+
+        self.input_value = Signal(32)
+        self.output_value = Signal(32)
+
+        mstatus = MStatus(self.comb, self.sync)
+        m = M(self.comb, self.sync)
+        mie = MIE(self.comb, self.sync)
+        mip = MIP()
+        self.mie = mstatus.mie
+        self.mepc = m.mepc
+        self.mcause = m.mcause
+
+        minfo = MInfo(self.comb)
+        misa = Misa(self.comb, self.sync)
+
+        ms = Instance("CPUMStatus", name="cpu_mstatus",
+            o_mstatus = mstatus.mstatus,
+            i_mpie = mstatus.mpie,
+            i_mie = mstatus.mie)
+
+        self.specials += ms
+
+        mp = Instance("CPUMIP", name="cpu_mip",
+            o_mip = mip.mip)
+
+        self.specials += mp
+
+        mii = Instance("CPUMIE", name="cpu_mie",
+            o_mie = mie.mie,
+            i_meie = mie.meie,
+            i_mtie = mie.mtie,
+            i_msie = mie.msie)
+
+        self.specials += mii
+
+        written_value = Signal(32)
+
+        c = {}
+
+        # cycle
+        c[csr_cycle]  = self.output_value.eq(minfo.cycle_counter[0:32])
+        c[csr_cycleh] = self.output_value.eq(minfo.cycle_counter[32:64])
+        # time
+        c[csr_time]  = self.output_value.eq(minfo.time_counter[0:32])
+        c[csr_timeh] = self.output_value.eq(minfo.time_counter[32:64])
+        # instret
+        c[csr_instret]  = self.output_value.eq(minfo.instret_counter[0:32])
+        c[csr_instreth] = self.output_value.eq(minfo.instret_counter[32:64])
+        # mvendorid/march/mimpl/mhart
+        c[csr_mvendorid] = self.output_value.eq(minfo.mvendorid)
+        c[csr_marchid  ] = self.output_value.eq(minfo.marchid  )
+        c[csr_mimpid   ] = self.output_value.eq(minfo.mimpid   )
+        c[csr_mhartid  ] = self.output_value.eq(minfo.mhartid  )
+        # misa
+        c[csr_misa     ] = self.output_value.eq(misa.misa)
+        # mstatus
+        c[csr_mstatus  ] = [
+            self.output_value.eq(mstatus.mstatus),
+            self.evaluate_csr_funct3_op(self.dc_funct3, self.output_value,
+                                                  written_value),
+            mstatus.mpie.eq(written_value[7]),
+            mstatus.mie.eq(written_value[3])
+        ]
+        # mie
+        c[csr_mie      ] = [
+            self.output_value.eq(mie.mie),
+            self.evaluate_csr_funct3_op(self.dc_funct3, self.output_value,
+                                                  written_value),
+            mie.meie.eq(written_value[11]),
+            mie.mtie.eq(written_value[7]),
+            mie.msie.eq(written_value[3]),
+        ]
+        # mtvec
+        c[csr_mtvec    ] = self.output_value.eq(self.mtvec)
+        # mscratch
+        c[csr_mscratch ] = [
+            self.output_value.eq(m.mscratch),
+            self.evaluate_csr_funct3_op(self.dc_funct3, self.output_value,
+                                                  written_value),
+            If(self.csr_writes,
+                m.mscratch.eq(written_value),
+            )
+        ]
+        # mepc
+        c[csr_mepc ] = [
+            self.output_value.eq(m.mepc),
+            self.evaluate_csr_funct3_op(self.dc_funct3, self.output_value,
+                                                  written_value),
+            If(self.csr_writes,
+                m.mepc.eq(written_value),
+            )
+        ]
+
+        # mcause
+        c[csr_mcause ] = [
+            self.output_value.eq(m.mcause),
+            self.evaluate_csr_funct3_op(self.dc_funct3, self.output_value,
+                                                  written_value),
+            If(self.csr_writes,
+                m.mcause.eq(written_value),
+            )
+        ]
+
+        # mip
+        c[csr_mip  ] = [
+            self.output_value.eq(mip.mip),
+            self.evaluate_csr_funct3_op(self.dc_funct3, self.output_value,
+                                                  written_value),
+        ]
+
+        self.sync += Case(self.csr_number, c)
+
+    def evaluate_csr_funct3_op(self, funct3, previous, written):
+        c = { "default": written.eq(Constant(0, 32))}
+        for f in [F3.csrrw, F3.csrrwi]:
+            c[f] = written.eq(self.input_value)
+        for f in [F3.csrrs, F3.csrrsi]:
+            c[f] = written.eq(self.input_value | previous)
+        for f in [F3.csrrc, F3.csrrci]:
+            c[f] = written.eq(~self.input_value & previous)
+        return Case(funct3, c)
+
+
+if __name__ == "__main__":
+    example = CPUHandleCSR()
+    print(verilog.convert(example,
+         {
+            example.dc_funct3,
+            example.mtvec,
+            example.csr_number,
+            example.csr_writes,
+            example.input_value,
+            example.output_value,
+            example.mie,
+            example.mepc,
+            example.mcause,
+           }))
diff --git a/cpu_handle_trap.py b/cpu_handle_trap.py
new file mode 100644 (file)
index 0000000..ad4510c
--- /dev/null
@@ -0,0 +1,120 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+
+class CPUHandleTrap(Module):
+    """
+    """
+
+    def __init__(self):
+        Module.__init__(self)
+        self.clk = ClockSignal()
+        self.reset = ResetSignal()
+
+        self.ft_action = Signal(fetch_action)
+        self.dc_action = Signal(decode_action)
+        self.dc_immediate = Signal(32)
+        self.mie = Signal()
+        self.new_mie = Signal()
+        self.new_mepc = Signal()
+        self.new_mpie = Signal()
+        self.new_mcause = Signal(32)
+        self.ft_output_pc = Signal(32)
+        self.load_store_misaligned = Signal()
+
+        s = [self.new_mpie.eq(self.mie),
+             self.new_mie.eq(0),
+             self.new_mepc.eq(Mux(self.ft_action == FA.noerror_trap,
+                           self.ft_output_pc + 4,
+                           self.ft_output_pc))]
+
+        # fetch action ack trap
+        i = If(self.ft_action == FA.ack_trap,
+                self.new_mcause.eq(cause_instruction_access_fault)
+              )
+
+        # ecall/ebreak
+        i = i.Elif((self.dc_action & DA.trap_ecall_ebreak) != 0,
+                self.new_mcause.eq(Mux(self.dc_immediate[0],
+                                cause_machine_environment_call,
+                                cause_breakpoint))
+              )
+
+        # load
+        i = i.Elif((self.dc_action & DA.load) != 0,
+                If(self.load_store_misaligned,
+                    self.new_mcause.eq(cause_load_address_misaligned)
+                ).Else(
+                    self.new_mcause.eq(cause_load_access_fault)
+                )
+              )
+
+        # store
+        i = i.Elif((self.dc_action & DA.store) != 0,
+                If(self.load_store_misaligned,
+                    self.new_mcause.eq(cause_store_amo_address_misaligned)
+                ).Else(
+                    self.new_mcause.eq(cause_store_amo_access_fault)
+                )
+              )
+
+        # jal/jalr -> misaligned=error, otherwise jump
+        i = i.Elif((self.dc_action & (DA.jal | DA.jalr | DA.branch)) != 0,
+                self.new_mcause.eq(cause_instruction_address_misaligned)
+              )
+
+        # defaults to illegal instruction
+        i = i.Else(self.new_mcause.eq(cause_illegal_instruction))
+
+        s.append(i)
+
+        self.sync += s
+
+
+if __name__ == "__main__":
+    example = CPUHandleTrap()
+    print(verilog.convert(example,
+         {
+            example.ft_action,
+            example.dc_immediate,
+            example.mie,
+            example.new_mcause,
+            example.new_mepc,
+            example.new_mpie,
+            example.new_mie,
+            example.ft_output_pc,
+            example.load_store_misaligned,
+           }))
diff --git a/cpu_loadstore_calc.py b/cpu_loadstore_calc.py
new file mode 100644 (file)
index 0000000..5a82a0d
--- /dev/null
@@ -0,0 +1,133 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+class CPULoadStoreCalc(Module):
+    """
+    """
+
+    def get_ls_misaligned(self, ls, funct3, load_store_address_low_2):
+        """ returns whether a load/store is misaligned
+        """
+        return Case(funct3[:2],
+                { F3.sb: ls.eq(Constant(0)),
+                  F3.sh: ls.eq(load_store_address_low_2[0] != 0),
+                  F3.sw: ls.eq(load_store_address_low_2[0:2] != Constant(0, 2)),
+                  "default": ls.eq(Constant(1))
+                })
+
+    def __init__(self):
+        Module.__init__(self)
+        self.clk = ClockSignal()
+        self.reset = ResetSignal()
+        self.dc_immediate = Signal(32)
+        self.dc_funct3 = Signal(3)
+        self.rs1 = Signal(32)
+        self.rs2 = Signal(32)
+        self.rw_data_in = Signal(32)
+        self.rw_data_out = Signal(32)
+
+        self.load_store_address = Signal(32)
+        self.load_store_address_low_2 = Signal(2)
+        self.load_store_misaligned = Signal()
+        self.loaded_value = Signal(32)
+
+        self.comb += self.load_store_address.eq(self.dc_immediate + self.rs1)
+        self.comb += self.load_store_address_low_2.eq(
+                            self.dc_immediate[:2] + self.rs1[:2])
+
+        lsa = self.get_ls_misaligned(self.load_store_misaligned, self.dc_funct3,
+                                     self.load_store_address_low_2)
+        self.comb += lsa
+
+        # XXX not obvious
+        b3 = Mux(self.load_store_address_low_2[1],
+                 Mux(self.load_store_address_low_2[0], self.rs2[0:8],
+                                                  self.rs2[8:16]),
+                 Mux(self.load_store_address_low_2[0], self.rs2[16:24],
+                                                  self.rs2[24:32]))
+        b2 = Mux(self.load_store_address_low_2[1], self.rs2[0:8],
+                                              self.rs2[16:24])
+        b1 = Mux(self.load_store_address_low_2[0], self.rs2[0:8],
+                                              self.rs2[8:16])
+        b0 = self.rs2[0:8]
+
+        self.comb += self.rw_data_in.eq(Cat(b0, b1, b2, b3))
+
+        # XXX not obvious
+        unmasked_loaded_value = Signal(32)
+
+        b0 = Mux(self.load_store_address_low_2[1],
+                 Mux(self.load_store_address_low_2[0], self.rw_data_out[24:32],
+                                                  self.rw_data_out[16:24]),
+                 Mux(self.load_store_address_low_2[0], self.rw_data_out[15:8],
+                                                  self.rw_data_out[0:8]))
+        b1 = Mux(self.load_store_address_low_2[1], self.rw_data_out[24:31],
+                                              self.rw_data_out[8:16])
+        b23 = self.rw_data_out[16:32]
+
+        self.comb += unmasked_loaded_value.eq(Cat(b0, b1, b23))
+
+        # XXX not obvious
+
+        b0 = unmasked_loaded_value[0:8]
+        b1 = Mux(self.dc_funct3[0:2] == 0,
+                Replicate(~self.dc_funct3[2] & unmasked_loaded_value[7], 8),
+                unmasked_loaded_value[8:16])
+        b2 = Mux(self.dc_funct3[1] == 0,
+                Replicate(~self.dc_funct3[2] &
+                           Mux(self.dc_funct3[0], unmasked_loaded_value[15],
+                                                  unmasked_loaded_value[7]),
+                          16),
+                unmasked_loaded_value[16:32])
+
+        self.comb += self.loaded_value.eq(Cat(b0, b1, b2))
+
+
+if __name__ == "__main__":
+    example = CPULoadStoreCalc()
+    print(verilog.convert(example,
+         {
+            example.dc_immediate,
+            example.dc_funct3,
+            example.rs1,
+            example.rs2,
+            example.rw_data_in,
+            example.rw_data_out,
+            example.load_store_address,
+            example.load_store_address_low_2,
+            example.load_store_misaligned,
+            example.loaded_value,
+           }))
diff --git a/cpu_mie.py b/cpu_mie.py
new file mode 100644 (file)
index 0000000..8345ba9
--- /dev/null
@@ -0,0 +1,77 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+class CPUMIE(Module):
+    def __init__(self):
+        Module.__init__(self)
+        self.meie = Signal(name="mie_meie", reset=0)
+        self.mtie = Signal(name="mie_mtie", reset=0)
+        self.msie = Signal(name="mie_msie", reset=0)
+        self.seie = Signal(name="mie_seie")
+        self.ueie = Signal(name="mie_ueie")
+        self.stie = Signal(name="mie_stie")
+        self.utie = Signal(name="mie_utie")
+        self.ssie = Signal(name="mie_ssie")
+        self.usie = Signal(name="mie_usie")
+
+        for n in dir(self):
+            if n.startswith("_"):
+                continue
+            n = getattr(self, n)
+            if not isinstance(n, Signal):
+                continue
+            self.comb += n.eq(0x0)
+
+        self.mie = Signal(32)
+
+        self.sync += self.mie.eq(self.make())
+
+    def make(self):
+        return Cat( self.usie, self.ssie, 0, self.msie,
+                    self.utie, self.stie, 0, self.mtie,
+                    self.ueie, self.seie, 0, self.meie, )
+
+
+
+if __name__ == "__main__":
+    example = CPUMIE()
+    print(verilog.convert(example,
+         {
+           example.meie,
+           example.mtie,
+           example.msie,
+           example.mie,
+           }))
diff --git a/cpu_mip.py b/cpu_mip.py
new file mode 100644 (file)
index 0000000..30a5cf3
--- /dev/null
@@ -0,0 +1,66 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+class CPUMIP(Module):
+    def __init__(self):
+        Module.__init__(self)
+        # TODO: implement ext interrupts
+        self.meip = Signal(name="mip_meip", reset=0)
+        self.seip = Signal(name="mip_seip", reset=0)
+        self.ueip = Signal(name="mip_uiep", reset=0)
+        # TODO: implement timer interrupts
+        self.mtip = Signal(name="mip_mtip", reset=0)
+        self.stip = Signal(name="mip_stip", reset=0)
+        self.msip = Signal(name="mip_stip", reset=0)
+        self.utip = Signal(name="mip_utip", reset=0)
+        self.ssip = Signal(name="mip_ssip", reset=0)
+        self.usip = Signal(name="mip_usip", reset=0)
+
+        self.mip = Signal(32)
+        self.comb += self.mip.eq(self.make())
+
+    def make(self):
+        return Cat( self.usip, self.ssip, 0, self.msip,
+                    self.utip, self.stip, 0, self.mtip,
+                    self.ueip, self.seip, 0, self.meip, )
+
+
+if __name__ == "__main__":
+    example = CPUMIP()
+    print(verilog.convert(example,
+         {
+           example.mip,
+           }))
diff --git a/cpu_mstatus.py b/cpu_mstatus.py
new file mode 100644 (file)
index 0000000..6afecc1
--- /dev/null
@@ -0,0 +1,96 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+import string
+from migen import *
+from migen.fhdl import verilog
+from migen.fhdl.structure import _Operator
+
+from riscvdefs import *
+from cpudefs import *
+
+class MStatus:
+    def __init__(self):
+        self.mpie = Signal(name="mstatus_mpie", reset=0)
+        self.mie = Signal(name="mstatus_mie", reset=0)
+        self.mprv = Signal(name="mstatus_mprv", reset=0)
+        self.tsr = Signal(name="mstatus_tsr", reset=0)
+        self.tw = Signal(name="mstatus_tw", reset=0)
+        self.tvm = Signal(name="mstatus_tvm", reset=0)
+        self.mxr = Signal(name="mstatus_mxr", reset=0)
+        self._sum = Signal(name="mstatus_sum", reset=0)
+        self.xs = Signal(name="mstatus_xs", reset=0)
+        self.fs = Signal(name="mstatus_fs", reset=0)
+        self.mpp = Signal(2, name="mstatus_mpp", reset=0b11)
+        self.spp = Signal(name="mstatus_spp", reset=0)
+        self.spie = Signal(name="mstatus_spie", reset=0)
+        self.upie = Signal(name="mstatus_upie", reset=0)
+        self.sie = Signal(name="mstatus_sie", reset=0)
+        self.uie = Signal(name="mstatus_uie", reset=0)
+
+        io = set()
+        for n in dir(self):
+            if n.startswith("_"):
+                continue
+            n = getattr(self, n)
+            if not isinstance(n, Signal):
+                continue
+            io.add(n)
+        self.io = io
+
+
+class CPUMStatus(Module, MStatus):
+
+    def __init__(self):
+        MStatus.__init__(self)
+        Module.__init__(self)
+
+        self.mstatus = Signal(32)
+
+        for io in self.io:
+            if io.name_override != self.mpp.name_override:
+                self.comb += io.eq(0x0)
+        self.comb += self.mpp.eq(0b11)
+        self.comb += self.mstatus.eq(self.make())
+
+        self.io = set({self.mstatus, self.mpie, self.mie})
+
+    def make(self):
+        return Cat(
+                self.uie, self.sie, Constant(0), self.mie,
+                self.upie, self.spie, Constant(0), self.mpie,
+                self.spp, Constant(0, 2), self.mpp,
+                self.fs, self.xs, self.mprv, self._sum,
+                self.mxr, self.tvm, self.tw, self.tsr,
+                Constant(0, 8),
+                (self.xs == Constant(0b11, 2)) | (self.fs == Constant(0b11, 2))
+                )
+
+if __name__ == "__main__":
+    example = CPUMStatus()
+    print(verilog.convert(example, example.io))
diff --git a/cpudefs.py b/cpudefs.py
new file mode 100644 (file)
index 0000000..b5217f9
--- /dev/null
@@ -0,0 +1,65 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+"""
+
+from migen import Constant
+fetch_action = 3
+
+class FA:
+    """ Fetch action constants
+    """
+    default = Constant(0x0, fetch_action)
+    fence = Constant(0x1, fetch_action)
+    jump = Constant(0x2, fetch_action)
+    wait = Constant(0x3, fetch_action)
+    error_trap = Constant(0x4, fetch_action)
+    noerror_trap = Constant(0x5, fetch_action)
+    ack_trap = Constant(0x6, fetch_action)
+
+fetch_output_state = 2
+
+class FOS:
+    """ Fetch output state constants
+    """
+    empty = Constant(0x0, fetch_output_state)
+    valid = Constant(0x1, fetch_output_state)
+    trap = Constant(0x2, fetch_output_state)
+
+decode_action = 12
+
+class DA:
+    """ Decode action constants
+    """
+    trap_illegal_instruction = Constant(0x1, decode_action)
+    load = Constant(0x2, decode_action)
+    fence = Constant(0x4, decode_action)
+    fence_i = Constant(0x8, decode_action)
+    op_op_imm = Constant(0x10, decode_action)
+    lui_auipc = Constant(0x20, decode_action)
+    store = Constant(0x40, decode_action)
+    branch = Constant(0x80, decode_action)
+    jalr = Constant(0x100, decode_action)
+    jal = Constant(0x200, decode_action)
+    trap_ecall_ebreak = Constant(0x400, decode_action)
+    csr = Constant(0x800, decode_action)
diff --git a/pipestage.py b/pipestage.py
new file mode 100644 (file)
index 0000000..4ec0da0
--- /dev/null
@@ -0,0 +1,90 @@
+""" Example 5: Making use of PyRTL and Introspection. """
+
+from copy import deepcopy
+from migen import Module, Signal
+from migen.fhdl import verilog
+from migen.fhdl.bitcontainer import value_bits_sign
+
+
+# The following example shows how pyrtl can be used to make some interesting
+# hardware structures using python introspection.  In particular, this example
+# makes a N-stage pipeline structure.  Any specific pipeline is then a derived
+# class of SimplePipeline where methods with names starting with "stage" are
+# stages, and new members with names not starting with "_" are to be registered
+# for the next stage.
+
+class SimplePipeline(object):
+    """ Pipeline builder with auto generation of pipeline registers. """
+
+    def __init__(self, pipe):
+        self._pipe = pipe
+        self._pipeline_register_map = {}
+        self._current_stage_num = 0
+
+    def _setup(self):
+        stage_list = []
+        for method in dir(self):
+            if method.startswith('stage'):
+                stage_list.append(method)
+        for stage in sorted(stage_list):
+            stage_method = getattr(self, stage)
+            stage_method()
+            self._current_stage_num += 1
+
+    def __getattr__(self, name):
+        try:
+            return self._pipeline_register_map[self._current_stage_num][name]
+        except KeyError:
+            raise AttributeError(
+                'error, no pipeline register "%s" defined for stage %d'
+                % (name, self._current_stage_num))
+
+    def __setattr__(self, name, value):
+        if name.startswith('_'):
+            # do not do anything tricky with variables starting with '_'
+            object.__setattr__(self, name, value)
+        else:
+            next_stage = self._current_stage_num + 1
+            pipereg_id = str(self._current_stage_num) + 'to' + str(next_stage)
+            rname = 'pipereg_' + pipereg_id + '_' + name
+            new_pipereg = Signal(value_bits_sign(value), name_override=rname)
+            if next_stage not in self._pipeline_register_map:
+                self._pipeline_register_map[next_stage] = {}
+            self._pipeline_register_map[next_stage][name] = new_pipereg
+            self._pipe.sync += new_pipereg.eq(value)
+
+
+class SimplePipelineExample(SimplePipeline):
+    """ A very simple pipeline to show how registers are inferred. """
+
+    def __init__(self, pipe):
+        super(SimplePipelineExample, self).__init__(pipe)
+        self._loopback = Signal(4)
+        self._setup()
+
+    def stage0(self):
+        self.n = ~self._loopback
+
+    def stage1(self):
+        self.n = self.n + 1
+
+    def stage2(self):
+        self.n = self.n << 1
+
+    def stage3(self):
+        self.n = ~self.n
+
+    def stage4(self):
+        self._pipe.sync += self._loopback.eq(self.n + 3)
+
+class PipeModule(Module):
+    def __init__(self):
+        Module.__init__(self)
+
+if __name__ == "__main__":
+    example = PipeModule()
+    pipe = SimplePipelineExample(example)
+    print(verilog.convert(example,
+         { 
+           pipe._loopback,
+         }))
diff --git a/regfile.py b/regfile.py
new file mode 100644 (file)
index 0000000..b544372
--- /dev/null
@@ -0,0 +1,95 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+`timescale 1ns / 1ps
+`include "riscv.vh"
+`include "cpu.vh"
+"""
+
+from migen import *
+from migen.fhdl import verilog
+
+class RegFile(Module):
+
+    def __init__(self):
+        Module.__init__(self)
+        l = []
+        for i in range(31):
+            r = Signal(32, name="register%d" % i)
+            l.append(r)
+            self.sync += r.eq(Constant(0, 32))
+        self.registers = Array(l)
+
+        self.ra_en = Signal() # read porta enable
+        self.rb_en = Signal() # read portb enable
+        self.w_en = Signal()  # write enable
+        self.read_a = Signal(32) # result porta read
+        self.read_b = Signal(32) # result portb read
+        self.writeval = Signal(32) # value to write
+        self.rs_a = Signal(5) # register port a to read
+        self.rs_b = Signal(5) # register port b to read
+        self.rd = Signal(5) # register to write
+
+        self.sync += If(self.ra_en,
+                        self.read(self.rs_a, self.read_a)
+                     )
+        self.sync += If(self.rb_en,
+                        self.read(self.rs_b, self.read_b)
+                     )
+        self.sync += If(self.w_en,
+                        self.write_register(self.rd, self.writeval)
+                     )
+
+    def read(self, regnum, dest):
+        """ sets the destination register argument
+            regnum =  0, dest = 0
+            regnum != 0, dest = regs[regnum-1]
+        """
+        return If(regnum == Constant(0, 5),
+                   dest.eq(Constant(0, 32))
+               ).Else(
+                   dest.eq(self.registers[regnum-1])
+               )
+
+    def write_register(self, regnum, value):
+        """ writes to the register file if the regnum is not zero
+        """
+        return If(regnum != 0,
+                  self.registers[regnum].eq(value)
+               )
+
+if __name__ == "__main__":
+    example = RegFile()
+    print(verilog.convert(example,
+         {
+           example.ra_en,
+           example.rb_en,
+           example.w_en,
+           example.read_a,
+           example.read_b,
+           example.writeval,
+           example.rs_a,
+           example.rs_b,
+           example.rd,
+           }))
+
diff --git a/riscvdefs.py b/riscvdefs.py
new file mode 100644 (file)
index 0000000..f00407a
--- /dev/null
@@ -0,0 +1,187 @@
+"""
+/*
+ * Copyright 2018 Jacob Lifshay
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+"""
+
+from migen import Constant
+
+cause_instruction_address_misaligned = Constant(0x0, 4)
+cause_instruction_access_fault = Constant(0x1, 4)
+cause_illegal_instruction = Constant(0x2, 4)
+cause_breakpoint = Constant(0x3, 4)
+cause_load_address_misaligned = Constant(0x4, 4)
+cause_load_access_fault = Constant(0x5, 4)
+cause_store_amo_address_misaligned = Constant(0x6, 4)
+cause_store_amo_access_fault = Constant(0x7, 4)
+cause_user_environment_call = Constant(0x8, 4)
+cause_supervisor_environment_call = Constant(0x9, 4)
+cause_machine_environment_call = Constant(0xB, 4)
+cause_instruction_page_fault = Constant(0xC, 4)
+cause_load_page_fault = Constant(0xD, 4)
+cause_store_amo_page_fault = Constant(0xF, 4)
+
+class OP:
+    """  Opcode constants
+    """
+    load = Constant(0x03, 7)
+    load_fp = Constant(0x07, 7)
+    custom_0 = Constant(0x0B, 7)
+    misc_mem = Constant(0x0F, 7)
+    op_imm = Constant(0x13, 7)
+    auipc = Constant(0x17, 7)
+    op_imm_32 = Constant(0x1B, 7)
+    op_48b_escape_0 = Constant(0x1F, 7)
+
+    store = Constant(0x23, 7)
+    store_fp = Constant(0x27, 7)
+    custom_1 = Constant(0x2B, 7)
+    amo = Constant(0x2F, 7)
+    op = Constant(0x33, 7)
+    lui = Constant(0x37, 7)
+    op_32 = Constant(0x3B, 7)
+    op_64b_escape = Constant(0x3F, 7)
+
+    madd = Constant(0x43, 7)
+    msub = Constant(0x47, 7)
+    nmsub = Constant(0x4B, 7)
+    nmadd = Constant(0x4F, 7)
+    op_fp = Constant(0x53, 7)
+    reserved_10101 = Constant(0x57, 7)
+    rv128_0 = Constant(0x5B, 7)
+    op_48b_escape_1 = Constant(0x5F, 7)
+
+    branch = Constant(0x63, 7)
+    jalr = Constant(0x67, 7)
+    reserved_11010 = Constant(0x6B, 7)
+    jal = Constant(0x6F, 7)
+    system = Constant(0x73, 7)
+    reserved_11101 = Constant(0x77, 7)
+    rv128_1 = Constant(0x7B, 7)
+    op_80b_escape = Constant(0x7F, 7)
+
+class F3:
+    """ Funct3 constants
+    """
+    jalr = Constant(0x0, 3)
+    beq = Constant(0x0, 3)
+    bne = Constant(0x1, 3)
+    blt = Constant(0x4, 3)
+    bge = Constant(0x5, 3)
+    bltu = Constant(0x6, 3)
+    bgeu = Constant(0x7, 3)
+
+    lb = Constant(0x0, 3)
+    lh = Constant(0x1, 3)
+    lw = Constant(0x2, 3)
+    lbu = Constant(0x4, 3)
+    lhu = Constant(0x5, 3)
+
+    sb = Constant(0x0, 3)
+    sh = Constant(0x1, 3)
+    sw = Constant(0x2, 3)
+
+    addi = Constant(0x0, 3)
+    slli = Constant(0x1, 3)
+    slti = Constant(0x2, 3)
+    sltiu = Constant(0x3, 3)
+    xori = Constant(0x4, 3)
+    srli_srai = Constant(0x5, 3)
+    ori = Constant(0x6, 3)
+    andi = Constant(0x7, 3)
+
+    add_sub = Constant(0x0, 3)
+    sll = Constant(0x1, 3)
+    slt = Constant(0x2, 3)
+    sltu = Constant(0x3, 3)
+    xor = Constant(0x4, 3)
+    srl_sra = Constant(0x5, 3)
+    _or = Constant(0x6, 3)
+    _and = Constant(0x7, 3)
+
+    fence = Constant(0x0, 3)
+    fence_i = Constant(0x1, 3)
+
+    ecall_ebreak = Constant(0x0, 3)
+    csrrw = Constant(0x1, 3)
+    csrrs = Constant(0x2, 3)
+    csrrc = Constant(0x3, 3)
+    csrrwi = Constant(0x5, 3)
+    csrrsi = Constant(0x6, 3)
+    csrrci = Constant(0x7, 3)
+
+csr_ustatus = Constant(0x000, 12)
+csr_fflags = Constant(0x001, 12)
+csr_frm = Constant(0x002, 12)
+csr_fcsr = Constant(0x003, 12)
+csr_uie = Constant(0x004, 12)
+csr_utvec = Constant(0x005, 12)
+csr_uscratch = Constant(0x040, 12)
+csr_uepc = Constant(0x041, 12)
+csr_ucause = Constant(0x042, 12)
+csr_utval = Constant(0x043, 12)
+csr_uip = Constant(0x044, 12)
+csr_cycle = Constant(0xC00, 12)
+csr_time = Constant(0xC01, 12)
+csr_instret = Constant(0xC02, 12)
+csr_cycleh = Constant(0xC80, 12)
+csr_timeh = Constant(0xC81, 12)
+csr_instreth = Constant(0xC82, 12)
+
+csr_sstatus = Constant(0x100, 12)
+csr_sedeleg = Constant(0x102, 12)
+csr_sideleg = Constant(0x103, 12)
+csr_sie = Constant(0x104, 12)
+csr_stvec = Constant(0x105, 12)
+csr_scounteren = Constant(0x106, 12)
+csr_sscratch = Constant(0x140, 12)
+csr_sepc = Constant(0x141, 12)
+csr_scause = Constant(0x142, 12)
+csr_stval = Constant(0x143, 12)
+csr_sip = Constant(0x144, 12)
+csr_satp = Constant(0x180, 12)
+
+csr_mvendorid = Constant(0xF11, 12)
+csr_marchid = Constant(0xF12, 12)
+csr_mimpid = Constant(0xF13, 12)
+csr_mhartid = Constant(0xF14, 12)
+csr_mstatus = Constant(0x300, 12)
+csr_misa = Constant(0x301, 12)
+csr_medeleg = Constant(0x302, 12)
+csr_mideleg = Constant(0x303, 12)
+csr_mie = Constant(0x304, 12)
+csr_mtvec = Constant(0x305, 12)
+csr_mcounteren = Constant(0x306, 12)
+csr_mscratch = Constant(0x340, 12)
+csr_mepc = Constant(0x341, 12)
+csr_mcause = Constant(0x342, 12)
+csr_mtval = Constant(0x343, 12)
+csr_mip = Constant(0x344, 12)
+csr_mcycle = Constant(0xB00, 12)
+csr_minstret = Constant(0xB02, 12)
+csr_mcycleh = Constant(0xB80, 12)
+csr_minstreth = Constant(0xB82, 12)
+
+csr_dcsr = Constant(0x7B0, 12)
+csr_dpc = Constant(0x7B1, 12)
+csr_dscratch = Constant(0x7B2, 12)
+