A GameCube/Wii emulator and debugger written in Rust.
improve cache and add old timing shit
Laylee781ae1ae133
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex 6237209..bf41ee0 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -455,7 +455,7 @@ impl GxRenderer {},);}- GxAction::InvalidateCaches => {+ GxAction::InvalidateStateCaches | GxAction::InvalidateCaches => {self.flush_pending_draws(device, queue);let _ = self.submit_pending(queue);self.texture_cache.clear();@@ -464,7 +464,9 @@ impl GxRenderer {self.return_to_pool(tex, view);}self.bind_group_cache.clear();- self.invalidate_pipeline_caches();+ if matches!(action, GxAction::InvalidateCaches) {+ self.invalidate_pipeline_caches();+ }}#[cfg(not(target_arch = "wasm32"))]GxAction::DumpTextures { dir } => {diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex d7ae9ac..afef07e 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -24,9 +24,7 @@ use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, Muse gecko::host::{DrawState, TextureKey};use glam::Mat4;use pipeline::{FullPipelineKey, UberPipelineKey};-use rustc_hash::FxHashMap;-#[cfg(not(target_arch = "wasm32"))]-use rustc_hash::FxHashSet;+use rustc_hash::{FxHashMap, FxHashSet};use shader_specialization::{ShaderKey, ShaderSpecializationKey};use std::num::NonZeroU64;#[cfg(feature = "gx-stats")]@@ -1241,6 +1239,8 @@ impl GxRenderer {}pub fn save_pipeline_cache(&self) -> std::io::Result<usize> {+ let uber_keys: Vec<UberPipelineKey> = self.uber_pipeline_cache.keys().copied().collect();+ pipeline::save_uber_pipeline_keys(&pipeline::uber_pipeline_cache_path(), &uber_keys)?;let path = pipeline::pipeline_cache_path();let keys: Vec<pipeline::FullPipelineKey> = self.pipeline_cache.keys().copied().collect();pipeline::save_pipeline_keys(&path, &keys)?;@@ -1293,51 +1293,83 @@ impl GxRenderer {pub fn prewarm_pipeline_cache(&mut self, device: &wgpu::Device) {let path = pipeline::pipeline_cache_path();- let keys: Vec<pipeline::FullPipelineKey> = pipeline::load_cached_pipeline_keys(&path)+ let keys = pipeline::load_cached_pipeline_keys(&path);++ let uber_keys: FxHashSet<UberPipelineKey> =+ pipeline::load_cached_uber_pipeline_keys(&pipeline::uber_pipeline_cache_path())+ .into_iter()+ .chain(keys.iter().copied().map(UberPipelineKey::from))+ .collect();+ let missing_shaders: FxHashSet<ShaderKey> = uber_keys+ .iter()+ .map(|k| k.shader)+ .filter(|k| !self.shader_cache.contains_key(k))+ .collect();+ self.shader_cache.extend(prewarm_shader_variants(+ device,+ &missing_shaders.into_iter().collect::<Vec<_>>(),+ ));++ #[derive(Clone, Copy)]+ enum WarmupKey {+ Specialized(FullPipelineKey),+ Uber(UberPipelineKey),+ }++ let mut jobs: Vec<WarmupKey> = uber_keys.into_iter()- .filter(|k| !self.pipeline_cache.contains_key(k) && self.shader_cache.contains_key(&k.shader))+ .filter(|k| !self.uber_pipeline_cache.contains_key(k))+ .map(WarmupKey::Uber).collect();+ let num_uber_pipelines = jobs.len();+ jobs.extend(+ keys.into_iter()+ .filter(|k| !self.pipeline_cache.contains_key(k))+ .map(WarmupKey::Specialized),+ );- if keys.is_empty() {+ if jobs.is_empty() {return;}let t0 = std::time::Instant::now();+ let compile = |&key: &WarmupKey| {+ let pipeline = match key {+ WarmupKey::Specialized(k) => pipeline::create_specialized_pipeline(+ device,+ &self.pipeline_layout,+ self.surface_format,+ &self.shader_cache[&k.shader],+ &k,+ ),+ WarmupKey::Uber(k) => pipeline::create_uber_pipeline(+ device,+ &self.pipeline_layout,+ self.surface_format,+ &self.shader_cache[&k.shader],+ &k,+ ),+ };+ (key, pipeline)+ };// wgpu 29's WebGPU backend wraps JS handles in Rc<Cell<_>>, making// Device/Queue !Send — so the threaded compile path can't even// type-check on wasm32. Fall back to a sequential pass there.#[cfg(not(target_arch = "wasm32"))]- let compiled: Vec<(pipeline::FullPipelineKey, wgpu::RenderPipeline)> = {+ let compiled: Vec<_> = {let num_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)- .min(keys.len());- let chunk_size = keys.len().div_ceil(num_threads);+ .min(jobs.len());+ let chunk_size = jobs.len().div_ceil(num_threads);- let self_ref = &*self;std::thread::scope(|s| {- let handles: Vec<_> = keys+ let handles: Vec<_> = jobs.chunks(chunk_size).map(|chunk| {- s.spawn(move || {- chunk- .iter()- .map(|&k| {- let module = &self_ref.shader_cache[&k.shader];- (- k,- pipeline::create_specialized_pipeline(- device,- &self_ref.pipeline_layout,- self_ref.surface_format,- module,- &k,- ),- )- })- .collect::<Vec<_>>()- })+ let compile = &compile;+ s.spawn(move || chunk.iter().map(compile).collect::<Vec<_>>())}).collect();handles.into_iter().flat_map(|h| h.join().unwrap()).collect()@@ -1345,29 +1377,22 @@ impl GxRenderer {};#[cfg(target_arch = "wasm32")]- let compiled: Vec<(pipeline::FullPipelineKey, wgpu::RenderPipeline)> = keys- .iter()- .map(|&k| {- let module = &self.shader_cache[&k.shader];- (- k,- pipeline::create_specialized_pipeline(- device,- &self.pipeline_layout,- self.surface_format,- module,- &k,- ),- )- })- .collect();+ let compiled: Vec<_> = jobs.iter().map(compile).collect();for (k, p) in compiled {- self.pipeline_cache.insert(k, p);+ match k {+ WarmupKey::Specialized(k) => {+ self.pipeline_cache.insert(k, p);+ }+ WarmupKey::Uber(k) => {+ self.uber_pipeline_cache.insert(k, p);+ }+ }}tracing::info!(- num_pipelines = keys.len(),+ num_pipelines = jobs.len() - num_uber_pipelines,+ num_uber_pipelines,elapsed_ms = t0.elapsed().as_millis() as u64,"prewarmed pipeline cache",);diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rsindex db30846..cee7cc9 100644--- a/crates/backend-wgpu/src/pipeline.rs+++ b/crates/backend-wgpu/src/pipeline.rs@@ -177,14 +177,36 @@ impl From<FullPipelineKey> for UberPipelineKey {}}+impl UberPipelineKey {+ fn to_bytes(self) -> [u8; UBER_PIPELINE_KEY_BYTES] {+ let mut out = [0u8; UBER_PIPELINE_KEY_BYTES];+ out[..SHADER_KEY_BYTES].copy_from_slice(&self.shader.to_bytes());+ out[SHADER_KEY_BYTES..].copy_from_slice(&self.fixed.to_bytes());+ out+ }++ fn from_bytes(b: &[u8; UBER_PIPELINE_KEY_BYTES]) -> Self {+ Self {+ shader: ShaderKey::from_bytes(b[..SHADER_KEY_BYTES].try_into().unwrap()),+ fixed: PipelineKey::from_bytes(b[SHADER_KEY_BYTES..].try_into().unwrap()),+ }+ }+}+pub(crate) const FULL_PIPELINE_KEY_BYTES: usize = SHADER_KEY_BYTES + SPECIALIZATION_KEY_BYTES + PipelineKey::BYTES;+const UBER_PIPELINE_KEY_BYTES: usize = SHADER_KEY_BYTES + PipelineKey::BYTES;const PIPELINE_CACHE_MAGIC: [u8; 4] = *b"GPKC";+const UBER_PIPELINE_CACHE_MAGIC: [u8; 4] = *b"GUKC";const PIPELINE_CACHE_VERSION: u32 = 11;pub(crate) fn pipeline_cache_path() -> std::path::PathBuf {gecko::paths::cache("pipeline_keys.bin")}+pub(crate) fn uber_pipeline_cache_path() -> std::path::PathBuf {+ gecko::paths::cache("uber_pipeline_keys.bin")+}+impl FullPipelineKey {pub(crate) fn alpha_pass_key(&self) -> Option<Self> {self.fixed.splits_dst_alpha().then_some(Self {@@ -224,6 +246,14 @@ impl FullPipelineKey {}pub(crate) fn load_cached_pipeline_keys(path: &Path) -> Vec<FullPipelineKey> {+ load_keys(path, PIPELINE_CACHE_MAGIC, FullPipelineKey::from_bytes)+}++pub(crate) fn load_cached_uber_pipeline_keys(path: &Path) -> Vec<UberPipelineKey> {+ load_keys(path, UBER_PIPELINE_CACHE_MAGIC, UberPipelineKey::from_bytes)+}++fn load_keys<const N: usize, K>(path: &Path, magic: [u8; 4], decode: fn(&[u8; N]) -> K) -> Vec<K> {let mut f = match File::open(path) {Ok(f) => f,Err(_) => return Vec::new(),@@ -234,7 +264,7 @@ pub(crate) fn load_cached_pipeline_keys(path: &Path) -> Vec<FullPipelineKey> {return Vec::new();}- if header[..4] != PIPELINE_CACHE_MAGIC {+ if header[..4] != magic {return Vec::new();}@@ -244,15 +274,28 @@ pub(crate) fn load_cached_pipeline_keys(path: &Path) -> Vec<FullPipelineKey> {}let mut keys = Vec::new();- let mut buf = [0u8; FULL_PIPELINE_KEY_BYTES];+ let mut buf = [0u8; N];while f.read_exact(&mut buf).is_ok() {- keys.push(FullPipelineKey::from_bytes(&buf));+ keys.push(decode(&buf));}keys}pub(crate) fn save_pipeline_keys(path: &Path, keys: &[FullPipelineKey]) -> std::io::Result<()> {+ save_keys(path, PIPELINE_CACHE_MAGIC, keys, FullPipelineKey::to_bytes)+}++pub(crate) fn save_uber_pipeline_keys(path: &Path, keys: &[UberPipelineKey]) -> std::io::Result<()> {+ save_keys(path, UBER_PIPELINE_CACHE_MAGIC, keys, UberPipelineKey::to_bytes)+}++fn save_keys<const N: usize, K: Copy>(+ path: &Path,+ magic: [u8; 4],+ keys: &[K],+ encode: fn(K) -> [u8; N],+) -> std::io::Result<()> {if let Some(parent) = path.parent() {std::fs::create_dir_all(parent)?;}@@ -260,11 +303,11 @@ pub(crate) fn save_pipeline_keys(path: &Path, keys: &[FullPipelineKey]) -> std::let f = File::create(path)?;let mut w = BufWriter::new(f);- w.write_all(&PIPELINE_CACHE_MAGIC)?;+ w.write_all(&magic)?;w.write_all(&PIPELINE_CACHE_VERSION.to_le_bytes())?;for k in keys {- w.write_all(&k.to_bytes())?;+ w.write_all(&encode(*k))?;}w.flush()?;diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rsindex 724c4dd..82c703d 100644--- a/crates/backend-wgpu/src/sink.rs+++ b/crates/backend-wgpu/src/sink.rs@@ -415,7 +415,7 @@ impl RenderSink for ThreadedSink {});}}- } else if matches!(&action, GxAction::InvalidateCaches) {+ } else if matches!(&action, GxAction::InvalidateStateCaches | GxAction::InvalidateCaches) {self.pending_efb_textures.clear();}@@ -633,7 +633,8 @@ impl RenderSink for InlineSink {pub fn action_resets_vertex_scratch(action: &GxAction) -> bool {match action {- GxAction::InvalidateCaches+ GxAction::InvalidateStateCaches+ | GxAction::InvalidateCaches| GxAction::CopyXfb { .. }| GxAction::PresentXfb { .. }| GxAction::PresentRawXfb { .. }diff --git a/crates/fifoplayer/src/debug/geometry.rs b/crates/fifoplayer/src/debug/geometry.rsindex a9f48b8..55a8122 100644--- a/crates/fifoplayer/src/debug/geometry.rs+++ b/crates/fifoplayer/src/debug/geometry.rs@@ -97,7 +97,7 @@ impl GeometryCapture {}}GxAction::SetTexture { slot, id, .. } => self.bindings[*slot] = Some(*id),- GxAction::InvalidateCaches => {+ GxAction::InvalidateStateCaches | GxAction::InvalidateCaches => {self.textures.clear();self.bindings.fill(None);}diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.tomlindex a40e558..79ed15b 100644--- a/crates/gecko/Cargo.toml+++ b/crates/gecko/Cargo.toml@@ -22,6 +22,7 @@ jit-stats = ["jit", "dep:backtrace"]# Run both interpreter and JIT for every draw call, reports driftvtx-jit-validate = ["jit", "gx-stats"]fps-counter = []+frame-timings = []gx-stats = []profile = ["dep:backtrace", "dep:windows-sys"]# Enables std::hint::black_box inside `EmptyRenderSink::exec`diff --git a/crates/gecko/src/flipper/dsp.rs b/crates/gecko/src/flipper/dsp.rsindex 04df5b1..f8725a2 100644--- a/crates/gecko/src/flipper/dsp.rs+++ b/crates/gecko/src/flipper/dsp.rs@@ -466,6 +466,8 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {}pub fn execute_dsp_batch(&mut self) {+ #[cfg(feature = "frame-timings")]+ let _timer = crate::profile::frame_timings::Timer::new(crate::profile::frame_timings::Kind::DspRun);#[cfg(feature = "jit")]if self.execution_mode == ExecutionMode::Jit {self.execute_dsp_batch_jit();@@ -475,6 +477,8 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {}pub fn drain_dsp_synchronous(&mut self, max_steps: u32) {+ #[cfg(feature = "frame-timings")]+ let _timer = crate::profile::frame_timings::Timer::new(crate::profile::frame_timings::Kind::DspRun);#[cfg(feature = "jit")]if self.execution_mode == ExecutionMode::Jit {self.drain_dsp_synchronous_jit(max_steps);diff --git a/crates/gecko/src/flipper/dsp/jit.rs b/crates/gecko/src/flipper/dsp/jit.rsindex 5acf750..a07f2a7 100644--- a/crates/gecko/src/flipper/dsp/jit.rs+++ b/crates/gecko/src/flipper/dsp/jit.rs@@ -397,6 +397,8 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {#[cfg_attr(feature = "hotpath", hotpath::measure(label = "dsp_jit_compile"))]fn compile(&mut self, spec: &block::BlockSpec) -> BlockEntry {+ #[cfg(feature = "frame-timings")]+ let _timer = crate::profile::frame_timings::Timer::new(crate::profile::frame_timings::Kind::DspCompile);let func_id = self.func_id_for(spec.start_pc);self.ctx.clear();diff --git a/crates/gecko/src/flipper/gx/jit.rs b/crates/gecko/src/flipper/gx/jit.rsindex 546a7b9..0a32ecd 100644--- a/crates/gecko/src/flipper/gx/jit.rs+++ b/crates/gecko/src/flipper/gx/jit.rs@@ -277,6 +277,8 @@ impl JitVertexEngine {#[cfg_attr(feature = "hotpath", hotpath::measure(label = "vtx_jit_compile"))]fn compile(&mut self, key: VtxKey) -> Option<CompiledParser> {+ #[cfg(feature = "frame-timings")]+ let _timer = crate::profile::frame_timings::Timer::new(crate::profile::frame_timings::Kind::VertexCompile);self.seq = self.seq.wrapping_add(1);let name = format!("gecko_vtx_parser_{:016x}", self.seq);let func_id = self@@ -296,6 +298,12 @@ impl JitVertexEngine {self.module.finalize_definitions().expect("finalize vtx jit");let raw = self.module.get_finalized_function(func_id);+ crate::jit::register_jit_code(+ "vertex",+ self.seq as u32,+ raw as usize,+ self.ctx.compiled_code().unwrap().code_buffer().len(),+ );let func: ParserFn = unsafe { std::mem::transmute(raw) };Some(CompiledParser { func, func_id })}diff --git a/crates/gecko/src/gekko/jit.rs b/crates/gecko/src/gekko/jit.rsindex 8023295..62a0754 100644--- a/crates/gecko/src/gekko/jit.rs+++ b/crates/gecko/src/gekko/jit.rs@@ -1033,6 +1033,9 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {#[cfg_attr(feature = "hotpath", hotpath::measure(label = "ppc_jit_compile"))]fn compile_div2i(&mut self, pc: u32) -> BlockEntry {+ #[cfg(feature = "frame-timings")]+ let _timer = crate::profile::frame_timings::Timer::new(crate::profile::frame_timings::Kind::PpcCompile);+let func_id = self.func_id_for(pc);#[cfg(feature = "jit-stats")]@@ -1165,6 +1168,9 @@ impl<const SYSTEM: SystemId> JitEngine<SYSTEM> {}fn compile(&mut self, spec: &block::BlockSpec, gprs: &[u32; 32], gqrs: &[u32; 8]) -> BlockEntry {+ #[cfg(feature = "frame-timings")]+ let _timer = crate::profile::frame_timings::Timer::new(crate::profile::frame_timings::Kind::PpcCompile);+let func_id = self.func_id_for(spec.start_pc);let _ = self.target_slot_addr(spec.start_pc);diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex a7a2b57..7d38c3f 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -77,6 +77,10 @@ pub enum GxAction {palette: Box<[[u8; 4]; 256]>,},+ /// Drop textures, EFB copies and bind groups derived from emulated memory+ /// after restoring a state. Immutable GPU pipelines remain valid.+ InvalidateStateCaches,+/// Debug action: Drop every cached pipeline, bind group, and texture on/// the renderer side. Used by the GX debug window to force fresh decodes.InvalidateCaches,diff --git a/crates/gecko/src/lib.rs b/crates/gecko/src/lib.rsindex 82743d3..52d449f 100644--- a/crates/gecko/src/lib.rs+++ b/crates/gecko/src/lib.rs@@ -13,7 +13,12 @@ pub mod ipl;pub mod jit;pub mod mmio;pub mod paths;-#[cfg(any(feature = "jit-stats", feature = "profile", feature = "gx-stats"))]+#[cfg(any(+ feature = "jit-stats",+ feature = "profile",+ feature = "gx-stats",+ feature = "frame-timings"+))]pub mod profile;pub mod savestate;pub mod scheduler;diff --git a/crates/gecko/src/profile.rs b/crates/gecko/src/profile.rsindex 2df2a09..3785173 100644--- a/crates/gecko/src/profile.rs+++ b/crates/gecko/src/profile.rs@@ -292,3 +292,54 @@ mod stub_sampler {#[cfg(all(feature = "profile", not(windows)))]pub use stub_sampler::IpSampler;++#[cfg(feature = "frame-timings")]+pub mod frame_timings {+ use std::cell::Cell;+ use std::time::Instant;++ #[derive(Clone, Copy)]+ pub enum Kind {+ PpcCompile,+ DspCompile,+ VertexCompile,+ DspRun,+ }++ const KINDS: usize = Kind::DspRun as usize + 1;++ thread_local! {+ static TOTALS: Cell<[(u64, u64); KINDS]> = const { Cell::new([(0, 0); KINDS]) };+ }++ pub struct Timer {+ kind: Kind,+ start: Instant,+ }++ impl Timer {+ pub fn new(kind: Kind) -> Self {+ Self {+ kind,+ start: Instant::now(),+ }+ }+ }++ impl Drop for Timer {+ fn drop(&mut self) {+ let ns = self.start.elapsed().as_nanos() as u64;++ TOTALS.with(|cell| {+ let mut totals = cell.get();+ totals[self.kind as usize].0 += 1;+ totals[self.kind as usize].1 += ns;+ cell.set(totals);+ });+ }+ }++ pub fn take() -> [(u64, u64); KINDS] {+ TOTALS.with(|cell| cell.replace([(0, 0); KINDS]))+ }+}diff --git a/crates/gecko/src/savestate.rs b/crates/gecko/src/savestate.rsindex 224270e..9244c98 100644--- a/crates/gecko/src/savestate.rs+++ b/crates/gecko/src/savestate.rs@@ -332,7 +332,7 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {#[cfg(not(feature = "jit"))]self.mmio.clear_code_refcount();- self.render_sink.exec(crate::host::GxAction::InvalidateCaches);+ self.render_sink.exec(crate::host::GxAction::InvalidateStateCaches);self.render_sink.reset_efb();self.audio_sink.set_sample_rate(self.ai.control.aid_sample_rate_hz());diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.tomlindex e57feba..ea7dcff 100644--- a/crates/tinyapp/Cargo.toml+++ b/crates/tinyapp/Cargo.toml@@ -13,6 +13,7 @@ fps-counter = ["gecko/fps-counter"]jit-stats = ["gecko/jit-stats"]gx-stats = ["gecko/gx-stats", "backend-wgpu/gx-stats"]profile = ["gecko/profile"]+frame-timings = ["gecko/frame-timings"]hotpath = ["dep:hotpath", "gecko/hotpath", "backend-wgpu/hotpath"]hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc"]hotpath-cpu = ["hotpath", "hotpath/hotpath-cpu"]