def build(self, build_dir='build', template=None, sources_dir=None, top_module_name='project_top', part=None): # This class is used for generating FuseSoC Core file fuse = FuseSocBuilder(part) for ip in self._ips.values(): filename = ip.top_name + '.v' fuse.add_source(filename, 'verilogSource') target_file = open(path.join(build_dir, filename), 'w') fragment = Fragment.get(ip, None) output = verilog.convert(fragment, name=ip.top_name, ports=ip.get_ports()) target_file.write(output) fuse.add_source(top_module_name + '.v', 'verilogSource') fuse.build(path.join(build_dir, 'top.core'), sources_dir=sources_dir) target_file = open(path.join(build_dir, top_module_name + '.v'), 'w') fragment = Fragment.get(self, None) output = verilog.convert(fragment, name=top_module_name, ports=self.get_ports()) target_file.write(output)
def test_generator(self): ''' This test creates wrappers for 2 IPs and connects them in a separate module ''' from fpga_topwrap.ipwrapper import IPWrapper from fpga_topwrap.ipconnect import IPConnect # wrap IPs dma = IPWrapper(yamlfile='tests/data/DMATop.yaml', ip_name='DMATop') disp = IPWrapper(yamlfile='tests/data/axi_dispctrl_v1_0.yaml', ip_name='axi_dispctrl_v1_0') dma_fragment = Fragment.get(dma, None) disp_fragment = Fragment.get(disp, None) assert verilog.convert(dma_fragment, name=dma.top_name, ports=dma.get_ports()) assert verilog.convert(disp_fragment, name=disp.top_name, ports=disp.get_ports()) # connect the IPs in another module connector = IPConnect() connector.add_ip(dma) connector.add_ip(disp) connector.connect_interfaces('AXIS_m0', dma.top_name, 'AXIS_s0', disp.top_name) # connect output of disp to two inputs of dma connector.connect_ports('io_sync_writerSync', dma.top_name, 'HSYNC_O', disp.top_name) connector.connect_ports('io_sync_readerSync', dma.top_name, 'HSYNC_O', disp.top_name) fragment = Fragment.get(connector, None) assert verilog.convert(fragment, name='top')
def to_hdl(self, **kwargs): """ Convert the nmigen description to Verilog """ return verilog.convert(self.fx_filt, ports=[self.fx_filt.i, self.fx_filt.o], **kwargs)
def main(cmd_args=None): import argparse from nmigen.back import verilog parser = argparse.ArgumentParser() parser.add_argument('--width-in', '-wi', type=int, default=12, help='Input port width') parser.add_argument('--width-gain', '-wg', type=int, default=10, help='Gain port width') parser.add_argument('--width-out', '-wo', type=int, default=14, help='Output port width') parser.add_argument('output', type=str, help='Output file (Verilog)') args = parser.parse_args(cmd_args) filename = args.output if args.output.endswith( '.v') else args.output + '.v' top = Gain(width_in=args.width_in, width_gain=args.width_gain, width_out=args.width_out) ports = [top.input, top.gain, top.output] with open(filename, "w") as f: f.write(verilog.convert(top, ports=ports))
def main(): args = get_args() core = DatapathSniffer(width=args.width, depth=args.depth, domain_data='data', domain_axi='axi') ports = core.get_ports() # to avoid submodules of different verilog files to have the same name. name = args.name submodule_posfix = f'_w{args.width}_d{args.depth}' fragment = Fragment.get(core, None) output = verilog.convert(fragment, name=name, ports=ports) output = re.sub('\*\)', '*/',re.sub('\(\*','/*', output)) output = output.replace('__', '_') modules = re.findall(r'^module (\S*) ?\(.*\);', output, re.MULTILINE) for m in modules: pattern = m.replace('\\', '\\\\').replace('$', '\$') with_posfix = m.replace('\\', '\\\\') + submodule_posfix output = re.sub('^module ' + pattern, 'module ' + with_posfix, output, 0, re.MULTILINE) output = re.sub('^ ' + pattern, ' ' + with_posfix, output, 0, re.MULTILINE) with open(args.file, 'w') as f: f.write(output)
def build(self, elaboratable, *, build_dir, **kwargs): sim = Simulator(elaboratable) os.makedirs(build_dir, exist_ok=True) cwd = os.getcwd() try: os.chdir(build_dir) with open("top.il", "w", encoding="utf-8") as f: f.write(rtlil.convert(elaboratable)) with open("top.v", "w", encoding="utf-8") as f: f.write(verilog.convert(elaboratable)) for name, number in self.resources: clock = self.lookup(name, number).clock if clock is not None: sim.add_clock(clock.period, domain=name) for process in self.processes: sim.add_sync_process(process) for domain, sync_processes in self.sync_processes.items(): for sync_process in sync_processes: sim.add_sync_process(sync_process, domain=domain) with sim.write_vcd("top.vcd"): sim.run() finally: os.chdir(cwd)
def main(): cfu = make_cfu() new_verilog = verilog.convert(cfu, name='Cfu', ports=cfu.ports) old_verilog = read_file() if new_verilog != old_verilog: with open(VERILOG_FILENAME, "w") as f: f.write(new_verilog)
def test_verilog(): from nmigen.hdl.ir import Fragment from nmigen.back import verilog ctr = Counter(width=16) fragment = Fragment.get(ctr, None) output = verilog.convert(fragment, name='example', ports=[ctr.o]) with open('./example.v', 'w') as f: f.write(output)
def generate_verilog(verilog_file, design, platform, name='top', ports=(), vcd_file=None): fragment = Fragment.get(design, platform) print(name, ports) output = verilog.convert(fragment, name=name, ports=ports) with open(verilog_file, 'w') as f: f.write('`timescale 1ns/1ps\n') f.write(output) if vcd_file: vcd_file = os.path.abspath(vcd_file) f.write(verilog_waveforms.format(vcd_file, name).replace('\\', '/'))
def main(cmd_args=None): import argparse from nmigen.back import verilog parser = argparse.ArgumentParser() parser.add_argument('output', type=str, help='Output file (Verilog)') args = parser.parse_args(cmd_args) filename = args.output if args.output.endswith('.v') else args.output + '.v' top = SumaPonderada() ports = [top.PiX0, top.PiX1, top.PiX2, top.PiW0, top.PiW1, top.PiW2, top.PoZ] with open(filename, "w") as f: f.write(verilog.convert(top, ports=ports))
def CPU_to_verilog(core_config: dict, vfile: str): cpu = Bellatrix(**core_config) ports = cpu.port_list() # generate the verilog file fragment = Fragment.get(cpu, None) output = verilog.convert(fragment, name='bellatrix_core', ports=ports) try: with open(vfile, 'w') as f: f.write(output) except EnvironmentError as error: print(f"Error: {error}. Check if the output path exists.", file=sys.stderr)
def main(): assert False, 'CLI not implemented!' args = get_args() core = WidthConverter(args.input_w, args.output_w) ports = [core.input[f] for f in core.input.fields] ports += [core.output[f] for f in core.output.fields] fragment = Fragment.get(core, None) output = verilog.convert(fragment, name=args.name, ports=ports) with open(args.file, 'w') as f: output = re.sub('\*\)', '*/', re.sub('\(\*', '/*', output)) output = output.replace('__', '_') f.write(output)
def main(cmd_args=None): import argparse from nmigen.back import verilog parser = argparse.ArgumentParser() parser.add_argument('--width', '-w', type=int, default=8, help='Input ports width') parser.add_argument('output', type=str, help='Output file (Verilog)') args = parser.parse_args(cmd_args) filename = args.output if args.output.endswith( '.v') else args.output + '.v' top = Suma6(width=args.width) ports = top.inputs ports.append(top.output) with open(filename, "w") as f: f.write(verilog.convert(top, ports=ports))
def main(): cpu = Minerva(as_instance=True, with_icache=False, with_dcache=False, with_muldiv=False) ports = [ cpu.clk, cpu.rst, cpu.external_interrupt, cpu.ibus.ack, cpu.ibus.adr, cpu.ibus.bte, cpu.ibus.cti, cpu.ibus.cyc, cpu.ibus.dat_r, cpu.ibus.dat_w, cpu.ibus.sel, cpu.ibus.stb, cpu.ibus.we, cpu.ibus.err, cpu.dbus.ack, cpu.dbus.adr, cpu.dbus.bte, cpu.dbus.cti, cpu.dbus.cyc, cpu.dbus.dat_r, cpu.dbus.dat_w, cpu.dbus.sel, cpu.dbus.stb, cpu.dbus.we, cpu.dbus.err ] if cpu.with_debug: ports += [cpu.jtag.tck, cpu.jtag.tdi, cpu.jtag.tdo, cpu.jtag.tms] frag = cpu.elaborate(platform=None) print(verilog.convert(frag, name="minerva_cpu", ports=ports))
def luna_wrapper(platform, elaboratable): ports = [] # Patch through all Records/Ports for port_name, port in vars(elaboratable).items(): if not port_name.startswith("_") and isinstance(port, (Signal, Record)): ports += port._lhs_signals() verilog_text = verilog.convert(elaboratable, name="USBSerialDevice", ports=ports) verilog_file = "build/luna_wrapper.USBSerialDevice.v" vdir = os.path.join(os.getcwd(), "build") os.makedirs(vdir, exist_ok=True) with open(verilog_file, "w") as f: f.write(verilog_text) platform.add_source(os.path.join(vdir, "luna_wrapper.USBSerialDevice.v"))
def build(self, module, **kwargs): # TODO: mkdir build with open('build/top.v', 'w') as f: f.write( verilog.convert(module, ports=[ module.serdes.rx_data, module.serdes.rx_clock, module.uart.tx_data, module.uart.tx_rdy, module.uart.tx_ack ])) os.chdir('build') with open('main.cpp', 'w') as f: f.write(HARNESS) subprocess.check_call([ 'verilator', '-Wno-fatal', '--trace', '-cc', '--exe', 'top.v', 'main.cpp' ]) subprocess.check_call(['make', '-C', 'obj_dir/', '-f', 'Vtop.mk']) subprocess.check_call(['./obj_dir/Vtop', "../" + sys.argv[2]])
def _generate(self): args = self.args fragment = Fragment.get(self.design, self.platform) generate_type = args.generate_type if generate_type is None and args.generate_file: if args.generate_file.name.endswith(".v"): generate_type = "v" if args.generate_file.name.endswith(".il"): generate_type = "il" if generate_type is None: parser.error("specify file type explicitly with -t") if generate_type == "il": output = rtlil.convert(fragment, name=self.name, ports=self._get_ports()) if generate_type == "v": output = verilog.convert(fragment, name=self.name, ports=self._get_ports()) if args.generate_file: args.generate_file.write(output) else: print(output)
p_DIVR=self.pll_config.divr, p_DIVF=self.pll_config.divf, p_DIVQ=self.pll_config.divq, p_FILTER_RANGE=self.pll_config.filter_range, p_FEEDBACK_PATH='SIMPLE', p_DELAY_ADJUSTMENT_MODE_FEEDBACK='FIXED', p_FDA_FEEDBACK=0, p_FDA_RELATIVE=0, p_SHIFTREG_DIV_MODE=0, p_PLLOUT_SELECT='GENCLK', p_ENABLE_ICEGATE=0, i_PACKAGEPIN=clock_in, o_PLLOUTGLOBAL=self.domain.clk, i_RESETB=Const(1), i_BYPASS=Const(0)) m.submodules += [pll] platform.add_clock_constraint(self.domain.clk, self.pll_config.mhz * 1e6) return m if __name__ == '__main__': # Nothing to test here, but can generate verilog for inspection from nmigen.back import verilog from nmigen_boards.icebreaker import * from video_config import PLLConfig platform = ICEBreakerPlatform() config = PLLConfig(25.125, 0, 66, 5, 1) pll = PLL(config, 'sync') print(verilog.convert(pll, name='Pll', platform=platform))
# hook up the clock source m.d.comb += ClockSignal("sync").eq(self.i_clock) m.d.comb += ResetSignal("sync").eq(0) m.submodules.cfcore = cfcore = self.cfcore # hook up the exposed cart signals for fi, field in enumerate(self.cart_signals._fields): m.d.comb += self.cart_signals[fi].eq( getattr(self, "i_snes_" + field)) # everything else just gets passed straight through for var in dir(self): if var == "i_clock" or var.startswith("i_snes_"): continue if var.startswith("i_"): m.d.comb += getattr(cfcore, var).eq(getattr(self, var)) elif var.startswith("o_"): m.d.comb += getattr(self, var).eq(getattr(cfcore, var)) return m # make all the inputs and outputs ports of the top level module m = Top() ports = [] for var in dir(m): if var.startswith("i_") or var.startswith("o_"): ports.append(getattr(m, var)) # then convert everything to verilog print(verilog.convert(m, "chrono_figure_sys", ports=ports))
if __name__ == "__main__": dda = Bresenham() ports = [ dda.i_x0, dda.i_y0, dda.i_r0, dda.i_g0, dda.i_b0, dda.i_x1, dda.i_y1, dda.i_r1, dda.i_g1, dda.i_b1, dda.i_start, dda.i_next, dda.o_x, dda.o_y, dda.o_valid, dda.o_last ] gtkw = open("sim.gtkw", "w") vcd = open("sim.vcd", "w") with open("line.v", "w") as f: f.write(verilog.convert(dda, ports=ports)) with open("line.il", "w") as f: f.write(rtlil.convert(dda, ports=ports)) def line_test(start, end, points): print("// ", start, "-> ", end) yield dda.i_x0.eq(start[0] << 4) yield dda.i_y0.eq(start[1] << 4) yield dda.i_x1.eq(end[0] << 4) yield dda.i_y1.eq(end[1] << 4) yield dda.i_start.eq(1) yield dda.i_next.eq(0) # Wait for setup yield; yield
m.d.sync += counter.eq(counter + 1) moving_average_full = Signal((self._dw + self.MAX_DELAY_BITS, True)) m.d.sync += moving_average_full.eq(moving_average_full + self.i - out_val) m.d.comb += [ self.o.eq(moving_average_full >> self.log_downsample_ratio) ] return m if __name__ == "__main__": dut = MovingAverage() print( verilog.convert( dut, name='moving_average', ports=[dut.i, dut.o, dut.data_valid, dut.log_downsample_ratio])) sim = pysim.Simulator(dut) log_downsample_ratio = 0 signal_in, signal_out = [], [] sim.add_clock(1e-6) def moving_average_tb(): yield dut.log_downsample_ratio.eq(log_downsample_ratio) for i in range(200): yield dut.i.eq(i) signal_in.append(i) signal_out.append((yield dut.o)) yield
#!/usr/bin/env python3 from nmigen.back import verilog from packet_blaster import PacketBlaster pb = PacketBlaster(0x100_0000) with open('packet_blaster.v', 'w') as f: f.write(verilog.convert(pb, ports=[pb.xgmii_d, pb.xgmii_c], strip_internal_attrs=True))
class Counter(Elaboratable): def __init__(self, width): self.v = Signal(width, reset=2**width - 1) self.o = Signal() self.en = Signal() def elaborate(self, platform): m = Module() m.d.sync += self.v.eq(self.v + 1) m.d.comb += self.o.eq(self.v[-1]) return EnableInserter(self.en)(m) ctr = Counter(width=16) print(verilog.convert(ctr, ports=[ctr.o, ctr.en])) sim = pysim.Simulator(ctr) sim.add_clock(1e-6) def ce_proc(): yield yield yield yield ctr.en.eq(1) yield yield yield yield ctr.en.eq(0) yield
from axi_stream_top import AxiStreamTop dut = AxiStreamTop() def bench(): tvalid_last = 0 tvalid_can_fall = 0 for i in range(2000): yield # Check that TVALID never goes low until the transmission completes. tvalid = (yield dut.tx.m_axis.tvalid) tx_done = (yield dut.tx.m_axis.tx_done()) # Don't care about no change in tvalid. # Don't care if tvalid is high. # Only allow tvalid to fall the cycle after a tx_done. assert ((tvalid == tvalid_last) or (tvalid) or (tvalid_can_fall)) tvalid_can_fall = tx_done tvalid_last = tvalid sim = Simulator(dut) sim.add_clock(1e-6) sim.add_sync_process(bench) with sim.write_vcd("axi_stream_top.vcd"): sim.run() with open("axi_stream_top.v", "w") as f: f.write(verilog.convert(dut))
self.v = Signal(width, reset=2**width-1) self.o = Signal() self.ce = Signal() def get_fragment(self, platform): m = Module() m.d.sync += self.v.eq(self.v + 1) m.d.comb += self.o.eq(self.v[-1]) return CEInserter(self.ce)(m.lower(platform)) ctr = Counter(width=16) frag = ctr.get_fragment(platform=None) # print(rtlil.convert(frag, ports=[ctr.o, ctr.ce])) print(verilog.convert(frag, ports=[ctr.o, ctr.ce])) with pysim.Simulator(frag, vcd_file=open("ctrl.vcd", "w"), gtkw_file=open("ctrl.gtkw", "w"), traces=[ctr.ce, ctr.v, ctr.o]) as sim: sim.add_clock(1e-6) def ce_proc(): yield; yield; yield yield ctr.ce.eq(1) yield; yield; yield yield ctr.ce.eq(0) yield; yield; yield yield ctr.ce.eq(1) sim.add_sync_process(ce_proc()) sim.run_until(100e-6, run_passive=True)
memory_signals = MemorySignals( o_clock=self.o_mem_clock, o_reset=self.o_mem_reset, o_addr=self.o_addr, o_re=self.o_re, i_rdata=self.i_rdata, o_we=self.o_we, o_wdata=self.o_wdata, ) # finally we can hook this all up to the system shell shell = TASHAShell(clock_signals=clock_signals, snes_signals=snes_signals, uart_signals=uart_signals, memory_signals=memory_signals) m.submodules += shell return m # make all the inputs and outputs ports of the top level module m = Top() ports = [] for var in dir(m): if var.startswith("i_") or var.startswith("o_"): ports.append(getattr(m, var)) # then convert everything to verilog print(verilog.convert(m, "tasha_sys_c5g", ports=ports))
def g(): top = Top(sim=False) platform = ICEBreakerPlatform() print(verilog.convert(top, ports=[], platform=platform))
def transmit_proc(): assert (yield uart.tx_ack) assert not (yield uart.rx_rdy) yield uart.tx_data.eq(0x5A) yield uart.tx_rdy.eq(1) yield yield uart.tx_rdy.eq(0) yield assert not (yield uart.tx_ack) for _ in range(uart.divisor * 12): yield assert (yield uart.tx_ack) assert (yield uart.rx_rdy) assert not (yield uart.rx_err) assert (yield uart.rx_data) == 0x5A yield uart.rx_ack.eq(1) yield sim.add_sync_process(transmit_proc()) sim.run() if args.action == "generate": from nmigen.back import verilog print(verilog.convert(uart, ports=ports))
if i != 0: summands += [self.stages[i - 1] * c_list[i - 1]] if (i + self.order) % 2 == 0 and i + 1 < self.order: summands += [self.stages[i + 1] * (-g_list[i // 2])] domain = m.d.sync if i < self.order else m.d.comb domain += self.stages[i].eq( sum(summands).cast(fmt, allow_precision_loss=True, allow_clamp=True) ) last_stage = self.stages[-1] for i, q in enumerate(self.quantization_values[1:]): tipping_point = (q + self.quantization_values[i]) / 2 with m.If(last_stage > tipping_point): m.d.comb += self.quantized_value.eq(fmt.Const(q, allow_clamp=True)) m.d.comb += self.output.eq(i + 1) return m if __name__ == "__main__": fmt = Q(8, 64) noiseshaper = Noiseshaper(fmt.Signal()) from nmigen.back.verilog import convert verilog = convert(noiseshaper) print("verilog lines: ", len(verilog.split("\n"))) size = get_size(noiseshaper, ports=[noiseshaper.input.value, noiseshaper.output]) print("cells: ", size)
#!/usr/bin/env python3 from nmigen.back import verilog from blink import * top = Blink() with open('top.v', 'w') as f: f.write(verilog.convert(top, ports=[top.led], strip_internal_attrs=True))