`timescale 1ns / 1ps // CPU-only test: runs an image in 64 KB of RAM and writes a register trace at // the start of every instruction (compared against tools/z80emu.py). // Console: port 0 reads {tx ready, input available}, port 1 reads/writes data. module tb_cpu; reg clk = 0, rst = 1; always #5 clk = ~clk; wire [15:0] ma, io_addr; wire we, io_rd, io_wr, halted, ins_start; wire [7:0] wd, io_wd; reg [7:0] din, io_din; wire [15:0] pc, af, bc, de, hl, ix, iy, sp; z80_cpu cpu ( .clk(clk), .rst(rst), .ma(ma), .we(we), .wd(wd), .din(din), .io_addr(io_addr), .io_rd(io_rd), .io_wr(io_wr), .io_wd(io_wd), .io_din(io_din), .halted(halted), .nmi(1'b0), .nmi_now(1'b0), .ins_start(ins_start), .dbg_pc(pc), .dbg_af(af), .dbg_bc(bc), .dbg_de(de), .dbg_hl(hl), .dbg_ix(ix), .dbg_iy(iy), .dbg_sp(sp) ); reg [7:0] mem [0:65535]; integer rom_top = 0; always @(posedge clk) begin if (we && ma >= rom_top) mem[ma] <= wd; din <= mem[ma]; end reg [7:0] inbuf [0:65535]; integer in_n = 0, in_p = 0, fd, tr, n = 0, cycles = 0, max_cycles; always @* io_din = io_addr[7:0] == 8'd0 ? {6'd0, 1'b1, in_p < in_n} : io_addr[7:0] == 8'd1 ? (in_p < in_n ? inbuf[in_p] : 8'd0) : 8'hFF; always @(posedge clk) if (io_rd && io_addr[7:0] == 8'd1 && in_p < in_n) in_p <= in_p + 1; always @(posedge clk) if (io_wr && io_addr[7:0] == 8'd1) $write("%c", io_wd); always @(posedge clk) if (!rst) begin cycles = cycles + 1; if (ins_start) begin if (tr) $fwrite(tr, "%h %h %h %h %h %h %h %h\n", pc, af, bc, de, hl, ix, iy, sp); n = n + 1; end end initial begin if (!$value$plusargs("max=%d", max_cycles)) max_cycles = 10_000_000; $value$plusargs("romtop=%d", rom_top); for (n = 0; n < 65536; n = n + 1) mem[n] = 8'h00; n = 0; $readmemh(`IMAGE, mem); fd = $fopen(`INPUT, "rb"); if (fd) begin while (!$feof(fd)) begin inbuf[in_n] = $fgetc(fd); in_n = in_n + 1; end in_n = in_n - 1; end tr = $fopen("trace_hw.txt", "w"); #20 rst = 0; wait (halted || cycles >= max_cycles); repeat (2) @(posedge clk); $display("\n[%0d instructions, %0d clocks%0s]", n, cycles, halted ? ", halted" : ""); $fclose(tr); fd = $fopen("mem_hw.txt", "w"); for (n = 32768; n < 65536; n = n + 1) $fwrite(fd, "%h\n", mem[n]); $fclose(fd); $finish; end endmodule