Skip to content

Instantly share code, notes, and snippets.

@GuzTech
Created July 17, 2020 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuzTech/5ffe02e502c4d10c32398c84f10ceba9 to your computer and use it in GitHub Desktop.
Save GuzTech/5ffe02e502c4d10c32398c84f10ceba9 to your computer and use it in GitHub Desktop.
from nmigen import *
from nmigen.build import Platform
from nmigen.sim.pysim import *
class InstructionFetch(Elaboratable):
def __init__(self):
# Inputs
self.i_data = Signal(8)
self.i_stall = Signal()
self.i_branch = Signal()
self.i_branch_addr = Signal(8)
self.i_load = Signal()
self.i_load_addr = Signal(8)
# Outputs
self.o_addr = Signal(8)
self.o_pc = Signal(8)
self.o_instr = Signal(8)
self.o_data = Signal(8)
def ports(self) -> []:
return [self.i_data, self.i_stall, self.i_branch, self.i_branch_addr, self.i_load, self.i_load_addr, self.o_addr, self.o_pc, self.o_instr, self.o_data]
def elaborate(self, platform: Platform) -> Module:
m = Module()
next_pc = Signal(8)
m.d.comb += next_pc.eq(Mux(self.i_branch,
self.i_branch_addr, self.o_pc + 1))
with m.If(~self.i_stall):
with m.If(self.i_load):
m.d.sync += self.o_addr.eq(self.i_load_addr)
m.d.sync += self.o_data.eq(self.i_data)
with m.Else():
m.d.sync += self.o_addr.eq(next_pc)
m.d.sync += self.o_pc.eq(next_pc)
m.d.sync += self.o_instr.eq(self.i_data)
return m
if __name__ == "__main__":
m = Module()
m.submodules.dut = dut = InstructionFetch()
m.domains.sync = cd = ClockDomain("sync")
sim = Simulator(m)
def proc():
yield dut.i_data.eq(0b1010_1010)
yield dut.i_stall.eq(1)
yield
yield dut.i_data.eq(0b0001_0000)
yield dut.i_stall.eq(0)
yield dut.i_branch.eq(0)
yield dut.i_branch_addr.eq(0)
yield dut.i_load.eq(1)
yield dut.i_load_addr.eq(0b1111_0000)
yield
yield dut.i_load.eq(0)
yield
yield
sim.add_clock(1e-6)
sim.add_sync_process(proc)
with sim.write_vcd("if.vcd", "if.gtkw", traces=[cd.clk, cd.rst] + dut.ports()):
sim.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment