Why Debugging CPU RTL Is Hard

Debugging CPU RTL logic is uniquely subtle and unforgiving. A hardware CPU bug almost always manifests somewhere completely unrelated to the buggy code that caused it. Picture what happens when a single edge case goes wrong: a shift instruction leaves the carry flag inverted or something like that. Nothing crashes on the spot. Instead, that single corrupted bit gets folded into a branch decision or written into a kernel data structure. Millions of cycles later, the operating system panics for some random reason, and the designer is left wondering what happened.

Lockstep co-simulation (--cosim in z86) solves this problem cleanly. You run a trusted reference CPU model (an existing emulator or instruction-set simulator such as 86Box) side by side with your RTL simulation. For every instruction your CPU commits, the harness steps the reference once and compares the next PC, registers, flags, and memory writes bit-for-bit. The moment a single bit disagrees, the simulation halts right at the offending instruction, dramatically shortening debugging time.

Whether you are building an 8-bit 6502, an in-order RISC-V core, or a superscalar out-of-order x86 CPU like z86, lockstep co-simulation is the highest-leverage verification tool you can build. This page documents the technique, how to get it right, its pitfalls, and how to mitigate them.


1. Implementing CPU Co-Simulation

Here is a common structure to implement CPU co-simulation and split responsibilities cleanly:

Full-System Lockstep CPU Co-Simulation & Portable Snapshots

  • The RTL system owns time, memory, and all peripherals. Timers, interrupt controllers, video hardware, disk/UART, and guest RAM run only in the RTL simulation.
  • The reference emulator is stripped down to a pure CPU + shadow RAM library. It has no timers, no video chip, and no independent interrupt schedule.
  • Non-deterministic inputs are captured and replayed. Whenever the RTL CPU reads an I/O port or MMIO register, receives an interrupt vector (INTA), or has memory modified behind its back by DMA, simulation probes (DPI-C in Verilator, VPI/PLI, or a C++ testbench wrapper) capture the exact bytes returned by the RTL platform and feed them verbatim to the reference CPU when it executes the matching instruction.

With this split, both CPUs always see the exact same external universe—exact same timer ticks, keyboard scancodes, disk sectors, and IRQ timing—regardless of how many cycles the RTL took between instructions.


2. Picking the Commit Point (In-Order vs. Pipelined vs. Out-of-Order)

Co-simulation should compare architectural state—the sequential programmer-visible view of the machine—so you must tap your RTL at a point where instructions become architecturally visible in strict program order.

2.1 Simple and In-Order CPUs

For a single-cycle, multi-cycle, or classic 5-stage in-order pipeline (like z486 or a simple RISC-V core), tapping is straightforward: * Emit a commit record (pc, next_pc, GPRs, flags/CSR, exception/IRQ vector) when an instruction finishes writeback (or at the start of the next instruction, with the reference trailing by one step). * Wait for any peripheral read data belonging to that instruction to arrive, step the reference CPU once, and compare.

2.2 Scaling to Pipelined, Cached, and Out-of-Order CPUs

The exact same harness actually generalizes cleanly to cached, superscalar, and out-of-order designs (like z86), with three additional rules:

  1. Check at in-order retirement, not at speculative issue. Wrong-path instructions never retire, so the reference never sees them. If your CPU retires N instructions in the same clock cycle, export the intermediate post-lane architectural states so the harness still steps the reference one instruction at a time.
  2. Match buffered stores in program order. With a store buffer or write-back cache, a store's bytes may reach the bus cycles after the store instruction retired. You can either capture the write at retire time or match the ordered bus/cache writes asynchronously against the write queue produced when the reference executed the instruction.
  3. Handle interruptible multi-step instructions. ISAs with long interruptible instructions (such as x86 REP MOVS/STOS or ARM LDM/STM) need a bit of care: either emit a checkpoint record per iteration or report the remaining iteration count when an interrupt cuts the instruction short so the reference stops at the exact same partial progress.

3. What to Compare, and How to Triage Divergences

