A GameCube/Wii emulator and debugger written in Rust.
caching incl. jit
Layle9c43d7291040
diff --git a/crates/gecko/src/flipper/dsp.rs b/crates/gecko/src/flipper/dsp.rsindex e531fb2..897216e 100644--- a/crates/gecko/src/flipper/dsp.rs+++ b/crates/gecko/src/flipper/dsp.rs@@ -767,6 +767,13 @@ pub trait DspJitHandle {fn dump_hot_blocks(&self, top_k: usize);fn dump_hot_blocks_csv(&self, top_k: usize, path: &std::path::Path) -> std::io::Result<()>;fn dump_top_clif(&mut self, top_k: usize, iram: &[u8], irom: &[u8]);+ fn cached_blocks(&self) -> Vec<crate::jit_cache::CachedBlockDsp>;+ fn precompile_blocks(+ &mut self,+ iram: &[u8],+ irom: &[u8],+ blocks: &[crate::jit_cache::CachedBlockDsp],+ ) -> (usize, usize);}#[cfg(feature = "jit")]@@ -798,6 +805,19 @@ impl<const SYSTEM: SystemId> DspJitHandle for jit::JitEngine<SYSTEM> {Ok(())}+ fn cached_blocks(&self) -> Vec<crate::jit_cache::CachedBlockDsp> {+ Self::cached_blocks(self)+ }++ fn precompile_blocks(+ &mut self,+ iram: &[u8],+ irom: &[u8],+ blocks: &[crate::jit_cache::CachedBlockDsp],+ ) -> (usize, usize) {+ Self::precompile_blocks(self, iram, irom, blocks)+ }+fn dump_top_clif(&mut self, _top_k: usize, _iram: &[u8], _irom: &[u8]) {#[cfg(feature = "jit-stats")]{diff --git a/crates/gecko/src/flipper/dsp/jit.rs b/crates/gecko/src/flipper/dsp/jit.rsindex 542cdd5..cb97c05 100644--- a/crates/gecko/src/flipper/dsp/jit.rs+++ b/crates/gecko/src/flipper/dsp/jit.rs@@ -50,8 +50,7 @@ pub struct JitEngine<const SYSTEM: SystemId> {chain_depth_histogram: [u64; CHAIN_DEPTH_HISTOGRAM_LEN],#[cfg(feature = "jit-stats")]pub(crate) hits: FxHashMap<u16, u64>,- #[cfg(feature = "jit-stats")]- block_specs: FxHashMap<u16, block::BlockSpec>,+ pub(crate) block_specs: FxHashMap<u16, block::BlockSpec>,#[cfg(feature = "jit-stats")]block_entry_counter_ptrs: FxHashMap<u16, usize>,}@@ -354,7 +353,6 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {chain_depth_histogram: [0; CHAIN_DEPTH_HISTOGRAM_LEN],#[cfg(feature = "jit-stats")]hits: FxHashMap::default(),- #[cfg(feature = "jit-stats")]block_specs: FxHashMap::default(),#[cfg(feature = "jit-stats")]block_entry_counter_ptrs: FxHashMap::default(),@@ -413,11 +411,63 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {#[cfg(feature = "jit-stats")]{*self.hits.entry(start_pc).or_insert(0) += 1;- self.block_specs.insert(start_pc, spec);}+ self.block_specs.insert(start_pc, spec);entry}+ pub fn cached_blocks(&self) -> Vec<crate::jit_cache::CachedBlockDsp> {+ self.cache+ .keys()+ .filter_map(|&pc| {+ let spec = self.block_specs.get(&pc)?;+ Some(crate::jit_cache::CachedBlockDsp {+ pc,+ instr_count: spec.instrs.len() as u16,+ hash: crate::jit_cache::hash_words(spec.instrs.iter().map(|e| e.raw)),+ })+ })+ .collect()+ }++ pub fn precompile_blocks(+ &mut self,+ iram: &[u8],+ irom: &[u8],+ blocks: &[crate::jit_cache::CachedBlockDsp],+ ) -> (usize, usize) {+ let mut compiled = 0usize;+ let mut skipped = 0usize;++ for b in blocks {+ if self.cache.contains_key(&b.pc) {+ continue;+ }++ if b.instr_count == 0 {+ skipped += 1;+ continue;+ }++ let spec = block::discover(iram, irom, b.pc);+ if spec.instrs.len() != b.instr_count as usize {+ skipped += 1;+ continue;+ }++ let actual = crate::jit_cache::hash_words(spec.instrs.iter().map(|e| e.raw));+ if actual != b.hash {+ skipped += 1;+ continue;+ }++ self.lookup_or_compile(iram, irom, b.pc);++ compiled += 1;+ }+ (compiled, skipped)+ }+fn func_id_for(&mut self, pc: u16) -> FuncId {if let Some(&id) = self.block_func_ids.get(&pc) {return id;diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex e7da95b..1d3160c 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -12,10 +12,12 @@ mod xf;use crate::flipper::gx::constants::{BP_REG_SIZE, CP_REG_SIZE, TLUT_MEM_ENTRIES, XF_MEM_SIZE};use crate::flipper::gx::draw::Matrix4;-use crate::flipper::gx::regs::{AlphaCompare, BlendMode, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode};+use crate::flipper::gx::regs::{+ AlphaCompare, BlendMode, ChanCtrl, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode,+};#[cfg(feature = "efb-writeback")]use crate::host::EfbWriteback;-use crate::host::{DrawVertex, GxAction, RenderSink, TextureKey, XfbPart};+use crate::host::{DrawVertex, GxAction, LightData, RenderSink, TextureKey, XfbPart};use crate::mmio::Mmio;use crate::system::{System, SystemId};use rustc_hash::FxHashMap;@@ -72,6 +74,12 @@ pub struct GraphicsProcessor {pub xfb_copies: Vec<XfbCopy>,pub vertices_scratch: Vec<draw::Vertex>,pub draw_vertices_scratch: Vec<DrawVertex>,+ pub lighting_dirty: bool,+ pub cached_color_ctrl: [ChanCtrl; 2],+ pub cached_alpha_ctrl: [ChanCtrl; 2],+ pub cached_ambient_color: [[f32; 4]; 2],+ pub cached_material_color: [[f32; 4]; 2],+ pub cached_lights: [LightData; 8],#[cfg(feature = "gx-stats")]pub(crate) stats: GxStats,// Hash of the raw texture data at each cache key; used to detect when@@ -150,6 +158,12 @@ impl GraphicsProcessor {xfb_copies: Vec::new(),vertices_scratch: Vec::with_capacity(256),draw_vertices_scratch: Vec::with_capacity(256),+ lighting_dirty: true,+ cached_color_ctrl: [ChanCtrl::default(); 2],+ cached_alpha_ctrl: [ChanCtrl::default(); 2],+ cached_ambient_color: [[0.0; 4]; 2],+ cached_material_color: [[0.0; 4]; 2],+ cached_lights: std::array::from_fn(|_| LightData::default()),#[cfg(feature = "gx-stats")]stats: GxStats::default(),texture_hashes: FxHashMap::default(),diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex ae78d98..a3a384e 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -286,7 +286,7 @@ impl GraphicsProcessor {{self.stats.texture_loads += 1;}-+renderer.exec(GxAction::LoadTexture {id: cache_id,width,diff --git a/crates/gecko/src/flipper/gx/texgen.rs b/crates/gecko/src/flipper/gx/texgen.rsindex 9e7052a..4de848a 100644--- a/crates/gecko/src/flipper/gx/texgen.rs+++ b/crates/gecko/src/flipper/gx/texgen.rs@@ -12,25 +12,24 @@ impl GraphicsProcessor {tex_mtx_indices: &[u8; 8],) -> [f32; 3] {let tg = TexGenReg::from_raw(self.xf_mem[XF_TEXGEN_BASE + texgen_idx]);- let dt = DualTexGenReg::from_raw(self.xf_mem[XF_DUALTEX_BASE + texgen_idx]);- // Select the source input vector based on texgen source_rowlet src = self.select_texgen_source(&tg, position, normal, raw_texcoords);- // Form input vector based on input_formlet input = match tg.input_form() {super::regs::TexGenInputForm::Ab11 => [src[0], src[1], 1.0, 1.0],super::regs::TexGenInputForm::Abc1 => [src[0], src[1], src[2], 1.0],};- // Texture matrix base from per-vertex indexlet tex_mtx_base = tex_mtx_indices[texgen_idx] as usize * XF_POS_MTX_STRIDE;- // Multiply input by texture matrix (2x4 or 3x4 depending on projection)let (s, t, q) = self.apply_tex_matrix(&tg, tex_mtx_base, &input);- // Dual texgen post-transform (normalization + post-matrix multiply)- let (s, t, q) = self.apply_dual_texgen(s, t, q, &dt);+ let (s, t, q) = if self.xf_mem[XF_DUAL_TEX_ENABLE] != 0 {+ let dt = DualTexGenReg::from_raw(self.xf_mem[XF_DUALTEX_BASE + texgen_idx]);+ self.apply_dual_texgen(s, t, q, &dt)+ } else {+ (s, t, q)+ };// Return (s, t, q) as a 3-component vector. The perspective divide// (s/q, t/q) is deferred to the fragment shader so the rasterizer@@ -93,66 +92,37 @@ impl GraphicsProcessor {}}+ #[inline(always)]fn apply_tex_matrix(&self, tg: &TexGenReg, tex_mtx_base: usize, input: &[f32; 4]) -> (f32, f32, f32) {+ let m: [f32; 12] = std::array::from_fn(|i| f32::from_bits(self.xf_mem[tex_mtx_base + i]));+ let s = m[0] * input[0] + m[1] * input[1] + m[2] * input[2] + m[3] * input[3];+ let t = m[4] * input[0] + m[5] * input[1] + m[6] * input[2] + m[7] * input[3];+match tg.projection() {- super::regs::TexGenProjection::St => {- // 2x4 matrix -> (s, t)- let s = f32::from_bits(self.xf_mem[tex_mtx_base]) * input[0]- + f32::from_bits(self.xf_mem[tex_mtx_base + 1]) * input[1]- + f32::from_bits(self.xf_mem[tex_mtx_base + 2]) * input[2]- + f32::from_bits(self.xf_mem[tex_mtx_base + 3]) * input[3];- let t = f32::from_bits(self.xf_mem[tex_mtx_base + 4]) * input[0]- + f32::from_bits(self.xf_mem[tex_mtx_base + 5]) * input[1]- + f32::from_bits(self.xf_mem[tex_mtx_base + 6]) * input[2]- + f32::from_bits(self.xf_mem[tex_mtx_base + 7]) * input[3];- (s, t, 1.0)- }+ super::regs::TexGenProjection::St => (s, t, 1.0),super::regs::TexGenProjection::Stq => {- // 3x4 matrix -> (s, t, q)- let s = f32::from_bits(self.xf_mem[tex_mtx_base]) * input[0]- + f32::from_bits(self.xf_mem[tex_mtx_base + 1]) * input[1]- + f32::from_bits(self.xf_mem[tex_mtx_base + 2]) * input[2]- + f32::from_bits(self.xf_mem[tex_mtx_base + 3]) * input[3];- let t = f32::from_bits(self.xf_mem[tex_mtx_base + 4]) * input[0]- + f32::from_bits(self.xf_mem[tex_mtx_base + 5]) * input[1]- + f32::from_bits(self.xf_mem[tex_mtx_base + 6]) * input[2]- + f32::from_bits(self.xf_mem[tex_mtx_base + 7]) * input[3];- let q = f32::from_bits(self.xf_mem[tex_mtx_base + 8]) * input[0]- + f32::from_bits(self.xf_mem[tex_mtx_base + 9]) * input[1]- + f32::from_bits(self.xf_mem[tex_mtx_base + 10]) * input[2]- + f32::from_bits(self.xf_mem[tex_mtx_base + 11]) * input[3];+ let q = m[8] * input[0] + m[9] * input[1] + m[10] * input[2] + m[11] * input[3];(s, t, q)}}}+ #[inline(always)]fn apply_dual_texgen(&self, s: f32, t: f32, q: f32, dt: &DualTexGenReg) -> (f32, f32, f32) {- let dual_tex_enabled = self.xf_mem[XF_DUAL_TEX_ENABLE] != 0;- if !dual_tex_enabled {- return (s, t, q);- }-let post_base = XF_POST_MTX_BASE + dt.post_mtx_idx() as usize * 4;- // Normalize (s, t, q) only if dt.normalize() is setlet (ns, nt, nq) = if dt.normalize() {let inv_q = if q.abs() > f32::EPSILON { 1.0 / q } else { 1.0 };(s * inv_q, t * inv_q, inv_q)} else {(s, t, q)};- // Post-transform: 3x4 matrix multiply on (ns, nt, nq)- let ps = f32::from_bits(self.xf_mem[post_base]) * ns- + f32::from_bits(self.xf_mem[post_base + 1]) * nt- + f32::from_bits(self.xf_mem[post_base + 2]) * nq- + f32::from_bits(self.xf_mem[post_base + 3]);- let pt = f32::from_bits(self.xf_mem[post_base + 4]) * ns- + f32::from_bits(self.xf_mem[post_base + 5]) * nt- + f32::from_bits(self.xf_mem[post_base + 6]) * nq- + f32::from_bits(self.xf_mem[post_base + 7]);- let pq = f32::from_bits(self.xf_mem[post_base + 8]) * ns- + f32::from_bits(self.xf_mem[post_base + 9]) * nt- + f32::from_bits(self.xf_mem[post_base + 10]) * nq- + f32::from_bits(self.xf_mem[post_base + 11]);++ let m: [f32; 12] = std::array::from_fn(|i| f32::from_bits(self.xf_mem[post_base + i]));++ let ps = m[0] * ns + m[1] * nt + m[2] * nq + m[3];+ let pt = m[4] * ns + m[5] * nt + m[6] * nq + m[7];+ let pq = m[8] * ns + m[9] * nt + m[10] * nq + m[11];+(ps, pt, pq)}}diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rsindex 605b1d7..9f85bd8 100644--- a/crates/gecko/src/flipper/gx/vertex.rs+++ b/crates/gecko/src/flipper/gx/vertex.rs@@ -2,7 +2,7 @@ use super::constants::*;use super::math::{Vec3, unpack_rgba};use super::regs::{self, *};use super::{GraphicsProcessor, draw};-use crate::host::{DrawData, DrawVertex, GxAction, LightData, RenderSink};+use crate::host::{DrawData, DrawVertex, GxAction, RenderSink};use crate::mmio::{Mmio, RamView};use crate::system::SystemId;use std::io::{Cursor, Read};@@ -75,7 +75,7 @@ impl GraphicsProcessor {self.vertices_scratch.clear();self.vertices_scratch.reserve(vertex_count);-+let mut cur = Cursor::new(&data);let view = mmio.ram_view();@@ -99,29 +99,7 @@ impl GraphicsProcessor {let tev_color_regs = self.resolve_tev_color_regs();let tev_orders = self.resolve_tev_orders();- // Snapshot light data for the action stream- let light_colors = self.snapshot_light_field(XF_LIGHT_COLOR);- let light_cosatt = self.snapshot_light_field(XF_LIGHT_A0);- let light_distatt = self.snapshot_light_field(XF_LIGHT_K0);- let light_pos = self.snapshot_light_field(XF_LIGHT_PX);- let light_dir = self.snapshot_light_field(XF_LIGHT_NX);-- let color_ctrl = [- regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]),- regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL1]),- ];- let alpha_ctrl = [- regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]),- regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL1]),- ];- let ambient_color = [- unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]),- unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR1]),- ];- let material_color = [- unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]),- unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR1]),- ];+ self.rebuild_lighting_cache_if_dirty();self.draw_vertices_scratch.clear();self.draw_vertices_scratch.reserve(self.vertices_scratch.len());@@ -137,14 +115,6 @@ impl GraphicsProcessor {}let draw_vertices = std::mem::take(&mut self.draw_vertices_scratch);- let lights: [LightData; 8] = std::array::from_fn(|i| LightData {- color: light_colors[i],- cosatt: light_cosatt[i],- distatt: light_distatt[i],- position: light_pos[i],- direction: light_dir[i],- });-// Flatten the three indirect matrices to 6 rows. Row 2M is row// 0 of matrix M, row 2M+1 is row 1. The .w lane carries the// shared scale exponent (positive means right-shift, negative@@ -191,11 +161,11 @@ impl GraphicsProcessor {num_indirect_stages: self.cur_num_indirect_stages,bump_imask: self.cur_bump_imask,tev_indirect: std::array::from_fn(|i| self.cur_tev_indirect[i].raw()),- color_ctrl,- alpha_ctrl,- ambient_color,- material_color,- lights,+ color_ctrl: self.cached_color_ctrl,+ alpha_ctrl: self.cached_alpha_ctrl,+ ambient_color: self.cached_ambient_color,+ material_color: self.cached_material_color,+ lights: self.cached_lights.clone(),}));#[cfg(feature = "gx-stats")]@@ -572,22 +542,66 @@ impl GraphicsProcessor {])}- fn snapshot_light_field(&self, field_offset: usize) -> [[f32; 4]; 8] {- std::array::from_fn(|i| {- let base = XF_LIGHT_BASE + i * XF_LIGHT_STRIDE + field_offset;- if field_offset == XF_LIGHT_COLOR {- // Color is stored as packed RGBA, not float- unpack_rgba(self.xf_mem[base])- } else {- // Float vec3, w = 0- [- f32::from_bits(self.xf_mem[base]),- f32::from_bits(self.xf_mem[base + 1]),- f32::from_bits(self.xf_mem[base + 2]),- 0.0,- ]- }- })+ fn rebuild_lighting_cache_if_dirty(&mut self) {+ if !self.lighting_dirty {+ return;+ }++ self.cached_color_ctrl = [+ regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]),+ regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL1]),+ ];++ self.cached_alpha_ctrl = [+ regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]),+ regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL1]),+ ];++ self.cached_ambient_color = [+ unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]),+ unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR1]),+ ];++ self.cached_material_color = [+ unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]),+ unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR1]),+ ];++ for i in 0..8 {+ let base = XF_LIGHT_BASE + i * XF_LIGHT_STRIDE;++ self.cached_lights[i].color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);++ self.cached_lights[i].cosatt = [+ f32::from_bits(self.xf_mem[base + XF_LIGHT_A0]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_A0 + 1]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_A0 + 2]),+ 0.0,+ ];++ self.cached_lights[i].distatt = [+ f32::from_bits(self.xf_mem[base + XF_LIGHT_K0]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_K0 + 1]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_K0 + 2]),+ 0.0,+ ];++ self.cached_lights[i].position = [+ f32::from_bits(self.xf_mem[base + XF_LIGHT_PX]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_PX + 1]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_PX + 2]),+ 0.0,+ ];++ self.cached_lights[i].direction = [+ f32::from_bits(self.xf_mem[base + XF_LIGHT_NX]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_NX + 1]),+ f32::from_bits(self.xf_mem[base + XF_LIGHT_NX + 2]),+ 0.0,+ ];+ }++ self.lighting_dirty = false;}}@@ -607,14 +621,14 @@ fn read_index(cur: &mut Cursor<&Vec<u8>>, attr: AttributeType) -> usize {}}-#[inline]+#[inline(always)]fn decode_position(data: &[u8], vat: &VatA) -> [f32; 3] {let num = vat.pos_cnt().components();let recip = 1.0f32 / ((1u32 << vat.pos_shift()) as f32);self::decode_components::<3>(data, num, vat.pos_fmt(), recip)}-#[inline]+#[inline(always)]fn decode_normal(data: &[u8], vat: &VatA) -> [f32; 3] {let cnt = vat.nrm_cnt().components().min(3);let fmt = vat.nrm_fmt();@@ -626,7 +640,7 @@ fn decode_normal(data: &[u8], vat: &VatA) -> [f32; 3] {self::decode_components::<3>(data, cnt, fmt, recip)}-#[inline]+#[inline(always)]fn decode_texcoord(data: &[u8], fmt: ComponentFormat, shift: u8, cnt: TexCount) -> [f32; 2] {let num = cnt.components();let recip = 1.0f32 / ((1u32 << shift) as f32);@@ -637,7 +651,7 @@ fn decode_texcoord(data: &[u8], fmt: ComponentFormat, shift: u8, cnt: TexCount)#[inline(always)]fn decode_components<const N: usize>(data: &[u8], num: usize, fmt: ComponentFormat, recip: f32) -> [f32; N] {let mut result = [0.0f32; N];-+match fmt {ComponentFormat::U8 => {for i in 0..num {@@ -724,4 +738,3 @@ fn decode_color(data: &[u8], fmt: regs::ColorFormat, cnt: regs::ColorCount) -> [}}}-diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rsindex 79b8a4c..21c2fb4 100644--- a/crates/gecko/src/flipper/gx/xf.rs+++ b/crates/gecko/src/flipper/gx/xf.rs@@ -4,21 +4,23 @@ use super::{GraphicsProcessor, draw};use crate::host::{GxAction, RenderSink};use crate::mmio::RamView;+const XF_LIGHT_END: usize = XF_LIGHT_BASE + 8 * XF_LIGHT_STRIDE;+const XF_CHAN_CFG_BEGIN: usize = XF_AMBIENT_COLOR0;+const XF_CHAN_CFG_END: usize = XF_ALPHA_CTRL1 + 1;++#[inline(always)]+fn ranges_overlap(a_begin: usize, a_end: usize, b_begin: usize, b_end: usize) -> bool {+ a_begin < b_end && b_begin < a_end+}+impl GraphicsProcessor {+ #[inline(always)]pub fn xf_transform_3x4(&self, base: usize, v: [f32; 3]) -> Vec3 {+ let m: [f32; 12] = std::array::from_fn(|i| f32::from_bits(self.xf_mem[base + i]));Vec3(- f32::from_bits(self.xf_mem[base]) * v[0]- + f32::from_bits(self.xf_mem[base + 1]) * v[1]- + f32::from_bits(self.xf_mem[base + 2]) * v[2]- + f32::from_bits(self.xf_mem[base + 3]),- f32::from_bits(self.xf_mem[base + 4]) * v[0]- + f32::from_bits(self.xf_mem[base + 5]) * v[1]- + f32::from_bits(self.xf_mem[base + 6]) * v[2]- + f32::from_bits(self.xf_mem[base + 7]),- f32::from_bits(self.xf_mem[base + 8]) * v[0]- + f32::from_bits(self.xf_mem[base + 9]) * v[1]- + f32::from_bits(self.xf_mem[base + 10]) * v[2]- + f32::from_bits(self.xf_mem[base + 11]),+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3],+ m[4] * v[0] + m[5] * v[1] + m[6] * v[2] + m[7],+ m[8] * v[0] + m[9] * v[1] + m[10] * v[2] + m[11],)}@@ -136,6 +138,12 @@ impl GraphicsProcessor {self.rebuild_viewport();renderer.exec(GxAction::SetViewport(self.cur_viewport));}++ if self::ranges_overlap(addr, end, XF_LIGHT_BASE, XF_LIGHT_END)+ || self::ranges_overlap(addr, end, XF_CHAN_CFG_BEGIN, XF_CHAN_CFG_END)+ {+ self.lighting_dirty = true;+ }}#[inline(always)]@@ -185,5 +193,11 @@ impl GraphicsProcessor {self.rebuild_viewport();renderer.exec(GxAction::SetViewport(self.cur_viewport));}++ if self::ranges_overlap(dst_addr, end, XF_LIGHT_BASE, XF_LIGHT_END)+ || self::ranges_overlap(dst_addr, end, XF_CHAN_CFG_BEGIN, XF_CHAN_CFG_END)+ {+ self.lighting_dirty = true;+ }}}diff --git a/crates/gecko/src/gekko/jit.rs b/crates/gecko/src/gekko/jit.rsindex 9e28a6a..7e0d836 100644--- a/crates/gecko/src/gekko/jit.rs+++ b/crates/gecko/src/gekko/jit.rs@@ -85,7 +85,6 @@ pub struct JitEngine<const SYSTEM: SystemId> {pending_chain_slots: FxHashMap<u32, Vec<usize>>,#[cfg(feature = "jit-stats")]hits: FxHashMap<u32, u64>,- #[cfg(feature = "jit-stats")]pub(crate) block_specs: FxHashMap<u32, block::BlockSpec>,#[cfg(feature = "jit-stats")]pub(crate) block_entry_counter_ptrs: FxHashMap<u32, usize>,@@ -480,7 +479,6 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {pending_chain_slots: FxHashMap::default(),#[cfg(feature = "jit-stats")]hits: FxHashMap::default(),- #[cfg(feature = "jit-stats")]block_specs: FxHashMap::default(),#[cfg(feature = "jit-stats")]block_entry_counter_ptrs: FxHashMap::default(),@@ -505,6 +503,58 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {}}+ pub fn cached_blocks(&self) -> Vec<crate::jit_cache::CachedBlockPpc> {+ self.cache+ .keys()+ .filter_map(|&pc| {+ let spec = self.block_specs.get(&pc)?;+ Some(crate::jit_cache::CachedBlockPpc {+ pc,+ instr_count: spec.instrs.len() as u16,+ hash: crate::jit_cache::hash_words(spec.instrs.iter().copied()),+ })+ })+ .collect()+ }++ pub fn precompile_blocks(+ &mut self,+ sys: &mut System<SYSTEM>,+ blocks: &[crate::jit_cache::CachedBlockPpc],+ ) -> (usize, usize) {+ let mut compiled = 0usize;+ let mut skipped = 0usize;++ for b in blocks {+ if self.cache.contains_key(&b.pc) {+ continue;+ }++ let count = b.instr_count as u32;+ if count == 0 {+ skipped += 1;+ continue;+ }++ let mut buf = Vec::with_capacity(count as usize);+ for i in 0..count {+ let instr_pc = b.pc.wrapping_add(i * 4);+ buf.push(sys.mmio.fetch_instruction(instr_pc));+ }++ let actual = crate::jit_cache::hash_words(buf.into_iter());+ if actual != b.hash {+ skipped += 1;+ continue;+ }++ self.lookup_or_compile(sys, b.pc);++ compiled += 1;+ }+ (compiled, skipped)+ }+pub fn lookup_or_compile(&mut self, sys: &mut System<SYSTEM>, pc: u32) -> BlockEntry {unsafe {let table = self.block_lookup_table_addr as *const BlockLookupSlot;@@ -532,10 +582,7 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {let entry = self.compile(&spec, &gprs_snapshot);self.cache.insert(pc, entry);- #[cfg(feature = "jit-stats")]- {- self.block_specs.insert(pc, spec);- }+ self.block_specs.insert(pc, spec);entry}diff --git a/crates/gecko/src/gekko/jit/translator.rs b/crates/gecko/src/gekko/jit/translator.rsindex 50b184f..17305aa 100644--- a/crates/gecko/src/gekko/jit/translator.rs+++ b/crates/gecko/src/gekko/jit/translator.rs@@ -1247,7 +1247,7 @@ fn emit_bclr_chain_fall<const SYSTEM: SystemId>(builder.switch_to_block(taken_block);builder.seal_block(taken_block);-+if instr.lk() {let lr_val = builder.ins().iconst(types::I32, pc.wrapping_add(4) as i64);lr_store::<SYSTEM>(builder, ctx_ptr, lr_val);@@ -1255,13 +1255,20 @@ fn emit_bclr_chain_fall<const SYSTEM: SystemId>(let lr = lr_load::<SYSTEM>(builder, ctx_ptr);let target_pc = builder.ins().band_imm(lr, !3i64);- emit_inline_cache_dispatch::<SYSTEM>(builder, ctx_ptr, target_pc, exit_block, block_sig_ref, lookup_table_addr);+ emit_inline_cache_dispatch::<SYSTEM>(+ builder,+ ctx_ptr,+ target_pc,+ exit_block,+ block_sig_ref,+ lookup_table_addr,+ );builder.switch_to_block(fall_block);builder.seal_block(fall_block);-+let fall_v = builder.ins().iconst(types::I32, pc.wrapping_add(4) as i64);-+if let Some(slot_addr) = fall_slot {emit_chain_or_exit::<SYSTEM>(builder, ctx_ptr, slot_addr, block_sig_ref, fall_v, exit_block);} else {@@ -1304,7 +1311,14 @@ fn emit_bcctr_chain_fall<const SYSTEM: SystemId>(}let ctr = ctr_load::<SYSTEM>(builder, ctx_ptr);let target_pc = builder.ins().band_imm(ctr, !3i64);- emit_inline_cache_dispatch::<SYSTEM>(builder, ctx_ptr, target_pc, exit_block, block_sig_ref, lookup_table_addr);+ emit_inline_cache_dispatch::<SYSTEM>(+ builder,+ ctx_ptr,+ target_pc,+ exit_block,+ block_sig_ref,+ lookup_table_addr,+ );builder.switch_to_block(fall_block);builder.seal_block(fall_block);@@ -3310,7 +3324,7 @@ pub(crate) fn emit_psq_store_quantized<const SYSTEM: SystemId>(let ps0_bits = builder.ins().bitcast(types::I32, MemFlags::new(), ps0_f32);let ps0_be = builder.ins().bswap(ps0_bits);builder.ins().store(MemFlags::new(), ps0_be, addr, 0);-+if !w {let ps1_f64 = ps1_load::<SYSTEM>(builder, ctx_ptr, fs);let ps1_f32 = builder.ins().fdemote(types::F32, ps1_f64);@@ -3318,19 +3332,19 @@ pub(crate) fn emit_psq_store_quantized<const SYSTEM: SystemId>(let ps1_be = builder.ins().bswap(ps1_bits);builder.ins().store(MemFlags::new(), ps1_be, addr, 4);}-+builder.ins().jump(merge, &[]);builder.switch_to_block(slow_f32_block);builder.seal_block(slow_f32_block);-+let fs_v = builder.ins().iconst(types::I32, fs as i64);let w_v = builder.ins().iconst(types::I32, if w { 1 } else { 0 });let gqr_const = builder.ins().iconst(types::I32, gqr_idx as i64);builder.ins().call(local.do_psq_store, &[ctx_ptr, fs_v, ea, w_v, gqr_const]);-+builder.ins().jump(merge, &[]);}diff --git a/crates/gecko/src/jit_cache.rs b/crates/gecko/src/jit_cache.rsnew file mode 100644index 0000000..0a309fe--- /dev/null+++ b/crates/gecko/src/jit_cache.rs@@ -0,0 +1,206 @@+use std::io::{Read, Write};+use std::path::{Path, PathBuf};++const MAGIC: [u8; 4] = *b"GBLK";++pub const JIT_VERSION: u32 = 2;++#[derive(Clone, Copy, Debug)]+#[repr(u8)]+pub enum CachedSystem {+ Gc = 0,+ Wii = 1,+}++#[derive(Clone, Copy, Debug)]+#[repr(u8)]+pub enum CachedKind {+ Ppc = 0,+ Dsp = 1,+}++#[derive(Clone, Copy, Debug)]+pub struct CachedBlockPpc {+ pub pc: u32,+ pub instr_count: u16,+ pub hash: u64,+}++#[derive(Clone, Copy, Debug)]+pub struct CachedBlockDsp {+ pub pc: u16,+ pub instr_count: u16,+ pub hash: u64,+}++#[inline]+pub fn hash_words(words: impl IntoIterator<Item = u32>) -> u64 {+ let mut h: u64 = 0xcbf29ce484222325;+ for w in words {+ h ^= w as u64;+ h = h.wrapping_mul(0x100000001b3);+ }+ h+}++pub fn cache_dir(game_id: &str) -> PathBuf {+ PathBuf::from("cache").join(game_id)+}++pub fn ppc_cache_path(game_id: &str) -> PathBuf {+ self::cache_dir(game_id).join("ppc.bin")+}++pub fn dsp_cache_path(game_id: &str) -> PathBuf {+ self::cache_dir(game_id).join("dsp.bin")+}++fn write_header<W: Write>(writer: &mut W, kind: CachedKind, system: CachedSystem, count: u32) -> std::io::Result<()> {+ writer.write_all(&MAGIC)?;+ writer.write_all(&JIT_VERSION.to_le_bytes())?;+ writer.write_all(&[kind as u8, system as u8, 0, 0])?;+ writer.write_all(&count.to_le_bytes())+}++fn read_header<R: Read>(reader: &mut R) -> std::io::Result<(CachedKind, CachedSystem, u32)> {+ let mut magic = [0u8; 4];+ reader.read_exact(&mut magic)?;++ if magic != MAGIC {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "bad jit cache magic",+ ));+ }++ let mut version_bytes = [0u8; 4];+ reader.read_exact(&mut version_bytes)?;+ let version = u32::from_le_bytes(version_bytes);++ if version != JIT_VERSION {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "jit cache version mismatch",+ ));+ }++ let mut tag = [0u8; 4];+ reader.read_exact(&mut tag)?;+ let kind = match tag[0] {+ 0 => CachedKind::Ppc,+ 1 => CachedKind::Dsp,+ _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad kind tag")),+ };++ let system = match tag[1] {+ 0 => CachedSystem::Gc,+ 1 => CachedSystem::Wii,+ _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad system tag")),+ };++ let mut count_bytes = [0u8; 4];+ reader.read_exact(&mut count_bytes)?;+ let count = u32::from_le_bytes(count_bytes);++ Ok((kind, system, count))+}++pub fn save_ppc_blocks(path: &Path, system: CachedSystem, blocks: &[CachedBlockPpc]) -> std::io::Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }++ let tmp = path.with_extension("tmp");+ {+ let mut file = std::fs::File::create(&tmp)?;+ self::write_header(&mut file, CachedKind::Ppc, system, blocks.len() as u32)?;+ for b in blocks {+ file.write_all(&b.pc.to_le_bytes())?;+ file.write_all(&b.instr_count.to_le_bytes())?;+ file.write_all(&[0u8; 2])?;+ file.write_all(&b.hash.to_le_bytes())?;+ }+ file.sync_data().ok();+ }++ std::fs::rename(&tmp, path)+}++pub fn load_ppc_blocks(path: &Path) -> std::io::Result<Vec<CachedBlockPpc>> {+ let mut file = std::fs::File::open(path)?;+ let (kind, _system, count) = self::read_header(&mut file)?;+ if !matches!(kind, CachedKind::Ppc) {+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "kind mismatch"));+ }++ let mut blocks = Vec::with_capacity(count as usize);+ for _ in 0..count {+ let mut pc_bytes = [0u8; 4];+ file.read_exact(&mut pc_bytes)?;++ let mut count_bytes = [0u8; 2];+ file.read_exact(&mut count_bytes)?;++ let mut reserved = [0u8; 2];+ file.read_exact(&mut reserved)?;++ let mut hash_bytes = [0u8; 8];+ file.read_exact(&mut hash_bytes)?;++ blocks.push(CachedBlockPpc {+ pc: u32::from_le_bytes(pc_bytes),+ instr_count: u16::from_le_bytes(count_bytes),+ hash: u64::from_le_bytes(hash_bytes),+ });+ }++ Ok(blocks)+}++pub fn save_dsp_blocks(path: &Path, system: CachedSystem, blocks: &[CachedBlockDsp]) -> std::io::Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }++ let tmp = path.with_extension("tmp");+ {+ let mut file = std::fs::File::create(&tmp)?;+ self::write_header(&mut file, CachedKind::Dsp, system, blocks.len() as u32)?;+ for b in blocks {+ file.write_all(&b.pc.to_le_bytes())?;+ file.write_all(&b.instr_count.to_le_bytes())?;+ file.write_all(&b.hash.to_le_bytes())?;+ }+ file.sync_data().ok();+ }++ std::fs::rename(&tmp, path)+}++pub fn load_dsp_blocks(path: &Path) -> std::io::Result<Vec<CachedBlockDsp>> {+ let mut file = std::fs::File::open(path)?;+ let (kind, _system, count) = self::read_header(&mut file)?;+ if !matches!(kind, CachedKind::Dsp) {+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "kind mismatch"));+ }++ let mut blocks = Vec::with_capacity(count as usize);+ for _ in 0..count {+ let mut pc_bytes = [0u8; 2];+ file.read_exact(&mut pc_bytes)?;++ let mut count_bytes = [0u8; 2];+ file.read_exact(&mut count_bytes)?;++ let mut hash_bytes = [0u8; 8];+ file.read_exact(&mut hash_bytes)?;++ blocks.push(CachedBlockDsp {+ pc: u16::from_le_bytes(pc_bytes),+ instr_count: u16::from_le_bytes(count_bytes),+ hash: u64::from_le_bytes(hash_bytes),+ });+ }++ Ok(blocks)+}diff --git a/crates/gecko/src/lib.rs b/crates/gecko/src/lib.rsindex b80aae5..80e80d8 100644--- a/crates/gecko/src/lib.rs+++ b/crates/gecko/src/lib.rs@@ -10,6 +10,7 @@ pub mod hollywood;pub mod host;pub mod input;pub mod ipl;+pub mod jit_cache;pub mod mmio;#[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]pub mod profile;diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsindex d203d2b..1e66ece 100644--- a/crates/gecko/src/system.rs+++ b/crates/gecko/src/system.rs@@ -228,6 +228,78 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {self.on_vsync_boundary();}+ #[cfg(feature = "jit")]+ pub fn load_jit_cache(&mut self, game_id: &str) -> (usize, usize, usize, usize) {+ let mut ppc_compiled = 0;+ let mut ppc_skipped = 0;+ let mut dsp_compiled = 0;+ let mut dsp_skipped = 0;++ let ppc_path = crate::jit_cache::ppc_cache_path(game_id);+ if let Ok(blocks) = crate::jit_cache::load_ppc_blocks(&ppc_path) {+ tracing::info!(count = blocks.len(), "loaded PPC JIT block cache");++ if self.jit.is_none() {+ self.jit = Some(Box::new(crate::gekko::jit::JitEngine::<SYSTEM>::new()));+ }++ let mut jit = self.jit.take().unwrap();+ let (c, s) = jit.precompile_blocks(self, &blocks);+ ppc_compiled = c;+ ppc_skipped = s;++ self.jit = Some(jit);+ }++ let dsp_path = crate::jit_cache::dsp_cache_path(game_id);+ if let Ok(blocks) = crate::jit_cache::load_dsp_blocks(&dsp_path) {+ tracing::info!(count = blocks.len(), "loaded DSP JIT block cache");++ if self.dsp.jit.is_none() {+ self.dsp.jit = Some(Box::new(crate::flipper::dsp::jit::JitEngine::<SYSTEM>::new()));+ }++ let iram_ptr = self.dsp.iram.as_ptr();+ let irom_ptr = self.dsp.irom.as_ptr();+ let iram_len = self.dsp.iram.len();+ let irom_len = self.dsp.irom.len();+ let iram = unsafe { ::core::slice::from_raw_parts(iram_ptr, iram_len) };+ let irom = unsafe { ::core::slice::from_raw_parts(irom_ptr, irom_len) };++ let (c, s) = self.dsp.jit.as_mut().unwrap().precompile_blocks(iram, irom, &blocks);+ dsp_compiled = c;+ dsp_skipped = s;+ }++ (ppc_compiled, ppc_skipped, dsp_compiled, dsp_skipped)+ }++ #[cfg(feature = "jit")]+ pub fn save_jit_cache(&self, game_id: &str) -> std::io::Result<(usize, usize)> {+ let cached_system = if SYSTEM == WII {+ crate::jit_cache::CachedSystem::Wii+ } else {+ crate::jit_cache::CachedSystem::Gc+ };++ let mut ppc_count = 0;+ let mut dsp_count = 0;++ if let Some(jit) = self.jit.as_ref() {+ let blocks = jit.cached_blocks();+ ppc_count = blocks.len();+ crate::jit_cache::save_ppc_blocks(&crate::jit_cache::ppc_cache_path(game_id), cached_system, &blocks)?;+ }++ if let Some(jit) = self.dsp.jit.as_ref() {+ let blocks = jit.cached_blocks();+ dsp_count = blocks.len();+ crate::jit_cache::save_dsp_blocks(&crate::jit_cache::dsp_cache_path(game_id), cached_system, &blocks)?;+ }++ Ok((ppc_count, dsp_count))+ }+#[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]fn on_vsync_boundary(&mut self) {self.vsync_count = self.vsync_count.wrapping_add(1);@@ -247,7 +319,7 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {if !self.heatmap.enabled || self.heatmap.interval_frames == 0 {return;}-+if self.vsync_count % self.heatmap.interval_frames as u64 != 0 {return;}diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex 9f980a4..1082ede 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -165,11 +165,11 @@ fn main() {if args.wii {let mut emulator = Wii::with_image(&dol);configure(&mut emulator, &args);- run(emulator, present_mode, &args);+ run(emulator, present_mode, &args, None);} else {let mut emulator = GameCube::with_image(&dol);configure(&mut emulator, &args);- run(emulator, present_mode, &args);+ run(emulator, present_mode, &args, None);}} else if let Some(ref ipl_path) = args.ipl {let ipl_data = std::fs::read(ipl_path).expect("failed to read IPL");@@ -179,10 +179,11 @@ fn main() {emulator.insert_dvd(image::load_dvd(dvd_data));}configure(&mut emulator, &args);- run(emulator, present_mode, &args);+ run(emulator, present_mode, &args, None);} else if let Some(ref dvd_path) = args.dvd {let dvd_data = std::fs::read(dvd_path).expect("failed to read DVD");let dvd = image::load_dvd(dvd_data);+ let game_id = self::game_id_from_header(dvd.header());if dvd.header().is_wii() {println!("Detected Wii disc, booting via apploader HLE");let builder = Wii::apploader_hle(dvd);@@ -195,18 +196,32 @@ fn main() {};let mut emulator = builder.build();configure(&mut emulator, &args);- run(emulator, present_mode, &args);+ run(emulator, present_mode, &args, Some(game_id));} else {println!("Detected GameCube disc, booting via IPL HLE");let mut emulator = GameCube::with_ipl_hle(dvd);configure(&mut emulator, &args);- run(emulator, present_mode, &args);+ run(emulator, present_mode, &args, Some(game_id));}} else {panic!("provide one of --dol, --ipl, or --dvd");}}+fn game_id_from_header(header: &image::dvd::Header) -> String {+ let mut buf = String::with_capacity(6);++ for &b in &header.game_code {+ buf.push(if b.is_ascii_graphic() { b as char } else { '_' });+ }++ for &b in &header.maker_code {+ buf.push(if b.is_ascii_graphic() { b as char } else { '_' });+ }++ buf+}+fn configure<const SYSTEM: SystemId>(emulator: &mut System<SYSTEM>, args: &Args) {if let Some(ref dsp_path) = args.dsp {let dsp_data = std::fs::read(dsp_path).expect("failed to read DSP IROM");@@ -250,7 +265,12 @@ fn configure<const SYSTEM: SystemId>(emulator: &mut System<SYSTEM>, args: &Args)}}-fn run<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>, present_mode: wgpu::PresentMode, args: &Args) {+fn run<const SYSTEM: SystemId>(+ mut emulator: System<SYSTEM>,+ present_mode: wgpu::PresentMode,+ args: &Args,+ game_id: Option<String>,+) {let target_aspect = resolve_aspect(&args.aspect, SYSTEM);let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {backends: wgpu::Backends::all(),@@ -310,9 +330,23 @@ fn run<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>, present_mode: wgpu:}let emu_input = input.clone();+ if let Some(ref id) = game_id {+ let (ppc_c, ppc_s, dsp_c, dsp_s) = emulator.load_jit_cache(id);+ if ppc_c > 0 || dsp_c > 0 || ppc_s > 0 || dsp_s > 0 {+ tracing::info!(+ ppc_compiled = ppc_c,+ ppc_skipped = ppc_s,+ dsp_compiled = dsp_c,+ dsp_skipped = dsp_s,+ game = id.as_str(),+ "pre-compiled JIT blocks from cache"+ );+ }+ }+let emu_handle = std::thread::Builder::new().name("emu".into())- .spawn(move || thread::emu_thread::<SYSTEM>(emulator, emu_input, proxy))+ .spawn(move || thread::emu_thread::<SYSTEM>(emulator, emu_input, proxy, game_id)).expect("failed to spawn emulator thread");let mut app = app::App {diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rsindex 213d84e..e2daf6f 100644--- a/crates/tinyapp/src/thread.rs+++ b/crates/tinyapp/src/thread.rs@@ -7,6 +7,7 @@ pub fn emu_thread<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>,input: Arc<Mutex<HostInput>>,proxy: EventLoopProxy<()>,+ game_id: Option<String>,) {loop {let input = *input.lock().unwrap();@@ -17,4 +18,11 @@ pub fn emu_thread<const SYSTEM: SystemId>(break;}}++ if let Some(game_id) = game_id.as_deref() {+ match emulator.save_jit_cache(game_id) {+ Ok((ppc, dsp)) => tracing::info!(ppc_blocks = ppc, dsp_blocks = dsp, "saved JIT cache"),+ Err(err) => tracing::warn!(?err, "failed to save JIT cache"),+ }+ }}