# A cached interpreter for the SH-2: what the prototype found Evidence for [proposals/2026-11-jit.md](../../emulator-lineage/docs/proposals/2026-11-jit.md) (accepted 2026-11-25; the charter now puts block caching in `x-rust-turbo`). The prototype was built here, in the `-fast` fork, behind a cargo feature, because a block cache that keeps every bus cycle identical is a `-fast` technique by the charter's own test ("a tier is defined by its proof"). It did not pay, so it is not on `main`: it is on the branch **`cached-interpreter`** (`eb7c747`), with its tests and seeded faults, as the starting point for `sh2-rust-turbo`. Measured 2026-11-25 on an i9-13900K shared with other agents (load 15-20 on 32 cores); nothing here is a hardware claim. ## What was built `src/blocks.rs` on the branch (feature `block-cache`; at run time `SH2_BLOCK_CACHE=1`, and `SH2_BLOCK_TRUST=1` for trust mode; wasm: `sh2_setup` bits 2 and 3): - **Blocks keyed by PC and memory kind.** The PC keeps its A31-A29 space bits; the kind is where its fetches come from: the cache area with CCR.CE = 1, the external bus (the cache area with the cache off, or the cache-through area), or the data array (H'C0000000-). A block is the straight-line run from its entry, at most 32 records, each the opcode and its decode (handler, pipeline plan, load-use registers, flags), ended by an instruction that redirects the fetch stream. - **Recorded as it runs.** The chip cannot read ahead: every read is a bus cycle the board sees (`Bus` has no side-effect-free peek, by design). So a block is recorded the first time its instructions run, and grows while later runs continue in sequence. - **The interpreter is the fallback** for delay slots, exception entries, interrupts, SLEEP, odd or on-chip PCs, the purge and address-array spaces, and a PC the host moved. - **Same bus cycles and states.** Every fetch still happens: the pipeline's IF slots, the cache lookups and LRU updates, the line fills. They are bus cycles and cache state that the board and the program can see (the address array shows the LRU), so the plain path makes them, block or not. A block replaces only the decode. - **Two modes.** *Verify* compares each record's opcode with the opcode the pipeline fetched and, on a difference, drops the block and runs the fetched one: exact whatever writes the code. *Trust* runs the record without looking, which is what a cached interpreter that does not model fetches does: exact only if the invalidation rules see every write that can change fetched code. - **Invalidation** (all conservative: dropping a block is always safe): - a CPU or DMA write to external memory drops the blocks on its 256-byte page; - a write-through hit also drops data-array blocks over the line it updated (the same bytes under their second name); - a data-array write drops its own blocks and those over the line that way and entry hold; - in trust mode, a line fill drops the blocks over the line and over its data-array slot (the fill may bring what another master wrote while the line was not cached); - CCR writes (purge, enable, two-way mode), address-array writes, `restore_state` and `reset` drop everything; - writes the chip never sees (the other SH-2, the 68000, the VDP) must be reported by the board through `Sh7604::invalidate_code(address, bytes)`. ## The proof | Check | Command (on the branch) | Result | | --- | --- | --- | | The ladder against sh2-python's cached traces, blocks on (verify) | `FEATURES=block-cache SH2_BLOCK_CACHE=1 scripts/ladder.sh` | passed: rung 0 66,078 lines; rung 1 16,600 of 16,600; rung 2 4 of 4 prefixes (2 M instructions each); rung 3 268 of 268; rung 4 168 of 168; rung 5 114 of 114 and 50 of 50 | | Lockstep against sh2-rust (rung U), verify | `FEATURES=block-cache SH2_BLOCK_CACHE=1 scripts/upstream.sh` | 900 of 900 scenarios (every family the ladder uses, plus fuzz and fresh-chip seeds 3-8) and 4 of 4 MAME prefixes of 4 M instructions, every trace byte-identical | | Rung U, trust | `... SH2_BLOCK_TRUST=1 SEEDS="3 ... 14" PREFIX_UP=2000000 scripts/upstream.sh` | 1,200 of 1,200 and 4 of 4, after one fix (below) | | Invalidation tests | `cargo test --release --features block-cache --test blocks` | 5 of 5: data-array code written through the cache area, self-modifying code (cache off and on), DMA into code (cache off and on; with the cache on the line keeps the old code, DMA does not snoop, HM 8.5.2), a purge after another master's write, another master's write with and without the board's report | | Seeded faults aimed at the shortcuts | `python3 scripts/block_faults.py` | 7 of 10 caught (tests/blocks.rs 5, rung U trust 2); 2 equivalent by analysis; 1 blind spot (below) | The traces compare every bus cycle (address, width, kind, the state it starts on, the value), every step's states and the CPU state at each slice, so they hold the proposal's "block-boundary lockstep" and more: every instruction boundary, not only block exits. **The seeded faults** (the proposal's "faults aimed at JIT bugs"): caught, a CPU or DMA write that drops nothing, a write-through hit that forgets the data array's name, a fill that drops nothing over its line, a fill that forgets its data-array slot, a data-array write that forgets the cached line, verification skipped, a record of the wrong opcode. Equivalent by analysis: "a delay slot leaves the block cursor" and "a block runs on past a branch" (a record is only ever replayed at the address it was recorded at, `block.pc + 2i`, because recording and replay both follow `next_pc`; and a branch already ends the cursor). **Blind spot**: "an address-array write keeps the blocks" passes every check: nothing in the corpus or the fuzz writes the address array to make a line valid over code that was recorded from other bytes. The test that would close it: record a block at B, write the address array so B's entry holds a valid line tagged for B whose data is A's code, and run B (trust mode then replays B's old record while the plain chip runs A's bytes). **What rung U found in trust mode.** The first trust run had one scenario of 900 different (`fuzz-0007-0034`): an interrupt vectored into H'D3B4E360, the data array, and ran a line the program had just written through the cache. The write had dropped the blocks over the external address, but the same bytes were also code under the data array's name. The rule "a write-through hit drops the data-array blocks of its line" (and "a fill drops the blocks of its slot") closed it. Two names for one byte is exactly the kind of fact a specification has to declare for a cached interpreter; see below. ## The speed Pinned to one E-core, alternating with the plain build of the same commit, best of 4-5 rounds, three code layouts (docs/not-kept.md has every ratio): | Build | Native | wasm32 under Node | | --- | --- | --- | | feature compiled in, off | x0.982 | | | verify mode | x0.891 / x0.904 / x0.900 (the three layouts) | x0.897 | | trust mode | x0.908 (default layout) | | **About 10 % slower, in both modes and on both targets.** The reason is structural, and the profile shows it (sh2-profile, cache on, after step 1): the time goes to the stage scheduler (`advance`, `issue`, `retire`, `place`, the MA bookkeeping: about 37 %), the step's own checks for events, DMA, interrupts and address errors (about 25 %), the fetch path (the cache lookup, LRU, data array, `opcode`: about 13 %), the handlers (about 10 %) and the dispatch (about 5 %). Decoding is one indexed load of a packed record (step 1 made it so): that line (`core.rs`, `tables.ops[op]`) is 3.6 % of the samples, the opcode's extraction from the fetched longword (`opcode`) about 4 %. A block can remove only the first (the second is the fetch, which stays), so 3-4 % is the most it could win with free bookkeeping, and its own cursor, bounds and verification cost more. Trust mode saves one compare, nothing else, because the fetch must still be made. ## What forced the fallbacks - **Delay slots** (about 11 % of the bench loop's instructions: the BF/S slot each pass): the slot runs with the PC set to the target and its own slot-illegal rule, so it stays on the plain path. Recording slots into blocks is possible but would not change the result. - **Exceptions and interrupts**, which may arrive after any instruction: the board can raise IRL or NMI inside any bus callback, so a block cannot hoist the interrupt check out of its loop. Per instruction the check is a few compares; the step boundary has to stay. - **A PC the host moves** (the replay host, the bench's restart): the next step is an entry. - **Unblockable fetch spaces**: on-chip, purge and address-array spaces (they hold no code). ## What a specification would need to declare For a cached interpreter that **keeps fetches** (exact bus cycles), nothing: verify mode is exact by construction and needs no invalidation at all. Such a cache can only remove the decode, which a packed table already makes cheap. So on a CPU whose fetches are modelled as bus cycles, the cached interpreter is not the lever; the lever is the scheduler and the fetch path, and those are turbo's (below). For one that **does not fetch** (an instruction-level model, the usual cached interpreter, or a JIT), the trust-mode rules are the list, and each is a fact the specification knows: 1. **Every name for a byte of code.** On the SH7604: the cache area, the cache-through area (+H'20000000), and, while a line is cached, the data array at H'C0000000 + way and entry; the associative purge space and the address array change which bytes a cached fetch sees. Rung U found the data-array name the hard way. 2. **Which masters can write each region, and whether the chip sees the write.** The chip sees its own writes and its DMAC's. The 32X's other SH-2, the 68000 (SDRAM through the 32X's window, the frame buffer), and the VDP do not go through this chip: the board must report them (`invalidate_code`), and the specification's memory map should say which regions can take such writes (the proposal's "memory kinds and who can write each"). tests/blocks.rs shows trust mode running stale code when the report is missing. 3. **Cache coherency rules.** DMA does not snoop (HM 8.5.2): a cached line keeps old code after a DMA write until it is purged or replaced, so "drop on write" is right but "the new code runs now" is not. Fills are the moment cached code can change without a write the chip sees. 4. **Where interrupts are sampled.** Here, at every instruction boundary, and the board can change the pins inside any callback. A block can run past a boundary only if the specification declares when the pins can change (the proposal's sync points). ## What would pay instead (for sh2-rust-turbo) - **Memoize the scheduler, not the decode.** For a straight-line block whose fetches all hit the cache and whose data accesses touch no external bus, the slot timing is a function of the pipeline's entry state; a block could carry its precomputed slot lengths and LRU updates and check its preconditions once. That removes the 37 % the scheduler costs on such code. It changes no cycle, but it is a large fast path with a fallback, which is turbo's shape. - **Threads around the SH-2 pair** (the charter's domains): the Mega Drive side, the 32X VDP and PWM on their own threads. - Native already covers the 32X: about 25-30 M instructions/s on one E-core, 50-60 M on an idle P-core, against the pair's need of about 11-35 M (docs/status.md). The browser is the open question: 20-23 M/s on the E-core under Node, at the edge of the cache-on need before the rest of the board.