After stepping the reference CPU for each committed instruction or delivered interrupt/exception, compare:

  • Next PC (and privilege/code-segment state, if the ISA has modes or segmentation)
  • All general-purpose registers (and FPU/vector/system registers where deterministic)
  • Architectural flags, masked strictly to defined bits (ignore reserved or architecturally undefined bits)
  • Committed memory writes (physical address, byte enables, and data bytes) and exception/IRQ vectors

When a mismatch occurs, halt immediately and print a state dump: 1. The DUT's commit record and cycle number 2. The reference CPU's state and raw instruction bytes at PC 3. A ring buffer of the last 10–20 committed instructions before the mismatch 4. A ring buffer of the last ~16 memory and I/O writes from both sides

Every divergence you hit will fall into one of three categories:

  1. A real bug in your RTL (or microcode): The happy case—co-simulation just saved you days of blind debugging. Fix the RTL, add a tiny standalone unit test for that corner case, and re-run.
  2. A bug in the reference emulator: Real-world emulators optimize for common software and occasionally miss strict ISA corner cases. For example, during z86 bring-up, lockstep co-simulation caught real discrepancies in 86Box (CMOVcc faulting memory reads before conditional select, CMPXCHG/CMPXCHG8B writeback on mismatch and 8-byte limit checks, LAR/LSL descriptor rules, and reserved debug-register masks) that we patched.
  3. Undefined or implementation-specific behavior: Examples include cycle counters (RDTSC, mcycle), architecturally undefined arithmetic flags (e.g., x86 16-bit SHLD/SHRD with count > 16), or CPU-model-specific reset values. Either align the reference or the DUT so the divergence never poisons later execution.

Iterate until the entire workload finishes with zero divergences.


4. Portable Architectural Snapshots (Surviving RTL Rebuilds)

Lockstep co-simulation has one practical bottleneck: RTL simulation is slow. A complex CPU + chipset in Verilator typically runs at tens of kilohertz—thousands of times slower than a 100 MHz FPGA. If an operating system diverges 300 million cycles into boot, re-running from reset for 30 minutes after every one-line RTL edit destroys iteration speed.

Simulator-native checkpoints (such as Verilator's --savable) do not solve this, because they serialize every internal signal and flip-flop. The moment you fix a bug by adding or renaming a single register in your RTL, all of your old checkpoints become useless.

One solution is portable architectural snapshots (implemented in z86):

  1. Wait for a quiet instruction boundary: Only save between clocks when the DUT and reference agree, no bus reads/writes/IRQs are in flight, write buffers and caches are drained, and peripheral state machines (like an I/O sequencer) are idle.
  2. Save only RTL-independent architectural state + compact diffs:
  3. CPU architectural state: PC, GPRs, flags, control/MMU registers, segment caches, FPU state—everything defined by the ISA, zero microarchitectural pipeline state.
  4. Guest RAM: For speed and compact storage, save a full-RAM keyframe plus incremental page diffs.
  5. Disk images: Store only the sectors modified relative to the base disk file.
  6. Peripherals & Reference: Serialize peripheral registers by name plus the reference CPU's state.
  7. Restore into any new RTL build: Add a simple simulation-only init port to your CPU that loads architectural state on the first clock out of reset, copy guest RAM into the memory model, restore the peripherals and reference CPU, and resume --cosim.
# 1. Run past boot and drop periodic portable snapshots:
./sim --cosim --disk os.img --snapshot-dir snaps/os --snapshot-at 50000000

# 2. Edit RTL, rebuild Verilator, and jump straight back to the failing region in seconds:
./sim --cosim --disk os.img --restore-snapshot snaps/os/snap_050000000

Portable snapshots turn multi-hour OS bring-up loops into 10-second edit-compile-reproduce cycles.


5. Limitations and Conclusion

The main limitation of lockstep co-simulation is still simulation speed. Even with portable snapshots, a bug that only triggers 60 seconds into an OS boot is painful to reach in software simulation. At that scale, lockstep co-simulation works best paired with a lightweight on-chip hardware debugger (clock-gated halt, register/pipeline inspection, hardware breakpoints, and a small BRAM retire trace ring). One such debugger is also implemented in z86.

All in all, lockstep co-simulation is a remarkably effective tool for debugging CPU RTL. Because almost every CPU architecture cleanly separates architectural state from internal microarchitectural state, the same technique works across nearly any CPU design.