// SPDX-License-Identifier: MIT //! The cached interpreter (prototype, cargo feature `block-cache`, off by default): decoded //! blocks of op records, replayed instead of decoding each instruction again. //! //! Not from the reference: a -fast execution technique, proven by the gate (the same bus //! cycles, states and step results as the plain interpreter: scripts/upstream.sh with //! `SH2_BLOCK_CACHE=1`, and tests/blocks.rs), never a behaviour. docs/cached-interpreter.md //! has the design, the measurements and what it means for the JIT proposal. //! //! **Blocks.** A block is the straight-line run of instructions from an entry PC, keyed by //! the PC (with its A31-A29 space bits) and the memory kind its fetches come from: the //! cache area with the cache on, the cache area with it off or the cache-through area (the //! external bus), or the data array (H'C0000000-). Each record holds the opcode and its //! decode (`Op`: handler, plan, load-use registers, flags). A block is recorded as the //! instructions first run (the chip cannot read ahead: every read is a bus cycle the board //! sees), grows while the run continues in sequence, and ends at an instruction that //! redirects the fetch stream (a branch, TRAPA, SLEEP, undefined code) or at 32 records. //! //! **Always the plain path for**: delay slots (they run in the step's slot arm), exception //! entries, interrupts, SLEEP, odd or on-chip PCs, the purge and address-array spaces, a //! PC the host moved. Every fetch still happens: the pipeline's IF slots, cache lookups, //! LRU updates and line fills are the plain interpreter's own, because they are bus cycles //! and cache state the board and the program can see. What a block saves is the decode. //! //! **Two modes.** `verify` (the default) compares each record's opcode with the opcode the //! pipeline fetched, and on a difference drops the block and uses the fetched one: always //! exact, whatever writes the code. `trust` runs the record's opcode without looking (what //! a cached interpreter that does not model fetches would do): exact only if every write //! that can change fetched code drops the blocks it covers. The invalidation rules, all //! conservative (dropping a block is always safe: the next run records it again from the //! fetched opcodes): //! //! - a CPU or DMA write to the external bus (spaces 0 and 1) drops blocks on its 256-byte //! page; a write to the data array drops data-array blocks there and blocks over the //! line that way and entry holds; //! - in `trust` mode a line fill drops the blocks over the filled line (the line may bring //! what another master wrote while it was not cached); //! - CCR writes (purge, enable, two-way mode), address-array writes, `restore_state` and //! `reset` drop every block; //! - writes the chip never sees (the other SH-2, the 68000, the VDP writing SDRAM or the //! frame buffer) must be reported by the board with [`Sh7604::invalidate_code`]: in //! `trust` mode a missing report runs stale code (tests/blocks.rs shows it). use crate::bus::Bus; use crate::cpu::{tables, Op, Sh7604}; use crate::pipeline::KIND_PLAIN; /// Records per block at most. const MAX_RECORDS: usize = 32; /// Direct-mapped entry table size (entries are checked against their key). const TABLE: usize = 4096; /// Invalidation pages: 256 bytes of the 29-bit external space, plus 16 data-array pages. const PAGE_SHIFT: u32 = 8; const EXTERNAL_PAGES: usize = 1 << (29 - PAGE_SHIFT); const NONE: u32 = u32::MAX; /// Where a block's fetches come from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MemoryKind { /// The cache area with CCR.CE = 1: hits from the cache, fills from the bus. Cached = 0, /// The cache area with the cache off, or the cache-through area: the external bus. External = 1, /// The data array (H'C0000000-H'C0000FFF). DataArray = 2, } #[derive(Clone, Copy, Debug)] struct Record { opcode: u32, op: Op, } #[derive(Clone, Debug)] struct Block { pc: u32, kind: MemoryKind, records: Vec, /// Ended by an instruction that redirects the fetch stream (or the size limit). closed: bool, alive: bool, } /// Counters for the report (docs/cached-interpreter.md). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct BlockStats { /// Instructions run from a block's records. pub replayed: u64, /// Instructions recorded into a block. pub recorded: u64, /// Instructions the plain path ran outside any block (delay slots, unblockable PCs). pub plain: u64, /// Blocks entered from the entry table. pub entries: u64, pub built: u64, /// Blocks dropped by an invalidation rule. pub invalidated: u64, /// `verify`: a record's opcode differed from the fetched one (the block was dropped). pub mismatches: u64, } /// The cached interpreter's state, a field of the chip. pub struct BlockCache { /// On (the tools turn it on with `SH2_BLOCK_CACHE=1`). pub enabled: bool, /// `false`: trust mode (see the module notes). pub verify: bool, blocks: Vec, table: Vec, /// Per page: the blocks recorded over it (ids; dead ones are skipped). pages: std::collections::HashMap>, /// A bit per page that holds a live block's code (the write paths' quick test). code: Vec, current: u32, next: usize, next_pc: u32, pub stats: BlockStats, } impl Default for BlockCache { fn default() -> Self { BlockCache { enabled: false, verify: true, blocks: Vec::new(), table: vec![NONE; TABLE], pages: std::collections::HashMap::new(), code: vec![0; (EXTERNAL_PAGES + 16).div_ceil(64)], current: NONE, next: 0, next_pc: 0, stats: BlockStats::default(), } } } /// The invalidation page of a fetch address in a kind's namespace. fn page_of(pc: u32, kind: MemoryKind) -> u32 { match kind { MemoryKind::DataArray => EXTERNAL_PAGES as u32 + ((pc & 0xFFF) >> PAGE_SHIFT), _ => (pc & 0x1FFF_FFFF) >> PAGE_SHIFT, } } fn slot_of(pc: u32, kind: MemoryKind) -> usize { (((pc >> 1) ^ (pc >> 13) ^ (kind as u32 * 0x9E5)) as usize) & (TABLE - 1) } impl BlockCache { /// Off unless ``SH2_BLOCK_CACHE=1`` in the environment (``SH2_BLOCK_TRUST=1``: trust /// mode), so every tool and every chip a tool makes (the fresh-chip scenarios) follows /// one switch. wasm32 has no environment: ``sh2_setup``'s bit 2 turns it on. pub fn from_env() -> BlockCache { let on = |name: &str| std::env::var(name).map(|v| v == "1").unwrap_or(false); BlockCache { enabled: on("SH2_BLOCK_CACHE"), verify: !on("SH2_BLOCK_TRUST"), ..BlockCache::default() } } fn mark(&mut self, page: u32, id: u32) { self.code[page as usize >> 6] |= 1 << (page & 63); self.pages.entry(page).or_default().push(id); } fn drop_page(&mut self, page: u32) { if self.code[page as usize >> 6] & (1 << (page & 63)) == 0 { return; } self.code[page as usize >> 6] &= !(1 << (page & 63)); if let Some(ids) = self.pages.remove(&page) { for id in ids { let block = &mut self.blocks[id as usize]; if block.alive { block.alive = false; self.stats.invalidated += 1; let slot = slot_of(block.pc, block.kind); if self.table[slot] == id { self.table[slot] = NONE; } } } } if self.current != NONE && !self.blocks[self.current as usize].alive { self.current = NONE; } } /// Drop the blocks over external addresses ``[address, address + bytes)``. pub fn invalidate_external(&mut self, address: u32, bytes: u32) { let first = (address & 0x1FFF_FFFF) >> PAGE_SHIFT; let last = ((address & 0x1FFF_FFFF) + bytes.max(1) - 1).min(0x1FFF_FFFF) >> PAGE_SHIFT; for page in first..=last { self.drop_page(page); } } fn invalidate_data_array(&mut self, offset: u32) { self.drop_page(EXTERNAL_PAGES as u32 + ((offset & 0xFFF) >> PAGE_SHIFT)); } /// Drop every block. pub fn clear(&mut self) { let live = self.blocks.iter().filter(|b| b.alive).count() as u64; self.stats.invalidated += live; self.blocks.clear(); self.table.iter_mut().for_each(|e| *e = NONE); self.pages.clear(); self.code.iter_mut().for_each(|w| *w = 0); self.current = NONE; } /// Live blocks (tests). pub fn live(&self) -> usize { self.blocks.iter().filter(|b| b.alive).count() } } impl Sh7604 { /// The memory kind of a fetch at ``pc``, or ``None`` where blocks are not kept. fn fetch_kind(&self, pc: u32) -> Option { match pc >> 29 { 0 if self.cache.enabled => Some(MemoryKind::Cached), 0 | 1 => Some(MemoryKind::External), 6 => Some(MemoryKind::DataArray), _ => None, } } /// The op to run at ``pc`` (outside a delay slot), given the opcode the pipeline /// fetched: from a block's record when one covers ``pc``, else decoded and recorded. /// Returns the opcode to run and its decode. pub(crate) fn block_op(&mut self, pc: u32, fetched: u32) -> (u32, Op) { let tables = tables(); let bc = &mut self.blocks; if bc.current != NONE && pc == bc.next_pc { let id = bc.current as usize; let i = bc.next; let block = &bc.blocks[id]; if i < block.records.len() { let record = block.records[i]; if bc.verify && record.opcode != fetched { bc.stats.mismatches += 1; let page = page_of(block.pc, block.kind); bc.drop_page(page); bc.stats.plain += 1; return (fetched, tables.ops[fetched as usize]); } bc.stats.replayed += 1; bc.next = i + 1; bc.next_pc = pc.wrapping_add(2); if bc.next == block.records.len() && block.closed { bc.current = NONE; } return (record.opcode, record.op); } if !block.closed { return self.block_record(id as u32, pc, fetched); } } // An entry: the table, or a new block. let Some(kind) = self.fetch_kind(pc) else { self.blocks.current = NONE; self.blocks.stats.plain += 1; return (fetched, tables.ops[fetched as usize]); }; let bc = &mut self.blocks; let slot = slot_of(pc, kind); let id = bc.table[slot]; if id != NONE { let block = &bc.blocks[id as usize]; if block.alive && block.pc == pc && block.kind == kind && !block.records.is_empty() { bc.stats.entries += 1; bc.current = id; bc.next = 0; bc.next_pc = pc; return self.block_op(pc, fetched); } } let id = bc.blocks.len() as u32; bc.blocks.push(Block { pc, kind, records: Vec::new(), closed: false, alive: true }); bc.table[slot] = id; bc.stats.built += 1; self.block_record(id, pc, fetched) } /// Append the instruction at ``pc`` to block ``id`` and run it from the decode. fn block_record(&mut self, id: u32, pc: u32, fetched: u32) -> (u32, Op) { let op = tables().ops[fetched as usize]; let bc = &mut self.blocks; let block = &mut bc.blocks[id as usize]; let kind = block.kind; block.records.push(Record { opcode: fetched, op }); let ends = block.records.len() >= MAX_RECORDS; block.closed = ends; let n = block.records.len(); bc.stats.recorded += 1; bc.mark(page_of(pc, kind), id); if ends { bc.current = NONE; } else { bc.current = id; bc.next = n; bc.next_pc = pc.wrapping_add(2); } (fetched, op) } /// The plain path ran an instruction outside the blocks (a delay slot): the block /// cursor no longer follows the stream. pub(crate) fn block_plain(&mut self) { self.blocks.current = NONE; self.blocks.stats.plain += 1; } /// A write the chip made reached external memory, or the data array. pub(crate) fn block_written(&mut self, address: u32, width: u32) { if address >> 29 == 6 { self.block_data_array_written(address & 0xFFF); } else { self.blocks.invalidate_external(address, width >> 3); if address >> 29 == 0 && self.cache.enabled { // Write-through updated a cached line: the same bytes are also data-array // code under its other name (found by rung U in trust mode: a handler // vectored into H'C0000000- ran a line the program had just written). let way = self.cache.lookup(address); if way >= 0 { self.blocks.invalidate_data_array(((way as u32) << 10) | (address & 0x3F0)); } } } } /// A data-array write: its own blocks, and the cached line that way and entry hold. pub(crate) fn block_data_array_written(&mut self, offset: u32) { self.blocks.invalidate_data_array(offset); let (way, entry) = ((offset >> 10) & 3, (offset >> 4) & 63); let index = (entry * 4 + way) as usize; if self.cache.valid[index] != 0 { let line = (self.cache.tags[index] << 10) | (entry << 4); self.blocks.invalidate_external(line, 16); } } /// A line fill into the data-array slot ``base`` (trust mode only: verify mode sees /// any change in the fetched opcode): blocks over the line, and data-array blocks over /// the slot, whose bytes the fill replaces. pub(crate) fn block_filled(&mut self, line: u32, base: u32) { if !self.blocks.verify { self.blocks.invalidate_external(line, 16); self.blocks.invalidate_data_array(base); } } /// The board reports a write the chip did not make (another bus master) over /// external addresses ``[address, address + bytes)``: blocks there are dropped. pub fn invalidate_code(&mut self, address: u32, bytes: u32) { self.blocks.invalidate_external(address, bytes); } }