diff --git a/Setup-DexNomRuntime.ps1 b/Setup-DexNomRuntime.ps1 index 48877431cd..b6a7013056 100644 --- a/Setup-DexNomRuntime.ps1 +++ b/Setup-DexNomRuntime.ps1 @@ -79,19 +79,19 @@ try { [IO.File]::WriteAllText($config, $game.FullName, [Text.UTF8Encoding]::new($false)) } finally { $lock.Dispose() } -$launcher = Join-Path $InstallDir 'victory-play.exe' Write-Host "Installed DexNom RayTime in $InstallDir" [IO.Directory]::CreateDirectory($ShortcutDirectory) | Out-Null $shell = New-Object -ComObject WScript.Shell foreach ($entry in @( - @{ Name = 'DexNom RayTime'; Arguments = '' } - @{ Name = 'DexNom RayTime (Experimental RT)'; Arguments = '--rt' } - @{ Name = 'DexNom RayTime (FSR Quality 4K)'; Arguments = '--rt --console series-x --local-gpu-memory --fsr-quality --sparse-textures --no-upload-ahead --capture-readbacks --rt-write-stats' } + @{ Name = 'DexNom RayTime'; Program = 'victory-play.exe'; Arguments = '' } + @{ Name = 'DexNom RayTime (Experimental RT)'; Program = 'victory-play.exe'; Arguments = '--rt' } + @{ Name = 'DexNom RayTime (FSR Quality 4K)'; Program = 'victory-play.exe'; Arguments = '--rt --console series-x --local-gpu-memory --fsr-quality --sparse-textures --no-upload-ahead --capture-readbacks --rt-write-stats' } + @{ Name = 'DexNom RayTime (Preload and Play)'; Program = 'victory-warm.exe'; Arguments = '--play' } )) { $shortcut = $shell.CreateShortcut((Join-Path $ShortcutDirectory ($entry.Name + '.lnk'))) - $shortcut.TargetPath = $launcher + $shortcut.TargetPath = Join-Path $InstallDir $entry.Program $shortcut.Arguments = $entry.Arguments $shortcut.WorkingDirectory = $InstallDir $shortcut.Save() } -Write-Host "Open DexNom RayTime from $ShortcutDirectory. The FSR Quality 4K shortcut uses the tested ray-tracing profile." +Write-Host "Open DexNom RayTime from $ShortcutDirectory. The FSR Quality 4K shortcut uses the tested ray-tracing profile. The Preload and Play shortcut finishes shader preloading before launch." diff --git a/apps/victory/src/bin/victory-warm.rs b/apps/victory/src/bin/victory-warm.rs index 151652374f..3e85b843fe 100644 --- a/apps/victory/src/bin/victory-warm.rs +++ b/apps/victory/src/bin/victory-warm.rs @@ -10,7 +10,7 @@ mod windows_launcher; #[cfg(windows)] fn main() { if let Err(error) = windows_launcher::run(true) { - eprintln!("Shader preload failed\n{error:#}"); + eprintln!("DexNom Runtime failed\n{error:#}"); std::process::exit(1); } } diff --git a/apps/victory/src/play_launcher.rs b/apps/victory/src/play_launcher.rs index 48f6b6c056..23e9369a80 100644 --- a/apps/victory/src/play_launcher.rs +++ b/apps/victory/src/play_launcher.rs @@ -27,6 +27,7 @@ struct LaunchOptions { rt_write_stats: bool, rt_store_trace: bool, lighting_trace: bool, + play: bool, } fn launcher_options( @@ -47,6 +48,7 @@ fn launcher_options( rt_write_stats: false, rt_store_trace: false, lighting_trace: false, + play: false, }; while let Some(option) = args.peek() { if option == "--warp" { @@ -87,6 +89,8 @@ fn launcher_options( options.rt_store_trace = true; } else if option == "--lighting-trace" { options.lighting_trace = true; + } else if option == "--play" { + options.play = true; } else if option == "--console" { args.next(); options.console = match args.next().as_deref().and_then(std::ffi::OsStr::to_str) { @@ -119,8 +123,12 @@ pub(super) fn run(warm: bool) -> anyhow::Result<()> { let mut args = std::env::args_os().skip(1).peekable(); let LaunchOptions { warp, ray_tracing, static_bvh, console, local_gpu_memory, native_1440p, render_1080p, fsr, - sparse_textures, upload_ahead, capture_readbacks, rt_write_stats, rt_store_trace, lighting_trace, + sparse_textures, upload_ahead, capture_readbacks, rt_write_stats, rt_store_trace, lighting_trace, play, } = launcher_options(&mut args)?; + if play && !warm { + bail!("--play is only accepted by victory-warm"); + } + let play = play || !warm; let game = match args.next() { Some(path) => PathBuf::from(path), None => { @@ -132,8 +140,9 @@ pub(super) fn run(warm: bool) -> anyhow::Result<()> { }; if args.next().is_some() { bail!( - "Usage\n{} [--rt | --no-rt | --rt-static-bvh] [--warp] [--console series-x|series-s] [--local-gpu-memory] [--native-1440p | --1080p-to-1440p | --fsr-quality | --fsr-balanced | --fsr-performance] [--sparse-textures] [--upload-ahead | --no-upload-ahead] [--capture-readbacks] [--rt-write-stats] [--rt-store-trace] [--lighting-trace] [game executable]", - launcher.display() + "Usage\n{}{} [--rt | --no-rt | --rt-static-bvh] [--warp] [--console series-x|series-s] [--local-gpu-memory] [--native-1440p | --1080p-to-1440p | --fsr-quality | --fsr-balanced | --fsr-performance] [--sparse-textures] [--upload-ahead | --no-upload-ahead] [--capture-readbacks] [--rt-write-stats] [--rt-store-trace] [--lighting-trace] [game executable]", + launcher.display(), + if warm { " [--play]" } else { "" } ); } if !game.is_file() || !runtime.is_file() { @@ -172,97 +181,105 @@ pub(super) fn run(warm: bool) -> anyhow::Result<()> { runtime.display(), game.display() )?; - let latest = if warm { - "latest-warm.txt" - } else { - "latest.txt" - }; - fs::write(logs.join(latest), path.display().to_string())?; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; - let mut child = Command::new(&runtime); - if let Some(on) = ray_tracing { - child.env("VICTORY_RAY_TRACING", if on { "1" } else { "0" }); - writeln!(log, "Ray tracing requested: {}", if on { "on" } else { "off" })?; - } else if static_bvh { - child.env("VICTORY_RAY_TRACING", "static-bvh"); - writeln!(log, "Ray tracing requested: static BVH traversal")?; - } - if warp { - child.env("VICTORY_D3D12_WARP", "1"); - } - if local_gpu_memory { - child.env("VICTORY_LOCAL_GPU_INPUTS", "1"); - } - if native_1440p { - child - .env("VICTORY_NATIVE_1440P", "1") - .env("VICTORY_RENDER_1080P", if render_1080p { "1" } else { "0" }) - .env("VICTORY_FSR_4K", "0"); - let expected_render = if render_1080p { "1920x1080" } else { "2560x1440" }; - writeln!(log, "Expected scene rendering {expected_render}, output 2560x1440")?; - } - if let Some(preset) = fsr { - child.env("VICTORY_FSR_4K", preset.name()); - let provider = folder.join("fidelityfx"); - if std::env::var_os("VICTORY_FIDELITYFX_DIR").is_none() - && provider.join("amd_fidelityfx_upscaler_dx12.dll").is_file() - { - child.env("VICTORY_FIDELITYFX_DIR", provider); + let new_child = |log: &mut File| -> anyhow::Result { + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut child = Command::new(&runtime); + if let Some(on) = ray_tracing { + child.env("VICTORY_RAY_TRACING", if on { "1" } else { "0" }); + writeln!(log, "Ray tracing requested: {}", if on { "on" } else { "off" })?; + } else if static_bvh { + child.env("VICTORY_RAY_TRACING", "static-bvh"); + writeln!(log, "Ray tracing requested: static BVH traversal")?; } - let [width, height] = preset.render_size(); - writeln!(log, "FSR {} (SDK mode {}) requested at {width}x{height} scene, 3840x2160 output", preset.name(), preset.mode())?; - } - if (fsr.is_some() || upload_ahead == Some(true)) && std::env::var_os("VICTORY_LOG").is_none() { - let filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "warn".into()); - child.env("VICTORY_LOG", format!( - "{filter},victory::run::native_1440p=info,victory_hle::modules::fidelityfx=info,victory_gpu::host=info,victory_gpu::texture::ahead=info" - )); - } - if let Some(enabled) = upload_ahead { - let value = if enabled { "1" } else { "0" }; - child.env("VICTORY_UPLOAD_AHEAD", value); - writeln!(log, "Texture copy queue requested: {}", if enabled { "on" } else { "off" })?; - } - for (enabled, key, message) in [ - (sparse_textures, "VICTORY_LEVELS_ON_DEMAND", "Sparse texture mips requested"), - (capture_readbacks, "VICTORY_CAPTURE_READBACKS", "Dirty-page readback capture requested"), - (rt_write_stats, "VICTORY_RT_WRITE_STATS", "Ray-tracing write statistics requested"), - ] { - if enabled { - child.env(key, "1"); - writeln!(log, "{message}")?; + if warp { + child.env("VICTORY_D3D12_WARP", "1"); + } + if local_gpu_memory { + child.env("VICTORY_LOCAL_GPU_INPUTS", "1"); + } + if native_1440p { + child + .env("VICTORY_NATIVE_1440P", "1") + .env("VICTORY_RENDER_1080P", if render_1080p { "1" } else { "0" }) + .env("VICTORY_FSR_4K", "0"); + let expected_render = if render_1080p { "1920x1080" } else { "2560x1440" }; + writeln!(log, "Expected scene rendering {expected_render}, output 2560x1440")?; + } + if let Some(preset) = fsr { + child.env("VICTORY_FSR_4K", preset.name()); + let provider = folder.join("fidelityfx"); + if std::env::var_os("VICTORY_FIDELITYFX_DIR").is_none() + && provider.join("amd_fidelityfx_upscaler_dx12.dll").is_file() + { + child.env("VICTORY_FIDELITYFX_DIR", provider); + } + let [width, height] = preset.render_size(); + writeln!(log, "FSR {} (SDK mode {}) requested at {width}x{height} scene, 3840x2160 output", preset.name(), preset.mode())?; + } + if (fsr.is_some() || upload_ahead == Some(true)) && std::env::var_os("VICTORY_LOG").is_none() { + let filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "warn".into()); + child.env("VICTORY_LOG", format!( + "{filter},victory::run::native_1440p=info,victory_hle::modules::fidelityfx=info,victory_gpu::host=info,victory_gpu::texture::ahead=info" + )); + } + if let Some(enabled) = upload_ahead { + let value = if enabled { "1" } else { "0" }; + child.env("VICTORY_UPLOAD_AHEAD", value); + writeln!(log, "Texture copy queue requested: {}", if enabled { "on" } else { "off" })?; + } + for (enabled, key, message) in [ + (sparse_textures, "VICTORY_LEVELS_ON_DEMAND", "Sparse texture mips requested"), + (capture_readbacks, "VICTORY_CAPTURE_READBACKS", "Dirty-page readback capture requested"), + (rt_write_stats, "VICTORY_RT_WRITE_STATS", "Ray-tracing write statistics requested"), + ] { + if enabled { + child.env(key, "1"); + writeln!(log, "{message}")?; + } + } + if rt_store_trace { + child.env("VICTORY_CAPTURE_RAW_STORES", victory_shader::emit::RAW_STORE_PROBE_HASH); + writeln!(log, "InitHeaders store trace requested")?; + } + if lighting_trace { + let trace = folder.join("lighting-trace").join(format!("{started}-{}", std::process::id())); + fs::create_dir_all(&trace)?; + let request = trace.join("request.txt"); + // Lighting using the shadow mask, RT resolve, auto-exposure, and the final composite. + child + .env("VICTORY_CAPTURE", &trace) + .env("VICTORY_CAPTURE_REQUEST", &request) + .env("VICTORY_DUMP_AFTER", "2bf91065944bcff4,7f05ddab771799a9,e622b718b6d9b057,6318f669e4f17d65") + .env("VICTORY_DUMP_INPUT", "e622b718b6d9b057:s1+0"); + writeln!(log, "Lighting trace request file {}", request.display())?; + } + if std::env::var_os("VICTORY_DEBUG_HUD").is_none() { + child.env("VICTORY_DEBUG_HUD", "1"); } - } - if rt_store_trace { - child.env("VICTORY_CAPTURE_RAW_STORES", victory_shader::emit::RAW_STORE_PROBE_HASH); - writeln!(log, "InitHeaders store trace requested")?; - } - if lighting_trace { - let trace = folder.join("lighting-trace").join(format!("{started}-{}", std::process::id())); - fs::create_dir_all(&trace)?; - let request = trace.join("request.txt"); - // Lighting using the shadow mask, RT resolve, auto-exposure, and the final composite. child - .env("VICTORY_CAPTURE", &trace) - .env("VICTORY_CAPTURE_REQUEST", &request) - .env("VICTORY_DUMP_AFTER", "2bf91065944bcff4,7f05ddab771799a9,e622b718b6d9b057,6318f669e4f17d65") - .env("VICTORY_DUMP_INPUT", "e622b718b6d9b057:s1+0"); - writeln!(log, "Lighting trace request file {}", request.display())?; - } - if std::env::var_os("VICTORY_DEBUG_HUD").is_none() { - child.env("VICTORY_DEBUG_HUD", "1"); + .current_dir(folder) + .env("VICTORY_DATA_DIR", &state) + .env("VICTORY_CACHE_DIR", &cache) + .stdin(Stdio::null()) + .stderr(log.try_clone()?) + .creation_flags(CREATE_NO_WINDOW); + Ok(child) + }; + if warm { + fs::write(logs.join("latest-warm.txt"), path.display().to_string())?; + let mut child = new_child(&mut log)?; + let status = preload(&mut child, &game, &cache, &path, &mut log)?; + if !status.success() { + bail!("Shader preload exited with {status}.\n\nLog file\n{}", path.display()); + } } - child - .current_dir(folder) - .env("VICTORY_DATA_DIR", &state) - .env("VICTORY_CACHE_DIR", &cache) - .stdin(Stdio::null()) - .stderr(log.try_clone()?) - .creation_flags(CREATE_NO_WINDOW); - let status = if warm { - preload(&mut child, &game, &cache, &path, &mut log)? - } else { - let status = child + if play { + if warm { + writeln!(log, "Shader preload finished. Starting the game.")?; + println!("Shader preload finished. Starting the game."); + } + fs::write(logs.join("latest.txt"), path.display().to_string())?; + let status = new_child(&mut log)? .arg("run") .arg(&game) .args([ @@ -276,13 +293,9 @@ pub(super) fn run(warm: bool) -> anyhow::Result<()> { .status() .with_context(|| format!("Could not start {}", runtime.display()))?; writeln!(log, "VIctory exited with {status}")?; - status - }; - if !status.success() { - bail!( - "VIctory exited with {status}.\n\nLog file\n{}", - path.display() - ); + if !status.success() { + bail!("VIctory exited with {status}.\n\nLog file\n{}", path.display()); + } } Ok(()) } @@ -476,6 +489,9 @@ mod tests { #[test] fn empty_and_incomplete_scans_are_reported() { assert!(check_warm_summary(None).is_err()); + assert!(check_warm_summary(Some( + "progress 15 s 2000 shaders checked 1990 translated 100 compute pipelines" + )).is_err()); assert!( check_warm_summary(Some( "warm 0 translated, 0 refused; 0 compute pipelines, 0 refused; 0 s" diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 133787a47b..6f14447b4d 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -140,14 +140,17 @@ impl Tally { } } -/// Emitted shaders by label, shared between threads. -type Kept = std::sync::Arc>>; +/// Emitted shaders by label, with their containers, shared between threads. +type Kept = std::sync::Arc)>>>; /// The optional checks after emission, one set per thread. struct Checks { /// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings), - /// kept to build those pipelines after the walk. + /// kept to build those pipelines after the walk: the names, and the + /// container being translated when its label holds one of them. keep: Option, + names: Vec, + current: Option>, validator: Option, host: Option<(Host, emit::HostShader)>, } @@ -175,7 +178,13 @@ pub fn run( ); } if pipelines { - Host::new(false).map_err(anyhow::Error::msg)?; + let host = Host::new(false).map_err(anyhow::Error::msg)?; + if emit::host_max_wave() == 0 + && let Some(max) = host.max_wave_lanes() + { + emit::set_host_max_wave(max); + println!("host waves at most {max} lanes"); + } } let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS") .unwrap_or_default() @@ -210,6 +219,8 @@ pub fn run( }; let mut checks = Checks { keep: (!pairs.is_empty()).then(|| kept.clone()), + names: pairs.iter().flat_map(|(v, p)| [v.clone(), p.clone()]).collect(), + current: None, validator: validate .then(|| Validator::load(dll.as_deref()).ok()) .flatten(), @@ -278,10 +289,34 @@ pub fn run( if !pairs.is_empty() { let host = Host::new(false).map_err(anyhow::Error::msg)?; let kept = lock(&kept); - let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); + let find = |name: &str| kept.iter().find(|(l, _, _)| l.contains(name)); + let mut validator = Validator::load(dll.as_deref()).ok(); for (v, p) in &pairs { let made = match (find(v), find(p)) { - (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { + // A mesh program whose outputs pass the host's 32 KiB alone: linked with + // this pixel program, as the runtime makes its pipeline + // (`emit::link_mesh`), each of the two validated. + (Some((_, ms, msc)), Some((_, ps, psc))) if ms.stage == HwStage::Ms && !emit::mesh_fits(&ms.dxil).unwrap_or(true) => { + match emit::link_mesh(msc, ms, psc, ps) { + Ok(Some((lms, lps))) => { + let mut checked = Vec::new(); + for (what, s) in [("mesh", &lms), ("pixel", &lps)] { + if let Some(v) = validator.as_mut() { + let mut copy = s.dxil.clone(); + checked.push(match v.validate(&mut copy) { + Ok(()) => format!("{what} validated"), + Err(e) => format!("{what} invalid: {}", e.lines().find(|l| l.contains("error")).unwrap_or(&e)), + }); + } + } + let made = host.mesh_pipeline(&lms, &lps).map(|_| "pipeline created".to_owned()).unwrap_or_else(|e| e); + format!("linked, {}, {made}", checked.join(", ")) + } + Ok(None) => "not linked (over 32 KiB)".to_owned(), + Err(e) => format!("not linked: {e}"), + } + } + (Some((_, vs, _)), Some((_, ps, _))) => if vs.stage == HwStage::Ms { host.mesh_pipeline(vs, ps) } else { host.pipeline(vs, ps) @@ -309,12 +344,17 @@ pub fn run( /// `victory warm`: fills the caches a run reads (`Command::Warm`). pub fn warm(paths: Vec, jobs: Option, pipelines: bool, rays: crate::RayOptions) -> Result<()> { let paths = crate::default_paths(paths)?; + if pipelines { + victory_hle::modules::d3d12x::check_preload_device()?; + } let cfg = victory_core::Config::load()?; rays.apply(&cfg); victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let threads = jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); let seen = Mutex::new(HashSet::new()); let [done, refused, made, unmade, omitted] = [const { AtomicUsize::new(0) }; 5]; + let completed = AtomicUsize::new(0); + let last_interval = AtomicUsize::new(0); let started = std::time::Instant::now(); for root in &paths { for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { @@ -355,14 +395,24 @@ pub fn warm(paths: Vec, jobs: Option, pipelines: bool, rays: cra continue; }; let count = if translated { &done } else { &refused }; - let n = count.fetch_add(1, Ordering::Relaxed) + 1; + count.fetch_add(1, Ordering::Relaxed); match pipeline { Some(true) => made.fetch_add(1, Ordering::Relaxed), Some(false) => unmade.fetch_add(1, Ordering::Relaxed), None => 0, }; - if n.is_multiple_of(2000) { - println!("{:6.0} s {n} shaders", started.elapsed().as_secs_f64()); + let n = completed.fetch_add(1, Ordering::Relaxed) + 1; + let elapsed = started.elapsed().as_secs(); + let interval = (elapsed / 15) as usize; + let periodic = + last_interval.fetch_max(interval, Ordering::Relaxed) < interval; + if n.is_multiple_of(2000) || periodic { + let translated = done.load(Ordering::Relaxed); + let checked = translated + refused.load(Ordering::Relaxed); + let pipelines = made.load(Ordering::Relaxed); + println!( + "progress {elapsed} s {checked} shaders checked {translated} translated {pipelines} compute pipelines" + ); } } }); @@ -442,6 +492,11 @@ fn translate( let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]); } } + // (`VICTORY_PAIRS`: a container whose label names a shader of a pair is kept) + checks.current = (!checks.names.is_empty()) + .then(example) + .filter(|line| checks.names.iter().any(|n| line.contains(n.as_str()))) + .map(|_| bytes.to_vec()); if !lock(seen).insert(code) { t.duplicates += 1; if t.list { @@ -611,8 +666,8 @@ fn check( checks: &mut Checks, label: impl Fn() -> String, ) { - if let Some(keep) = &checks.keep { - lock(keep).push((label(), shader.clone())); + if let (Some(keep), Some(bytes)) = (&checks.keep, &checks.current) { + lock(keep).push((label(), shader.clone(), bytes.clone())); } // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. if t.list diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index c4c538e510..923a04698b 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -929,19 +929,52 @@ pub(crate) fn probe_view_limit() { }; made.is_ok() }; - let views = if fits(UNCAPPED_VIEWS) { - UNCAPPED_VIEWS - } else { - PORTABLE_VIEWS - }; + let mut caps = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: the feature query fills this structure. + let tier = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut caps).cast(), + size_of_val(&caps) as u32, + ) + } + .is_ok() + .then_some(caps.ResourceBindingTier); + let mut limits = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + // SAFETY: the feature query fills this structure on runtimes that support it. + let max_views = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS19, + (&raw mut limits).cast(), + size_of_val(&limits) as u32, + ) + } + .is_ok() + .then_some(limits.MaxViewDescriptorHeapSize) + .filter(|&count| count >= PORTABLE_VIEWS); + let views = view_heap_size(tier, max_views, fits); tracing::info!( views, + binding_tier = ?tier, + ?max_views, "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" ); victory_shader::emit::set_view_heap_limit(views - 1); }); } +fn view_heap_size( + tier: Option, + max_views: Option, + fits: impl FnOnce(u32) -> bool, +) -> u32 { + let desired = max_views.unwrap_or(UNCAPPED_VIEWS).min(UNCAPPED_VIEWS); + if tier == Some(D3D12_RESOURCE_BINDING_TIER_3) && desired > PORTABLE_VIEWS && fits(desired) { + return desired; + } + PORTABLE_VIEWS +} + /// Slots past the title's in a view heap, for tables a draw needs made /// afresh (constant buffers copied per draw). A list holds the slots it /// took until it is reset (its submissions have run) or released. @@ -4002,6 +4035,22 @@ mod tests { crate::shadow::unregister(1, start); } + #[test] + fn shader_visible_heap_probe_respects_the_reported_limits() { + fn unexpected(_: u32) -> bool { + panic!("unsupported heap size was probed"); + } + for tier in [None, Some(D3D12_RESOURCE_BINDING_TIER_1), Some(D3D12_RESOURCE_BINDING_TIER_2)] { + assert_eq!(view_heap_size(tier, None, unexpected), PORTABLE_VIEWS); + } + let tier = Some(D3D12_RESOURCE_BINDING_TIER_3); + assert_eq!(view_heap_size(tier, Some(PORTABLE_VIEWS), unexpected), PORTABLE_VIEWS); + let limit = 1_500_000; + assert_eq!(view_heap_size(tier, Some(limit), |count| count == limit), limit); + assert_eq!(view_heap_size(tier, None, |count| count == UNCAPPED_VIEWS), UNCAPPED_VIEWS); + assert_eq!(view_heap_size(tier, None, |_| false), PORTABLE_VIEWS); + } + #[test] fn texture_remaps_visit_each_changed_region_once() { let mut ranges = Vec::new(); diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index dfbf2b2253..c00926fa12 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -346,25 +346,23 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } -/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both -/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface -/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the -/// object `out` names and draws with it; on failure it goes without that -/// pipeline, silently. What the descriptions hold is not known: the calls -/// fail as they always did, with `out` null, and the first ones log the -/// description's words and what its first word points at, so that the two -/// methods can be written. -/// shortcut: not implemented. Answering `S_OK` here without making the +/// Device method 0x1c8 (title+0x2477578): a graphics pipeline from programs +/// the title compiled itself, called as `(this, description, interface id, +/// out)` for `ID3D12PipelineState`. On failure the title goes without that +/// pipeline, silently. The first calls log the description's words and what +/// its first word points at. +/// shortcut: not implemented. A host pipeline also needs the render-target +/// formats, which only the draw gives; answering `S_OK` without making the /// pipeline would hand the title whatever its stack held as an object. -extern "system" fn unknown_pipeline( +extern "system" fn unknown_graphics_pipeline( _: This, desc: *const u8, _iid: *const Iid, out: *mut This, ) -> HRESULT { use std::sync::atomic::{AtomicU32, Ordering}; - static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; - let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1; + static CALLS: AtomicU32 = AtomicU32::new(0); + let calls = CALLS.fetch_add(1, Ordering::Relaxed) + 1; if !out.is_null() { // SAFETY: the title's out pointer (a local of its own). unsafe { *out = std::ptr::null() }; @@ -389,7 +387,7 @@ extern "system" fn unknown_pipeline( .as_ref() .and_then(|w| words(w[0] as usize)); tracing::warn!( - slot = format_args!("{:#x}", SLOT), + slot = "0x1c8", calls, description = format_args!("{description:x?}"), first_points_at = format_args!("{first:x?}"), @@ -435,10 +433,10 @@ static FUNCTIONS: Table<160> = { f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 f[48] = queue::create_x as *const (); // 0x180 - f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8 + f[57] = unknown_graphics_pipeline as *const (); // 0x1c8 f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 f[62] = pipeline::create_compute_x as *const (); // 0x1f0 - f[67] = unknown_pipeline::<0x218> as *const (); // 0x218 + f[67] = pipeline::create_native_compute as *const (); // 0x218 f[69] = object::ignore as *const (); // 0x228 debug error filter f[70] = descriptor::create_placed_srv as *const (); // 0x230 f[71] = descriptor::create_placed_uav as *const (); // 0x238 diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index d45319f536..26c5857f93 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -231,18 +231,29 @@ mod tests { // origin poll that times out (and starts the frame), then a // blocking flip wait. Each flip takes its own tick. const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + // (The ticks are far apart, and it may take a few tries: a busy PC + // wakes a wait tens of milliseconds late at times.) + assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK); let mut token = 0; - let flips: Vec = (0..4) - .map(|_| { - let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - LAST[2].load(Ordering::Relaxed) - }) - .collect(); + let mut four = || -> Vec { + (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect() + }; + let mut flips = four(); + for _ in 0..10 { + if flips.windows(2).all(|w| w[1] == w[0] + 1) { + break; + } + flips = four(); + } assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f859688e10..4b672dfaca 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -46,6 +46,7 @@ const RTV_RING: u32 = 1024; pub(crate) struct Host { pub(crate) device: ID3D12Device, pub(crate) small_textures: crate::resource::SmallTextures, + pub(crate) wave_lanes: Option>, queue: ID3D12CommandQueue, fence: ID3D12Fence, /// The last value signalled on `fence`, behind the submission lock. @@ -652,12 +653,14 @@ fn create() -> windows::core::Result { // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose // cross-lane code stays in 32-lane halves translated for waves of 32 let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); - if device + let wave_lanes = device .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32) .is_ok() - { - tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); - victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + .then_some(o1.WaveLaneCountMin..=o1.WaveLaneCountMax) + .filter(|lanes| *lanes.start() != 0 && !lanes.is_empty()); + if let Some(lanes) = &wave_lanes { + tracing::info!(min = lanes.start(), max = lanes.end(), "host wave lanes"); + victory_shader::emit::set_host_max_wave(*lanes.end()); } let messages = debug .then(|| device.cast::().ok()) @@ -698,10 +701,16 @@ fn create() -> windows::core::Result { } else { None }; + if let Some(desc) = adapter.as_ref().and_then(|adapter| adapter.GetDesc1().ok()) { + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..end]); + tracing::info!(%name, vendor = format_args!("{:#06x}", desc.VendorId), device = format_args!("{:#06x}", desc.DeviceId), "host D3D12 adapter"); + } tracing::info!("host D3D12 device ready"); Ok(Host { device, small_textures: Default::default(), + wave_lanes, queue, fence, submitted: Mutex::new(0), @@ -4001,16 +4010,31 @@ fn hand_back(back: &[Declared], owners: &crate::writeback::Owners) { } impl Host { + pub(crate) fn shader_model_6_6(&self) -> bool { + static SUPPORTED: OnceLock = OnceLock::new(); + *SUPPORTED.get_or_init(|| { + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: writes the feature's structure of the given size. + let query = unsafe { + self.device.CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut model).cast(), + size_of_val(&model) as u32, + ) + }; + query.is_ok() && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0 + }) + } + /// Whether the host runs mesh shaders at shader model 6.6 (translated /// mesh shaders need both); logged once. pub(crate) fn mesh_shaders(&self) -> bool { static MESH: OnceLock = OnceLock::new(); *MESH.get_or_init(|| { let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); - let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { - HighestShaderModel: D3D_SHADER_MODEL_6_6, - }; - // SAFETY: each query writes its own structure of the given size. + // SAFETY: writes the feature's structure of the given size. let ok = unsafe { self.device .CheckFeatureSupport( @@ -4019,18 +4043,10 @@ impl Host { size_of_val(&options) as u32, ) .is_ok() - && self - .device - .CheckFeatureSupport( - D3D12_FEATURE_SHADER_MODEL, - (&raw mut model).cast(), - size_of_val(&model) as u32, - ) - .is_ok() }; let mesh = ok && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED - && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + && self.shader_model_6_6(); tracing::info!(mesh, "host mesh shader support"); mesh }) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 39c360a648..4b539d8245 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -465,7 +465,7 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; @@ -495,10 +495,26 @@ void main() { event: HANDLE, clamp: Clamp, worker: Clamp, + /// Last, so given up last. + _turn: std::sync::MutexGuard<'static, ()>, + } + + /// The software adapter is one test's at a time. Two tests that compile + /// and run shaders on it at once (it is one device for the process) make + /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in + /// its own shader compiler, in `ExecuteCommandLists` (a compute pipeline + /// compiled on first dispatch, `JITBaseVariable::OptimizeCopy` as it is + /// torn down) and on its own worker threads (`Task_CompileShader`). Under + /// a debugger, which spreads the tests out, 50 of 588 runs of all tests + /// ended so; none of 240 once they take turns. + pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) } impl WarpHarness { fn new() -> Option { + let turn = warp_turn(); // SAFETY: plain DXGI WARP query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = @@ -537,6 +553,7 @@ void main() { event, clamp, worker, + _turn: turn, }) } } diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 46175ab60c..a76504e0c5 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -1333,6 +1333,23 @@ mod tests { } } + /// Tries `free` (a `VirtualFree` of pages a heap was opened on) until + /// it succeeds, for two seconds at most: when the heap's last reference + /// goes, the runtime may destroy it, and unlock its pages, a moment + /// later. Whether it succeeded. + fn once_released(mut free: impl FnMut() -> bool) -> bool { + let until = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + if free() { + return true; + } + if std::time::Instant::now() > until { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + pub(crate) fn warp() -> Option { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; @@ -1356,6 +1373,7 @@ mod tests { /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. #[test] fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); @@ -1379,6 +1397,7 @@ mod tests { /// whole is turned down without asking the host. #[test] fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { return; @@ -1398,10 +1417,13 @@ mod tests { rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); drop(placed); - // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + // Half of it decommitted: turned down, the host not asked. The + // heap's pages stay locked until the runtime has destroyed it, + // which may come a moment after the last reference goes. + assert!(once_released(|| mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0), "the pages are given back once the heap goes"); assert!(matches!(place_part(&device, start, len), Err(None))); - mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + drop(rig); + assert_ne!(mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE), 0); } } diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index b29087a531..02e3ce9a6d 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -668,6 +668,203 @@ pub(crate) extern "system" fn create_compute_x( create_compute(this, desc, iid, out) } +/// Device method 0x218: a compute pipeline from a program the title has +/// compiled already and put in its own memory. `desc` is a record of 0x60 +/// bytes: the root signature, then (address, size) pairs of the program's +/// registers (0x1c bytes), of a second register block, of its code and of +/// its resource table, two addresses and the program's 64-bit hash. The +/// title makes one for every variant of its small compute programs (mip +/// generation of texture arrays) at start. +/// +/// The code is not that of the title's container of the same program: it is +/// compiled again, for a root signature whose table can hold more ranges. +/// So the program is read from the record +/// ([`victory_shader::native::console_compute_container_rooted`], with the +/// root signature's parameters the table does not name) and put in a +/// container of its own, which is translated and cached as the title's +/// containers are. +pub(crate) extern "system" fn create_native_compute( + _: This, + desc: *const u8, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + use std::sync::atomic::{AtomicU32, Ordering}; + static MADE: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; + if !out.is_null() { + // SAFETY: the title's out pointer. + unsafe { *out = std::ptr::null() }; + } + let program = (|| -> Result, String> { + let registers = title_bytes(desc, 1).map_err(|e| format!("registers: {e}"))?; + let code = title_bytes(desc, 5).map_err(|e| format!("code: {e}"))?; + let table = title_bytes(desc, 7).map_err(|e| format!("resource table: {e}"))?; + let root = root_blob(desc); + victory_shader::native::console_compute_container_rooted(®isters, &table, &code, root.as_deref()) + .map_err(|e| e.to_string()) + })(); + let made = MADE[usize::from(program.is_err())].fetch_add(1, Ordering::Relaxed) + 1; + let container = match program { + Ok(container) => container, + Err(why) => { + dump_native(desc, &why); + if made <= 4 || made.is_power_of_two() { + tracing::warn!( + missed = made, + why, + description = format_args!("{:x?}", title_words(desc)), + "a compute pipeline from compiled code that is not read: the title goes without it" + ); + } + return crate::object::E_NOTIMPL; + } + }; + // With VICTORY_DUMP_NATIVE, a description whose program does not + // translate is saved too. + if dumping() + && let Err(e) = victory_shader::emit::translate(&container) + { + dump_native(desc, &format!("translation: {e}")); + } + let shader = shader("compute", &container); + if made.is_power_of_two() { + tracing::info!(made, hash = %shader.hash, "native compute descriptions decoded"); + } + hand_out( + vec![shader], + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// The bytes named by words `at` (address) and `at + 1` (size) of the +/// title's description `desc`, read through the kernel: the title's own +/// memory, which may not be mapped. Why not, if not. +fn title_bytes(desc: *const u8, at: usize) -> Result, String> { + #[cfg(windows)] + { + let mut words = [0u8; 16]; + if desc.is_null() { + return Err("no description".to_owned()); + } + let start = desc.wrapping_add(8 * at); + if !crate::host::read_into(start, &mut words) { + return Err("the description is not readable".to_owned()); + } + let address = u64::from_le_bytes(words[..8].try_into().unwrap()) as usize; + let size = u64::from_le_bytes(words[8..].try_into().unwrap()) as usize; + if address == 0 || !(4..=1 << 20).contains(&size) { + return Err(format!("implausible block {address:#x}+{size:#x}")); + } + let mut bytes = vec![0u8; size]; + if crate::host::read_into(address as *const u8, &mut bytes) { + Ok(bytes) + } else { + Err(format!("block {address:#x}+{size:#x} not readable")) + } + } + #[cfg(not(windows))] + { + let _ = (desc, at); + Err("not on this host".to_owned()) + } +} + +/// The serialized root signature word 0 of a 0x218 description names, if +/// it is one of ours. +fn root_blob(desc: *const u8) -> Option> { + #[cfg(windows)] + { + crate::root::blob_of(title_words(desc)?[0] as usize as This) + } + #[cfg(not(windows))] + { + let _ = desc; + None + } +} + +/// The folder `VICTORY_DUMP_NATIVE` names, if set. +fn dump_folder() -> Option<&'static std::path::Path> { + use std::sync::OnceLock; + static FOLDER: OnceLock> = OnceLock::new(); + FOLDER + .get_or_init(|| std::env::var_os("VICTORY_DUMP_NATIVE").map(std::path::PathBuf::from)) + .as_deref() +} + +fn dumping() -> bool { + dump_folder().is_some() +} + +/// `VICTORY_DUMP_NATIVE=`: a description device method 0x218 could +/// not read, or whose program does not translate, is saved there, with the +/// blocks it names, as `slot218--desc-
.bin`, +/// `slot218--dNN-
-.bin` and its root signature's +/// serialized form as `slot218--root.bin` (what `pr64-replay` reads); +/// four of each reason, 200 in all. +fn dump_native(desc: *const u8, why: &str) { + #[cfg(windows)] + { + use std::collections::HashMap; + use std::sync::Mutex; + static SEEN: Mutex)>> = Mutex::new(None); + let Some(folder) = dump_folder() else { + return; + }; + let Some(words) = title_words(desc) else { return }; + let n = { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let (total, reasons) = seen.get_or_insert_with(Default::default); + let reason = reasons.entry(why.to_owned()).or_default(); + if *total >= 200 || *reason >= 4 { + return; + } + *reason += 1; + *total += 1; + *total + }; + let _ = std::fs::create_dir_all(folder); + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-desc-{:x}.bin", desc as usize)), bytes); + for at in [1, 3, 5, 7] { + let (address, size) = (words[at] as usize, words[at + 1] as usize); + if address == 0 || size == 0 || size > 1 << 20 { + continue; + } + let mut block = vec![0u8; size]; + if crate::host::read_into(address as *const u8, &mut block) { + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-d{at:02}-{address:x}-{size:x}.bin")), block); + } + } + if let Some(root) = root_blob(desc) { + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-root.bin")), root); + } + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-why.txt")), why); + } + #[cfg(not(windows))] + let _ = (desc, why); +} + +/// The twelve words of a description (0x60 bytes), for the log. +fn title_words(desc: *const u8) -> Option<[u64; 12]> { + #[cfg(windows)] + { + let mut bytes = [0u8; 0x60]; + if desc.is_null() || !crate::host::read_into(desc, &mut bytes) { + return None; + } + Some(std::array::from_fn(|k| u64::from_le_bytes(bytes[8 * k..8 * k + 8].try_into().unwrap()))) + } + #[cfg(not(windows))] + { + let _ = desc; + None + } +} + /// A pipeline described as a stream: its size and the subobjects, each a /// type then its data, padded to 8 bytes. #[repr(C)] @@ -797,6 +994,18 @@ pub(crate) fn library_removal_note() -> String { library::removal_note() } +/// Checks that the same D3D12 device as the game can build translated pipelines. +#[cfg(windows)] +pub fn check_preload_device() -> anyhow::Result<()> { + use anyhow::Context; + let host = crate::host::host().context("Cannot initialize the Direct3D 12 device for shader preload")?; + anyhow::ensure!( + host.shader_model_6_6(), + "The selected Direct3D 12 device does not support Shader Model 6.6" + ); + Ok(()) +} + /// Keeps compiled host pipelines, and the list of title pipelines to start /// early, in `dir` (a folder of the cache) across runs. #[cfg(windows)] @@ -833,6 +1042,38 @@ mod tests { .collect() } + #[cfg(windows)] + #[test] + fn native_compute_slot_reads_the_description_and_clears_failed_outputs() { + type Create = extern "system" fn(This, *const u8, *const Iid, *mut This) -> HRESULT; + let device = crate::device::device(); + let create = slot::(device, 0x218); + let regs = [0u32, 0, 0, 1 << 16 | 1, 1, 0, 0]; + let code = [0xBF81_0000u32]; + // Short table header and a terminal hash entry, with no resources. + let mut table = [0u32; 12]; + table[1] = 36; + table[4] = 0x43; + let mut desc = [0usize; 12]; + for (at, words) in [(1, regs.as_slice()), (5, &code[..]), (7, &table[..])] { + desc[at] = words.as_ptr() as usize; + desc[at + 1] = size_of_val(words); + } + let mut out = std::ptr::null(); + assert_eq!(create(device, desc.as_ptr().cast(), &PIPELINE_IIDS[0], &mut out), S_OK); + let shaders = shaders(out); + assert_eq!(shaders.len(), 1); + assert_eq!(shaders[0].0, "compute"); + let c = victory_shader::Container::parse(&shaders[0].1).unwrap(); + let programs = victory_shader::native_programs(c.part(victory_shader::FourCC::DXIL).unwrap().data).unwrap(); + assert_eq!(programs[0].code, code[0].to_le_bytes()); + assert_eq!(slot:: u32>(out, 0x10)(out), 0); + + desc[6] = 0; + assert_eq!(create(device, desc.as_ptr().cast(), &PIPELINE_IIDS[0], &mut out), crate::object::E_NOTIMPL); + assert!(out.is_null()); + } + #[test] fn pipelines_keep_their_shaders() { let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 499792fb71..60e2fa258b 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -421,6 +421,19 @@ impl HostPipeline { s.translated()?; } let host = host()?; + if let Some(cs) = compute + && let Some(lanes) = &host.wave_lanes + && let Some(required) = cs.translated()?.host.incompatible_wave_size(lanes) + { + tracing::warn!( + ?shaders, + required, + min = lanes.start(), + max = lanes.end(), + "host compute pipeline requires a wave size outside the adapter range" + ); + return None; + } // The root signature the translated shaders' bindings define. let mut params: Vec = Vec::new(); @@ -620,7 +633,19 @@ impl HostPipeline { false }; let state = g.describe(); - if mesh.is_some() { + if let Some(ms) = mesh { + // A mesh program whose outputs pass D3D12's 32 KiB is linked with this pixel + // program ([`linked`]): the pipeline gets the two made for each other, which bind + // as the shared translations do. + let pair = stages.get(1).and_then(|(ps, _)| linked(ms, ps)); + let bytecode = |dxil: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: dxil.as_ptr().cast(), + BytecodeLength: dxil.len(), + }; + let (ms_code, ps_code) = match &pair { + Some(pair) => (bytecode(&pair.0.dxil), bytecode(&pair.1.dxil)), + None => (code(0), code(1)), + }; // "triangles": the stream names its topology since it did not // load from the library without one (see `mesh_pipeline`); a // new name keeps such entries, stored before, from being @@ -628,10 +653,10 @@ impl HostPipeline { let name = super::library::name( "mesh triangles", &root_blob, - &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &[&code_bytes(&ms_code), &code_bytes(&ps_code)], &state, ); - let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, depth_bounds, &name) { + let pso = match mesh_pipeline(&host.device, &root, ms_code, ps_code, g, depth_bounds, &name) { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); @@ -886,6 +911,59 @@ fn graphics_depth_bounds_pipeline( } } +/// The mesh program `ms` and the pixel program `ps` translated for one pipeline +/// ([`victory_shader::emit::link_mesh`]), when `ms`'s outputs pass D3D12's 32 KiB as it is +/// translated alone: 71 of the title's mesh programs (pedestrian, vehicle and prop transforms +/// with fire, spatter, decal and transmission variants) declare 65 to 71 output components +/// for 128 vertices, which the validator refuses; NVIDIA's driver built them anyway. Linked, +/// the mesh program writes only the outputs `ps` reads and `ps` declares only the inputs it +/// reads. Made once per pair (both programs translated again, not kept on disk: the pipeline +/// library keeps the pipeline); `None` when `ms` fits, or the pair does not link (then the +/// pipeline is made of the shared translations, as before). `VICTORY_MESH_LINK=0` turns it +/// off. +fn linked( + ms: &Arc, + ps: &Arc, +) -> Option> { + type Pair = Option>; + static PAIRS: std::sync::Mutex>> = + std::sync::Mutex::new(None); + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_MESH_LINK").is_none_or(|v| v != "0")) { + return None; + } + let (tm, tp) = (ms.translated()?, ps.translated()?); + // (most mesh programs fit: nothing more to do for them) + if victory_shader::emit::mesh_fits(&tm.host.dxil).unwrap_or(true) { + return None; + } + let key = (ms.hash.clone(), ps.hash.clone()); + if let Some(pair) = PAIRS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Default::default).get(&key) { + return pair.clone(); + } + // (translated outside the lock: two workers on one pair translate it twice at worst) + let pair = match victory_shader::emit::link_mesh(&ms.container, &tm.host, &ps.container, &tp.host) { + Ok(Some(pair)) => { + tracing::info!(shaders = ?[ms, ps], "mesh outputs over 32 KiB: the pair is linked for its pipeline"); + Some(Arc::new(pair)) + } + Ok(None) => { + tracing::warn!(shaders = ?[ms, ps], "mesh outputs over 32 KiB, and the pair does not link"); + None + } + Err(e) => { + tracing::warn!(shaders = ?[ms, ps], error = %e, "mesh outputs over 32 KiB, and the pair does not translate linked"); + None + } + }; + PAIRS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(Default::default) + .insert(key, pair.clone()); + pair +} + /// A mesh pipeline from the title's graphics state: the pipeline-state /// stream form (no input layout). /// diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index c451aad41b..c1ad17b368 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -23,7 +23,7 @@ //! Ported from the sibling fork `joshuu/victory-amd`'s 4436f8f1 (its //! loading waits only). -use std::collections::{HashMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use std::time::{Duration, Instant}; @@ -338,14 +338,22 @@ struct FrameWait { /// The waiting counted against the budget so far (the window: time in /// which some thread waited, up to `since`). spent: Duration, - /// The window: threads waiting now, and since when one has been. + /// Actual wait time, excluding any unspent reservations. + completed: Duration, + /// Threads waiting now, and when the current shared interval began. waiting: u32, since: Option, } impl FrameWait { const fn new() -> FrameWait { - FrameWait { frame: u64::MAX, spent: Duration::ZERO, waiting: 0, since: None } + FrameWait { + frame: u64::MAX, + spent: Duration::ZERO, + completed: Duration::ZERO, + waiting: 0, + since: None, + } } /// A thread is to wait in `frame` at `now`: how long it may. @@ -365,8 +373,11 @@ impl FrameWait { return left; } let left = budget.saturating_sub(self.spent); - if sharing == Sharing::Reserve { - self.spent += left; + if !left.is_zero() { + self.waiting += 1; + if sharing == Sharing::Reserve { + self.spent += left; + } } left } @@ -378,17 +389,51 @@ impl FrameWait { if self.frame != frame { return; } - match sharing { + self.waiting = self.waiting.saturating_sub(1); + let elapsed = match sharing { Sharing::Window => { - self.waiting = self.waiting.saturating_sub(1); - if self.waiting == 0 - && let Some(at) = self.since.take() - { - self.spent += now.saturating_duration_since(at); - } + let interval = self.since.map_or(Duration::ZERO, |at| now.saturating_duration_since(at)); + self.since = (self.waiting != 0).then_some(now); + self.spent += interval; + interval + } + Sharing::Reserve => { + self.spent = self.spent.saturating_sub(left.saturating_sub(waited)); + waited } - Sharing::Reserve => self.spent = self.spent.saturating_sub(left - waited), - Sharing::PerThread => self.spent += waited, + Sharing::PerThread => { + self.spent += waited; + waited + } + }; + self.completed += elapsed; + } +} + +/// Waits by frame and the run's cumulative loading allowance used by one pipeline kind. +#[derive(Default)] +struct WaitBudgets { + frames: BTreeMap, + past_base: Duration, +} + +impl WaitBudgets { + fn budget(&self, frame: u64, base: Duration, compute: bool, allowance: Duration) -> Duration { + // This frame's extra wait already reduces its remaining frame window. + let current_extra = self.frames.get(&frame).map_or(Duration::ZERO, |wait| wait.completed.saturating_sub(base)); + frame_budget(base, compute, allowance, self.past_base.saturating_sub(current_extra)) + } + + fn begin(&mut self, sharing: Sharing, frame: u64, budget: Duration, now: Instant) -> Duration { + self.frames.retain(|&number, wait| number >= frame || wait.waiting != 0); + self.frames.entry(frame).or_insert_with(FrameWait::new).begin(sharing, frame, budget, now) + } + + fn end(&mut self, sharing: Sharing, frame: u64, base: Duration, left: Duration, waited: Duration, now: Instant) { + if let Some(wait) = self.frames.get_mut(&frame) { + let before = wait.completed.saturating_sub(base); + wait.end(sharing, frame, left, waited, now); + self.past_base += wait.completed.saturating_sub(base).saturating_sub(before); } } } @@ -399,19 +444,17 @@ fn wait(p: &Pending, frame: u64) { if base.is_zero() || p.slow() { return; } - // What was waited past the base budget since the start, in - // milliseconds, by kind (others, compute). - static PAST: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + static BUDGETS: [std::sync::LazyLock>; 2] = + [const { std::sync::LazyLock::new(|| Mutex::new(WaitBudgets::default())) }; 2]; let compute = p.computes(); - let past = &PAST[usize::from(compute)]; - let budget = frame_budget(base, compute, loading_allowance(), Duration::from_millis(past.load(Ordering::Relaxed))); - // The frame the budget belongs to, and what was waited of it (or is - // taken by a thread waiting now), by kind. - static FRAMES: [Mutex; 2] = [const { Mutex::new(FrameWait::new()) }; 2]; - let frame_wait = &FRAMES[usize::from(compute)]; + let budgets = &BUDGETS[usize::from(compute)]; let sharing = shared_budget(); - let started = Instant::now(); - let left = frame_wait.lock().unwrap_or_else(|e| e.into_inner()).begin(sharing, frame, budget, started); + let (started, left) = { + let mut budgets = budgets.lock().unwrap_or_else(|e| e.into_inner()); + let budget = budgets.budget(frame, base, compute, loading_allowance()); + let started = Instant::now(); + (started, budgets.begin(sharing, frame, budget, started)) + }; if left.is_zero() { return; } @@ -427,9 +470,11 @@ fn wait(p: &Pending, frame: u64) { held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; } drop(held); - let waited = started.elapsed().min(left); - past.fetch_add(waited.saturating_sub(base).as_millis() as u64, Ordering::Relaxed); - frame_wait.lock().unwrap_or_else(|e| e.into_inner()).end(sharing, frame, left, waited, Instant::now()); + let mut budgets = budgets.lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + let waited = now.saturating_duration_since(started).min(left); + budgets.end(sharing, frame, base, left, waited, now); + drop(budgets); #[cfg(feature = "diagnostics")] crate::copystat::add( crate::copystat::C::PipelineWaitUs, @@ -581,7 +626,7 @@ fn drained() { #[cfg(test)] mod loading_tests { - use super::{FrameWait, LOADING_FRAME, LOADING_FRAME_COMPUTE, Sharing, frame_budget, held_too_long, sharing_from}; + use super::{FrameWait, LOADING_FRAME, LOADING_FRAME_COMPUTE, Sharing, WaitBudgets, frame_budget, held_too_long, sharing_from}; use std::time::{Duration, Instant}; /// Two threads ask for pipelines still being made in one frame, the @@ -644,6 +689,40 @@ mod loading_tests { assert_eq!(frame_budget(Duration::from_secs(20), true, allowance, Duration::ZERO), Duration::from_secs(20)); } + #[test] + fn successive_waits_in_a_frame_charge_one_base_budget() { + let base = Duration::from_millis(500); + let allowance = Duration::from_secs(2); + let mut budgets = WaitBudgets::default(); + let mut now = Instant::now(); + for waited in [400, 400, 200].map(Duration::from_millis) { + let budget = budgets.budget(7, base, true, allowance); + let left = budgets.begin(Sharing::Window, 7, budget, now); + now += waited; + budgets.end(Sharing::Window, 7, base, left, waited, now); + } + assert_eq!(budgets.past_base, Duration::from_millis(500)); + assert_eq!(budgets.budget(7, base, true, allowance), allowance); + assert_eq!(budgets.budget(8, base, true, allowance), Duration::from_millis(1500)); + } + + #[test] + fn overlapping_waits_charge_once_even_if_a_new_frame_starts() { + let base = Duration::from_millis(500); + let budget = Duration::from_secs(2); + let waited = Duration::from_millis(800); + let start = Instant::now(); + let mut budgets = WaitBudgets::default(); + let a = budgets.begin(Sharing::Window, 7, budget, start); + let b = budgets.begin(Sharing::Window, 7, budget, start); + budgets.end(Sharing::Window, 7, base, a, waited, start + waited); + assert_eq!(budgets.past_base, Duration::from_millis(300)); + let later = Duration::from_millis(900); + budgets.begin(Sharing::Window, 8, budget, start + waited); + budgets.end(Sharing::Window, 7, base, b, later, start + later); + assert_eq!(budgets.past_base, Duration::from_millis(400)); + } + /// No frame waits for a pipeline the driver has held past 10 s /// (compute) or 3 s (others), while the frame budget is shorter; a /// budget at or above that is the bound alone. diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index 5bded71dc8..344362b311 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -195,6 +195,22 @@ pub(crate) extern "system" fn create( object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out) } +/// The serialized form of the root signature `this`, if it is one of ours +/// (device method 0x218 names the program's root signature by pointer). +#[cfg(windows)] +pub(crate) fn blob_of(this: This) -> Option> { + let mut head = [0u8; 8]; + if this.is_null() || !crate::host::read_into(this.cast(), &mut head) { + return None; + } + if usize::from_le_bytes(head) != FUNCTIONS.0.as_ptr() as usize { + return None; + } + // SAFETY: an object with this table is a `RootSignature` of ours, which + // the title holds while it passes it. + Some(unsafe { &*this.cast::() }.blob.clone()) +} + extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this); object::answer(ROOT_SIGNATURE, iid, found, out) @@ -255,6 +271,38 @@ mod tests { create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root), S_OK ); + // What a 0x218 description names: the blob back, and nothing for + // another object or no object. + // SAFETY: the blob's `size` bytes. + let bytes = unsafe { std::slice::from_raw_parts(data, size) }; + assert_eq!(blob_of(root).as_deref(), Some(bytes)); + assert_eq!(blob_of(blob), None); + assert_eq!(blob_of(null), None); + // The 0x218 decoder reads the host's serialization: the constant at + // dword 4 is the one the table names; a fifth user SGPR is past it. + let mut table = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 1 << 16 | 0x440, 0x41, 0x002, 0, 0, 0, 0x404, u32::MAX, 0] + .into_iter() + .chain([0x43, 1, 2, 3, 4, 0, 0, 0]) + { + table.extend(w.to_le_bytes()); + } + let size = (table.len() - 0x14) as u32; + table[4..8].copy_from_slice(&size.to_le_bytes()); + let mut registers: Vec = [0u32, 0, 0, 1 << 16 | 64, 1, 3, 5 << 1] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let code = 0xBF81_0000u32.to_le_bytes(); + let rooted = |registers: &[u8]| { + victory_shader::native::console_compute_container_rooted(registers, &table, &code, Some(bytes)) + }; + assert_eq!( + rooted(®isters), + victory_shader::native::console_compute_container(®isters, &table, &code) + ); + registers[0x18..0x1c].copy_from_slice(&(6u32 << 1).to_le_bytes()); + assert!(rooted(®isters).is_err()); assert_eq!(slot:: u32>(root, 0x10)(root), 0); slot:: u32>(blob, 0x10)(blob); } diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 7545af0df9..802d4d4631 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -50,7 +50,7 @@ pub fn use_shader_cache(dir: std::path::PathBuf) { } #[cfg(windows)] -pub use victory_gpu::pipeline::{save_pipeline_cache, warm, warm_selected}; +pub use victory_gpu::pipeline::{check_preload_device, save_pipeline_cache, warm, warm_selected}; pub(crate) fn module() -> HleModule { HleModule { diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs index 7a20963b60..c377ad1ed7 100644 --- a/crates/victory-shader/src/dxbc.rs +++ b/crates/victory-shader/src/dxbc.rs @@ -129,9 +129,8 @@ pub(crate) fn u64_at(data: &[u8], at: usize) -> Result { .ok_or(ShaderError::Malformed("truncated")) } -/// Builds a container from parts (test helper). -#[cfg(test)] -pub fn build(parts: &[(FourCC, &[u8])]) -> Vec { +/// Packs parts into an unsigned container for the internal shader reader. +pub(crate) fn build(parts: &[(FourCC, &[u8])]) -> Vec { let table = HEADER_SIZE + 4 * parts.len(); let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); let mut out = Vec::with_capacity(total); diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index eff0ac08a6..5b98004d74 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -30,6 +30,7 @@ enum TypeDef { Void, Int(u32), Float, + /// A 64-bit float. Double, /// Pointee and address space. Ptr(Ty, u32), @@ -108,6 +109,7 @@ pub(crate) enum Cast { FpToSi = 4, UiToFp = 5, SiToFp = 6, + FpExt = 8, Bitcast = 11, } @@ -326,6 +328,15 @@ impl Module { } } + /// `x` when `v` is `sub 0, x` (an integer negation); `None` for anything else. + pub fn negated(&self, v: V) -> Option { + let V::Inst(i) = v else { return None }; + match self.insts[i as usize].op { + Op::Bin(Bin::Sub, a, x) if self.int_value(a) == Some(0) => Some(x), + _ => None, + } + } + /// Gives constant `old` the content of `new` (both stay valid). pub fn replace_const(&mut self, old: V, new: V) { if let (V::Const(o), V::Const(n)) = (old, new) { diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 13551c371f..1dbbd56cd2 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -67,12 +67,16 @@ pub(crate) struct Usage { pub int64: bool, /// A typed load of several components from a UAV. pub typed_uav_loads: bool, + /// A handle annotated as a rasterizer-ordered view. + pub rovs: bool, /// A handle from the view heap. pub heap_views: bool, /// A handle from the sampler heap. pub heap_samplers: bool, /// A 64-bit atomic. pub atomic64: bool, + /// A 64-bit float, as a result or an operand. + pub doubles: bool, } /// What makes two instructions without an effect the same value. @@ -968,6 +972,7 @@ impl Module { let mut u = Usage::default(); let reached = self.reached(); let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64); + let double = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Double; // The first field of a handle's annotation: its kind, with the UAV // bit; the second: the component type and count. let annotation = |h: V| -> Option<(i64, i64)> { @@ -996,13 +1001,19 @@ impl Module { for &i in blk.phis.iter().chain(&blk.body) { let inst = &self.insts[i as usize]; u.int64 |= wide(inst.ty); - for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + u.doubles |= double(inst.ty); + for_each_operand(&inst.op, |v| { + u.int64 |= wide(self.type_of(v)); + u.doubles |= double(self.type_of(v)); + }); let Op::Call(f, args) = &inst.op else { continue; }; let name = self.funcs[*f as usize].name.as_str(); let name = name.strip_prefix("dx.op.").unwrap_or(name); - if name.starts_with("wave") || name.starts_with("quad") { + if name == "annotateHandle" { + u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0); + } else if name.starts_with("wave") || name.starts_with("quad") { u.wave_ops = true; } else if name == "createHandleFromHeap" { match args.get(2).and_then(|&s| self.int_k(s)) { diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 7f204a484d..e1e27a0c28 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -72,7 +72,11 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { // Validator 1.6 writes one name per element in element order, repeats // included, except that system values share theirs (it keys names by // the semantic's string, which is one static string per system value); - // the rows sorted by register (unallocated last), then name offset. + // the rows sorted by register (unallocated last), then by name offset: + // of two elements packed into one register, the one first in element + // order comes first whatever its columns (a sort by column made the + // validator refuse 72 of the title's vertex, mesh and pixel programs: + // "does not match expected for module"). let mut offsets: Vec = Vec::new(); let mut next = 8 + 32 * elements.len() as u32; let mut names = Vec::new(); @@ -115,6 +119,52 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { out } +/// One interpolation mode per register. The console's compiler packs only elements of one +/// mode into a register, and the validator refuses two ("has interpolation mode that differs +/// from another element packed into the same row"), but the modes here are partly defaults: a +/// float is linear unless a pixel program's reads say otherwise, so a float the console +/// declared `nointerpolation` beside an integer came out linear. Where a register's modes +/// differ, the elements whose mode is fixed give it to the others if they agree on one: an +/// integer or the front face (constant only) and, with `read` (pixel inputs), an element the +/// program reads (the mode its reads asked for). The others' mode decides nothing: an +/// output's interpolation is the pixel input's, and an input no read asks for is never +/// interpolated. A register whose modes agree stays as it was. +/// The title's 70 programs that packed two modes into a register (23 vertex and mesh, 47 +/// pixel) each had a float of the console's constant mode (its `PSV0`) beside an integer, the +/// front face, or an input read at its vertices, that float written (outputs) or not read +/// (inputs). +pub(crate) fn one_mode_per_register(elements: &mut [SigElement], read: bool) { + let fixed = |e: &SigElement| e.comp != 9 || e.kind == 13 || (read && e.usage != 0); + let mut rows: Vec = elements.iter().filter_map(|e| e.row).collect(); + rows.sort_unstable(); + rows.dedup(); + for row in rows { + // (an undefined mode, 0, takes the others' in the validator) + let of = |e: &SigElement| e.row == Some(row) && e.interp != 0; + let mut modes: Vec = elements + .iter() + .filter(|e| of(e)) + .map(|e| e.interp) + .collect(); + modes.sort_unstable(); + modes.dedup(); + if modes.len() < 2 { + continue; + } + let mut given: Vec = elements + .iter() + .filter(|e| of(e) && fixed(e)) + .map(|e| e.interp) + .collect(); + given.sort_unstable(); + given.dedup(); + let [mode] = given[..] else { continue }; + for e in elements.iter_mut().filter(|e| of(e) && !fixed(e)) { + e.interp = mode; + } + } +} + /// The most a mesh shader's outputs may take, in bytes (D3D12). pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024; @@ -163,6 +213,18 @@ pub(crate) struct Psv<'a> { pub wave_size: Option, } +/// The minimum and maximum wave lane counts in PSV runtime info. +const PSV_WAVE_LANES: std::ops::Range = 16..24; + +pub(super) fn fixed_wave_size(psv: &[u8]) -> Option { + let size = u32::from_le_bytes(psv.get(..4)?.try_into().ok()?) as usize; + let info = psv.get(4..)?.get(..size)?; + let lanes = info.get(PSV_WAVE_LANES)?; + let min = u32::from_le_bytes(lanes[..4].try_into().ok()?); + let max = u32::from_le_bytes(lanes[4..].try_into().ok()?); + (min != 0 && min == max).then_some(min) +} + /// `PSV0` with runtime info version 2 (validator 1.6). pub(crate) fn psv(p: &Psv) -> Vec { let vectors = |els: &[SigElement]| { @@ -192,8 +254,9 @@ pub(crate) fn psv(p: &Psv) -> Vec { ); } let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n)); - info[16..20].copy_from_slice(&min.to_le_bytes()); - info[20..24].copy_from_slice(&max.to_le_bytes()); + let (min_lanes, max_lanes) = info[PSV_WAVE_LANES].split_at_mut(4); + min_lanes.copy_from_slice(&min.to_le_bytes()); + max_lanes.copy_from_slice(&max.to_le_bytes()); info[24] = p.stage; for (k, n) in p.threads.into_iter().enumerate() { info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes()); @@ -400,6 +463,140 @@ fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { mod tests { use super::*; + /// Two elements packed into one register are written in element order, not by column + /// (the title's packed pedestrian outputs: TEXCOORD22 in columns 1-2 of the register + /// whose column 0 is COLOR0, listed after it). + #[test] + fn rows_of_one_register_keep_the_element_order() { + let element = |name: &str, index, row, col, cols| SigElement { + name: name.into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: false, + }; + let part = signature( + &[ + element("TEXCOORD", 19, 13, 0, 3), + element("TEXCOORD", 22, 14, 1, 2), + element("COLOR", 0, 14, 0, 1), + element("TEXCOORD", 21, 15, 0, 3), + ], + false, + ); + let u32_at = |at: usize| u32::from_le_bytes(part[at..at + 4].try_into().unwrap()); + // (register, semantic index, mask) of each 32-byte row after the 8-byte header + let rows: Vec<(u32, u32, u8)> = (0..4) + .map(|k| 8 + 32 * k) + .map(|at| (u32_at(at + 20), u32_at(at + 8), part[at + 24])) + .collect(); + assert_eq!(rows, [(13, 19, 0b111), (14, 22, 0b110), (14, 0, 0b1), (15, 21, 0b111)]); + } + + /// The registers of the title's programs that packed two modes: a float beside an integer + /// or the front face, an unread input beside one read at its vertices. Registers whose modes + /// agree, and those whose fixed elements disagree, keep their modes. + #[test] + fn one_register_takes_the_mode_of_its_fixed_elements() { + let element = |name: &str, row, col, cols, comp, interp, usage| SigElement { + name: name.into(), + index: 0, + kind: if name == "SV_IsFrontFace" { 13 } else { 0 }, + comp, + interp, + row: Some(row), + col, + cols, + usage, + half: false, + }; + let modes = |els: &[SigElement]| els.iter().map(|e| e.interp).collect::>(); + // VS_Transform_VfxVBuffer_AlphaClip's outputs: TEXCOORD2 (float2) beside TEXCOORD14 + // (uint2) in register 7; register 6 holds two linear floats. + let mut outputs = vec![ + element("TEXCOORD", 6, 0, 3, 9, 2, 0b111), + element("TEXCOORD", 6, 3, 1, 9, 2, 0b1), + element("TEXCOORD", 7, 0, 2, 9, 2, 0b11), + element("TEXCOORD", 7, 2, 2, 5, 1, 0b11), + ]; + one_mode_per_register(&mut outputs, false); + assert_eq!(modes(&outputs), [2, 2, 1, 1]); + // A pixel program's inputs: an unread float beside the front face; another beside an + // input read at its vertices (constant), where the float would be linear. + let mut inputs = vec![ + element("TEXCOORD", 9, 0, 1, 9, 2, 0), + element("SV_IsFrontFace", 9, 1, 1, 5, 1, 0b1), + element("NORMAL", 5, 0, 3, 9, 2, 0), + element("TEXCOORD", 5, 3, 1, 9, 1, 0b1), + ]; + one_mode_per_register(&mut inputs, true); + assert_eq!(modes(&inputs), [1, 1, 1, 1]); + // Two floats a pixel program reads in two modes: no element gives the register one. + let mut both = vec![ + element("TEXCOORD", 3, 0, 2, 9, 2, 0b11), + element("TEXCOORD", 3, 2, 2, 9, 3, 0b11), + ]; + one_mode_per_register(&mut both, true); + assert_eq!(modes(&both), [2, 3]); + // As outputs nothing is read: the floats keep their defaults too. + one_mode_per_register(&mut both, false); + assert_eq!(modes(&both), [2, 3]); + } + + #[test] + fn fixed_wave_size_requires_matching_lanes_in_complete_runtime_info() { + let mut p = Psv { + stage: 5, + flag: false, + inputs: &[], + outputs: &[], + prims: &[], + mesh: None, + geometry: None, + bindings: &[], + threads: [64, 1, 1], + wave_size: None, + }; + assert_eq!(fixed_wave_size(&psv(&p)), None); + for lanes in [32, 64] { + p.wave_size = Some(lanes); + let data = psv(&p); + assert_eq!(fixed_wave_size(&data), Some(lanes)); + assert_eq!(fixed_wave_size(&data[..51]), None); + } + } + + #[test] + #[cfg(windows)] + fn fixed_wave_size_is_checked_against_both_device_limits() { + let psv = psv(&Psv { + stage: 5, + flag: false, + inputs: &[], + outputs: &[], + prims: &[], + mesh: None, + geometry: None, + bindings: &[], + threads: [32, 1, 1], + wave_size: Some(32), + }); + let shader = super::super::HostShader { + stage: crate::HwStage::Cs, + dxil: build(&[(b"PSV0", &psv)]), + ..super::super::host::stub_ps() + }; + assert_eq!(shader.incompatible_wave_size(&(32..=32)), None); + assert_eq!(shader.incompatible_wave_size(&(32..=64)), None); + assert_eq!(shader.incompatible_wave_size(&(64..=64)), Some(32)); + assert_eq!(shader.incompatible_wave_size(&(16..=16)), Some(32)); + } + #[test] fn packed_vertex_outputs_preserve_name_order_and_declared_interpolation() { let integer = SigElement { diff --git a/crates/victory-shader/src/emit/descriptor_data.rs b/crates/victory-shader/src/emit/descriptor_data.rs new file mode 100644 index 0000000000..6f3efab1ca --- /dev/null +++ b/crates/victory-shader/src/emit/descriptor_data.rs @@ -0,0 +1,372 @@ +//! Descriptor loads whose dwords the code reads as numbers: the console compiler computes a +//! texture's or a buffer's size from its descriptor's bits instead of asking for it, and walks +//! the memory a buffer's address points at. The fields the host can tell are rebuilt from its +//! view; the others have no value. + +use super::{ + Attr, Bin, Fields, Inst, Lower, Operand, Reg, ResourceType, Role, RootType, Site, Source, UsedResource, V, + Val, Why, +}; + +impl<'a> Lower<'a> { + /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords + /// the code reads as numbers, besides using the descriptor or (an image's + /// size) instead of it: the console compiler computes sizes + /// from descriptor bits (an image's width, height, depth, levels; a + /// buffer's record count) instead of querying them. Those fields are + /// rebuilt from the host view's dimensions in the GFX10 layout (image + /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits + /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at + /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). + // shortcut: the base level reads 0 (the host view starts at its own + // level 0, so sizes the code shifts by it come out right) and the other + // dwords (addresses, formats, tiling) have no host value: reading them + // stops the program. + pub(super) fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + const OTHER: Why = "a descriptor's address or format read as data"; + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar memory read as data"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory read as data"), + }; + // How the program uses the descriptor tells the view's kind: an image or buffer + // instruction before a scalar buffer load, which reads any buffer. + let x = self.x; + let uses = |of: Site| { + x.res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .filter_map(move |d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } if load == of => Some((d.site, first)), + _ => None, + }) + }) + }; + let by_scalar_load = |u: &(Site, u8)| { + matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) + }; + let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); + // The console compiler loads a descriptor again wherever it needs it, and for a + // size it reads the dwords of a load that nothing uses as a descriptor (a texture + // picked from the heap by an index held per lane: one load for its width, one for + // its base level, one for each read of the image). Another load of as many dwords + // from the same address reads the same descriptor, so what uses that one tells + // this one's kind. The handle is still made from this load's own operands, which + // hold here. + let address = self.scalar.get(&site).copied(); + let twin = || { + let a = address?; + let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); + x.res + .scalar + .iter() + .filter(|(s, b)| *s != site && *b == a && same(*s)) + .find_map(|(s, _)| use_of(*s)) + }; + let use_at = use_of(site).or_else(twin); + // `sized`: no instruction uses the descriptor, the code reads a size from it + // ([`Self::unused_descriptor_kind`]). + let (first, used, uav, props, image, sized) = if let Some((at, first)) = use_at { + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + let ty = if !uav && self.scalar_uint_srv(&src, kind) { 0x105 } else { 0x409 }; + ((kind | u, ty), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + let ty = if !uav && self.scalar_uint_srv(&src, 10) { 0x105 } else { 0x409 }; + (10 | u, ty) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) + { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + (props, None) + } + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. + Fields::Smem { .. } => { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + _ => return Err("a scalar memory read as data"), + }; + (first, used, uav, props, image, false) + } else { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as a + // descriptor's address or format is. + let sampler = x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk the memory behind it + // (a ray-tracing structure), or tests a structured view's record count: the + // address from the host, the record count where it is a structured view's, the + // other dwords have no value. + let mut pointer = if count <= 4 { self.view_address(site) } else { None }; + if pointer.is_none() && count == 4 && self.picked_address_words(site, code) { + pointer = Some(self.picked_address(site)?); + } + // Puddle detection looks up a 2D texture's dimensions by heap index without + // sampling it: that index queries the bound host view. Only the heap supplies + // this otherwise untyped 2D lookup. + let puddle = count == 8 + && address.is_some_and(|a| { + a.dynamic.is_some() + && x.native + .layout + .get(a.param) + .is_some_and(|p| p.root == RootType::ResourceHeap) + }); + if count <= 4 + && let Some((lo, hi)) = pointer + { + let records = inst + .write(Reg::S(code + 2)) + .and_then(|value| self.structured_srv_records(site, value)); + for k in 0..count { + let reg = Reg::S(code + k as u8); + match (k, records) { + (0, _) => self.write(inst, reg, lo, None), + (1, _) => self.write(inst, reg, hi, None), + (2, Some(n)) => self.write(inst, reg, n, None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); + } else if puddle { + (0, None, false, (2, 0x409), Some(2), false) + } else if let Some((used, uav, props, image)) = + self.unused_descriptor_kind(inst, site, code, count) + { + (0, used, uav, props, image, true) + } else { + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + eprintln!( + "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", + inst.machine.offset, + inst.name(), + address, + self.x.res.lane_copied.contains(&site) + ); + } + return Err("a descriptor read only as data"); + } + }; + let src = Source::Loaded { load: site, first }; + let h = self.handle(site, &src, false, props)?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = if image.is_some() && !uav { + self.s.m.i32(0) + } else { + self.s.m.undef(i32t) + }; + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); + let words: Vec<(u32, V)> = match image { + Some(kind) => { + let one = self.s.m.i32(1); + let w = field(self, 0); + let (height, depth) = match kind { + 1 => (one, one), + 2 => (field(self, 1), one), + 6 => (one, field(self, 1)), + _ => (field(self, 1), field(self, 2)), + }; + let levels = if uav { one } else { field(self, 3) }; + let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); + let (w, height, depth, levels) = ( + less(self, w), + less(self, height), + less(self, depth), + less(self, levels), + ); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k30, k2, k14, k16, mask) = ( + k(self, 30), + k(self, 2), + k(self, 14), + k(self, 16), + k(self, 0x3FFF), + ); + let d1 = self.s.m.bin(c, Bin::Shl, w, k30); + let hi = self.s.m.bin(c, Bin::LShr, w, k2); + let hi = self.s.m.bin(c, Bin::And, hi, mask); + let ht = self.s.m.bin(c, Bin::Shl, height, k14); + let d2 = self.s.m.bin(c, Bin::Or, hi, ht); + let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; + let base = k(self, 0xFAC | ty << 28); + let last = self.s.m.bin(c, Bin::Shl, levels, k16); + let d3 = self.s.m.bin(c, Bin::Or, base, last); + vec![(1, d1), (2, d2), (3, d3), (4, depth)] + } + None => { + // A raw view counts bytes; the descriptor's record count is in elements. + let n = field(self, 0); + let stride = used.map_or(0, |u| u.stride); + let n = if props.0 & 0xFF == 11 && stride > 1 { + let k = self.s.m.i32(stride); + self.s.m.bin(c, Bin::UDiv, n, k) + } else { + n + }; + let mut words = vec![(2, n)]; + // Its address too, where the code computes with it and the + // host can tell it. + let computed = (0..2u8).any(|k| { + inst.write(Reg::S(code + first + k)) + .is_some_and(|v| self.computed_with(v, 6)) + }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) + if first == 0 + && (computed || sized) + && let Some((lo, hi)) = self.view_address(site) + { + words.extend([(0, lo), (1, hi)]); + } + words + } + }; + for k in 0..count { + let rel = k.wrapping_sub(u32::from(first)); + match words.iter().find(|w| w.0 == rel) { + Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), + None => { + if let Some(v) = inst.write(Reg::S(code + k as u8)) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + Ok(()) + } + + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose size the code reads (the console compiler computes `GetDimensions` + /// from the descriptor's bits): its used-resource entry, whether it is an unordered view, + /// the handle properties and the image kind (none for a buffer). None for anything else + /// (a constant buffer, a buffer whose address alone is read). The caller has handled + /// descriptors kept per lane and samplers'. + /// - An image's eight dwords: a 2D texture's (the title's puddle and shadow mask programs + /// take the texel size of a heap texture they do not sample). + /// - A buffer's four dwords whose table entry says what it is: a view as the title made + /// it, structured where its elements are whole dwords (the title's water simulation + /// tests a structured buffer it does not read for being empty, by its record count). + /// A raw handle of the structured view the heap holds answers wrong: 2 records for 9 + /// of 16 bytes on an RTX 5090 (`descriptor_tests`, run with a raw handle). + /// With no entry, a raw view where the code reads the record count (dword 2). + // shortcut: an image whose kind nothing tells is taken for a 2D texture; a host view of + // another kind is queried through a 2D texture's handle. + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(Option<&'a UsedResource>, bool, (u32, u32), Option)> { + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + 8 if used.is_none_or(|u| u.dwords == 8) => Some((used, uav, (2 | u, 0x409), Some(2))), + 4 if used.is_some_and(|u| u.dwords == 4) || used.is_none() && read(2) => { + let stride = used.map_or(0, |u| u.stride); + let props = if stride >= 4 && stride.is_multiple_of(4) { + (12 | u, stride) + } else { + (11 | u, 0) + }; + Some((used, uav, props, None)) + } + _ => None, + } + } +} diff --git a/crates/victory-shader/src/emit/descriptor_tests.rs b/crates/victory-shader/src/emit/descriptor_tests.rs new file mode 100644 index 0000000000..b71ffaac19 --- /dev/null +++ b/crates/victory-shader/src/emit/descriptor_tests.rs @@ -0,0 +1,244 @@ +//! End-to-end tests of descriptors that no instruction names alone: an image's or a buffer's +//! descriptor the code reads only the size of, and an immediate sampler each arm of a uniform +//! branch sets its own of. Synthetic GFX10 compute programs translated ([`super::emit`]), +//! validated by `dxil.dll` when present, and run on the host GPU and WARP. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{Container, dxbc, io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// A wave32 compute program of one thread: 4 root constants in s0..s3 and, in s4, a table +/// with a texture's descriptor at dword 0 and a raw UAV's at dword 8; `body` follows the +/// loads of the texture's descriptor into s[8:15] and the UAV's into s[16:19]. +fn native(body: &[u32]) -> NativeProgram { + native_of(body, 8, 0) +} + +/// [`native`] with a view of `dwords` dwords (8: a texture, 4: a buffer of elements of +/// `stride` bytes) at dword 0, loaded into s8 on. +fn native_of(body: &[u32], dwords: u8, stride: u32) -> NativeProgram { + let load = match dwords { + 8 => 0xF40C_0202, // s_load_dwordx8 s[8:15], s[4:5], null + _ => 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], null + }; + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + load, + 0xFA00_0000, + 0xF408_0402, + 0xFA00_0020, // s_load_dwordx4 s[16:19], s[4:5], 0x20 + ]; + words.extend_from_slice(body); + words.push(S_ENDPGM); + let range = |kind, table_offset_dwords, dwords, stride| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data: 4, + slot: 1, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 16, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![ + range(ResourceType::Srv, 0, dwords, stride), + range(ResourceType::Uav, 8, 4, 0), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// `native` translated as the title's programs are, and validated. +fn translate(native: &NativeProgram) -> HostShader { + let container = dxbc::build(&[]); + let c = Container::parse(&container).expect("container"); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, native).expect("io::raise"); + let shader = super::emit(&c, native, &p, &st, &io, &res).expect("emit"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader +} + +/// Runs `shader` with root constant 0 at `s0`, the texture and a UAV of 4 dwords at heap +/// indices 0 and 1, on the hardware GPU and on WARP (each skipped without a device), and +/// returns per one that ran the UAV's dwords. +fn run(shader: &HostShader, s0: u32, texture: View) -> Vec<(&'static str, Vec)> { + run_with_records(shader, s0, texture, 0) +} + +/// [`run`] with `records` in the root word a structured view's record count is read from +/// (`USER_VIEW_RECORDS`, which the runtime fills from the bound view). +fn run_with_records( + shader: &HostShader, + s0: u32, + texture: View, + records: u32, +) -> Vec<(&'static str, Vec)> { + let views = [texture, View::RawUav(4)]; + let mut out = Vec::new(); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + // The constant is s0; the table starts at heap index 0. + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.dword) { + (RootType::Constants, 0) => s0, + (RootType::Other(super::USER_VIEW_RECORDS), _) => records, + _ => 0, + }; + } + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words[0].clone())); + } + out +} + +#[test] +fn a_texture_read_only_for_its_size_gives_the_views_size() { + // The console compiler's `GetDimensions` of a texture the program does not sample: width + // and height from the descriptor's bits, and its last level; stored to the UAV. + let shader = translate(&native(&[ + 0x9014_9E09, // s_lshr_b32 s20, s9, 30 + 0x8F15_820A, // s_lshl_b32 s21, s10, 2 + 0x8814_1514, // s_or_b32 s20, s20, s21 + 0x8714_FF14, + 0x0000_3FFF, // s_and_b32 s20, s20, 0x3fff + 0x8114_8114, // s_add_i32 s20, s20, 1 + 0x9396_FF0A, + 0x000E_000E, // s_bfe_u32 s22, s10, 0x000e000e (bits 14-27) + 0x8116_8116, // s_add_i32 s22, s22, 1 + 0x9397_FF0B, + 0x0004_0010, // s_bfe_u32 s23, s11, 0x00040010 (bits 16-19) + 0x7E02_0214, // v_mov_b32 v1, s20 + 0x7E04_0216, // v_mov_b32 v2, s22 + 0x7E06_0217, // v_mov_b32 v3, s23 + 0xE070_0000, + 0x8004_0100, // buffer_store_dword v1, off, s[16:19], 0 + 0xE070_0004, + 0x8004_0200, // buffer_store_dword v2, off, s[16:19], 0 offset:4 + 0xE070_0008, + 0x8004_0300, // buffer_store_dword v3, off, s[16:19], 0 offset:8 + ])); + let texels = [[0.0f32; 4]; 13 * 7]; + let results = run(&shader, 0, View::Texture(13, 7, &texels)); + for (label, words) in results { + // 13 x 7 texels, one level (the last is level 0). + assert_eq!(words, [13, 7, 0, 0], "{label}"); + } +} + +#[test] +fn a_buffer_read_only_for_its_size_gives_the_views_element_count() { + // The title's water simulation: whether a structured buffer has any elements, from its + // descriptor's record count, the buffer itself not read; stored to the UAV. + let shader = translate(&native_of( + &[ + 0x7E02_020A, // v_mov_b32 v1, s10 + 0xE070_0000, + 0x8004_0100, // buffer_store_dword v1, off, s[16:19], 0 + ], + 4, + 16, + )); + let data = [0u32; 4 * 9]; + let buffer = View::Buffer { + data: &data, + stride: super::host::Stride::Structured(16), + }; + for (label, words) in run_with_records(&shader, 0, buffer, 9) { + // nine elements of 16 bytes + assert_eq!(words[0], 9, "{label}"); + } +} + +#[test] +fn a_sampler_each_arm_of_a_uniform_branch_sets_samples_as_that_arm_says() { + // The title's terrain programs: an immediate sampler that clamps (0x92: clamp in x, y and + // z) or wraps (0) by a root constant, joined before one sample. Point filtering at u = + // 1.25 of a 2 x 1 texture: wrapped, texel 0 (red 1.0); clamped, texel 1 (red 2.0). + let shader = translate(&native(&[ + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // s_cbranch_scc1 -> s_mov_b32 s20, 0 + 0xB014_0092, // s_movk_i32 s20, 0x92 + 0xBF82_0001, // s_branch -> the join + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE95_03FF, + 0x00C0_0000, // s_mov_b32 s21, 0x00c00000 (levels up to 12) + 0xBE96_0380, // s_mov_b32 s22, 0 (point filtering) + 0xBE97_0380, // s_mov_b32 s23, 0 + 0x7E02_02FF, + 0x3FA0_0000, // v_mov_b32 v1, 1.25 + 0x7E04_02FF, + 0x3F00_0000, // v_mov_b32 v2, 0.5 + 0xF09C_0F08, + 0x00A2_0301, // image_sample_lz v[3:6], v[1:2], s[8:15], s[20:23] dmask:0xf 2D + 0xE070_0000, + 0x8004_0300, // buffer_store_dword v3, off, s[16:19], 0 + ])); + // One immediate sampler per arm, each the arm's own. + assert_eq!(shader.static_samplers.len(), 2); + let texels = [[1.0f32, 0.0, 0.0, 1.0], [2.0, 0.0, 0.0, 1.0]]; + for (s0, red) in [(0, 1.0f32), (1, 2.0)] { + for (label, words) in run(&shader, s0, View::Texture(2, 1, &texels)) { + assert_eq!(f32::from_bits(words[0]), red, "{label}, s0 = {s0}"); + } + } +} diff --git a/crates/victory-shader/src/emit/float64.rs b/crates/victory-shader/src/emit/float64.rs new file mode 100644 index 0000000000..5a6c16eb52 --- /dev/null +++ b/crates/victory-shader/src/emit/float64.rs @@ -0,0 +1,320 @@ +//! 64-bit floats: `v_add_f64`, `v_mul_f64` and `v_cvt_f64_f32` as the host's doubles, +//! `v_cvt_f32_f64` on 32-bit integers, and the 64-bit float wave sums of whole-wave sections +//! ([`super::super::wave::Shape::Sum64`]). The title's water volumetrics count their lanes in +//! doubles (`WaveActiveSum(1.0L)`, `v_add_f64` over DPP-moved dword pairs) and take the count +//! back as a float. +//! +//! The host's doubles are IEEE, rounded to nearest with denormals kept, as the console's FP64 +//! mode is. A double is made from its two dwords (`dx.op.makeDouble`) and taken apart again +//! (`dx.op.splitDouble`), so no 64-bit integer is needed. `v_cvt_f32_f64` takes the double's +//! dwords apart itself, rounding as IEEE does with float denormals kept, so a conversion alone +//! asks no double support of the host. + +use super::{Attr, Bin, Cast, Fields, Inst, Lower, MaskData, Operand, Reg, V, Value, Why, flags, need, pred}; +use crate::gfx10::NULL; + +impl Lower<'_> { + /// The 64-bit float operations, if `name` is one. + pub(super) fn valu_f64(&mut self, inst: &Inst, name: &str, guard: Option) -> Option> { + let c = self.cur; + Some(match name { + "v_cvt_f32_f64" => self.f64_pair(inst, 0).and_then(|(lo, hi)| { + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + self.write_f(inst, r, guard) + }), + "v_cvt_f64_f32" => self.fsrc(inst, 0).and_then(|x| { + let f64t = self.s.m.double(); + self.s.flags |= flags::DOUBLES; + let r = self.s.m.cast(c, Cast::FpExt, x, f64t); + self.write_f64(inst, r, guard) + }), + "v_add_f64" | "v_mul_f64" => (|| { + let (a, b) = (self.fsrc64(inst, 0)?, self.fsrc64(inst, 1)?); + let op = if name == "v_add_f64" { Bin::Add } else { Bin::Mul }; + let r = self.s.m.bin(c, op, a, b); + self.write_f64(inst, r, guard) + })(), + _ => return None, + }) + } + + /// The 64-bit float `WaveActiveSum` over the console's wave of each lane's own + /// `mask ? (lo, hi) : 0.0`, as its two dwords: the host's wave operation on doubles, and + /// on two host waves of 32 their sums added (the lower half's first). Made once per + /// block, for both dwords. + /// shortcut: the host adds a wave's terms in its own order, not the console's tree of + /// lanes; the sum can differ in its last bits where terms round (as for 32-bit sums). + pub(super) fn sum64(&mut self, lo: Value, hi: Value, mask: Value) -> Result<[V; 2], Why> { + let key = (lo, hi, mask, self.cur); + if let Some(&d) = self.sums64.get(&key) { + return Ok(d); + } + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self.x.st.masks.get(&mask).ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let (l, h) = (self.i32_of(lo)?, self.i32_of(hi)?); + let x = self.masked_double(on, l, h); + let r = self.wave_sum_f64(x); + // two host waves of 32 hold the console's 64 lanes: their sums add up + let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { + r + } else if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (rl, rh) = self.split_double(r); + let c = self.cur; + let (lower_lo, upper_lo) = self.exchange_halves(c, rl); + let (lower_hi, upper_hi) = self.exchange_halves(c, rh); + let lower = self.make_double(lower_lo, lower_hi); + let upper = self.make_double(upper_lo, upper_hi); + self.s.m.bin(self.cur, Bin::Add, lower, upper) + } else { + r + }; + let (dl, dh) = self.split_double(r); + self.sums64.insert(key, [dl, dh]); + Ok([dl, dh]) + } + + /// [`Self::sum64`] in the paired form: the lower lanes' sum, then the upper lanes' added, + /// as two host waves add theirs; dword `high` of it, for both lanes of this thread. + pub(super) fn paired_sum64(&mut self, high: bool, lo: Value, hi: Value, mask: Value) -> Result<[V; 2], Why> { + let key = (lo, hi, mask, self.cur); + let d = match self.sums64.get(&key) { + Some(&d) => d, + None => { + let &m = self.x.st.masks.get(&mask).ok_or("a wave reduction's untracked mask")?; + let c = self.cur; + let [x0, x1] = self.both(|l| { + let on = l.boolean(m, c)?; + let (dl, dh) = (l.i32_of(lo)?, l.i32_of(hi)?); + Ok(l.masked_double(on, dl, dh)) + })?; + let (s0, s1) = (self.wave_sum_f64(x0), self.wave_sum_f64(x1)); + let total = self.s.m.bin(self.cur, Bin::Add, s0, s1); + let (dl, dh) = self.split_double(total); + self.sums64.insert(key, [dl, dh]); + [dl, dh] + } + }; + let x = d[usize::from(high)]; + Ok([x, x]) + } + + /// `on ? (lo, hi) : +0.0` as a double. + fn masked_double(&mut self, on: V, lo: V, hi: V) -> V { + let x = self.make_double(lo, hi); + let z = self.s.m.i32(0); + let zero = self.make_double(z, z); + self.s.m.select(self.cur, on, x, zero) + } + + /// `WaveActiveSum` of the double `x` over this host wave's active lanes. + fn wave_sum_f64(&mut self, x: V) -> V { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let f64t = self.s.m.double(); + let (sum, signed) = (self.s.m.i8(0), self.s.m.i8(0)); + self.s.op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[x, sum, signed]) + } + + /// The double whose dwords are `lo` and `hi` (`dx.op.makeDouble`). + fn make_double(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let f64t = self.s.m.double(); + self.s.flags |= flags::DOUBLES; + self.s.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]) + } + + /// The low and high dwords of the double `d` (`dx.op.splitDouble`). + fn split_double(&mut self, d: V) -> (V, V) { + let c = self.cur; + let i32t = self.s.t.i32; + let pair = self.s.m.named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let r = self.s.op(c, "splitDouble.f64", Attr::ReadNone, pair, 102, &[d]); + (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)) + } + + /// A 64-bit float source as a double ([`Self::f64_pair`]). + fn fsrc64(&mut self, inst: &Inst, k: usize) -> Result { + let (lo, hi) = self.f64_pair(inst, k)?; + Ok(self.make_double(lo, hi)) + } + + /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying + /// `abs` and `neg` input modifiers on operand `k`. + fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok((lo, hi)) + }; + let (lo, mut hi) = match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1))? + } + Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), + Operand::Const(c @ 240..=248) => { + const INLINE_F64: [f64; 9] = [ + 0.5, + -0.5, + 1.0, + -1.0, + 2.0, + -2.0, + 4.0, + -4.0, + // 1 / (2 pi) as the hardware holds it (the nearest double ends in ...883) + f64::from_bits(0x3FC4_5F30_6DC9_C882), + ]; + let bits = INLINE_F64[(c - 240) as usize].to_bits(); + (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) + } + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), + _ => return Err("a 64-bit float operand"), + }; + let c = self.cur; + if v.abs >> k & 1 != 0 { + let mask = self.s.m.i32(0x7FFF_FFFF); + hi = self.s.m.bin(c, Bin::And, hi, mask); + } + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000_0000); + hi = self.s.m.bin(c, Bin::Xor, hi, sign); + } + Ok((lo, hi)) + } + + /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, + /// without requiring host `DOUBLES` (`f64`) support. + fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k0 = self.s.m.i32(0); + let k1 = self.s.m.i32(1); + let sign_mask = self.s.m.i32(0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + + let k20 = self.s.m.i32(20); + let k7ff = self.s.m.i32(0x7FF); + let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); + let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); + + let frac_mask = self.s.m.i32(0x000F_FFFF); + let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); + let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); + let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); + + let k3 = self.s.m.i32(3); + let k29 = self.s.m.i32(29); + let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); + let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); + let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); + + let rem_mask = self.s.m.i32(0x1FFF_FFFF); + let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); + let half_rem = self.s.m.i32(0x1000_0000); + let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); + let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); + let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); + let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); + let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); + let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); + let norm_inc = self.s.m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + let k896 = self.s.m.i32(896); + let k23 = self.s.m.i32(23); + let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); + let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); + let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); + let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); + let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + let k897 = self.s.m.i32(897); + let k32 = self.s.m.i32(32); + let k31 = self.s.m.i32(31); + let imp = self.s.m.i32(0x0080_0000); + let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); + let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); + let shift = self.s.m.select(c, lt1, k1, raw_shift); + let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); + let shift = self.s.m.select(c, gt23, k23, shift); + let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); + let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); + let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); + let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); + let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); + let low31 = self.s.m.i32(0x7FFF_FFFF); + let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); + let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); + let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); + let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); + let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); + let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); + let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); + let sub_inc = self.s.m.select(c, sub_round, k1, k0); + let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); + let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). + let k873 = self.s.m.i32(873); + let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); + let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); + let min_bit = self.s.m.select(c, round_min, k1, k0); + let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); + let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); + let inf_bits = self.s.m.i32(0x7F80_0000); + let qnan_bits = self.s.m.i32(0x7FC0_0000); + let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); + let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); + let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + let k874 = self.s.m.i32(874); + let k1151 = self.s.m.i32(1151); + let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); + let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); + let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); + let r = self.s.m.select(c, is_over, over_res, norm_res); + let r = self.s.m.select(c, is_sub, sub_res, r); + self.s.m.select(c, is_under, under_res, r) + } + + /// A 64-bit float result into its VGPR pair. + fn write_f64(&mut self, inst: &Inst, d: V, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.clamp || v.omod != 0 { + return Err("64-bit float output modifiers"); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split_double(d); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + Ok(()) + } +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index a4e2e7a98b..270575e67d 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -2,6 +2,7 @@ //! tests, drawing a full-screen triangle and reading the target back. use std::ffi::CString; +use std::ops::RangeInclusive; use windows::Win32::Graphics::Direct3D::*; use windows::Win32::Graphics::Direct3D12::*; @@ -15,6 +16,7 @@ use crate::dxbc::{Container, FourCC}; pub struct Host { pub device: ID3D12Device, + wave_lanes: Option>, } /// What the stage declares that a pipeline must match. @@ -131,7 +133,17 @@ impl Host { sm.HighestShaderModel.0 )); } - Ok(Host { device }) + let mut caps = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + let wave_lanes = device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS1, + (&raw mut caps).cast(), + size_of_val(&caps) as u32, + ) + .is_ok() + .then_some(caps.WaveLaneCountMin..=caps.WaveLaneCountMax) + .filter(|lanes| *lanes.start() != 0 && !lanes.is_empty()); + Ok(Host { device, wave_lanes }) } } @@ -140,6 +152,11 @@ impl Host { software(&self.device) } + /// The widest wave supported by this D3D12 device. + pub fn max_wave_lanes(&self) -> Option { + self.wave_lanes.as_ref().map(|lanes| *lanes.end()) + } + /// The root signature translated shaders expect: user data per stage /// at `b0`, immediate samplers per stage at `s`, heaps directly /// indexed. @@ -257,6 +274,15 @@ impl Host { &self, cs: &HostShader, ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + if let Some(lanes) = &self.wave_lanes + && let Some(required) = cs.incompatible_wave_size(lanes) + { + return Err(format!( + "shader requires wave{required}, host supports {}..={} lanes", + lanes.start(), + lanes.end() + )); + } let root = self.root_signature_for(&[(cs, D3D12_SHADER_VISIBILITY_ALL)])?; let pso = self.compute_pipeline_with(&root, &cs.dxil)?; Ok((root, pso)) diff --git a/crates/victory-shader/src/emit/idiom.rs b/crates/victory-shader/src/emit/idiom.rs new file mode 100644 index 0000000000..450944799e --- /dev/null +++ b/crates/victory-shader/src/emit/idiom.rs @@ -0,0 +1,331 @@ +//! Whether a console wave64 program's wave operations are the allocation idiom +//! ([`wave_local`]), which each host wave may run on its own: moved out of `lower` whole. + +use std::collections::{HashMap, HashSet}; + +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Inst, Program, Reg, Value}; +use crate::structure::{Atom, LaneExit, Structured}; + +type Why = &'static str; + +/// What a register value holds, for [`wave_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Wave { + /// Nothing that depends on how the threads are divided into waves. + Plain, + /// The number of the wave's first lane in a mask (`s_ff1`). + First, + /// A reduction over the wave's lanes: a count, a sum, a minimum... + Total(super::wave::Op), + /// A count or sum over the lanes below this one. + Prefix, + /// Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + /// A mix the idiom does not make. + Mixed, +} + +/// Whether a console wave64 program may run with each host wave as a wave of its own +/// ([`super::lower::with_local_waves`]): its wave-wide values are used only as the allocation idiom uses +/// them, which does not care how the threads are divided into waves. A first-lane number only +/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; +/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. +/// Anything else done with them takes one wave to be the whole thread group (a tile's result, +/// say) and is refused, with the offset and what was found. +/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections +/// are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this +// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is +// the only mix of old and new lanes that is looked at. +pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { + use super::wave::{Op, Shape}; + const FIRST: Why = "a wave's first-lane number used as data"; + const TOTAL: Why = "a count or sum over the wave used as data"; + const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; + const MIXED: Why = "a value that depends on the wave on some paths only"; + const EFFECT: Why = "a write by the wave's first lane other than its reservation"; + fn of(kind: &HashMap, v: Option) -> Wave { + v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) + } + fn put(kind: &mut HashMap, v: Value, k: Wave) { + if k == Wave::Plain { + kind.remove(&v); + } else { + kind.insert(v, k); + } + } + let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); + let why = |k: Wave| match k { + Wave::First => FIRST, + Wave::Total(_) => TOTAL, + Wave::Prefix => PREFIX, + _ => MIXED, + }; + // a mask (by its low dword) under which only a wave's first lane runs + let first_mask = |firsts: &HashSet, m: Option| { + m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { + st.bools + .support(b) + .iter() + .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) + }) + }; + // One instruction outside a section: the kind of what it writes, and whether it is a + // first lane's reservation. + let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { + let name = inst.name(); + let val = |op: &Operand| match *op { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let ops: Vec = match &inst.fields { + Fields::Valu(v) => v.src.clone(), + Fields::Sop { dst, src, .. } => { + let mut o = src.clone(); + if matches!(name, "s_addk_i32" | "s_mulk_i32") { + o.extend(dst.iter().copied()); + } + o + } + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + data.iter().copied().collect() + } + _ => Vec::new(), + }; + let kinds: Vec = ops.iter().map(|o| of(kind, val(o))).collect(); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide + // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it + // writes, which only the lanes outside EXEC keep. + let named: Vec = ops.iter().filter_map(&val).collect(); + for &(r, v) in &inst.reads { + let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); + if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + continue; + } + let k = of(kind, Some(v)); + if wild(k) { + return Err(why(k)); + } + } + let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); + let sum = |k: Wave| k == Wave::Total(Op::AddU); + let is_mask = |o: &Operand| { + val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) + }; + let mut reserved = false; + let out = match (name, &kinds[..]) { + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, + ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::Total(Op::AddU) + } + // bits of a mask below the lane; with -1 for the mask, the lane's number + ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { + match (matches!(ops[0], Operand::Scalar { .. }), *b) { + (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, + (false, Wave::Plain | Wave::Base) => Wave::Plain, + (_, k) => return Err(why(k)), + } + } + // nothing wave-dependent goes in; what derives from a reserved base stays marked + _ if !kinds.iter().any(|&k| wild(k)) => { + let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); + if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } + } + ("v_mov_b32" | "s_mov_b32", [k]) => *k, + ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { + // the lane whose own number is the first lane's + let lane = match (*a, *b) { + (Wave::First, k) if !wild(k) => &ops[1], + (k, Wave::First) if !wild(k) => &ops[0], + _ => return Err(why(w)), + }; + if !matches!(lane, Operand::Vector { .. }) { + return Err(FIRST); + } + let mask = match &inst.fields { + _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), + Fields::Valu(v) => match v.dst { + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), + _ => None, + }, + _ => None, + }; + firsts.extend(mask); + Wave::Plain + } + ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { + (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, + (x, y) if sum(x) && sum(y) => x, + _ => return Err(why(w)), + }, + ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { + (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain) => Wave::Prefix, + (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, + _ => return Err(why(w)), + }, + ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { + (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, + _ => return Err(why(w)), + }, + ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) + if sum(*x) || *x == Wave::Prefix => + { + *x + } + ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the prefix in units of a plain size, onto the base: the lens-flare scans reserve + // their count times the size, and each lane takes base + below × size + ("v_mad_u32_u24" | "v_mad_u32_u16", [Wave::Prefix, Wave::Plain, c] | [Wave::Plain, Wave::Prefix, c]) + if !wild(*c) => + { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the reservation: the first lane adds its wave's total to a shared counter + (_, [Wave::Total(op)]) if name.contains("_atomic_") => { + let want = match op { + Op::AddU => "buffer_atomic_add", + Op::MinU => "buffer_atomic_umin", + Op::MaxU => "buffer_atomic_umax", + Op::MinI => "buffer_atomic_smin", + Op::MaxI => "buffer_atomic_smax", + Op::Or => "buffer_atomic_or", + Op::And => "buffer_atomic_and", + Op::Xor => "buffer_atomic_xor", + _ => "", + }; + if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err(TOTAL); + } + reserved = true; + Wave::Base + } + _ => return Err(why(w)), + }; + Ok((out, reserved)) + }; + let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + let order = crate::ir::reverse_postorder(&p.blocks); + let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + for &b in &order { + let block = &p.blocks[b]; + for phi in &block.phis { + let mut k = Wave::Plain; + for (n, &a) in phi.args.iter().enumerate() { + let x = of(kind, Some(a)); + k = match (k, x) { + _ if n == 0 => x, + (k, x) if k == x => k, + (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) + | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, + _ => Wave::Mixed, + }; + } + put(kind, phi.value, k); + } + for (i, inst) in block.insts.iter().enumerate() { + // inside a whole-wave section: what the simulation found each value to be + if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { + for &(_, w) in &inst.writes { + let k = match sec.shapes.get(&w) { + None => Wave::Mixed, + Some(&Shape::K(_)) => Wave::Plain, + Some(&Shape::Value(v)) => of(kind, Some(v)), + Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), + Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Total(op), + // the first lane's own sum of a total is that total + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + _ => Wave::Mixed, + }, + Some(_) => Wave::Mixed, + }; + put(kind, w, k); + } + continue; + } + let name = inst.name(); + if name.starts_with("s_cbranch") { + continue; // with the block's exit, below + } + let (k, reserved) = match step(inst, kind, firsts) { + Ok(r) => r, + Err(why) if check => return Err((inst.machine.offset, why)), + Err(_) => (Wave::Mixed, false), + }; + // the same test as `Lower::inst`'s `effect` + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err((inst.machine.offset, EFFECT)); + } + let guarded = st.guards[b][i].is_some(); + for &(r, w) in &inst.writes { + let mut kw = match r { + // "some lane is counted" keeps the count's kind; any other SCC is one bit of data + Reg::Scc if !name.starts_with("s_bcnt1") => { + if wild(k) { Wave::Mixed } else { Wave::Plain } + } + _ => k, + }; + // a guarded write leaves the old value in the lanes outside EXEC + if guarded + && matches!(r, Reg::V(_)) + && kw == Wave::Plain + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + { + kw = Wave::Mixed; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's + // own bit (the mask is EXEC under a scalar condition) + if check + && let Some(last) = block.insts.last() + && last.name().starts_with("s_cbranch_scc") + && let Some(scc) = last.read(Reg::Scc) + && wild(of(kind, Some(scc))) + { + let own = matches!(st.exits[b], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); + if !own { + return Err((last.machine.offset, TOTAL)); + } + } + } + Ok(()) + }; + let mut kind: HashMap = HashMap::new(); + let mut firsts: HashSet = HashSet::new(); + // to a fixpoint (values carried around loops), then once more to say what is wrong + let mut settled = false; + for _ in 0..16 { + let before = (kind.clone(), firsts.len()); + pass(&mut kind, &mut firsts, false)?; + if (&before.0, before.1) == (&kind, firsts.len()) { + settled = true; + break; + } + } + if !settled { + return Err((0, MIXED)); + } + pass(&mut kind, &mut firsts, true) +} diff --git a/crates/victory-shader/src/emit/link.rs b/crates/victory-shader/src/emit/link.rs new file mode 100644 index 0000000000..6d28e7b147 --- /dev/null +++ b/crates/victory-shader/src/emit/link.rs @@ -0,0 +1,204 @@ +//! A mesh program and the pixel program drawn with it, translated for one host pipeline +//! ([`link_mesh`]). +//! +//! D3D12 caps a mesh shader's outputs at 32 KiB: 4 bytes per component of every vertex +//! element times the declared vertex maximum rounded up to 32, plus the same for primitive +//! elements (`container::mesh_output_bytes`, as the validator measures it). 71 of the +//! title's mesh programs pass it as the console declares their outputs: pedestrian, +//! vehicle and prop transforms with fire, spatter, decal and transmission variants, 128 +//! vertices of 65 to 71 components (33,280 to 36,352 bytes). NVIDIA's driver builds their +//! pipelines anyway, but the programs are invalid. D3D12 links the two stages by semantic, +//! and a pipeline needs only the outputs its pixel program reads: of the title's pixel +//! programs whose inputs such a mesh program writes, the one that reads most reads 55 +//! components (a pedestrian fire prepass). So the pair is translated again for its +//! pipeline: the mesh program declares and writes only the outputs the pixel program reads +//! (and its system values), and the pixel program leaves out the inputs it never reads, +//! which D3D12 would otherwise refuse as inputs the mesh program does not write. The +//! elements kept keep their rows and columns, each program its code and bindings. Measured +//! offline (`victory translate` with `VICTORY_PAIRS`): the ten pixel programs that read most +//! for each of the 71, and the three pairs drawn in the runs so far, all link, validate and +//! get a pipeline on an RTX 5090. + +use super::container::{MESH_OUTPUT_LIMIT, SigElement, mesh_output_bytes}; +use super::{HostShader, translate}; +use crate::dxbc::{Container, FourCC, u32_at}; +use crate::native::HwStage; +use crate::ShaderError; + +thread_local! { + /// See [`with_linked`]. + static LINKED: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// What a stage leaves out of its signatures for its partner in one host pipeline +/// ([`link_mesh`]): elements of arbitrary semantics, by name and index. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(super) struct Linked { + pub inputs: Vec<(String, u32)>, + pub outputs: Vec<(String, u32)>, +} + +/// Runs `f` with programs lowered for a linked pipeline: the elements `linked` names leave +/// the signatures; stores to such an output are not made, and the other elements keep their +/// rows and modes (ids count only what is kept). An input left out must be one the program +/// never reads: a lowering that reads one fails. +pub(super) fn with_linked(linked: Linked, f: impl FnOnce() -> R) -> R { + let was = LINKED.replace(Some(linked)); + let r = f(); + LINKED.set(was); + r +} + +/// Per element of `inputs` and of `outputs` (the signatures as the console declares them), +/// whether the stage being lowered leaves it out ([`with_linked`]); empty when not linking. +pub(super) fn left_out(inputs: &[SigElement], outputs: &[SigElement]) -> (Vec, Vec) { + LINKED.with_borrow(|l| match l { + Some(l) => { + let of = |els: &[SigElement], names: &[(String, u32)]| { + els.iter() + .map(|e| e.kind == 0 && names.iter().any(|(n, i)| n.eq_ignore_ascii_case(&e.name) && *i == e.index)) + .collect::>() + }; + (of(inputs, &l.inputs), of(outputs, &l.outputs)) + } + None => (Vec::new(), Vec::new()), + }) +} + +/// The translations of the mesh program `ms` (container `ms_container`) and the pixel program +/// `ps` (container `ps_container`) for one host pipeline, when `ms`'s outputs pass D3D12's 32 +/// KiB as translated alone: the mesh program without the outputs the pixel program does not +/// read, the pixel program without the inputs it does not read (see the module notes). +/// +/// `None` (make the pipeline of `ms` and `ps` as they are) when `ms` fits, when the pixel +/// program reads every output `ms` has, when the linked mesh program still does not fit, or +/// when a linked translation binds anything differently from its shared one (the pipeline's +/// root signature is made from the shared ones). +pub fn link_mesh( + ms_container: &[u8], + ms: &HostShader, + ps_container: &[u8], + ps: &HostShader, +) -> Result, ShaderError> { + if ms.stage != HwStage::Ms || ps.stage != HwStage::Ps || mesh_fits(&ms.dxil)? { + return Ok(None); + } + let named = |e: &Element| (e.name.clone(), e.index); + let inputs = elements(&ps.dxil, FourCC::ISG1)?; + let read = |e: &Element| { + inputs + .iter() + .any(|i| i.arbitrary() && i.used != 0 && i.name.eq_ignore_ascii_case(&e.name) && i.index == e.index) + }; + let outputs: Vec<(String, u32)> = elements(&ms.dxil, FourCC::OSG1)? + .iter() + .filter(|e| e.arbitrary() && !read(e)) + .map(named) + .collect(); + if outputs.is_empty() { + return Ok(None); + } + let unread: Vec<(String, u32)> = inputs.iter().filter(|i| i.arbitrary() && i.used == 0).map(named).collect(); + let linked_ms = with_linked( + Linked { + inputs: Vec::new(), + outputs, + }, + || translate(ms_container), + )?; + let linked_ps = if unread.is_empty() { + ps.clone() + } else { + with_linked( + Linked { + inputs: unread, + outputs: Vec::new(), + }, + || translate(ps_container), + )? + }; + let same = |a: &HostShader, b: &HostShader| HostShader { dxil: Vec::new(), ..a.clone() } == HostShader { dxil: Vec::new(), ..b.clone() }; + if !mesh_fits(&linked_ms.dxil)? || !same(ms, &linked_ms) || !same(ps, &linked_ps) { + return Ok(None); + } + Ok(Some((linked_ms, linked_ps))) +} + +/// Whether an emitted mesh program's outputs fit D3D12's 32 KiB (a program of another stage +/// fits). +pub fn mesh_fits(dxil: &[u8]) -> Result { + let c = Container::parse(dxil)?; + let Some(psv) = c.part(FourCC::PSV0) else { + return Ok(true); + }; + // runtime info (its size first): shader kind at byte 24, mesh maxima at bytes 12 and 14 + let info = psv.data.get(4..).ok_or(ShaderError::Malformed("truncated"))?; + if info.get(24) != Some(&13) { + return Ok(true); + } + let half = |at: usize| info.get(at..at + 2).map_or(0, |b| u32::from(u16::from_le_bytes([b[0], b[1]]))); + let declared = |fourcc| -> Result, ShaderError> { + Ok(elements(dxil, fourcc)? + .into_iter() + .map(|e| SigElement { + name: e.name, + index: e.index, + kind: 0, + comp: 0, + interp: 0, + row: None, + col: 0, + cols: e.mask.count_ones() as u8, + usage: 0, + half: false, + }) + .collect()) + }; + let bytes = mesh_output_bytes(&declared(FourCC::OSG1)?, &declared(FourCC::PSG1)?, half(12), half(14)); + Ok(bytes <= MESH_OUTPUT_LIMIT) +} + +/// A row of an emitted signature part (`container::signature`). +struct Element { + name: String, + index: u32, + /// The system value (0: an arbitrary semantic). + sv: u32, + mask: u8, + /// Inputs: the components read. + used: u8, +} + +impl Element { + fn arbitrary(&self) -> bool { + self.sv == 0 + } +} + +fn elements(dxil: &[u8], fourcc: FourCC) -> Result, ShaderError> { + let c = Container::parse(dxil)?; + let Some(part) = c.part(fourcc) else { + return Ok(Vec::new()); + }; + let part = part.data; + let count = u32_at(part, 0)? as usize; + let base = u32_at(part, 4)? as usize; + (0..count) + .map(|i| { + let at = base + 32 * i; + let name_at = u32_at(part, at + 4)? as usize; + let name = part + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let bytes = part.get(at + 24..at + 26).ok_or(ShaderError::Malformed("truncated"))?; + Ok(Element { + name: String::from_utf8_lossy(name).into_owned(), + index: u32_at(part, at + 8)?, + sv: u32_at(part, at + 12)?, + mask: bytes[0], + used: bytes[1], + }) + }) + .collect() +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 718a9765c4..62339cfc88 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -16,7 +16,7 @@ use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; -use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage}; +use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source}; use crate::structure::{Atom, Bool, LaneExit, Structured}; @@ -32,6 +32,16 @@ mod packed_mask; #[path = "typed_views.rs"] mod typed_views; +/// Descriptors whose dwords the code reads as numbers (`descriptor_data`), a child module so it +/// shares the emitter's state. +#[path = "descriptor_data.rs"] +mod descriptor_data; + +/// 64-bit floats (the water volumetrics' wave sums of doubles, taken back as floats), a child +/// module so it shares the emitter's state. +#[path = "float64.rs"] +mod float64; + type Why = &'static str; /// How an interpolation evaluates an input channel. @@ -261,6 +271,9 @@ struct Lower<'a> { console_lanes: bool, /// Mesh: the thread index in the group (made in the entry block). flat: Option, + /// 64-bit float wave sums made (their two dwords), by the terms' dwords, mask and the + /// block made in: a section's result asks for each dword on its own. + sums64: HashMap<(Value, Value, Value, usize), [V; 2]>, /// Mesh: IR blocks whose `s_barrier` is left out. no_barrier: HashSet, /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane @@ -289,6 +302,9 @@ struct Lower<'a> { /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane /// read of one needs nothing from the other host wave. uniform: HashSet, + /// With `exchange`: VGPR values built from scalars alone, and those a guarded write went + /// into ([`scalar_built`]). + built: (HashSet, HashSet), /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]). own_bits: super::own_bits::OwnBits, @@ -327,8 +343,46 @@ struct Lower<'a> { /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by /// IR block, and its incoming (value, DXIL block) pairs. counters: HashMap)>, + /// The program tests rays against tree nodes (`image_bvh*`): its loops + /// are cut at [`TRACE_LOOP_LIMIT`]. + traces: bool, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// The paired form ([`with_paired_lanes`]): what the lowering keeps per lane for the other + /// console lane of this thread, and whether the lane being lowered is the upper one (its + /// console lane the host lane plus 32). + twin: Option>, + upper: bool, + /// The paired form: whether the last LDS access of the IR block being lowered wrote (none + /// at its start), for the fences between accesses ([`Self::paired_inst`]). + lds_last: Option, + /// The paired form: scalars each lane has its own of (a waterfall loop's first-lane reads + /// and what is computed from them), on which no branch takes both lanes of a thread. + lane_scalars: HashSet, + /// Linked for one pipeline ([`super::link`]): per input and output element, whether it + /// is left out (empty when not linking). + drop_in: Vec, + drop_out: Vec, +} + +/// What the lowering keeps per console lane, for the paired form ([`with_paired_lanes`]): each +/// host thread runs two lanes of one console wave, and what a lane runs is lowered once for +/// each with this state exchanged between them ([`Lower::swap_lanes`]): the values (scalar ones +/// too, the same in both), the lane booleans and their joins, the handles of descriptors a lane +/// may have its own of, the phis still to fill. +#[derive(Default)] +struct LaneState { + vals: HashMap, + floats: HashMap, + bools: HashMap<(usize, Bool), V>, + lane_bits: HashMap, + lane_fail: HashMap, + mask_phis: HashMap, + pending_masks: Vec<(V, usize, usize)>, + data_phis: Vec<(V, usize, usize)>, + handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, + strides: HashMap<(usize, Site, u8), V>, + clane: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -340,6 +394,18 @@ struct Lower<'a> { // shortcut: a genuine loop of more iterations than this is cut short too. pub(super) const LOOP_LIMIT: u32 = 1 << 20; +/// Iterations after which a loop of a program that tests rays against tree +/// nodes is left, unless [`super::loop_limit`] names a limit for all. +/// +/// A ray's walk of a well-formed tree visits some hundreds of nodes at +/// most. The title's shadow-mask rays ran to the compute limit of 4,096: the +/// trees of moving objects are built by the title's builder, which is off, +/// so a walk into one follows whatever its memory holds. At 4,096 the +/// shadow mask took 11.7 ms of the card a frame, at 1,024 2.4 ms (timing +/// runs of the opening of the gameplay, RTX 5090); a ray stopped either way +/// leaves the program as killed, as before. +pub(super) const TRACE_LOOP_LIMIT: u32 = 1 << 10; + /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar /// compares, bit tests) are ballots of the lanes' booleans, taken where the /// mask is written: structurisation's `active` masks hold only lanes that @@ -366,6 +432,9 @@ pub(super) const LANE_MASK: Why = "a lane mask read as data"; /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that /// run that block are not all of the wave. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; +/// A descriptor joined from the ways into a block, where one of them brings what a heap index +/// cannot stand for (an immediate sampler, say), or comes from later in the program. +pub(super) const CHOSEN: Why = "a descriptor chosen by control flow"; /// Instructions that read a lane mask (not EXEC implicitly, not a lane's /// bit) as a number. @@ -535,318 +604,143 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { same } -/// What a register value holds, for [`wave_local`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Wave { - /// Nothing that depends on how the threads are divided into waves. - Plain, - /// The number of the wave's first lane in a mask (`s_ff1`). - First, - /// A reduction over the wave's lanes: a count, a sum, a minimum... - Total(super::wave::Op), - /// A count or sum over the lanes below this one. - Prefix, - /// Derived from what a first-lane atomic returned: the slots the wave reserved. - Base, - /// A mix the idiom does not make. - Mixed, -} - -/// Whether a console wave64 program may run with each host wave as a wave of its own -/// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses -/// them, which does not care how the threads are divided into waves. A first-lane number only -/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; -/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. -/// Anything else done with them takes one wave to be the whole thread group (a tile's result, -/// say) and is refused, with the offset and what was found. -/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections -/// are stopped by the lowering itself. -// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this -// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is -// the only mix of old and new lanes that is looked at. -pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { - use super::wave::{Op, Shape}; - const FIRST: Why = "a wave's first-lane number used as data"; - const TOTAL: Why = "a count or sum over the wave used as data"; - const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; - const MIXED: Why = "a value that depends on the wave on some paths only"; - const EFFECT: Why = "a write by the wave's first lane other than its reservation"; - fn of(kind: &HashMap, v: Option) -> Wave { - v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) - } - fn put(kind: &mut HashMap, v: Value, k: Wave) { - if k == Wave::Plain { - kind.remove(&v); - } else { - kind.insert(v, k); +/// VGPR values built from scalars alone (`all` is [`all_lane_blocks`]): VALU results, LDS and +/// buffer loads whose every VGPR input is such a value, and phis of them at a loop header or +/// where every predecessor is a block all lanes run. Guards are allowed, which [`lane_uniform`] +/// refuses: a lane that wrote the value holds what every other writing lane does. With them, +/// the values a guarded write (or one of its inputs) made, which a lane outside that guard may +/// still hold from before. +/// +/// A first-lane read of such a value in a branch only some lanes take is the console +/// compiler's scalar copy of a value it proved the same in every active lane (a prefix of +/// per-wave totals read back from LDS in a loop, say): the host wave's own first lane is +/// exact, with nothing asked of the other half. +fn scalar_built(p: &Program, st: &Structured, all: &[bool]) -> (HashSet, HashSet) { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let order = crate::ir::reverse_postorder(&p.blocks); + let mut rank = vec![usize::MAX; p.blocks.len()]; + for (i, &b) in order.iter().enumerate() { + rank[b] = i; + } + // each candidate value with the VGPR values it is made of + let mut deps: HashMap> = HashMap::new(); + let mut guarded: HashSet = HashSet::new(); + for &b in &order { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + let header = block.preds.iter().any(|&q| rank[q] >= rank[b]); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) && (whole || header) { + deps.insert(phi.value, phi.args.clone()); + } } - } - let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); - let why = |k: Wave| match k { - Wave::First => FIRST, - Wave::Total(_) => TOTAL, - Wave::Prefix => PREFIX, - _ => MIXED, - }; - // a mask (by its low dword) under which only a wave's first lane runs - let first_mask = |firsts: &HashSet, m: Option| { - m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { - st.bools - .support(b) - .iter() - .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) - }) - }; - // One instruction outside a section: the kind of what it writes, and whether it is a - // first lane's reservation. - let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { - let name = inst.name(); - let val = |op: &Operand| match *op { - Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), - Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), - _ => None, - }; - let ops: Vec = match &inst.fields { - Fields::Valu(v) => v.src.clone(), - Fields::Sop { dst, src, .. } => { - let mut o = src.clone(); - if matches!(name, "s_addk_i32" | "s_mulk_i32") { - o.extend(dst.iter().copied()); + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + // the operands read (not the old value a guarded write keeps outside its lanes) + let ops: Vec = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.clone() + } + Fields::Ds { addr, data, .. } if name.starts_with("ds_read") || name.starts_with("ds_load") => { + addr.iter().chain(data).copied().collect() + } + _ => continue, + }; + let mut inputs = Vec::new(); + let mut mask_read = false; + for op in &ops { + match *op { + Operand::Vector { reg, dwords } => { + for r in reg..reg.saturating_add(dwords.max(1)) { + match inst.read(Reg::V(r)) { + Some(x) => inputs.push(x), + None => mask_read = true, + } + } + } + Operand::Scalar { code, .. } if code != NULL => { + mask_read |= inst.read(Reg::S(code)).is_some_and(is_mask); + } + _ => {} } - o - } - Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { - data.iter().copied().collect() } - _ => Vec::new(), - }; - let kinds: Vec = ops.iter().map(|o| of(kind, val(o))).collect(); - // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide - // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it - // writes, which only the lanes outside EXEC keep. - let named: Vec = ops.iter().filter_map(&val).collect(); - for &(r, v) in &inst.reads { - let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); - if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + if mask_read { continue; } - let k = of(kind, Some(v)); - if wild(k) { - return Err(why(k)); - } - } - let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); - let sum = |k: Wave| k == Wave::Total(Op::AddU); - let is_mask = |o: &Operand| { - val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) - }; - let mut reserved = false; - let out = match (name, &kinds[..]) { - ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, - ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { - Wave::Total(Op::AddU) - } - // bits of a mask below the lane; with -1 for the mask, the lane's number - ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { - match (matches!(ops[0], Operand::Scalar { .. }), *b) { - (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, - (false, Wave::Plain | Wave::Base) => Wave::Plain, - (_, k) => return Err(why(k)), - } - } - // nothing wave-dependent goes in; what derives from a reserved base stays marked - _ if !kinds.iter().any(|&k| wild(k)) => { - let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); - if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } - } - ("v_mov_b32" | "s_mov_b32", [k]) => *k, - ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { - // the lane whose own number is the first lane's - let lane = match (*a, *b) { - (Wave::First, k) if !wild(k) => &ops[1], - (k, Wave::First) if !wild(k) => &ops[0], - _ => return Err(why(w)), - }; - if !matches!(lane, Operand::Vector { .. }) { - return Err(FIRST); - } - let mask = match &inst.fields { - _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), - Fields::Valu(v) => match v.dst { - Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), - _ => None, - }, - _ => None, - }; - firsts.extend(mask); - Wave::Plain - } - ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { - (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, - (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, - (x, y) if sum(x) && sum(y) => x, - _ => return Err(why(w)), - }, - ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { - (Wave::Base, Wave::Prefix) => Wave::Base, - (Wave::Prefix, Wave::Plain) => Wave::Prefix, - (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, - _ => return Err(why(w)), - }, - ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { - (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, - _ => return Err(why(w)), - }, - ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) - if sum(*x) || *x == Wave::Prefix => - { - *x - } - ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { - if *c == Wave::Base { Wave::Base } else { Wave::Prefix } - } - // the reservation: the first lane adds its wave's total to a shared counter - (_, [Wave::Total(op)]) if name.contains("_atomic_") => { - let want = match op { - Op::AddU => "buffer_atomic_add", - Op::MinU => "buffer_atomic_umin", - Op::MaxU => "buffer_atomic_umax", - Op::MinI => "buffer_atomic_smin", - Op::MaxI => "buffer_atomic_smax", - Op::Or => "buffer_atomic_or", - Op::And => "buffer_atomic_and", - Op::Xor => "buffer_atomic_xor", - _ => "", - }; - if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { - return Err(TOTAL); + for &(r, x) in &inst.writes { + if matches!(r, Reg::V(_)) { + deps.insert(x, inputs.clone()); + if st.guards[b][i].is_some() { + guarded.insert(x); + } } - reserved = true; - Wave::Base } - _ => return Err(why(w)), - }; - Ok((out, reserved)) - }; - let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + } + } + // the largest set closed under its inputs (loop-carried values need it) + let mut built: HashSet = deps.keys().copied().collect(); + loop { + let out: Vec = + built.iter().copied().filter(|v| !deps[v].iter().all(|d| built.contains(d))).collect(); + if out.is_empty() { + break; + } + for v in out { + built.remove(&v); + } + } + // a guarded write anywhere in a value's making + loop { + let more: Vec = built + .iter() + .copied() + .filter(|v| !guarded.contains(v) && deps[v].iter().any(|d| guarded.contains(d))) + .collect(); + if more.is_empty() { + break; + } + guarded.extend(more); + } + guarded.retain(|v| built.contains(v)); + (built, guarded) +} + +/// The paired form: scalar values each console lane has its own of in the lowering, a waterfall +/// loop's first-lane reads (the lane's own dword, `resource::Waterfall`) and what scalar code +/// and joins make of them. +fn lane_scalars(p: &Program, res: &Resources) -> HashSet { + let mut own: HashSet = res.waterfall.reads.iter().copied().collect(); + if own.is_empty() { + return own; + } let order = crate::ir::reverse_postorder(&p.blocks); - let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + loop { + let before = own.len(); for &b in &order { let block = &p.blocks[b]; for phi in &block.phis { - let mut k = Wave::Plain; - for (n, &a) in phi.args.iter().enumerate() { - let x = of(kind, Some(a)); - k = match (k, x) { - _ if n == 0 => x, - (k, x) if k == x => k, - (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) - | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, - _ => Wave::Mixed, - }; + if !matches!(phi.reg, Reg::V(_)) && phi.args.iter().any(|a| own.contains(a)) { + own.insert(phi.value); } - put(kind, phi.value, k); } - for (i, inst) in block.insts.iter().enumerate() { - // inside a whole-wave section: what the simulation found each value to be - if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { - for &(_, w) in &inst.writes { - let k = match sec.shapes.get(&w) { - None => Wave::Mixed, - Some(&Shape::K(_)) => Wave::Plain, - Some(&Shape::Value(v)) => of(kind, Some(v)), - Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), - Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { - Wave::Plain | Wave::Base => Wave::Total(op), - // the first lane's own sum of a total is that total - Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), - _ => Wave::Mixed, - }, - Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { - Wave::Plain | Wave::Base => Wave::Prefix, - Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, - _ => Wave::Mixed, - }, - Some(_) => Wave::Mixed, - }; - put(kind, w, k); - } - continue; - } - let name = inst.name(); - if name.starts_with("s_cbranch") { - continue; // with the block's exit, below - } - let (k, reserved) = match step(inst, kind, firsts) { - Ok(r) => r, - Err(why) if check => return Err((inst.machine.offset, why)), - Err(_) => (Wave::Mixed, false), - }; - // the same test as `Lower::inst`'s `effect` - let effect = matches!(inst.fields, Fields::Exp { .. }) - || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") - || name.contains("store") - || name.contains("atomic") - || matches!(inst.fields, Fields::Ds { .. }) - && !(name.starts_with("ds_read") - || name.starts_with("ds_swizzle") - || name.contains("permute")); - if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { - return Err((inst.machine.offset, EFFECT)); - } - let guarded = st.guards[b][i].is_some(); - for &(r, w) in &inst.writes { - let mut kw = match r { - // "some lane is counted" keeps the count's kind; any other SCC is one bit of data - Reg::Scc if !name.starts_with("s_bcnt1") => { - if wild(k) { Wave::Mixed } else { Wave::Plain } - } - _ => k, - }; - // a guarded write leaves the old value in the lanes outside EXEC - if guarded - && matches!(r, Reg::V(_)) - && kw == Wave::Plain - && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) - { - kw = Wave::Mixed; - } - put(kind, w, kw); - } - } - // a branch on "some lane is counted": fine where the structure made it the lane's - // own bit (the mask is EXEC under a scalar condition) - if check - && let Some(last) = block.insts.last() - && last.name().starts_with("s_cbranch_scc") - && let Some(scc) = last.read(Reg::Scc) - && wild(of(kind, Some(scc))) - { - let own = matches!(st.exits[b], LaneExit::Branch { when, .. } - if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); - if !own { - return Err((last.machine.offset, TOTAL)); + for inst in &block.insts { + if matches!(inst.fields, Fields::Sop { .. } | Fields::Smem { .. }) + && inst.reads.iter().any(|r| own.contains(&r.1)) + { + own.extend(inst.writes.iter().map(|w| w.1)); } } } - Ok(()) - }; - let mut kind: HashMap = HashMap::new(); - let mut firsts: HashSet = HashSet::new(); - // to a fixpoint (values carried around loops), then once more to say what is wrong - let mut settled = false; - for _ in 0..16 { - let before = (kind.clone(), firsts.len()); - pass(&mut kind, &mut firsts, false)?; - if (&before.0, before.1) == (&kind, firsts.len()) { - settled = true; - break; + if own.len() == before { + return own; } } - if !settled { - return Err((0, MIXED)); - } - pass(&mut kind, &mut firsts, true) } /// The mode of a group barrier the translation adds (host waves meeting): @@ -983,6 +877,31 @@ thread_local! { static LOCAL_WAVES: std::cell::Cell = const { std::cell::Cell::new(false) }; /// See [`with_local_waves_any`]. static LOCAL_ANY: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// See [`with_paired_lanes`]. + static PAIRED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with console wave64 compute programs on 32-lane hosts lowered in the paired form: +/// each console wave is one host wave of 32 lanes, and host lane n runs console lanes n and +/// n + 32. The group has half the console's threads; each thread runs what a lane does twice, +/// once for each of its lanes, in the order of the console's instructions, so the wave's lanes +/// stay together as on the console: what one writes to LDS, the next instruction of another +/// reads (a fence between the accesses keeps the host compiler from reordering them; no thread +/// waits for another). Cross-lane operations reach any of the 64 lanes through the host wave's +/// own operations on either half (lane n + 32 is lane n's upper half), and a lane mask is the +/// two ballots. The caller makes every per-lane branch one the wave takes together, as the +/// console does (`structure::structure_wide`): the wave goes where some lane has to, and EXEC +/// stays each lane's guard. So control flow is the same in every thread of a host wave, and +/// the program's barriers are reached as on the console. +// shortcut: D3D12 orders no groupshared accesses of two threads without a group barrier; the +// host is taken to run a wave's threads in step where they all go the same way (as for the +// console's 32-lane programs that share LDS within a wave), the fences only keeping its +// compiler from moving one thread's accesses past each other. +pub(super) fn with_paired_lanes(f: impl FnOnce() -> R) -> R { + let was = PAIRED.replace(true); + let r = f(); + PAIRED.set(was); + r } /// As [`with_local_waves`], with every other use of a lane mask as a number @@ -1050,6 +969,10 @@ fn own_bits_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) } +/// The refusal of a first half of an interpolation whose result is read +/// as data ([`Lower::interp`]). +pub(super) const FIRST_HALF: &str = "the first half of an interpolation"; + /// What [`set_host_max_wave`] was told (0: nothing). pub fn host_max_wave() -> u32 { #[cfg(test)] @@ -1099,12 +1022,6 @@ pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { /// signature packs a short element into the free columns of an earlier /// register) is NOT in that row's halves: it follows in the first /// parameter, in row order, that has whole dwords left. -/// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, -/// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3 -/// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4, -/// column 3, behind the three columns of TEXCOORD4) in dword 3 of -/// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of -/// TEXCOORD4's second dword stays zero. type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>; fn packed_layout(elements: &[SigElement], packs: &[(u8, Option)]) -> PackedLayout { @@ -1275,6 +1192,9 @@ impl<'a> Lower<'a> { let mut s = Shader::new(x.native.stage == HwStage::Ps); s.inputs = x.inputs.clone(); s.outputs = x.outputs.clone(); + // (the signatures stay whole while the program is lowered: rows of 16-bit values and + // the like are found by the elements around them; what is left out goes at the end) + let (drop_in, drop_out) = super::link::left_out(&x.inputs, &x.outputs); let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) @@ -1290,7 +1210,25 @@ impl<'a> Lower<'a> { let mut exchange: Option<(u32, bool, Vec)> = None; // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter let mut halves: Option = None; - if let StageIo::Cs(cs) = x.native.io { + let paired = PAIRED.get() && x.native.wave64 && host_max_wave() == 32; + if let StageIo::Cs(cs) = x.native.io + && paired + { + // (`with_paired_lanes`) a host wave of 32 for each console wave of the group, its + // threads in a row; the caller has checked that the console's waves are full + let waves = cs.threads.iter().product::().div_ceil(64); + s.threads = Some([32 * waves, 1, 1]); + s.lds_dwords = cs.lds_bytes() / 4; + if waves > 1 { + // `wave_base`'s counter: a dword past the program's LDS, or the program's + // first where it takes all a host group has (32 KiB) + let slot = if s.lds_dwords < 8192 { s.lds_dwords } else { 0 }; + s.lds_dwords = s.lds_dwords.max(slot + 1); + halves = Some(slot); + } + console_lanes = true; + s.wave_size = Some(32); + } else if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; // Code reading other lanes needs the console's wave size and @@ -1569,6 +1507,10 @@ impl<'a> Lower<'a> { Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), _ => HashSet::new(), }, + built: match &exchange { + Some((_, false, all)) if !LOCAL_WAVES.get() => scalar_built(p, x.st, all), + _ => Default::default(), + }, own_bits: match &exchange { Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => { super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some()) @@ -1581,6 +1523,7 @@ impl<'a> Lower<'a> { halves, wave_base: None, flat: None, + sums64: HashMap::new(), no_barrier, fence_only, half_outputs: half_outputs(&x.native.io, &x.outputs), @@ -1609,7 +1552,65 @@ impl<'a> Lower<'a> { section_out: HashSet::new(), code_table: None, counters: HashMap::new(), + traces: p.blocks.iter().any(|b| b.insts.iter().any(|i| i.name().starts_with("image_bvh"))), abort: None, + twin: paired.then(Box::default), + upper: false, + lds_last: None, + lane_scalars: if paired { lane_scalars(p, x.res) } else { HashSet::new() }, + drop_in, + drop_out, + } + } + + /// Element `id` of the inputs (`input`) or the vertex outputs as the finished signature + /// numbers it, without those left out ([`super::link`]). + fn sig_id(&self, input: bool, id: usize) -> u32 { + let drop = if input { &self.drop_in } else { &self.drop_out }; + (id - drop.iter().take(id).filter(|&&d| d).count()) as u32 + } + + /// The paired form: makes the other console lane of this thread the one being lowered. + fn swap_lanes(&mut self) { + let Some(t) = self.twin.as_deref_mut() else { + return; + }; + std::mem::swap(&mut self.vals, &mut t.vals); + std::mem::swap(&mut self.floats, &mut t.floats); + std::mem::swap(&mut self.bools, &mut t.bools); + std::mem::swap(&mut self.lane_bits, &mut t.lane_bits); + std::mem::swap(&mut self.lane_fail, &mut t.lane_fail); + std::mem::swap(&mut self.mask_phis, &mut t.mask_phis); + std::mem::swap(&mut self.pending_masks, &mut t.pending_masks); + std::mem::swap(&mut self.data_phis, &mut t.data_phis); + std::mem::swap(&mut self.handles, &mut t.handles); + std::mem::swap(&mut self.strides, &mut t.strides); + std::mem::swap(&mut self.clane, &mut t.clane); + self.upper = !self.upper; + } + + /// The paired form: `f` for each console lane of this thread, the lower one first; the lane + /// being lowered stays the same. + fn both(&mut self, mut f: impl FnMut(&mut Self) -> Result) -> Result<[T; 2], Why> { + let was = self.upper; + if was { + self.swap_lanes(); + } + let lo = f(self); + self.swap_lanes(); + let hi = f(self); + if !was { + self.swap_lanes(); + } + Ok([lo?, hi?]) + } + + /// The paired form: `lo` as the lower lane's value of `v`, `hi` as the upper lane's. + fn put_lanes(&mut self, v: Value, lo: Val, hi: Val) { + let (mine, other) = if self.upper { (hi, lo) } else { (lo, hi) }; + self.vals.insert(v, mine); + if let Some(t) = self.twin.as_deref_mut() { + t.vals.insert(v, other); } } @@ -1826,6 +1827,29 @@ impl<'a> Lower<'a> { } } + /// [`Self::section_inst`] in the paired form: a value over the wave's lanes takes both + /// lanes of every thread ([`Self::paired_shape`]), a lane's own value each lane's. + fn paired_section_inst(&mut self, b: usize, i: usize, start: usize) { + use super::wave::Shape; + const UNKNOWN: Why = "a whole-wave section step the simulation does not follow"; + let inst = &self.x.p.blocks[b].insts[i]; + for &(_, w) in &inst.writes { + let shape = match self.section_out.contains(&w) { + true => self.sections[&b][&start].shapes.get(&w).copied(), + false => None, + }; + let made = match shape { + None => Err(UNKNOWN), + Some(sh @ (Shape::Active(..) | Shape::Prefix(..) | Shape::Sum64 { .. })) => self.paired_shape(sh), + Some(sh) => self.both(|l| l.shape(sh, false)), + }; + match made { + Ok([lo, hi]) => self.put_lanes(w, Val::I32(lo), Val::I32(hi)), + Err(why) => self.put_lanes(w, Val::Missing(why), Val::Missing(why)), + } + } + } + /// A value a whole-wave section leaves, as DXIL wave operations over the /// host's active lanes: the console's result with console lanes; on /// another wave size, what the HLSL wave operation the console compiler @@ -1839,10 +1863,10 @@ impl<'a> Lower<'a> { let (op, src, mask, ident, prefix) = match shape { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), - Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), - Shape::ActiveF64(lo, hi, mask, high) => { - return self.active_f64_sum(lo, hi, mask, high); + Shape::Sum64 { high, lo, hi, mask } => { + return self.sum64(lo, hi, mask).map(|d| d[usize::from(high)]); } + Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), Shape::Masked(src, mask, ident) => { let c = self.cur; let &m = self @@ -1897,53 +1921,7 @@ impl<'a> Lower<'a> { let arg = if float { self.as_float(x) } else { x }; let ty = if float { f32t } else { i32t }; let sfx = if float { "f32" } else { "i32" }; - let r = match (op, prefix) { - (Op::AddU | Op::AddF, Some(inclusive)) => { - let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); - let r = self.s.op( - c, - &format!("wavePrefixOp.{sfx}"), - Attr::NoUnwind, - ty, - 121, - &[arg, k0, k1], - ); - if inclusive { - self.s.m.bin(c, Bin::Add, r, arg) - } else { - r - } - } - (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), - (Op::Or | Op::And | Op::Xor, None) => { - let k = self.s.m.i8(match op { - Op::And => 0, - Op::Or => 1, - _ => 2, - }); - self.s - .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) - } - (_, None) => { - let (code, unsigned) = match op { - Op::AddU => (0, 1), - Op::AddF => (0, 0), - Op::MinU => (2, 1), - Op::MaxU => (3, 1), - Op::MinI | Op::MinF => (2, 0), - _ => (3, 0), - }; - let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); - self.s.op( - c, - &format!("waveActiveOp.{sfx}"), - Attr::NoUnwind, - ty, - 119, - &[arg, k, u], - ) - } - }; + let r = self.host_wave_op(op, arg, float, prefix)?; // two host waves of 32 hold the console's 64 lanes: their results combine let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { // this host wave's own result (and prefix): each wave on its own, or a group of @@ -1982,24 +1960,7 @@ impl<'a> Lower<'a> { let c = self.cur; let (lo, hi) = self.exchange_halves(c, rb); let (lo, hi) = (back(self, lo), back(self, hi)); - match op { - Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), - Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), - Op::And => self.s.m.bin(c, Bin::And, lo, hi), - Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), - _ => { - // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 - let code = match op { - Op::MaxF => 35, - Op::MinF => 36, - Op::MinU => 40, - Op::MaxU => 39, - Op::MinI => 38, - _ => 37, - }; - self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) - } - } + self.join_halves(op, lo, hi, float) } } } else { @@ -2008,72 +1969,145 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } - /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), - /// returning the low (`!high`) or high (`high`) 32-bit word. - fn active_f64_sum( + /// `op` of `arg` (`float`: a float, else bits) over this host wave's active lanes; with + /// `prefix` the sum over the lanes below each lane (`Some(true)`: and the lane's own). + fn host_wave_op( &mut self, - lo: Value, - hi: Value, - mask: Value, - high: bool, + op: super::wave::Op, + arg: V, + float: bool, + prefix: Option, ) -> Result { - if self.mask_data == MaskData::None { - return Err("a wave reduction in a mesh shader"); - } + use super::wave::Op; let c = self.cur; - let &m = self - .x - .st - .masks - .get(&mask) - .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; - let lo = self.i32_of(lo)?; - let hi = self.i32_of(hi)?; - let z = self.s.m.i32(0); - let lo = self.s.m.select(c, on, lo, z); - let hi = self.s.m.select(c, on, hi, z); - self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; - let f64t = self.s.m.double(); - let i32t = self.s.t.i32; - let split_ty = self - .s - .m - .named_struct("dx.types.splitdouble", vec![i32t, i32t]); - let arg = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); - let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); - let sum = self - .s - .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); - let mut r_lo = self.s.m.extract(c, split, 0); - let mut r_hi = self.s.m.extract(c, split, 1); - if self.exchange.is_some() { - if !self.all_lanes(self.cur_ir) { - need(self.cur_ir); - return Err("a wave reduction where not every lane runs"); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let ty = if float { f32t } else { i32t }; + let sfx = if float { "f32" } else { "i32" }; + Ok(match (op, prefix) { + (Op::AddU | Op::AddF, Some(inclusive)) => { + let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); + let r = self.s.op( + c, + &format!("wavePrefixOp.{sfx}"), + Attr::NoUnwind, + ty, + 121, + &[arg, k0, k1], + ); + if inclusive { + self.s.m.bin(c, Bin::Add, r, arg) + } else { + r + } } - let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); - let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); - let c = self.cur; - let d0 = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); - let d1 = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); - let total = self.s.m.bin(c, Bin::Add, d0, d1); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); - r_lo = self.s.m.extract(c, split, 0); - r_hi = self.s.m.extract(c, split, 1); + (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), + (Op::Or | Op::And | Op::Xor, None) => { + let k = self.s.m.i8(match op { + Op::And => 0, + Op::Or => 1, + _ => 2, + }); + self.s + .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) + } + (_, None) => { + let (code, unsigned) = match op { + Op::AddU => (0, 1), + Op::AddF => (0, 0), + Op::MinU => (2, 1), + Op::MaxU => (3, 1), + Op::MinI | Op::MinF => (2, 0), + _ => (3, 0), + }; + let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); + self.s.op( + c, + &format!("waveActiveOp.{sfx}"), + Attr::NoUnwind, + ty, + 119, + &[arg, k, u], + ) + } + }) + } + + /// The results of a reduction by `op` (`float`: floats, else bits) over the two halves of + /// a console wave, joined into the wave's. + fn join_halves(&mut self, op: super::wave::Op, lo: V, hi: V, float: bool) -> V { + use super::wave::Op; + let c = self.cur; + let ty = if float { self.s.t.f32 } else { self.s.t.i32 }; + let sfx = if float { "f32" } else { "i32" }; + match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), + Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), + Op::And => self.s.m.bin(c, Bin::And, lo, hi), + Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), + _ => { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + let code = match op { + Op::MaxF => 35, + Op::MinF => 36, + Op::MinU => 40, + Op::MaxU => 39, + Op::MinI => 38, + _ => 37, + }; + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + } + } + } + + /// [`Self::shape`] of a reduction or prefix in the paired form, over the console wave's 64 + /// lanes: for the lower and the upper lane of this thread. Each half is a host wave + /// operation over the lower or the upper lanes, and the halves join as two host waves' do + /// in `shape`: a reduction of the two results, a prefix of the upper lanes after the lower + /// lanes' total. + fn paired_shape(&mut self, shape: super::wave::Shape) -> Result<[V; 2], Why> { + use super::wave::{Op, Shape}; + if let Shape::Sum64 { high, lo, hi, mask } = shape { + return self.paired_sum64(high, lo, hi, mask); + } + let (op, src, mask, ident, prefix) = match shape { + Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::Prefix(op, src, mask, ident, inclusive) => (op, src, mask, ident, Some(inclusive)), + _ => return Err("a whole-wave section value of another shape"), + }; + let &m = self.x.st.masks.get(&mask).ok_or("a wave reduction's untracked mask")?; + let c = self.cur; + let [lo, hi] = self.both(|l| { + let on = l.boolean(m, c)?; + let x = l.i32_of(src)?; + let id = l.s.m.i32(ident); + Ok(l.s.m.select(c, on, x, id)) + })?; + self.s.flags |= flags::WAVE_OPS; + if op == Op::AddH { + if prefix.is_some() { + return Err("a wave prefix of an operation other than a sum"); + } + let (lo, hi) = (self.half_tree(lo, 5), self.half_tree(hi, 5)); + let r = self.join_half_sums(lo, hi); + return Ok([r, r]); } - Ok(if high { r_hi } else { r_lo }) + let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); + let (lo, hi) = if float { (self.as_float(lo), self.as_float(hi)) } else { (lo, hi) }; + let r = match prefix { + Some(inclusive) => { + let mine = self.host_wave_op(op, lo, float, Some(inclusive))?; + let theirs = self.host_wave_op(op, hi, float, Some(inclusive))?; + let below = self.host_wave_op(op, lo, float, None)?; + [mine, self.s.m.bin(c, Bin::Add, theirs, below)] + } + None => { + let lo = self.host_wave_op(op, lo, float, None)?; + let hi = self.host_wave_op(op, hi, float, None)?; + let r = self.join_halves(op, lo, hi, float); + [r, r] + } + }; + Ok(if float { r.map(|x| self.as_int(x)) } else { r }) } /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's @@ -2151,11 +2185,24 @@ impl<'a> Lower<'a> { // block only the lanes inside the matrix reach.) return Ok(self.half_sum_here(x)); } + let c = self.cur; + let mine = self.half_tree(x, if halves { 5 } else { 6 }); + if !halves { + return Ok(mine); + } + let (lo, hi) = self.exchange_halves(c, mine); + Ok(self.join_half_sums(lo, hi)) + } + + /// The first `steps` levels of [`Self::half_sum`]'s tree over this host wave: its lanes' + /// sum when they are all of its waves' lanes (6 steps for 64, 5 for 32), in the low half; + /// the high half lane 0's. + fn half_tree(&mut self, x: V, steps: u32) -> V { let c = self.cur; let i32t = self.s.t.i32; let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let mut sum = x; - for step in 0..if halves { 5 } else { 6 } { + for step in 0..steps { let bit = self.s.m.i32(1 << step); let partner = self.s.m.bin(c, Bin::Xor, lane, bit); let theirs = self.read_lane(sum, partner); @@ -2165,16 +2212,18 @@ impl<'a> Lower<'a> { let first = self.read_lane(x, zero); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); - let mine = self.s.m.bin(c, Bin::Or, first, sum); - if !halves { - return Ok(mine); - } - let (lo, hi) = self.exchange_halves(c, mine); + self.s.m.bin(c, Bin::Or, first, sum) + } + + /// The last addition of [`Self::half_sum`]'s tree: the sums of a console wave's two halves + /// (from [`Self::half_tree`]), with the high half of the lower one's (lane 0's). + fn join_half_sums(&mut self, lo: V, hi: V) -> V { let c = self.cur; let total = self.add_halves(lo, hi); + let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF)); let total = self.s.m.bin(c, Bin::And, total, low); let first = self.s.m.bin(c, Bin::And, lo, high); - Ok(self.s.m.bin(c, Bin::Or, first, total)) + self.s.m.bin(c, Bin::Or, first, total) } fn run(mut self, partial: bool) -> Result { @@ -2227,6 +2276,13 @@ impl<'a> Lower<'a> { self.cur = self.s.entry; self.find_sections(); self.inputs()?; + if self.twin.is_some() { + // (the upper lanes' inputs: their own thread ids) + self.swap_lanes(); + let r = self.inputs(); + self.swap_lanes(); + r?; + } if let Some(mesh) = self.s.mesh { self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; self.block[order[0]] = Some(self.cur); @@ -2241,32 +2297,30 @@ impl<'a> Lower<'a> { .filter(|&q| self.block[q].is_some()) .collect(); self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q)); - for (i, phi) in p.blocks[b].phis.iter().enumerate() { - let val = match phi.reg { - Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), - _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), - Reg::Scc => { - let v = self.s.m.phi(self.cur, self.s.t.i1); - self.data_phis.push((v, b, i)); - Val::Bit(v) - } - _ => { - let v = self.s.m.phi(self.cur, self.s.t.i32); - self.data_phis.push((v, b, i)); - Val::I32(v) - } - }; - self.vals.insert(phi.value, val); + self.block_phis(b); + if self.twin.is_some() { + self.swap_lanes(); + self.block_phis(b); + self.swap_lanes(); } if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) { self.lds_meeting(); } + self.lds_last = None; let mut i = 0; while i < p.blocks[b].insts.len() { - self.inst(b, i)?; + if self.twin.is_some() { + self.paired_inst(b, i)?; + } else { + self.inst(b, i)?; + } if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) { for j in i + 1..end { - self.section_inst(b, j, i); + if self.twin.is_some() { + self.paired_section_inst(b, j, i); + } else { + self.section_inst(b, j, i); + } } i = end; continue; @@ -2281,6 +2335,35 @@ impl<'a> Lower<'a> { self.exit(b)?; } self.fill_phis()?; + // (the paired form: the other lane's joins too; filling one lane's can ask for lane + // masks joined in either lane, until neither has any left) + while self.twin.is_some() { + self.swap_lanes(); + let r = self.fill_phis(); + self.swap_lanes(); + r?; + let left = self.twin.as_deref().is_some_and(|t| !t.pending_masks.is_empty()); + if self.pending_masks.is_empty() && !left { + break; + } + self.fill_phis()?; + } + // A linked stage's signatures without what it leaves out; an input left out must not + // have been read. + if !self.drop_in.is_empty() || !self.drop_out.is_empty() { + if self.s.inputs.iter().zip(&self.drop_in).any(|(e, &d)| d && e.usage != 0) { + return Err(unsupported(0, "an input left out of a linked pipeline read")); + } + let keep = |els: &mut Vec, drop: &[bool]| { + let mut d = drop.iter(); + els.retain(|_| !d.next().copied().unwrap_or(false)); + }; + keep(&mut self.s.inputs, &self.drop_in); + keep(&mut self.s.outputs, &self.drop_out); + } + // (the reads have given the pixel inputs their modes) + super::container::one_mode_per_register(&mut self.s.inputs, self.s.pixel); + super::container::one_mode_per_register(&mut self.s.outputs, false); let user_data = self.user_reads.values().copied().collect(); self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); @@ -2306,6 +2389,29 @@ impl<'a> Lower<'a> { }) } + /// The joins at the start of IR block `b`, filled once every block is lowered + /// ([`Self::fill_phis`]). + fn block_phis(&mut self, b: usize) { + let p = self.x.p; + for (i, phi) in p.blocks[b].phis.iter().enumerate() { + let val = match phi.reg { + Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), + _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), + Reg::Scc => { + let v = self.s.m.phi(self.cur, self.s.t.i1); + self.data_phis.push((v, b, i)); + Val::Bit(v) + } + _ => { + let v = self.s.m.phi(self.cur, self.s.t.i32); + self.data_phis.push((v, b, i)); + Val::I32(v) + } + }; + self.vals.insert(phi.value, val); + } + } + fn exported_out(&self, b: usize) -> bool { self.exported[b] || self.has_done_export(b) } @@ -2328,11 +2434,10 @@ impl<'a> Lower<'a> { } Reg::S(n) => match io_inputs.get(&v) { Some(&input) => self.input(input), - // Above the SGPRs the hardware initializes, a register - // holds what the last wave left, so no program depends - // on it: a read the paths only seem to allow (a branch - // past the write, taken only with one past the read) - // reads zero, as VGPRs do. + None if super::pops::collision_register(self.x.native) == Some(n) => { + Val::I32(self.s.m.i32(super::pops::NO_COLLISION)) + } + // Treat SGPRs above the hardware inputs like unset VGPRs. None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { Val::I32(self.s.m.i32(0)) } @@ -2503,8 +2608,9 @@ impl<'a> Lower<'a> { ".f32" }; let entry = self.s.entry; + let sig = self.sig_id(true, id); let args = [ - self.s.m.i32(id as u32), + self.s.m.i32(sig), self.s.m.i32(0), self.s.m.i8(col), self.s.m.undef(self.s.t.i32), @@ -3238,9 +3344,11 @@ impl<'a> Lower<'a> { let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; // A mask that holds lanes outside EXEC where it is written (the complement of one, // say) is the ballot of the lanes that are there: all of them, where two exchanging - // host waves know every lane runs that block. + // host waves know every lane runs that block, and in the paired form, whose host wave + // runs every block with all its lanes. let made = self.def_block.get(&lo).copied(); - let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + let whole = self.twin.is_some() + || self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); if !self.x.st.active.contains(&lo) && !whole { if let Some(source) = self.copied_mask_word(v) { return self.i32_of(source); @@ -3265,9 +3373,14 @@ impl<'a> Lower<'a> { if !self.balloting.insert(lo) { return Err("a lane mask whose lanes depend on its own value"); } - let bit = self.boolean(m, at); + // (the paired form: the upper lanes' bits too, lanes 32-63) + let bits = if self.twin.is_some() { + self.both(|l| l.boolean(m, at)).map(|[a, b]| (a, Some(b))) + } else { + self.boolean(m, at).map(|a| (a, None)) + }; self.balloting.remove(&lo); - let bit = bit?; + let (bit, upper) = bits?; let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -3275,7 +3388,10 @@ impl<'a> Lower<'a> { .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); self.s.flags |= flags::WAVE_OPS; let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); - if self.exchange.is_some() { + if let Some(upper) = upper { + let r = self.s.op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[upper]); + xy.1 = self.s.m.extract(at, r, 0); + } else if self.exchange.is_some() { // a host wave's ballot is its half's 32 bits: the halves exchange them let b = self.def_block.get(&lo).copied(); if self.local { @@ -3309,6 +3425,7 @@ impl<'a> Lower<'a> { let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?; self.i32_of(v) } + super::pops::EXITING_WAVE_ID if super::pops::active(self.x.native) => Ok(self.s.m.i32(0)), Operand::Const(c) => crate::resource::inline(c) .map(|x| self.s.m.i32(x)) .ok_or("a special operand (vccz, execz, scc, lds_direct)"), @@ -3770,10 +3887,11 @@ impl<'a> Lower<'a> { } /// A console wave64 program in host waves of 32: the first console thread of this host wave - /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's - /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread - /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it - /// found. Branch-free, in the entry block, which every thread runs. + /// (0, 32, 64, ...; in the paired form 0, 64, 128, ...). A GPU need not give a host wave + /// consecutive thread indices (NVIDIA's 8 x 8 groups), so each wave takes the next 32 (64) + /// from an LDS counter instead: every thread zeroes it, the group meets, each wave's first + /// lane adds 32 (64) and the wave takes what it found. Branch-free, in the entry block, + /// which every thread runs. fn wave_base(&mut self) -> Option { let slot = self.halves?; if let Some(v) = self.wave_base { @@ -3788,21 +3906,36 @@ impl<'a> Lower<'a> { self.group_sync(e); let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let first = self.s.m.cmp(e, pred::EQ, lane, zero); - let k32 = self.s.m.i32(32); - let add = self.s.m.select(e, first, k32, zero); + let step = self.s.m.i32(if self.twin.is_some() { 64 } else { 32 }); + let add = self.s.m.select(e, first, step, zero); let ptr = self.s.m.element(e, lds, k); let old = self.s.m.atomic(e, Rmw::Add, ptr, add); let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); self.s.flags |= flags::WAVE_OPS; + // a counter in the program's own LDS (the paired form's, when it has no dword to + // spare): every wave has its base before any thread runs the program + if matches!(self.x.native.io, StageIo::Cs(cs) if slot < cs.lds_bytes() / 4) { + self.group_sync(e); + } self.wave_base = Some(base); Some(base) } /// The console thread index of this thread in the group: `wave_base` plus the host lane - /// (host waves of 32), else the wave's first thread index rounded down plus the lane. + /// (host waves of 32), else the wave's first thread index rounded down plus the lane. In + /// the paired form, of the lane being lowered: its console wave's first thread, plus the + /// host lane, plus 32 for the upper lane. fn console_thread(&mut self) -> V { let (e, i32t) = (self.s.entry, self.s.t.i32); let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + if self.twin.is_some() { + let half = self.s.m.i32(if self.upper { 32 } else { 0 }); + let t = self.s.m.bin(e, Bin::Add, lane, half); + return match self.wave_base() { + Some(base) => self.s.m.bin(e, Bin::Add, base, t), + None => t, + }; + } if let Some(base) = self.wave_base() { return self.s.m.bin(e, Bin::Add, base, lane); } @@ -3815,9 +3948,10 @@ impl<'a> Lower<'a> { } /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host - /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane. + /// wave holds a 32-aligned run of console lanes (in the paired form, the lane being + /// lowered). Without `exchange` or the paired form: the host lane. fn console_lane(&mut self) -> V { - if self.exchange.is_none() { + if self.exchange.is_none() && self.twin.is_none() { return self.lane_index(); } if let Some(v) = self.clane { @@ -3909,19 +4043,28 @@ impl<'a> Lower<'a> { /// console wave has its bit of the result, asked where the operation stands. The lanes /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with /// the console's waves the host wave's answer is the console's; two host waves of 32 - /// exchange theirs, which needs every lane there. + /// exchange theirs, which needs every lane there. In the paired form the host wave asks + /// both lanes of each thread. fn scc_some(&mut self, scc: Value) -> Result { let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?; + let made = self.def_block.get(&scc).copied(); + let at = |l: &Self| match made { + None => Ok(l.s.entry), + Some(b) if b == l.cur_ir => Ok(l.cur), + Some(b) => l.tail[b].ok_or("a lane mask written after its use"), + }; + if self.twin.is_some() { + let at = at(self)?; + let [lo, hi] = self.both(|l| l.boolean(m, at))?; + let either = self.s.m.bin(at, Bin::Or, lo, hi); + self.s.flags |= flags::WAVE_OPS; + return Ok(self.s.op(at, "waveAnyTrue", Attr::NoUnwind, self.s.t.i1, 113, &[either])); + } // (not for a console wave cut into host waves that do not exchange) if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() { return Err(LANE_MASK); } - let made = self.def_block.get(&scc).copied(); - let at = match made { - None => self.s.entry, - Some(b) if b == self.cur_ir => self.cur, - Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, - }; + let at = at(self)?; let bit = self.boolean(m, at)?; let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); @@ -3943,6 +4086,18 @@ impl<'a> Lower<'a> { fn wave_wide(&mut self, b: usize, when: Bool) -> Result { const WHY: Why = "a wave-wide branch where not every lane runs"; let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; + if self.twin.is_some() { + // The paired form: the host wave is the console's, each thread with two of its + // lanes; every lane is here (control flow is the wave's), and a lane outside EXEC + // says what it says on the console (no set bit for "some lane", no objection to + // "every lane"). + let c = self.cur; + let [lo, hi] = self.both(|l| l.boolean(when, c))?; + let pair = self.s.m.bin(c, if any { Bin::Or } else { Bin::And }, lo, hi); + self.s.flags |= flags::WAVE_OPS; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + return Ok(self.s.op(c, name, Attr::NoUnwind, self.s.t.i1, code, &[pair])); + } if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { // The host's waves are the console's: the wave's own answer. The lanes that are // elsewhere have no bit set, as on the console, so "some lane" needs no one but @@ -3991,7 +4146,7 @@ impl<'a> Lower<'a> { /// This lane's bit of the mask `lo`, `hi` (wave64). fn lane_bit(&mut self, at: usize, lo: V, hi: Option) -> V { self.s.flags |= flags::WAVE_OPS; - let lane = if self.exchange.is_some() { + let lane = if self.exchange.is_some() || self.twin.is_some() { self.console_lane() } else { self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) @@ -4225,15 +4380,20 @@ impl<'a> Lower<'a> { /// thread is relabelled so that its host lane is its console lane: the /// flat id is the wave's first lane's, rounded down to the wave size, /// plus the lane index. (A bijection while each host wave holds a - /// wave-aligned run of flat ids, as the console's waves do.) + /// wave-aligned run of flat ids, as the console's waves do.) In the paired form, of the + /// console lane being lowered, in the console's group (the host's is a row of half as + /// many threads). fn thread_id(&mut self, c: u8) -> Val { if !self.console_lanes { return self.compute_id("threadIdInGroup.i32", 95, c); } - let [x, y, _] = self.s.threads.expect("compute"); + let [x, y, _] = match self.x.native.io { + StageIo::Cs(cs) => cs.threads, + _ => self.s.threads.expect("compute"), + }; let e = self.s.entry; let i32t = self.s.t.i32; - if self.halves.is_some() { + if self.halves.is_some() || self.twin.is_some() { let f = self.console_thread(); self.s.flags |= flags::WAVE_OPS; let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); @@ -4300,7 +4460,15 @@ impl<'a> Lower<'a> { // never reached: they come down to the lane count when the outputs // do not fit. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes}; - let (outputs, prims) = (&self.s.outputs, &self.s.prims); + // (linked: the outputs the pixel program reads, which are all that is declared) + let kept: Vec; + let outputs = if self.drop_out.is_empty() { + &self.s.outputs + } else { + kept = self.s.outputs.iter().zip(&self.drop_out).filter(|(_, d)| !**d).map(|(e, _)| e.clone()).collect(); + &kept + }; + let prims = &self.s.prims; let fits = |m: super::shader::Mesh| { mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT }; @@ -4791,10 +4959,20 @@ impl<'a> Lower<'a> { return Ok(()); } let at = self.begin_guarded(guard); - let r = match rmw { - Some(op) => self.s.m.atomic(self.cur, op, p, v0), + // A subtraction, or an addition of a negated value (which host compilers turn into + // one): group-shared memory has no atomic subtraction in DXIL, and the D3D12 drivers + // refuse such a pipeline (E_OUTOFMEMORY from NVIDIA's and from WARP), so it is a + // compare-exchange loop. + let subtract = match rmw { + Some(Rmw::Sub) => Some(v0), + Some(Rmw::Add) => self.s.m.negated(v0), + _ => None, + }; + let r = match (rmw, subtract) { + (Some(_), Some(x)) => self.lds_subtract(p, x), + (Some(op), None) => self.s.m.atomic(self.cur, op, p, v0), // Compare with data0, store data1. - None => self + (None, _) => self .s .m .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?), @@ -4817,7 +4995,31 @@ impl<'a> Lower<'a> { /// numbers compare as floats with -0 below +0. // shortcut: f32 denormals compare as kept; with the console's MODE // flushing them they would order as ±0 first (MODE is not modelled). + /// Subtracts `x` from the LDS dword at `p` atomically, with a compare-exchange loop; the + /// old value returns (`ds_sub_u32`, see the caller). + fn lds_subtract(&mut self, p: V, x: V) -> V { + let pre = self.cur; + let init = self.s.m.load(pre, p); + let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(pre, Term::Br(lp)); + let i32t = self.s.t.i32; + let old = self.s.m.phi(lp, i32t); + let new = self.s.m.bin(lp, Bin::Sub, old, x); + let prev = self.s.m.cmpxchg(lp, p, old, new); + let done = self.s.m.cmp(lp, pred::EQ, prev, old); + self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); + self.s.m.terminate(lp, Term::CondBr(done, exit, lp)); + self.cur = exit; + old + } + fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V { + self.lds_rmw_loop(p, |l, old| l.lds_float_pick(old, data, max)) + } + + /// A read-modify-write of the LDS dword at `p` as a compare-exchange loop: `new` gives, + /// in the loop's one block, what is written over the old value; the old value returns. + fn lds_rmw_loop(&mut self, p: V, new: impl FnOnce(&mut Self, V) -> V) -> V { let pre = self.cur; let init = self.s.m.load(pre, p); let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); @@ -4825,7 +5027,7 @@ impl<'a> Lower<'a> { let i32t = self.s.t.i32; let old = self.s.m.phi(lp, i32t); self.cur = lp; - let new = self.lds_float_pick(old, data, max); + let new = new(self, old); let prev = self.s.m.cmpxchg(lp, p, old, new); let done = self.s.m.cmp(lp, pred::EQ, prev, old); self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); @@ -4990,6 +5192,150 @@ impl<'a> Lower<'a> { } } + /// Instruction `i` of IR block `b` in the paired form ([`with_paired_lanes`]), for both + /// console lanes of the thread: what a lane does is lowered for the lower lane, then for + /// the upper one, which keeps the console's order of the wave's instructions; scalar + /// control (the title's barrier) and scalar memory writes once; a read of other lanes once + /// with what both lanes hold ([`Self::paired_cross`]). An LDS access that follows another + /// gets a fence first unless both read: what one lane wrote (or still read) must not move + /// past another lane's access the console made after it. + fn paired_inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { + let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; + let name = inst.name(); + let once = matches!(inst.fields, Fields::Sopp { .. }) + || matches!(inst.fields, Fields::Smem { .. }) + && (name.contains("store") || name.contains("atomic")); + if once { + self.inst(b, i)?; + self.mirror(inst); + return Ok(()); + } + let cross = match name { + "v_readlane_b32" | "ds_bpermute_b32" => true, + // (not a waterfall loop's read, the lane's own dword: `Self::valu`) + "v_readfirstlane_b32" => { + !inst.writes.first().is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) + } + _ => false, + }; + if cross { + if let Err(why) = self.paired_cross(inst, b, i) { + for &(_, w) in &inst.writes { + self.put_lanes(w, Val::Missing(why), Val::Missing(why)); + } + } + return Ok(()); + } + if matches!(inst.fields, Fields::Ds { .. }) + && !name.starts_with("ds_swizzle") + && !name.contains("permute") + { + let write = !name.starts_with("ds_read"); + if write || self.lds_last != Some(false) { + let (mode, void) = (self.s.m.i32(8), self.s.t.void); + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + self.lds_last = Some(write); + } + self.inst(b, i)?; + self.swap_lanes(); + let r = self.inst(b, i); + self.swap_lanes(); + r + } + + /// The paired form: what `inst` wrote in the lane being lowered, for the other lane too (a + /// scalar result, the same in both). + fn mirror(&mut self, inst: &Inst) { + let Some(t) = self.twin.as_deref_mut() else { + return; + }; + for &(_, w) in &inst.writes { + if let Some(&v) = self.vals.get(&w) { + t.vals.insert(w, v); + } + } + } + + /// The paired form: an instruction that reads other lanes of the console wave, any of its + /// 64: `v_readlane_b32` and `v_readfirstlane_b32` (scalar results, the same in both lanes of + /// the thread) and `ds_bpermute_b32`. Lane n and lane n + 32 are the lower and the upper + /// lane of host lane n. + fn paired_cross(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + self.cross_lane(false)?; + let c = self.cur; + let (k31, k32, z) = (self.s.m.i32(31), self.s.m.i32(32), self.s.m.i32(0)); + // a lane's value from the lower or upper value of the host lane `at` (of 0..63) + let pick = |l: &mut Self, lo: V, hi: V, at: V| { + let host = l.s.m.bin(c, Bin::And, at, k31); + let upper = l.s.m.bin(c, Bin::And, at, k32); + let upper = l.s.m.cmp(c, pred::NE, upper, z); + let (lo, hi) = (l.read_lane(lo, host), l.read_lane(hi, host)); + l.s.m.select(c, upper, hi, lo) + }; + match inst.name() { + "v_readlane_b32" => { + // the lane: a scalar or a constant + let lane = self.src(inst, 1)?; + let [lo, hi] = self.both(|l| l.src(inst, 0))?; + let r = pick(self, lo, hi, lane); + self.write_i(inst, r, None)?; + } + "v_readfirstlane_b32" => { + let [(lo, in_lo), (hi, in_hi)] = self.both(|l| { + let x = l.src(inst, 0)?; + let guard = l.guard(b, i)?; + Ok(l.first_lane(x, guard)) + })?; + // the first lane in EXEC is a lower one if there is one; with none, lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + let r = self.s.m.select(c, in_lo, lo, hi); + self.write_i(inst, r, None)?; + } + _ => { + // `ds_bpermute_b32`: each lane reads the lane its address names, which gives + // its data, or 0 outside EXEC + let Fields::Ds { + dst: Some(Operand::Vector { reg, .. }), + addr: Some(addr), + data, + offset0, + offset1, + .. + } = &inst.fields + else { + return Err("a permute's operands"); + }; + let data = data.first().ok_or("a permute source")?; + let offset = u32::from(*offset0) | u32::from(*offset1) << 8; + let [(from_lo, x_lo, g_lo), (from_hi, x_hi, g_hi)] = self.both(|l| { + let at = l.vgprs(inst, addr, 1)?[0]; + let x = l.vgprs(inst, data, 1)?[0]; + let guard = l.guard(b, i)?; + let (o, two) = (l.s.m.i32(offset), l.s.m.i32(2)); + let at = l.s.m.bin(c, Bin::Add, at, o); + let from = l.s.m.bin(c, Bin::LShr, at, two); + let x = match guard { + Some(g) => l.s.m.select(c, g, x, z), + None => x, + }; + Ok((from, x, guard)) + })?; + let read = [pick(self, x_lo, x_hi, from_lo), pick(self, x_lo, x_hi, from_hi)]; + let guards = [g_lo, g_hi]; + let reg = *reg; + self.both(|l| { + let n = usize::from(l.upper); + l.write(inst, Reg::V(reg), read[n], guards[n]); + Ok(()) + })?; + return Ok(()); + } + } + self.mirror(inst); + Ok(()) + } + /// The two host waves of a console wave meet (a group barrier with a shared-memory /// fence): LDS writes before are seen by reads after. fn lds_meeting(&mut self) { @@ -5096,6 +5442,9 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if self.x.native.stage == HwStage::Ps && super::pops::skip_setreg(self.x.native, inst) { + return Ok(()); + } let scc = inst.write(Reg::Scc); let dst_code = match dst { Some(Operand::Scalar { code, .. }) => Some(*code), @@ -5768,308 +6117,6 @@ impl<'a> Lower<'a> { Ok(()) } - /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords - /// the code also reads as numbers: the console compiler computes sizes - /// from descriptor bits (an image's width, height, depth, levels; a - /// buffer's record count) instead of querying them. Those fields are - /// rebuilt from the host view's dimensions in the GFX10 layout (image - /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits - /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at - /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). - // shortcut: the base level reads 0 (the host view starts at its own - // level 0, so sizes the code shifts by it come out right) and the other - // dwords (addresses, formats, tiling) have no host value: reading them - // stops the program. - fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { - const OTHER: Why = "a descriptor's address or format read as data"; - let Fields::Smem { - data: Some(Operand::Scalar { code, .. }), - .. - } = inst.fields - else { - return Err("a scalar memory read as data"); - }; - let count = match inst.name().strip_prefix("s_load_dword") { - Some("") => 1u32, - Some("x2") => 2, - Some("x4") => 4, - Some("x8") => 8, - Some("x16") => 16, - _ => return Err("a scalar memory read as data"), - }; - // How the program uses the descriptor tells the view's kind: an image or buffer - // instruction before a scalar buffer load, which reads any buffer. - let x = self.x; - let uses = |of: Site| { - x.res - .descriptors - .iter() - .filter(|d| d.role == Role::Resource) - .filter_map(move |d| { - d.source.leaves().into_iter().find_map(|l| match *l { - Source::Loaded { load, first } if load == of => Some((d.site, first)), - _ => None, - }) - }) - }; - let by_scalar_load = |u: &(Site, u8)| { - matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) - }; - let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); - // The console compiler loads a descriptor again wherever it needs it, and for a - // size it reads the dwords of a load that nothing uses as a descriptor (a texture - // picked from the heap by an index held per lane: one load for its width, one for - // its base level, one for each read of the image). Another load of as many dwords - // from the same address reads the same descriptor, so what uses that one tells - // this one's kind. The handle is still made from this load's own operands, which - // hold here. - let address = self.scalar.get(&site).copied(); - let twin = || { - let a = address?; - let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); - x.res - .scalar - .iter() - .filter(|(s, b)| *s != site && *b == a && same(*s)) - .find_map(|(s, _)| use_of(*s)) - }; - let use_at = use_of(site).or_else(twin); - let Some((at, first)) = use_at else { - // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only - // copies its dwords and compares them, lane against first lane, and every load - // that reaches those lanes reads one address. Each dword stands in as its place - // in the table, so the lanes compare equal as they do on the console. - if self.x.res.lane_copied.contains(&site) - && let Some(a) = self.scalar.get(&site).copied() - { - for k in 0..count { - let x = self.s.m.i32(a.offset / 4 + k); - self.write(inst, Reg::S(code + k as u8), x, None); - } - return Ok(()); - } - // A sampler's descriptor: no program reads its dwords as numbers, so where one - // meets numbers at a join the register is dead on that path (`dead`), as a - // descriptor's address or format is. - let sampler = x.res.descriptors.iter().any(|d| { - d.role == Role::Sampler - && d.source.leaves().into_iter().any( - |l| matches!(*l, Source::Loaded { load, .. } if load == site), - ) - }); - if sampler { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a sampler's descriptor read as data"); - } - // Code may walk the title address or test a structured view's record count. - let mut pointer = if count <= 4 { self.view_address(site) } else { None }; - if pointer.is_none() && count == 4 && self.picked_address_words(site, code) { - pointer = Some(self.picked_address(site)?); - } - if count <= 4 && let Some((lo, hi)) = pointer - { - let records = inst.write(Reg::S(code + 2)) - .and_then(|value| self.structured_srv_records(site, value)); - for k in 0..count { - let reg = Reg::S(code + k as u8); - match (k, records) { - (0, _) => self.write(inst, reg, lo, None), - (1, _) => self.write(inst, reg, hi, None), - (2, Some(n)) => self.write(inst, reg, n, None), - _ => { - if let Some(v) = inst.write(reg) { - self.vals.insert(v, Val::Missing(OTHER)); - self.stale.insert(v); - } - } - } - } - return Ok(()); - } - // Puddle detection looks up a 2D texture's dimensions by heap index - // without sampling it. Use that index to query the bound host view. - // Only the heap supplies this otherwise untyped 2D lookup. - if count == 8 && address.is_some_and(|a| { - a.dynamic.is_some() - && x.native.layout.get(a.param).is_some_and(|p| p.root == RootType::ResourceHeap) - }) { - let src = Source::Loaded { load: site, first: 0 }; - let h = self.handle(site, &src, false, (2, 0x409))?; - let words = self.image_size_words(h, 2, false); - self.write_descriptor_words(inst, code, count, 0, &words); - return Ok(()); - } - if std::env::var_os("VICTORY_DESC_WHY").is_some() { - eprintln!( - "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", - inst.machine.offset, - inst.name(), - address, - self.x.res.lane_copied.contains(&site) - ); - } - return Err("a descriptor read only as data"); - }; - let src = Source::Loaded { load: site, first }; - let used = self.used_kind(&src); - let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; - let un = ui.name(); - let uav = un.contains("store") - || un.contains("atomic") - || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; - let (props, image) = match &ui.fields { - // A ray-tracing structure in a buffer of the host: read raw. - Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), - Fields::Image { dim, .. } => { - let kind = match dim { - 0 => 1, - 1 => 2, - 2 => 4, - 4 => 6, - 5 => 7, - _ => return Err("an image dimension (cube or MSAA)"), - }; - let ty = if !uav && self.scalar_uint_srv(&src, kind) { 0x105 } else { 0x409 }; - ((kind | u, ty), Some(kind)) - } - Fields::Buffer { idxen, format, .. } => { - let stride = used.map_or(0, |u| u.stride); - let props = if un.starts_with("buffer_load_format") - || un.starts_with("buffer_store_format") - { - let ty = if !uav && self.scalar_uint_srv(&src, 10) { 0x105 } else { 0x409 }; - (10 | u, ty) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { - (12 | u, stride) - } else { - (11 | u, 0) - }; - if used.is_some_and(|u| u.kind == ResourceType::Cbv) { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a constant buffer's descriptor read as data"); - } - (props, None) - } - // Read by scalar buffer loads alone: the raw view `smem` reads it through. - Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { - ((11, 0), None) - } - // A constant buffer: nothing of its descriptor is a number. - Fields::Smem { .. } => { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a constant buffer's descriptor read as data"); - } - _ => return Err("a scalar memory read as data"), - }; - let h = self.handle(site, &src, false, props)?; - let words: Vec<(u32, V)> = match image { - Some(kind) => self.image_size_words(h, kind, uav), - None => { - let c = self.cur; - let i32t = self.s.t.i32; - let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); - let mip = self.s.m.undef(i32t); - let d = self - .s - .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); - // A raw view counts bytes; the descriptor's record count is in elements. - let n = self.s.m.extract(c, d, 0); - let stride = used.map_or(0, |u| u.stride); - let n = if props.0 & 0xFF == 11 && stride > 1 { - let k = self.s.m.i32(stride); - self.s.m.bin(c, Bin::UDiv, n, k) - } else { - n - }; - let mut words = vec![(2, n)]; - // Its address too, where the code computes with it and the - // host can tell it. - let computed = (0..2u8).any(|k| { - inst.write(Reg::S(code + first + k)) - .is_some_and(|v| self.computed_with(v, 6)) - }); - if first == 0 - && computed - && let Some((lo, hi)) = self.view_address(site) - { - words.extend([(0, lo), (1, hi)]); - } - words - } - }; - self.write_descriptor_words(inst, code, count, u32::from(first), &words); - Ok(()) - } - - /// An image descriptor's size fields in the GFX10 layout, from the dimensions of the - /// host view `h` of `kind` (as `descriptor_data` explains): (dword, value). - fn image_size_words(&mut self, h: V, kind: u32, uav: bool) -> Vec<(u32, V)> { - let c = self.cur; - let i32t = self.s.t.i32; - let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); - let mip = if uav { self.s.m.undef(i32t) } else { self.s.m.i32(0) }; - let d = self - .s - .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); - let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); - let one = self.s.m.i32(1); - let w = field(self, 0); - let (height, depth) = match kind { - 1 => (one, one), - 2 => (field(self, 1), one), - 6 => (one, field(self, 1)), - _ => (field(self, 1), field(self, 2)), - }; - let levels = if uav { one } else { field(self, 3) }; - let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); - let (w, height, depth, levels) = ( - less(self, w), - less(self, height), - less(self, depth), - less(self, levels), - ); - let k = |l: &mut Self, v: u32| l.s.m.i32(v); - let (k30, k2, k14, k16, mask) = ( - k(self, 30), - k(self, 2), - k(self, 14), - k(self, 16), - k(self, 0x3FFF), - ); - let d1 = self.s.m.bin(c, Bin::Shl, w, k30); - let hi = self.s.m.bin(c, Bin::LShr, w, k2); - let hi = self.s.m.bin(c, Bin::And, hi, mask); - let ht = self.s.m.bin(c, Bin::Shl, height, k14); - let d2 = self.s.m.bin(c, Bin::Or, hi, ht); - let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; - let base = k(self, 0xFAC | ty << 28); - let last = self.s.m.bin(c, Bin::Shl, levels, k16); - let d3 = self.s.m.bin(c, Bin::Or, base, last); - vec![(1, d1), (2, d2), (3, d3), (4, depth)] - } - - /// The `count` dwords an `s_load_dword*` writes from `s[code]` on, the descriptor's - /// dword `first` first: those of `words` (dword, value) get their value, the others - /// have none (reading them stops the program). - fn write_descriptor_words( - &mut self, inst: &Inst, code: u8, count: u32, first: u32, words: &[(u32, V)], - ) { - const OTHER: Why = "a descriptor's address or format read as data"; - for k in 0..count { - let rel = k.wrapping_sub(first); - match words.iter().find(|w| w.0 == rel) { - Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), - None => { - if let Some(v) = inst.write(Reg::S(code + k as u8)) { - self.vals.insert(v, Val::Missing(OTHER)); - self.stale.insert(v); - } - } - } - } - } - /// `s_load_dword*` from the program's constant table. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { @@ -6342,6 +6389,11 @@ impl<'a> Lower<'a> { sampler: bool, props: (u32, u32), ) -> Result { + let ordered = super::pops::active(self.x.native) && props.0 & 0x1000 != 0; + let props = (props.0 | (u32::from(ordered) << 13), props.1); + if ordered { + self.s.flags |= flags::ROVS; + } match src { Source::Loaded { load, first } => { let key = (self.cur, *load, *first, sampler, props); @@ -6403,7 +6455,9 @@ impl<'a> Lower<'a> { // (11) or writes (11 with the UAV bit). Indexed // accesses reach here as raw ones at index times the // entry's stride (`buffer`). - (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => { + (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) + if !super::pops::active(self.x.native) => + { Ok(self.s.root_uav_handle(rp.slot)) } (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => { @@ -6457,7 +6511,7 @@ impl<'a> Lower<'a> { sampler: bool, depth: u32, ) -> Result { - const WHY: Why = "a descriptor chosen by control flow"; + const WHY: Why = CHOSEN; let p = self.x.p; let mut incoming = Vec::new(); for (&q, arg) in p.blocks[block].preds.iter().zip(args) { @@ -6563,6 +6617,10 @@ impl<'a> Lower<'a> { let clear = self.lane_heap_index(b, sampler)?; Ok(self.s.m.select(self.cur, cond, set, clear)) } + // (in the paired form a thread comes the wave's way, not each lane its own) + Source::LanePhi { .. } if self.twin.is_some() => { + Err("a per-lane descriptor chosen by the lanes' ways, in paired lanes") + } Source::LanePhi { block, args } => { // Each predecessor computes its heap index at its end (what // it reads is there: the dwords are, on that edge); the join @@ -6833,7 +6891,9 @@ impl<'a> Lower<'a> { if let Some((rows, banks)) = masks { // Row (16 lanes) and bank (4 lanes of a row) write masks. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3)); - let ri = self.s.m.bin(c, Bin::LShr, lane, four); + // (in the paired form rows 2 and 3 are the upper lanes') + let row_lane = if self.twin.is_some() { self.console_lane() } else { lane }; + let ri = self.s.m.bin(c, Bin::LShr, row_lane, four); let ri = self.s.m.bin(c, Bin::And, ri, three); let bi = self.s.m.bin(c, Bin::LShr, lane, two); let bi = self.s.m.bin(c, Bin::And, bi, three); @@ -6868,6 +6928,9 @@ impl<'a> Lower<'a> { if let Some(op) = name.strip_prefix("v_pk_") { return self.packed16(inst, op, guard); } + if let Some(r) = self.valu_f64(inst, name, guard) { + return r; + } match name { "v_mad_u64_u32" => { // a * b + c, c and the result 64 bits wide; the carry out @@ -7362,12 +7425,6 @@ impl<'a> Lower<'a> { let r = self.read_lane(x, from); int(self, r) } - "v_cvt_f32_f64" => { - let (lo, hi) = self.f64_pair(inst, 0)?; - let bits = self.f64_to_f32_bits(lo, hi); - let r = self.as_float(bits); - float(self, r) - } "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { let mut a = s(self, 0)?; @@ -7425,9 +7482,13 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("a mixed-precision result"); }; - let old = match inst.read(Reg::V(reg)) { - Some(o) => self.i32_of(o)?, - None => self.s.m.i32(0), + // (a first interpolation half held there before keeps nothing anyone reads: + // its pair is evaluated by the second half, and code reads the f16 result's + // half of the register) + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + Some(Err(FIRST_HALF)) | None => self.s.m.i32(0), + Some(Err(why)) => return Err(why), }; let h = self .s @@ -7638,6 +7699,14 @@ impl<'a> Lower<'a> { return Err("a lane write in a half-wave"); } let me = self.console_lane(); + // (the paired form: a wave64 lane select takes the low six bits) + let lane = match self.twin { + Some(_) => { + let k63 = self.s.m.i32(63); + self.s.m.bin(c, Bin::And, lane, k63) + } + None => lane, + }; let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); int(self, r) @@ -7683,6 +7752,16 @@ impl<'a> Lower<'a> { if *OWN.get_or_init(|| std::env::var_os("VICTORY_FIRSTLANE_OWN").is_some_and(|v| v == "1")) { return int(self, mine); } + // A value built from scalars alone, the same in every lane that holds + // it ([`scalar_built`]); one a guarded write made only inside a branch + // (lanes past its end may hold an older one). + if let Some(&Operand::Vector { reg, .. }) = v.src.first() + && let Some(x) = inst.read(Reg::V(reg)) + && self.built.0.contains(&x) + && (guard.is_some() || !self.built.1.contains(&x)) + { + return int(self, mine); + } need(self.cur_ir); return Err("a first-lane read where not every lane runs"); } @@ -7753,159 +7832,6 @@ impl<'a> Lower<'a> { } } - /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying - /// `abs` and `neg` input modifiers on operand `k`. - fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { - let Fields::Valu(v) = &inst.fields else { - unreachable!() - }; - if v.sdwa.is_some() || v.dpp.is_some() { - return Err("64-bit operand modifiers"); - } - let op = *v.src.get(k).ok_or("a missing operand")?; - let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { - let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; - let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; - Ok((lo, hi)) - }; - let (lo, mut hi) = match op { - Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, - Operand::Scalar { code, .. } if code != NULL => { - pair(self, Reg::S(code), Reg::S(code + 1))? - } - Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), - Operand::Const(c @ 240..=248) => { - const INLINE_F64: [f64; 9] = [ - 0.5, - -0.5, - 1.0, - -1.0, - 2.0, - -2.0, - 4.0, - -4.0, - 1.0 / std::f64::consts::TAU, - ]; - let bits = INLINE_F64[(c - 240) as usize].to_bits(); - (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) - } - // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. - Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), - _ => return Err("a 64-bit float operand"), - }; - let c = self.cur; - if v.abs >> k & 1 != 0 { - let mask = self.s.m.i32(0x7FFF_FFFF); - hi = self.s.m.bin(c, Bin::And, hi, mask); - } - if v.neg >> k & 1 != 0 { - let sign = self.s.m.i32(0x8000_0000); - hi = self.s.m.bin(c, Bin::Xor, hi, sign); - } - Ok((lo, hi)) - } - - /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, - /// without requiring host `DOUBLES` (`f64`) support. - fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { - let c = self.cur; - let k0 = self.s.m.i32(0); - let k1 = self.s.m.i32(1); - let sign_mask = self.s.m.i32(0x8000_0000); - let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); - - let k20 = self.s.m.i32(20); - let k7ff = self.s.m.i32(0x7FF); - let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); - let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); - - let frac_mask = self.s.m.i32(0x000F_FFFF); - let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); - let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); - let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); - - let k3 = self.s.m.i32(3); - let k29 = self.s.m.i32(29); - let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); - let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); - let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); - - let rem_mask = self.s.m.i32(0x1FFF_FFFF); - let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); - let half_rem = self.s.m.i32(0x1000_0000); - let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); - let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); - let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); - let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); - let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); - let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); - let norm_inc = self.s.m.select(c, norm_round, k1, k0); - - // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. - let k896 = self.s.m.i32(896); - let k23 = self.s.m.i32(23); - let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); - let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); - let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); - let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); - let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); - - // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. - let k897 = self.s.m.i32(897); - let k32 = self.s.m.i32(32); - let k31 = self.s.m.i32(31); - let imp = self.s.m.i32(0x0080_0000); - let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); - let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); - // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. - let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); - let shift = self.s.m.select(c, lt1, k1, raw_shift); - let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); - let shift = self.s.m.select(c, gt23, k23, shift); - let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); - let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); - let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); - let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); - let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); - let low31 = self.s.m.i32(0x7FFF_FFFF); - let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); - let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); - let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); - let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); - let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); - let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); - let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); - let sub_inc = self.s.m.select(c, sub_round, k1, k0); - let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); - let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); - - // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). - let k873 = self.s.m.i32(873); - let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); - let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); - let min_bit = self.s.m.select(c, round_min, k1, k0); - let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); - - // Overflow / Inf / NaN: exp64 >= 1151. - let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); - let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); - let inf_bits = self.s.m.i32(0x7F80_0000); - let qnan_bits = self.s.m.i32(0x7FC0_0000); - let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); - let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); - let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); - - // Select final result by exponent range. - let k874 = self.s.m.i32(874); - let k1151 = self.s.m.i32(1151); - let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); - let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); - let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); - let r = self.s.m.select(c, is_over, over_res, norm_res); - let r = self.s.m.select(c, is_sub, sub_res, r); - self.s.m.select(c, is_under, under_res, r) - } - fn join64(&mut self, lo: V, hi: V) -> V { let c = self.cur; let ty = self.s.m.int(64); @@ -7916,69 +7842,6 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, lo, hi) } - /// The bits of the float nearest the double whose dwords are `lo` and - /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN - /// kept (a NaN stays quiet), a result below the smallest normal float - /// signed zero (flushed, as the console's default float mode does). - // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's - // float mode for this instruction is checked. - #[allow(dead_code)] - fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V { - let c = self.cur; - let k = |l: &mut Self, x: u32| l.s.m.i32(x); - let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23)); - let sign_mask = k(self, 0x8000_0000); - let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); - let e = self.s.m.bin(c, Bin::LShr, hi, k20); - let e_mask = k(self, 0x7ff); - let e = self.s.m.bin(c, Bin::And, e, e_mask); - // The top 23 bits of the 52-bit mantissa, and the 29 below them. - let m_mask = k(self, 0x000f_ffff); - let mh = self.s.m.bin(c, Bin::And, hi, m_mask); - let mh = self.s.m.bin(c, Bin::Shl, mh, k3); - let ml = self.s.m.bin(c, Bin::LShr, lo, k29); - let m = self.s.m.bin(c, Bin::Or, mh, ml); - let rest_mask = k(self, 0x1fff_ffff); - let rest = self.s.m.bin(c, Bin::And, lo, rest_mask); - // Round to nearest even: up past half, or at half when odd. - let half = k(self, 0x1000_0000); - let one = k(self, 1); - let above = self.s.m.cmp(c, pred::IUGT, rest, half); - let at = self.s.m.cmp(c, pred::EQ, rest, half); - let odd = self.s.m.bin(c, Bin::And, m, one); - let zero = k(self, 0); - let odd = self.s.m.cmp(c, pred::NE, odd, zero); - let tie = self.s.m.bin(c, Bin::And, at, odd); - let up = self.s.m.bin(c, Bin::Or, above, tie); - let up = self.s.m.select(c, up, one, zero); - // Rebias the exponent (1023 → 127); a carry out of the mantissa - // steps the exponent, up to infinity. - let bias = k(self, 1023 - 127); - let e32 = self.s.m.bin(c, Bin::Sub, e, bias); - let ex = self.s.m.bin(c, Bin::Shl, e32, k23); - let normal = self.s.m.bin(c, Bin::Add, ex, m); - let normal = self.s.m.bin(c, Bin::Add, normal, up); - let normal = self.s.m.bin(c, Bin::Or, normal, sign); - // Exponents out of the float's range (signed, after rebiasing). - let inf = k(self, 0x7f80_0000); - let inf = self.s.m.bin(c, Bin::Or, inf, sign); - let k255 = k(self, 255); - let big = self.s.m.cmp(c, pred::SGE, e32, k255); - let small = self.s.m.cmp(c, pred::SLE, e32, zero); - let r = self.s.m.select(c, big, inf, normal); - let r = self.s.m.select(c, small, sign, r); - // Infinity and NaN (a NaN with any mantissa bit set stays a NaN). - let all = k(self, 0x7ff); - let special = self.s.m.cmp(c, pred::EQ, e, all); - let any = self.s.m.bin(c, Bin::Or, mh, ml); - let any = self.s.m.bin(c, Bin::Or, any, rest); - let nan = self.s.m.cmp(c, pred::NE, any, zero); - let quiet = k(self, 0x0040_0000); - let quiet = self.s.m.select(c, nan, quiet, zero); - let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet); - self.s.m.select(c, special, special_bits, r) - } - /// The low and high dwords of an i64. fn split64(&mut self, x: V) -> (V, V) { let c = self.cur; @@ -9149,7 +9012,13 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { - return Err("the first half of an interpolation"); + // The first half of a pair: its second half interpolates the attribute itself, so + // this half has no value of its own. Where its register is kept, a 16-bit write over + // it reads 0 for the half it keeps (`v_fma_mix*`); read as data, the program is + // translated once more with first halves evaluated as the pairs they start + // ([`with_first_half_pairs`]). (Writing 0 here for every first half changed 59 of + // the title's pixel programs that translated already, and translated none more.) + return Err(FIRST_HALF); }; let name = inst.name(); let (dst, src) = match &inst.fields { @@ -9406,8 +9275,9 @@ impl<'a> Lower<'a> { }; self.s.flags |= flags::BARYCENTRICS; let entry = self.s.entry; + let sig = self.sig_id(true, id); let args = [ - self.s.m.i32(id as u32), + self.s.m.i32(sig), self.s.m.i32(0), self.s.m.i8(col), self.s.m.i8(k), @@ -9852,6 +9722,10 @@ impl<'a> Lower<'a> { return Err("an image result"); }; let f32t = self.s.t.f32; + // The level comes from the coordinates the size divides: an array's layer + // is none of them (DXIL wants it undefined). + let mut at = [fu; 3]; + at[..spatial].copy_from_slice(&cs[..spatial]); for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { let clamped = self.s.m.bool(ch == 0); let lod = self.s.op( @@ -9860,7 +9734,7 @@ impl<'a> Lower<'a> { Attr::ReadOnly, f32t, 81, - &[h, sh, cs[0], cs[1], cs[2], clamped], + &[h, sh, at[0], at[1], at[2], clamped], ); let x = self.as_int(lod); self.write(inst, Reg::V(reg + k as u8), x, guard); @@ -10985,6 +10859,10 @@ impl<'a> Lower<'a> { None }; for (id, col, value, half) in stores { + // (an output a linked pixel program does not read: neither stored nor declared) + if !primitive && self.drop_out.get(id).copied().unwrap_or(false) { + continue; + } let mut x = self.i32_of(value)?; if let Some(high) = half { // An f16 half, declared a 32-bit float on the host. @@ -11012,6 +10890,7 @@ impl<'a> Lower<'a> { } _ => (".i32", x), }; + let sig = if primitive { id as u32 } else { self.sig_id(false, id) }; if let Some(rgb) = ambient.filter(|_| col < 3 && suffix == ".f32") { let c = self.cur; let base = self.s.m.extract(c, rgb, u32::from(col)); @@ -11020,7 +10899,7 @@ impl<'a> Lower<'a> { x = self.s.op(c, "binary.f32", Attr::ReadNone, self.s.t.f32, 35, &[x, fill]); } let mut args = vec![ - self.s.m.i32(id as u32), + self.s.m.i32(sig), self.s.m.i32(0), self.s.m.i8(col), x, @@ -11151,6 +11030,16 @@ impl<'a> Lower<'a> { let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; (c, taken, not_taken) } + // (the paired form: a branch the wave does not take together must be one + // that both lanes of every thread take the same way) + _ if self.twin.is_some() + && !self.x.st.bools.support(when).iter().all( + |a| matches!(a, Atom::Uniform(v) if !self.lane_scalars.contains(v)), + ) => + { + const APART: Why = "a branch the two lanes of a thread may not take together"; + return Err(unsupported(offset, APART)); + } Some((atom, Bool::TRUE, Bool::FALSE)) => { let a = self .atom(atom, self.cur) @@ -11243,6 +11132,7 @@ impl<'a> Lower<'a> { let limit = match super::loop_limit() { LOOP_LIMIT if self.s.pixel => 1 << 7, LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, + LOOP_LIMIT if self.traces => TRACE_LOOP_LIMIT, LOOP_LIMIT => 1 << 12, named => named, }; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 2f413de87d..099f7f7ce3 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -2,7 +2,10 @@ //! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts. //! Compute shaders keep the console's thread-group size; one that depends //! on the lane layout (cross-lane operations) declares the console's wave -//! size (`WaveSize`), so the host device must support it. +//! size (`WaveSize`), so the host device must support it. On a host of +//! 32-lane waves, a wave64 program that no form in 32-lane waves gives as +//! the console runs it takes the paired form instead (`paired`): a host +//! wave for each console wave, two console lanes a thread, half the threads. //! //! What the host binds for a translated shader ([`HostShader`]): //! @@ -85,6 +88,8 @@ mod container; #[cfg(all(test, windows))] mod cube_lod_tests; #[cfg(all(test, windows))] +mod descriptor_tests; +#[cfg(all(test, windows))] mod diff_tests; #[cfg(all(test, windows))] mod helper_lane_tests; @@ -92,8 +97,11 @@ mod helper_lane_tests; mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +mod idiom; +mod link; mod lower; mod own_bits; +mod pops; mod rect; mod sampler; mod shader; @@ -113,6 +121,7 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; +pub use link::{link_mesh, mesh_fits}; pub use sampler::StaticSampler; pub use lower::{host_max_wave, set_host_max_wave}; @@ -332,6 +341,13 @@ pub struct HostShader { } impl HostShader { + /// The fixed wave size declared in the emitted DXIL if it is outside the device's range. + pub fn incompatible_wave_size(&self, supported: &std::ops::RangeInclusive) -> Option { + let container = Container::parse(&self.dxil).ok()?; + container::fixed_wave_size(container.part(FourCC::PSV0)?.data) + .filter(|n| !supported.contains(n)) + } + /// Size of the user-data buffer the shader declares, in dwords (a /// multiple of 4; 0 when it reads none). Root constants must cover it. pub fn user_data_dwords(&self) -> u32 { @@ -417,6 +433,135 @@ pub fn emit( io: &io::Io, res: &resource::Resources, ) -> Result { + if native.stage == HwStage::Ps && !pops::active(native) { + pops::check(p)?; + } + let r = emit_any(c, native, p, st, io, res); + if r.is_ok() && !permutes_outside_sections(p) { + return r; + } + // A lane mask parked in two lanes of a VGPR, one of which holds a single scalar at other + // times, came back as two scalars: once more with the program built so that it comes back + // as the mask it is ([`ir::with_shared_slots`]). The original's error if that does not + // translate either. + if matches!(&r, Err(ShaderError::Unsupported { what, .. }) if *what == "an opaque lane mask") { + let again = ir::with_shared_slots(|| crate::spill::build(native)).and_then(|q| { + let st = structure::structure(&q)?; + let io = io::raise(&q, native)?; + let res = resource::track(&q, &native.layout, native.stage, Some(&st))?; + emit_any(c, native, &q, &st, &io, &res) + }); + if again.is_ok() { + return again; + } + } + // A whole-wave section that a jump splits (two reductions a branch chooses between that + // share their end): once more with each such section in one block + // ([`ir::whole_sections`]), where the simulation follows it. The original's result if that + // does not translate. Tried for a program that translates too where it permutes lanes + // outside the sections followed (the title's water optical depth: `v_permlanex16_b32` + // before the jump): such a permute lowered on its own reads the lanes the host has as they + // are, where the console's section reads every lane, a lane outside the saved mask with + // the reduction's identity. + let mut q = None; + for _ in 0..4 { + match ir::whole_sections(q.as_ref().unwrap_or(p)) { + Some(next) => q = Some(next), + None => break, + } + } + let Some(q) = q else { return r }; + let again = (|| { + let st = structure::structure(&q)?; + let io = io::raise(&q, native)?; + let res = resource::track(&q, &native.layout, native.stage, Some(&st))?; + emit_any(c, native, &q, &st, &io, &res) + })(); + match again { + Ok(shader) => Ok(shader), + Err(_) => r, + } +} + +/// Whether `p` has a `v_permlane16_b32` or `v_permlanex16_b32` that no whole-wave section the +/// simulation follows ([`wave::sections`]) holds. +fn permutes_outside_sections(p: &ir::Program) -> bool { + let permute = |inst: &ir::Inst| matches!(inst.name(), "v_permlane16_b32" | "v_permlanex16_b32"); + p.blocks.iter().enumerate().any(|(b, block)| { + if !block.insts.iter().any(permute) { + return false; + } + let sections = wave::sections(p, b); + let held = |i: usize| sections.iter().any(|(&start, s)| start < i && i < s.end); + block.insts.iter().enumerate().any(|(i, inst)| permute(inst) && !held(i)) + }) +} + +/// [`emit`] of `p` as it is. +fn emit_any( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result { + let r = emit_forms(c, native, p, st, io, res); + // A console wave64 compute program on a host of 32-lane waves that no form above gives + // the host (it still asks for 64-lane waves, or does not translate): once more in the + // paired form, each console wave run by one host wave (`paired`; `VICTORY_WAVE_PAIRS=0` + // turns it off). + let refused = match &r { + Ok((_, wave)) => *wave == Some(64), + Err(e) => matches!(e, ShaderError::Unsupported { .. }), + }; + if refused + && native.stage == HwStage::Cs + && native.wave64 + && lower::host_max_wave() == 32 + && pairs_on() + { + let again = paired(c, native, p, io, res); + if std::env::var_os("VICTORY_WAVE_WHY").is_some() { + match &again { + Ok((_, wave)) => eprintln!("WAVE64-RETRY paired lanes: wave {wave:?}"), + Err(e) => eprintln!("WAVE64-RETRY paired lanes: {e}"), + } + } + if let Ok((shader, _)) = again { + return Ok(shader); + } + } + r.map(|(shader, _)| shader) +} + +/// Whether console wave64 compute programs may take the paired form ([`paired`]): +/// `VICTORY_WAVE_PAIRS=0` turns it off (a test can choose for its own thread). +fn pairs_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_PAIRS.get() { + return on; + } + std::env::var_os("VICTORY_WAVE_PAIRS").is_none_or(|v| v != "0") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`pairs_on`], for its thread only. + static TEST_PAIRS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// [`emit`] in every form but the paired one, with the wave size the result requires of the +/// host; where an approximate form translates the program, the paired form instead if it +/// does. +fn emit_forms( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option), ShaderError> { // (what an earlier program's lowering on this thread left behind) lower::take_needs(); let original = emit_program(c, native, p, st, io, res); @@ -448,12 +593,12 @@ pub fn emit( // for programs still stopped where not every lane runs. let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0"); // Where the wave operations are the allocation idiom - // ([`lower::wave_local`]) that is exact. Other programs are taken + // ([`idiom::wave_local`]) that is exact. Other programs are taken // the same way last of all, each half-wave giving its own results // (approximate: a tile-wide result becomes two half-tile ones); // `VICTORY_WAVE_LOCAL=idiom` refuses those instead. let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom"); - let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) { + let idiom = |p: &ir::Program, st: &structure::Structured| match idiom::wave_local(p, st) { Ok(()) => true, Err((offset, what)) => { if why { @@ -481,7 +626,7 @@ pub fn emit( let again = emit_program(c, native, p, st, io, res); report(name, &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } } @@ -491,6 +636,30 @@ pub fn emit( // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which // has no barrier, stays on. let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); + // Where an approximate form below translates the program, the paired form + // ([`paired`]) is tried first: it runs each console wave as one host wave and gives + // what the console's 64 lanes compute, at no barrier but the entry's; the approximate + // form is kept for a program the paired form does not take. Before, the paired form + // was tried only where no form took the program, and 39 of the title's programs ran + // approximate, each half-wave counting, ORing or electing over its own 32 lanes + // (shadow-mask tiles and traces, temporal resolves, irradiance-cache and fallback + // lighting, light clustering, scattering gathers, decal and fire resolves, the light + // atlas, lens-flare scans). 36 now take the paired form; the other three (lens-flare + // scans) were the allocation idiom with a multiply-add (`idiom::wave_local` now knows it) + // and keep the per-half form, which is exact for them. Only these change: a program + // an approximate form does not take goes on as before, and the paired form stays + // last for it (`emit_any`). (`VICTORY_WAVE_PAIRS=0` turns the paired form off here + // too.) + let exactly = |approximate: Result<(HostShader, Option), ShaderError>| { + if pairs_on() { + let again = paired(c, native, p, io, res); + report("paired lanes, before an approximate form", &again); + if again.is_ok() { + return again; + } + } + approximate + }; // exact first: each host wave on its own where that is exact (the idiom, every // form; no barriers), then the other exact forms; then approximate for exact in [true, false] { @@ -506,7 +675,7 @@ pub fn emit( let again = emit_program(c, native, p, st, io, res); report("without skips, scalars followed", &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } // Still stopped where not every lane runs: the per-lane branches around @@ -523,7 +692,7 @@ pub fn emit( let again = widen(c, native, base, why); report("wave-wide branches", &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } } @@ -541,7 +710,7 @@ pub fn emit( let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); if done(&local) { - return local.map(|(shader, _)| shader); + return if exact { local } else { exactly(local) }; } } } @@ -549,7 +718,7 @@ pub fn emit( let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); if done(&local) { - return local.map(|(shader, _)| shader); + return if exact { local } else { exactly(local) }; } } } @@ -561,14 +730,37 @@ pub fn emit( let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); if done(&local) { - return local.map(|(shader, _)| shader); + return exactly(local); } } } let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); report("local waves (APPROXIMATE, any mask)", &local); if done(&local) { - return local.map(|(shader, _)| shader); + return exactly(local); + } + } + } + // Last of all, with the wave-wide form not asked for: a program that no other form + // takes off 64-lane waves is refused by a 32-lane host, and its dispatches are + // dropped (`sr_tracing:CS_Tiling_Generate_Opaque` and `GpuParticleUpdate:CS_Visibility` + // on an RTX 5060 Ti). The wave-wide form is exact and makes a pipeline for those two, + // so it is tried here, where the only other outcome is the pass not running at all. + // The programs that lost a card with it had another form and never reach this point. + // `VICTORY_WAVE_WIDE=0` leaves them refused, as before. + if !wide_on && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") { + let deep = form(ir::without_skips(p, true)); + let bases = [ + deep.as_ref().map(|f| &f.0), + forms[1].1.as_ref().map(|f| &f.0), + forms[0].1.as_ref().map(|f| &f.0), + Some(p), + ]; + if let Some(base) = bases.into_iter().flatten().next() { + let again = widen(c, native, base, why); + report("wave-wide branches (last resort)", &again); + if done(&again) { + return again; } } } @@ -590,7 +782,16 @@ pub fn emit( } other => other, }; - let original = original.map(|(shader, _)| shader); + // A descriptor joined from what each way into a block brings, where a way brings what no + // heap index stands for (the title's terrain programs pick an immediate sampler that + // clamps or wraps by a uniform condition, each arm setting its own constant): once more + // with that block copied for each way in ([`split_choices`]). + let original = match original { + Err(ShaderError::Unsupported { what, .. }) if what == lower::CHOSEN => { + split_choices(c, native, p, res).unwrap_or(original) + } + other => other, + }; // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. if !matches!(original, Err(ShaderError::Unsupported { .. })) { @@ -604,7 +805,54 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res) +} + +/// `p` translated with the joins of its descriptors chosen by control flow copied for each way +/// in ([`ir::split_joins`]), so that each copy holds one descriptor; again while the choice +/// moves on to a later join (a use further down), a few times at most. `None` unless a form +/// translates. +fn split_choices( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + res: &resource::Resources, +) -> Option), ShaderError>> { + /// The joins where a descriptor is chosen from what a heap index cannot stand for: a way + /// in that brings neither a loaded descriptor nor an earlier join's choice. + fn joins(res: &resource::Resources) -> Vec { + fn walk(s: &resource::Source, out: &mut Vec) { + use resource::Source; + if let Source::Phi { block, args } = s { + let other = |a: &Source| !matches!(a, Source::Loaded { .. } | Source::Phi { .. }); + if args.iter().any(other) && !out.contains(block) { + out.push(*block); + } + for a in args { + walk(a, out); + } + } + } + let mut out = Vec::new(); + for d in &res.descriptors { + walk(&d.source, &mut out); + } + out + } + let mut form = ir::split_joins(p, &joins(res))?; + for _ in 0..4 { + let st = structure::structure(&form).ok()?; + let io = io::raise(&form, native).ok()?; + let res = resource::track(&form, &native.layout, native.stage, Some(&st)).ok()?; + match emit_program(c, native, &form, &st, &io, &res) { + Err(ShaderError::Unsupported { what, .. }) if what == lower::CHOSEN => { + form = ir::split_joins(&form, &joins(&res))?; + } + Ok(done) => return Some(Ok(done)), + Err(_) => return None, + } + } + None } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -688,6 +936,62 @@ fn tiled_lighting_uint_srvs(digest: [u8; 16]) -> &'static [(u8, u32, u32)] { } } +/// `p` (a console wave64 compute program on a host of 32-lane waves) in the paired form +/// ([`lower::with_paired_lanes`]): each console wave run by one host wave of 32 lanes, each +/// thread two of its lanes, with every per-lane branch taken by the whole wave as the console +/// takes it ([`structure::structure_wide`]), so that a host wave's threads go the same way and +/// EXEC stays each lane's guard. The program's barriers are reached by whole host waves where +/// the console's waves reach them; the only barriers added are on entry, before the program, +/// where a group of several console waves numbers its waves (`Lower::wave_base`). A thread +/// group whose console waves are not full would need the lanes past its end kept out of every +/// effect: refused. +/// Descriptors and addresses stay those traced on the lanes' own paths (`res`, as for every +/// other form): the per-lane form rests on a lane that reads a scalar after a join having +/// come the way the wave did, and knowing less of a lane's way the wave-wide form would miss +/// some of them (a sampler set in a skip that only a wave with no lane left for it skips). +fn paired( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option), ShaderError> { + let crate::native::StageIo::Cs(cs) = native.io else { + return Err(ShaderError::Unsupported { + offset: 0, + what: "paired lanes outside compute", + }); + }; + // The ray-tracing structure builder's programs (a spilled user-data table) exchange + // across the halves. The per-half form got that wrong and hung NVIDIA cards + // (Marvisak/VIctory#2711); the paired form keeps both halves in one host wave, as the + // console does. The builder still runs only when `victory-gpu` allows it + // (`VICTORY_BVH_BUILDER=1`) and every one of its pipelines exists. + if cs.threads.iter().product::() % 64 != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "paired lanes in a thread group that does not fill its console waves", + }); + } + // every per-lane branch the wave's; again while that leaves another branch per lane + let mut wide = std::collections::HashSet::new(); + let st = loop { + let st = structure::structure_wide(p, &wide)?; + let lanes: Vec = (0..st.exits.len()) + .filter(|b| !wide.contains(b)) + .filter(|&b| { + matches!(st.exits[b], structure::LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().all(|a| matches!(a, structure::Atom::Uniform(_)))) + }) + .collect(); + if lanes.is_empty() { + break st; + } + wide.extend(lanes); + }; + lower::with_paired_lanes(|| emit_program(c, native, p, &st, io, res)) +} + /// The translated program, and the wave size it requires of the host. fn emit_program( c: &Container, @@ -1863,7 +2167,7 @@ mod atomic_tests { mod barycentric_tests { use super::container::SigElement; use super::*; - use crate::native::{PsInput, StageIo, Usage}; + use crate::native::{PsInput, ResourceType, RootParam, RootType, StageIo, Usage, UsedResource}; /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. const PERSP_CENTER: u32 = 1 << 1; @@ -1900,17 +2204,134 @@ mod barycentric_tests { pixel_with_inputs(words, input_addr, &[element("TEXCOORD", 0, 0)]) } + #[test] + fn pixel_ordering_requires_native_pops_support() { + for marker in [ + 0xb982_0019, // s_setreg_b32 hwreg(POPS_PACKER, 0, 1), s2 + 0x8100_80ef, // s_add_i32 s0, src_pops_exiting_wave_id, 0 + 0xbf90_0007, // s_sendmsg ORDERED_PS_DONE + 0xbf9e_0000, // s_endpgm_ordered_ps_done + ] { + let Err(error) = pixel(&[0xbf80_0000, marker, 0xbf90_0007, 0xbf81_0000], 0) else { + panic!("POPS requires rasterizer ordering"); + }; + assert!( + matches!( + error, + ShaderError::Unsupported { + offset: 4, + what: "primitive-ordered pixel shading (POPS)", + } + ), + "{marker:#x}: {error:?}" + ); + } + } + + #[test] + fn pixel_ordering_checks_the_branch_around_completion() { + let words = [ + 0xb982_0019, // s_setreg_b32 hwreg(POPS_PACKER, 0, 1), s2 + 0xbf06_8000, // s_cmp_eq_u32 s0, 0 + 0xbf85_0002, // s_cbranch_scc1 to the second end + 0xbf90_0007, // s_sendmsg ORDERED_PS_DONE + 0xbf81_0000, // s_endpgm + 0xbf81_0000, // s_endpgm on the edge that bypasses completion + ]; + let Err(error) = pixel(&words, 0) else { + panic!("ordered scope is unsupported"); + }; + assert!(matches!( + error, + ShaderError::Unsupported { + offset: 20, + what: "primitive-ordered pixel shading (POPS) with a path that bypasses explicit completion", + } + )); + } + + #[test] + fn pixel_can_clear_the_inactive_pops_packer() { + let tail = [exp_mrt0(0).as_slice(), &[0xbf81_0000]].concat(); + let baseline = pixel(&tail, 0).unwrap(); + // s_setreg_imm32_b32 hwreg(POPS_PACKER, 0, 3), 0 + let words = [&[0xba80_1019, 0][..], &tail].concat(); + let cleared = pixel(&words, 0).unwrap(); + assert_eq!(cleared.dxil, baseline.dxil); + } + + #[test] + fn active_pops_texture_store_declares_rasterizer_ordering() { + use crate::native::{RootParam, RootType}; + + let words: [u32; 10] = [ + 0xb982_0019, // s_setreg_b32 hwreg(POPS_PACKER, 0, 1), s2 + 0xbe81_0380, // s_mov_b32 s1, 0 (table address high half) + 0xf40c_0200, + 0xfa00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0 + 0x7e00_0280, + 0x7e02_0280, // v0 and v1 = 0 (coordinate) + 0xf020_0f08, + 0x0002_0000, // image_store v[0:3], v[0:1], s[8:15], 2D + 0xbf90_0007, // s_sendmsg ORDERED_PS_DONE + 0xbf81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 1 << 16, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let program = ir::build(&native.code, false, native.vgprs).unwrap(); + let structured = structure::structure(&program).unwrap(); + let resources = resource::track(&program, &native.layout, native.stage, Some(&structured)).unwrap(); + let io = io::raise(&program, &native).unwrap(); + let bytes = crate::dxbc::build(&[]); + let container = Container::parse(&bytes).unwrap(); + let shader = emit(&container, &native, &program, &structured, &io, &resources).unwrap(); + assert_ne!(parts(&shader).0 & 0x1000, 0); + } + pub(super) fn pixel_with_inputs( words: &[u32], input_addr: u32, inputs: &[SigElement], + ) -> Result { + pixel_of(words, input_addr, inputs, false, Vec::new(), Vec::new()) + } + + /// [`pixel_with_inputs`] with the inputs' first row a 16-bit attribute when `fp16` (one + /// value in the low half of each dword), and the root parameters `layout` and used + /// resources `used`. + fn pixel_of( + words: &[u32], + input_addr: u32, + inputs: &[SigElement], + fp16: bool, + layout: Vec, + used: Vec, ) -> Result { let native = NativeProgram { stage: HwStage::Ps, wave64: false, vgprs: 8, - layout: vec![], - used: vec![], + layout, + used, io: StageIo::Ps { inputs: vec![PsInput { usage: Usage::Generic, @@ -1918,7 +2339,7 @@ mod barycentric_tests { mask: 0b1111, attr: 0, flat: false, - fp16: false, + fp16, pack2: false, row2: 0, }], @@ -2007,6 +2428,75 @@ mod barycentric_tests { validate(&shader); } + /// A 16-bit result written over a first interpolation half's register + /// (`v_fma_mixlo_f16` keeps the other half): the second half evaluates the pair, and + /// what the first half leaves in the half kept is no number the code reads. + #[test] + fn a_half_written_over_a_first_interpolation_half_translates() { + let [e0, e1] = exp_mrt0(4); + let words = [ + 0xD742_0002, + 0x0002_0000, // v_interp_p1ll_f16 v2, v0, attr0.x + 0xD75A_0003, + 0x040A_0200, // v_interp_p2_f16 v3, v1, attr0.x, v2 + 0xCC21_0002, + 0x0A01_E503, // v_fma_mixlo_f16 v2, sel_lo(v3), 1.0, 0 + 0x7E08_1702, // v_cvt_f32_f16 v4, v2 + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel_of(&words, PERSP_CENTER, &[element("TEXCOORD", 0, 0)], true, Vec::new(), Vec::new()).unwrap(); + validate(&shader); + } + + /// A level-of-detail query of a 2D array texture: the layer is no coordinate of the + /// level, and DXIL wants it undefined (the validator refused three of the title's + /// deferred programs: "out of bound coord must be undef"). + #[test] + fn a_level_query_of_an_array_leaves_the_layer_out() { + // A table of textures at s0, one of samplers at s1. + let table = |user_data| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: user_data, + }; + let range = |kind, dwords, user_data| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords, + user_data, + slot: user_data, + }; + let [e0, e1] = exp_mrt0(4); + let words = [ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0101, + 0xFA00_0000, // s_load_dwordx8 s[4:11], s[2:3], null + 0xBE8C_0301, // s_mov_b32 s12, s1 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0406, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[12:13], null + 0x7E04_0280, // v_mov_b32 v2, 0 (layer 0) + 0xF180_0328, + 0x0081_0400, // image_get_lod v[4:5], v[0:2], s[4:11], s[16:19] dmask:0x3 2D array + e0, + e1, + 0xBF81_0000, + ]; + let layout = vec![table(0), table(1)]; + let used = vec![range(ResourceType::Srv, 8, 0), range(ResourceType::Sampler, 4, 1)]; + let shader = pixel_of(&words, PERSP_CENTER, &[element("TEXCOORD", 0, 0)], false, layout, used).unwrap(); + validate(&shader); + } + /// Two kinds of barycentrics read directly: one element per mode. #[test] fn two_barycentric_modes_get_two_elements() { @@ -2158,6 +2648,160 @@ mod barycentric_tests { validate(&shader); } + /// The `PSV0` interpolation mode of the element at `row`, `col` with `cols` columns and + /// signature component type `comp` (1 u32, 3 f32). + fn mode_at(shader: &HostShader, row: u8, col: u8, cols: u8, comp: u8) -> u8 { + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + let element = [1, row, 0x40 | col << 4 | cols, 0, comp]; + let at = psv.windows(5).position(|w| w == element).unwrap(); + psv[at + 5] + } + + /// A program of `stage` with the signature parts `isg1`, `osg1` and stage data `io`. + fn translate_with( + stage: HwStage, + words: &[u32], + io: StageIo, + isg1: &[SigElement], + osg1: &[SigElement], + ) -> HostShader { + let native = NativeProgram { + stage, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let isg1 = container::signature(isg1, true); + let osg1 = container::signature(osg1, false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + emit(&c, &native, &p, &st, &io, &res).unwrap() + } + + fn packed(name: &str, kind: u8, comp: u8, row: u32, col: u8, cols: u8) -> SigElement { + SigElement { + col, + cols, + comp, + ..element(name, kind, row) + } + } + + /// VS_Transform_VfxVBuffer_AlphaClip's register 1: a float2 the console declared + /// `nointerpolation` beside a uint2. The float's default, linear, packed two modes into + /// the register (refused by the validator); it takes the uint's. + #[test] + fn a_vertex_output_beside_an_integer_takes_its_mode() { + use crate::native::VsOutput; + let words = [ + 0x7E02_02F2, // v_mov_b32 v1, 1.0 + 0x7E04_0287, // v_mov_b32 v2, 7 + 0xF800_020F, + 0x0202_0101, // exp param0, v1, v1, v2, v2 + 0xF800_08CF, + 0x0101_0101, // exp pos0, v1, v1, v1, v1 done + S_ENDPGM, + ]; + let io = StageIo::Vs { + inputs: vec![], + outputs: vec![VsOutput { + usage: Usage::Generic, + row: 1, + param: 0, + fp16: false, + pack2: false, + }], + }; + let osg1 = [ + element("SV_Position", 3, 0), + packed("TEXCOORD", 0, 9, 1, 0, 2), + SigElement { + index: 14, + ..packed("TEXCOORD", 0, 5, 1, 2, 2) + }, + ]; + let shader = translate_with(HwStage::Vs, &words, io, &[], &osg1); + assert_eq!(mode_at(&shader, 1, 0, 2, 3), 1, "the float2"); + assert_eq!(mode_at(&shader, 1, 2, 2, 1), 1, "the uint2"); + validate(&shader); + } + + /// The pixel side of that register: the program reads the uint2 at its provoking vertex + /// (`v_interp_mov`, constant) and never the float2, whose default would be linear. + #[test] + fn an_unread_pixel_input_takes_the_mode_of_its_register() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC80A_0202, // v_interp_mov_f32 v2, p0, attr0.z + e0, + e1, + S_ENDPGM, + ]; + let io = StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0b1100, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let isg1 = [ + packed("TEXCOORD", 0, 9, 0, 0, 2), + SigElement { + index: 14, + ..packed("TEXCOORD", 0, 5, 0, 2, 2) + }, + ]; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let shader = translate_with(HwStage::Ps, &words, io, &isg1, &[target]); + assert_eq!(mode_at(&shader, 0, 0, 2, 3), 1, "the float2"); + assert_eq!(mode_at(&shader, 0, 2, 2, 1), 1, "the uint2"); + validate(&shader); + } + + /// PS_PropFoliageDeferred_Fire_ExportDepth's register 9: a float the program never reads + /// beside the front face (constant). + #[test] + fn an_unread_pixel_input_beside_the_front_face_is_constant() { + let words = [ + 0x7E04_02F2, // v_mov_b32 v2, 1.0 + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + S_ENDPGM, + ]; + let io = StageIo::Ps { + inputs: vec![], + input_addr: 1 << 12, + db_shader_control: 0, + patches: vec![], + }; + let isg1 = [ + packed("TEXCOORD", 0, 9, 0, 0, 1), + packed("SV_IsFrontFace", 13, 5, 0, 1, 1), + ]; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let shader = translate_with(HwStage::Ps, &words, io, &isg1, &[target]); + assert_eq!(mode_at(&shader, 0, 0, 1, 3), 1, "the float"); + validate(&shader); + } + /// P10 of an attribute the program interpolates is P1 - P0. #[test] fn p10_of_an_interpolated_attribute() { @@ -2179,4 +2823,132 @@ mod barycentric_tests { let words = [0xC812_0000, e0, e1, S_ENDPGM]; assert!(pixel(&words, PERSP_CENTER).is_err()); } + + /// A pixel program with TEXCOORD0..2 in rows 0..2 that reads only attribute 2's z + /// (`v_interp_mov_f32 v2, p0, attr2.z`), translated with `linked` (`link_mesh`'s pixel + /// side). + fn linked_pixel(linked: link::Linked) -> Result { + let [e0, e1] = exp_mrt0(2); + let words = [0xC80A_0A02, e0, e1, S_ENDPGM]; + let input = |row: u8| PsInput { + usage: Usage::Generic, + row, + mask: 0b1111, + attr: row, + flat: true, + fp16: false, + pack2: false, + row2: row, + }; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![input(0), input(1), input(2)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let texcoord = |i: u32| SigElement { + index: i, + ..element("TEXCOORD", 0, i) + }; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let isg1 = container::signature(&[texcoord(0), texcoord(1), texcoord(2)], true); + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage, None)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + link::with_linked(linked, || emit(&c, &native, &p, &st, &io, &res)) + } + + /// `link_mesh`'s pixel side: the inputs the program never reads leave its signature, the + /// one it reads keeps its row and is read as the signature's first element now; leaving + /// out an input it reads is refused. + #[test] + fn a_linked_pixel_program_declares_only_the_inputs_it_reads() { + let rows = |s: &HostShader| -> Vec<(u32, Option)> { + let c = Container::parse(&s.dxil).unwrap(); + let isg1 = signature(c.part(FourCC::ISG1).unwrap().data).unwrap(); + isg1.iter().map(|e| (e.index, e.row)).collect() + }; + let whole = linked_pixel(link::Linked::default()).unwrap(); + assert_eq!(rows(&whole), [(0, Some(0)), (1, Some(1)), (2, Some(2))]); + let unread = vec![("TEXCOORD".to_owned(), 0), ("texcoord".to_owned(), 1)]; + let linked = linked_pixel(link::Linked { + inputs: unread, + outputs: Vec::new(), + }) + .unwrap(); + assert_eq!(rows(&linked), [(2, Some(2))]); + // (dxil.dll checks each read against the element its id names) + validate(&whole); + validate(&linked); + let read = linked_pixel(link::Linked { + inputs: vec![("TEXCOORD".to_owned(), 2)], + outputs: Vec::new(), + }); + assert!( + matches!(&read, Err(ShaderError::Unsupported { what, .. }) if *what == "an input left out of a linked pipeline read"), + "{:?}", + read.err() + ); + } + + /// The other side, for a stage whose outputs a pixel program reads: an output left out is + /// neither stored nor declared, the others keep their rows and are stored to their element + /// as the signature numbers it now (SV_Position 0, TEXCOORD1 1). + #[test] + fn a_linked_stage_stores_only_the_outputs_it_keeps() { + use crate::native::VsOutput; + let words = [ + 0x7E02_02F2, // v_mov_b32 v1, 1.0 + 0x7E04_0287, // v_mov_b32 v2, 7 + 0xF800_020F, + 0x0202_0101, // exp param0, v1, v1, v2, v2 + 0xF800_021F, + 0x0101_0101, // exp param1, v1, v1, v1, v1 + 0xF800_08CF, + 0x0101_0101, // exp pos0, v1, v1, v1, v1 done + S_ENDPGM, + ]; + let output = |row: u8, param: u8| VsOutput { + usage: Usage::Generic, + row, + param, + fp16: false, + pack2: false, + }; + let io = StageIo::Vs { + inputs: vec![], + outputs: vec![output(1, 0), output(2, 1)], + }; + let osg1 = [ + element("SV_Position", 3, 0), + element("TEXCOORD", 0, 1), + SigElement { + index: 1, + ..element("TEXCOORD", 0, 2) + }, + ]; + let linked = link::Linked { + inputs: Vec::new(), + outputs: vec![("TEXCOORD".to_owned(), 0)], + }; + let shader = link::with_linked(linked, || translate_with(HwStage::Vs, &words, io, &[], &osg1)); + let c = Container::parse(&shader.dxil).unwrap(); + let out = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + let rows: Vec<(&str, u32, Option)> = out.iter().map(|e| (e.name.as_str(), e.index, e.row)).collect(); + assert_eq!(rows, [("SV_Position", 0, Some(0)), ("TEXCOORD", 1, Some(2))]); + validate(&shader); + } } diff --git a/crates/victory-shader/src/emit/pops.rs b/crates/victory-shader/src/emit/pops.rs new file mode 100644 index 0000000000..79487c2e64 --- /dev/null +++ b/crates/victory-shader/src/emit/pops.rs @@ -0,0 +1,120 @@ +//! GFX10 primitive-ordered pixel shading (POPS) before host lowering. + +use crate::ShaderError; +use crate::gfx10::{Fields, Operand, Valu}; +use crate::ir::{Exit, Inst, Program}; +use crate::native::{NativeProgram, StageIo}; + +pub(super) const EXITING_WAVE_ID: Operand = Operand::Const(239); +pub(super) const NO_COLLISION: u32 = 1 << 16; +const POPS_PACKER: u16 = 25; +const ORDERED_PS_DONE: u16 = 7; + +pub(super) fn active(native: &NativeProgram) -> bool { + matches!(native.io, StageIo::Ps { db_shader_control, .. } if db_shader_control & (1 << 16) != 0) +} + +/// The collision input follows the user data and the primitive mask. +/// The host orders UAV accesses with ROVs. Seed distinct synthetic wave IDs +/// with overlap clear so native polling does not wait on an AMD wave. +pub(super) fn collision_register(native: &NativeProgram) -> Option { + if !active(native) { + return None; + } + let user = native + .layout + .iter() + .map(|r| u32::from(r.user_data) + r.sgprs) + .max(); + Some(user.unwrap_or(0).clamp(8, 104) as u8 + 1) +} + +pub(super) fn skip_setreg(native: &NativeProgram, inst: &Inst) -> bool { + disables_ordering(inst) || (active(native) && packer_write(inst).is_some()) +} + +fn packer_write(inst: &Inst) -> Option<(u16, &[Operand])> { + match (inst.name(), &inst.fields) { + ( + "s_setreg_b32" | "s_setreg_imm32_b32", + Fields::Sop { imm: Some(imm), src, .. }, + ) if imm & 0x3f == POPS_PACKER => Some((*imm, src)), + _ => None, + } +} + +/// With POPS inactive, explicitly clearing its enable bit changes no shader +/// value. Any other use of the packer or ordered protocol still needs `check`. +pub(super) fn disables_ordering(inst: &Inst) -> bool { + matches!(packer_write(inst), Some((imm, [Operand::Literal(0)])) if imm >> 6 & 0x1f == 0) +} + +fn completes_ordering(inst: &Inst) -> bool { + match (inst.name(), &inst.fields) { + ("s_endpgm_ordered_ps_done", _) => true, + ("s_sendmsg", Fields::Sopp { imm }) => imm & 0xf == ORDERED_PS_DONE, + _ => false, + } +} + +fn uses_ordering(inst: &Inst) -> bool { + if packer_write(inst).is_some() { + return !disables_ordering(inst); + } + completes_ordering(inst) + || match &inst.fields { + Fields::Sop { src, .. } | Fields::Valu(Valu { src, .. }) => src.contains(&EXITING_WAVE_ID), + _ => false, + } +} + +pub(super) fn check(p: &Program) -> Result<(), ShaderError> { + let Some((block, index, inst)) = p.blocks.iter().enumerate().find_map(|(b, block)| { + block + .insts + .iter() + .enumerate() + .find(|(_, inst)| uses_ordering(inst)) + .map(|(i, inst)| (b, i, inst)) + }) else { + return Ok(()); + }; + + // Visit all successors after the packer write to find paths that bypass + // the explicit completion. A rasterizer-ordered view translation needs + // to account for these paths too. + if packer_write(inst).is_some() + && let Some(exit) = exit_before_completion(p, block, index) + { + return Err(ShaderError::Unsupported { + offset: exit, + what: "primitive-ordered pixel shading (POPS) with a path that bypasses explicit completion", + }); + } + Err(ShaderError::Unsupported { + offset: inst.machine.offset, + what: "primitive-ordered pixel shading (POPS)", + }) +} + +fn exit_before_completion(p: &Program, start: usize, first: usize) -> Option { + let mut seen = vec![false; p.blocks.len()]; + let mut pending = vec![(start, first)]; + while let Some((b, index)) = pending.pop() { + // A back edge to the first block enters it from the beginning. + if index == 0 && std::mem::replace(&mut seen[b], true) { + continue; + } + let block = &p.blocks[b]; + if block.insts[index..].iter().any(completes_ordering) { + continue; + } + match block.exit { + Exit::End => { + return Some(block.insts.last().map_or(block.offset, |i| i.machine.offset)); + } + exit => pending.extend(exit.successors().into_iter().map(|b| (b, 0))), + } + } + None +} diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 10878e891b..07ce7cedaa 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -87,6 +87,7 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result u32 { - let r = x as f32; - if r.is_subnormal() || (r == 0.0 && x != 0.0) { - r.to_bits() & 0x8000_0000 - } else { - r.to_bits() - } -} - +/// 64-bit floats, which the title's water volumetrics count their lanes in: `v_add_f64` and +/// `v_mul_f64` of register pairs (one operand negated, one an inline double), +/// `v_cvt_f64_f32`, and `v_cvt_f32_f64` rounding to nearest (1 + 0.75 of a float's last +/// place becomes 1 + one place). The doubles come in s0..s3 (v1..v4): a in v[1:2], b in +/// v[3:4]. #[test] -#[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"] -fn v_cvt_f32_f64_rounds_to_nearest_even() { - // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f) - let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); - let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0 - let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp - let values = [ - 0.0, - -0.0, - 1.0, - -2.5, - std::f64::consts::PI, - 1.0e-3, - 123_456_789.123, - tie_even, - tie_odd, - 1.0 + f64::from(f32::EPSILON) * 0.75, - f64::from(f32::MAX), - f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity - 1.0e300, - -1.0e300, - 1.0e-40, // a float denormal: flushed - -1.0e-300, - f64::from(f32::MIN_POSITIVE), - f64::INFINITY, - f64::NEG_INFINITY, - f64::NAN, +fn f64_arithmetic_and_conversions_are_ieee() { + let to_f32 = vop1(0x0F, 0, vgpr(5)); // v_cvt_f32_f64 v0, v[5:6] + let d = |a: f64, b: f64| { + let (a, b) = (a.to_bits(), b.to_bits()); + [a as u32, (a >> 32) as u32, b as u32, (b >> 32) as u32] + }; + let with = |first: &[u32]| { + let mut w = first.to_vec(); + w.push(to_f32); + w + }; + let add = with(&vop3(0x164, 5, vgpr(1), vgpr(3), 0)); // v_add_f64 v[5:6], v[1:2], v[3:4] + let neg_mul = with(&vop3_mod(0x165, 5, vgpr(1), vgpr(3), 0, 0, 1, 0, false)); // -a * b + let half = with(&vop3(0x164, 5, 240, vgpr(1), 0)); // v_add_f64 v[5:6], 0.5, v[1:2] + let mut wide = vec![vop1(0x10, 5, vgpr(1))]; // v_cvt_f64_f32 v[5:6], v1 + wide.extend(vop3(0x164, 5, vgpr(5), vgpr(5), 0)); // v_add_f64 v[5:6], v[5:6], v[5:6] + wide.push(to_f32); + let near = 1.0 + 3.0 * 2f64.powi(-25); + let cases: [(&[u32], [u32; 4], f32); 6] = [ + (&add, d(1.5, 2.25), 3.75), + (&add, d(near, 0.0), f32::from_bits(0x3F80_0001)), + (&add, d(1e300, -1e300), 0.0), + (&neg_mul, d(3.0, 0.5), -1.5), + (&half, d(2.0, 0.0), 2.5), + (&wide, [1.25f32.to_bits(), 0, 0, 0], 2.5), ]; - let inputs: Vec<[u32; 4]> = values - .iter() - .map(|x| { - let b = x.to_bits(); - [b as u32, (b >> 32) as u32, 0, 0] - }) - .collect(); - run_cases(&shader, &inputs, |backend, i, _, got| { - let x = values[i]; - if x.is_nan() { - assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); - return; - } - let want = cvt_f32_f64_reference(x); - assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); - }); + for (body, inputs, want) in cases { + let shader = build_valu_cs(body); + run_cases(&shader, &[inputs], |backend, _, _, got| { + assert_eq!(f32::from_bits(got), want, "{backend}: {body:08x?} on {inputs:08x?}"); + }); + } } /// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads @@ -1379,6 +1360,81 @@ fn ds_min_max_f32_are_atomic_across_waves() { } } +const DS_ADD_RTN_U32: u8 = 0x20; +const DS_SUB_RTN_U32: u8 = 0x21; + +/// `buffer_store_dword v, v, s[8:11], 0 offen offset:`. +const fn store_at(data: u8, addr: u8, offset: u16) -> [u32; 2] { + [0xE070_1000 | offset as u32, 0x8002_0000 | (data as u32) << 8 | addr as u32] +} + +/// One console wave of 32 threads takes slots off an LDS counter as the title's +/// `weatherParticle:CS_BeginUpdate` does: `v_sub_nc_u32 v7, 0, v6` then `ds_add_rtn_u32` of +/// that negation (HLSL's `InterlockedAdd(shared, -x)`), and the same with `ds_sub_rtn_u32`. +/// NVIDIA's compiler refuses either as an atomic on group-shared memory (`E_OUTOFMEMORY` at +/// pipeline creation, RTX 5090): the translation's compare-exchange loop gets a pipeline. +/// Thread t takes t ^ s1 (s1 = 0x100, unknown to any compiler: the negation stays one) from +/// 1,000,000; each must get the counter as it stood before its own subtraction, in some +/// order of the threads, and the counter must end at the total. +#[test] +fn lds_subtractions_get_a_pipeline_and_stay_atomic() { + const INIT: u32 = 1_000_000; + const S1: u32 = 0x100; + for (op, negate, what) in [(DS_ADD_RTN_U32, true, "ds_add_rtn_u32 of 0 - x"), (DS_SUB_RTN_U32, false, "ds_sub_rtn_u32")] { + let mut body = vec![vop1(0x001, 5, 0x80)]; // v_mov_b32 v5, 0: the counter's address + body.extend(ds(DS_WRITE_B32, 0, 5, 1)); // the counter = s0 (every thread the same) + body.push(S_BARRIER); + body.push(vop2(0x1D, 6, sgpr(1), 0)); // v_xor_b32 v6, s1, v0: x = t ^ s1 + body.push(vop2(0x26, 7, 0x80, 6)); // v_sub_nc_u32 v7, 0, v6: -x + body.extend(ds(op, 2, 5, if negate { 7 } else { 6 })); // v2: the counter found + body.push(vop2(0x1A, 3, 0x82, 0)); // v_lshlrev_b32 v3, 2, v0 + body.extend(store_at(2, 3, 4)); // dword t + 1: what thread t got + body.push(S_BARRIER); + body.extend(ds(DS_READ_B32, 0, 5, 0)); // dword 0: the counter at the end + let shader = build_cs(&body, 32, 512); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + // (the refusal this is about: a pipeline must be made) + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{what}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = [INIT, S1][d as usize]; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(33)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{what}: dispatch failed: {e}")); + let got = &out[0]; + // In the order the subtractions took effect (largest counter first), each thread + // found what the one before left. + let mut order: Vec<(u32, u32)> = (0..32).map(|t| (got[t as usize + 1], t ^ S1)).collect(); + order.sort_unstable_by(|a, b| b.cmp(a)); + let mut counter = INIT; + for (old, x) in order { + assert_eq!(old, counter, "{what}: the thread taking {x} found {old}, the counter stood at {counter}"); + counter -= x; + } + assert_eq!(got[0], counter, "{what}: the counter at the end"); + assert_eq!(counter, INIT - (0..32).map(|t| t ^ S1).sum::()); + } + eprintln!("ran on the hardware device: LDS subtractions as compare-exchange loops, atomic"); +} + #[test] fn v_cmp_class_f16_matches_rdna2() { // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 1d7a91b7f4..df6013422b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -112,17 +112,120 @@ pub(crate) enum Sym { ident: u32, lanes: u64, }, - /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over - /// `lanes` of `mask ? f64(lo, hi) : 0.0`. - Red64F { + /// The low (`high` clear) or high dword of the 64-bit float sum (`v_add_f64`) over + /// `lanes` of `mask ? (lo, hi) : 0.0`, the double whose dwords are `lo` and `hi`. + Half64 { + high: bool, lo: Value, hi: Value, mask: Value, lanes: u64, - high: bool, }, } +/// Both dwords of a 64-bit float in one lane, as [`add64`] takes them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Pair { + /// +0.0, the sum's identity. + Zero, + /// The sum over `lanes` of `mask ? (lo, hi) : 0.0` (one lane's own value when `lanes` is + /// that lane). + Sum { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + }, +} + +impl Pair { + /// The pair a lane's two dwords hold, if they are one. + fn of(lo: Sym, hi: Sym) -> Option { + match (lo, hi) { + (Sym::K(0), Sym::K(0)) => Some(Pair::Zero), + // a lane's own masked value: both dwords picked by one mask, beside +0.0 + ( + Sym::Red { + op: None, + src: lo, + mask, + ident: 0, + lanes, + }, + Sym::Red { + op: None, + src: hi, + mask: m, + ident: 0, + lanes: l, + }, + ) if (mask, lanes) == (m, l) => Some(Pair::Sum { lo, hi, mask, lanes }), + ( + Sym::Half64 { + high: false, + lo, + hi, + mask, + lanes, + }, + Sym::Half64 { + high: true, + lo: l2, + hi: h2, + mask: m2, + lanes: n2, + }, + ) if (lo, hi, mask, lanes) == (l2, h2, m2, n2) => Some(Pair::Sum { lo, hi, mask, lanes }), + _ => None, + } + } + + /// The lane's two dwords. + fn syms(self) -> (Sym, Sym) { + match self { + Pair::Zero => (Sym::K(0), Sym::K(0)), + Pair::Sum { lo, hi, mask, lanes } => { + let half = |high| Sym::Half64 { + high, + lo, + hi, + mask, + lanes, + }; + (half(false), half(true)) + } + } + } +} + +/// The 64-bit float sum of two pairs: of the same terms over lanes that do not meet, or one +/// of them +0.0. +fn add64(a: Pair, b: Pair) -> Option { + match (a, b) { + (Pair::Zero, x) | (x, Pair::Zero) => Some(x), + ( + Pair::Sum { + lo, + hi, + mask, + lanes: la, + }, + Pair::Sum { + lo: l2, + hi: h2, + mask: m2, + lanes: lb, + }, + ) if (lo, hi, mask) == (l2, h2, m2) && la & lb == 0 => Some(Pair::Sum { + lo, + hi, + mask, + lanes: la | lb, + }), + _ => None, + } +} + /// What a value a section leaves holds in every lane. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Shape { @@ -132,10 +235,16 @@ pub(crate) enum Shape { Masked(Value, Value, u32), /// `op` over every lane. Active(Op, Value, Value, u32), - /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. - ActiveF64(Value, Value, Value, bool), /// `op` over the lanes below (`inclusive`: and including) each lane. Prefix(Op, Value, Value, u32, bool), + /// The low (`high` clear) or high dword of the 64-bit float sum over every lane of the + /// lane's own `mask ? (lo, hi) : 0.0`. + Sum64 { + high: bool, + lo: Value, + hi: Value, + mask: Value, + }, } /// The section starting at instruction `start` of a block: its restore @@ -233,7 +342,8 @@ fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> { fn combine(op: Op, a: Sym, b: Sym) -> Sym { match (a, b) { - (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x, + // (a dword of a 64-bit sum is no 32-bit term: not even a float's identity keeps it) + (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) && !matches!(x, Sym::Half64 { .. }) => x, ( Sym::Red { op: oa, @@ -316,6 +426,9 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { { masked.push(w); } + // A scalar copied: what its source holds (a dword of a 64-bit sum read from a lane + // and moved to the register the code reads it from, `s_mov_b32 s20, s18` after + // `v_readlane_b32 s18, v2, 0`; a value from before the section; a constant). if name == "s_mov_b32" && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) && *dc != NULL @@ -331,6 +444,19 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { }; uni.insert(w, sym); } + // both dwords of a 64-bit sum moved at once + if name == "s_mov_b64" + && inst.reads.len() == inst.writes.len() + && inst + .reads + .iter() + .all(|r| matches!(r.0, Reg::S(_)) && matches!(uni.get(&r.1), Some(Sym::Half64 { .. }))) + { + for (w, r) in inst.writes.iter().zip(&inst.reads) { + let s = uni[&r.1]; + uni.insert(w.1, s); + } + } for &(_, w) in &inst.writes { uni.entry(w).or_insert(Sym::Unknown); } @@ -365,6 +491,50 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } }; let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some(); + if name == "v_add_f64" { + // Each lane adds its two pairs of dwords; a sum the simulation does not follow + // leaves both dwords unknown. + let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { + continue; + }; + let pair = |op: Option<&Operand>| -> Vec> { + let (lo, hi) = match op { + Some(&Operand::Vector { reg, .. }) => ( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes(&Operand::Vector { reg: reg + 1, dwords: 1 }, &vec, &uni), + ), + Some(&Operand::Scalar { code, .. }) if code != NULL => ( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes(&Operand::Scalar { code: code + 1, dwords: 1 }, &vec, &uni), + ), + Some(&Operand::Const(128)) => (vec![Sym::K(0); wave as usize], vec![Sym::K(0); wave as usize]), + _ => return vec![None; wave as usize], + }; + lo.into_iter().zip(hi).map(|(l, h)| Pair::of(l, h)).collect() + }; + let (a, b) = (pair(v.src.first()), pair(v.src.get(1))); + let follows = !modifiers && v.dpp.is_none(); + let old = |r: u8| lanes(&Operand::Vector { reg: r, dwords: 1 }, &vec, &uni); + let (old_lo, old_hi) = (old(dreg), old(dreg + 1)); + let (mut lo, mut hi) = (Vec::with_capacity(wave as usize), Vec::with_capacity(wave as usize)); + for l in 0..wave as usize { + let sum = match (a[l], b[l]) { + (Some(x), Some(y)) if follows => add64(x, y), + _ => None, + }; + let (sl, sh) = sum.map_or((Sym::Unknown, Sym::Unknown), Pair::syms); + let writes = exec >> l & 1 != 0; + lo.push(if writes { sl } else { old_lo[l] }); + hi.push(if writes { sh } else { old_hi[l] }); + } + if let Some(w) = inst.write(Reg::V(dreg)) { + vec.insert(w, lo); + } + if let Some(w) = inst.write(Reg::V(dreg + 1)) { + vec.insert(w, hi); + } + continue; + } if name == "v_readlane_b32" { let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) = (v.dst, v.src.first(), v.src.get(1)) @@ -385,130 +555,6 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } continue; } - if name == "v_add_f64" - && !modifiers - && v.dpp.is_none() - && let Some(Operand::Vector { reg: dreg, .. }) = v.dst - && let (Some(dst_lo), Some(dst_hi)) = - (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) - { - let pair_lanes = |op: Option<&Operand>| -> Option<(Vec, Vec)> { - match *op? { - Operand::Vector { reg, .. } => Some(( - lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), - lanes( - &Operand::Vector { - reg: reg + 1, - dwords: 1, - }, - &vec, - &uni, - ), - )), - Operand::Scalar { code, .. } if code != NULL => Some(( - lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), - lanes( - &Operand::Scalar { - code: code + 1, - dwords: 1, - }, - &vec, - &uni, - ), - )), - _ => None, - } - }; - let old_lo = lanes( - &Operand::Vector { - reg: dreg, - dwords: 1, - }, - &vec, - &uni, - ); - let old_hi = lanes( - &Operand::Vector { - reg: dreg + 1, - dwords: 1, - }, - &vec, - &uni, - ); - let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { - match (lo_s, hi_s) { - ( - Sym::Red { - op: None, - src: lo, - mask: ml, - ident: 0, - lanes: ll, - }, - Sym::Red { - op: None, - src: hi, - mask: mh, - ident: 0, - lanes: lh, - }, - ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), - ( - Sym::Red64F { - lo: lo1, - hi: hi1, - mask: m1, - lanes: l1, - high: false, - }, - Sym::Red64F { - lo: lo2, - hi: hi2, - mask: m2, - lanes: l2, - high: true, - }, - ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), - _ => None, - } - }; - let mut out_lo = vec![Sym::Unknown; wave as usize]; - let mut out_hi = vec![Sym::Unknown; wave as usize]; - if let (Some((alo, ahi)), Some((blo, bhi))) = - (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) - { - for l in 0..wave as usize { - let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { - (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) - if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => - { - ( - Sym::Red64F { - lo: lo1, - hi: hi1, - mask: m1, - lanes: la | lb, - high: false, - }, - Sym::Red64F { - lo: lo1, - hi: hi1, - mask: m1, - lanes: la | lb, - high: true, - }, - ) - } - _ => (Sym::Unknown, Sym::Unknown), - }; - out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; - out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; - } - } - vec.insert(dst_lo, out_lo); - vec.insert(dst_hi, out_hi); - continue; - } let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { for &(_, w) in &inst.writes { uni.insert(w, Sym::Unknown); @@ -710,13 +756,13 @@ fn shapes( ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), - Sym::Red64F { + Sym::Half64 { + high, lo, hi, mask, lanes, - high, - } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), + } if lanes == all => Some(Shape::Sum64 { high, lo, hi, mask }), _ => None, }; for (v, s) in uni { @@ -760,13 +806,13 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), - Sym::Red64F { + Sym::Half64 { + high, lo, hi, mask, lanes, - high, - } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), + } if lanes == all => Some(Shape::Sum64 { high, lo, hi, mask }), _ => None, }; } diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 6ecf89b652..881f09c330 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -1,7 +1,10 @@ //! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a //! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`]) -//! so that the two host waves can exchange their halves inside it. Lowered, validated by -//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32. +//! so that the two host waves can exchange their halves inside it; and programs in the +//! paired form (one host wave for each console wave, two lanes a thread: `super::paired`), +//! whose LDS, lane reads and masks cross the halves without barriers, checked against what +//! the console's 64 lanes compute. Lowered, validated by `dxil.dll` when present, and run on +//! the host GPU when it takes waves of 32 (WARP's are 4 lanes: neither form runs there). use std::collections::HashSet; @@ -46,6 +49,11 @@ fn native(body: &[u32]) -> NativeProgram { /// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads. fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { + native_with(body, wave64, threads, 0) +} + +/// [`native_of`] with `lds` bytes of LDS (512-byte granules). +fn native_with(body: &[u32], wave64: bool, threads: u32, lds: u32) -> NativeProgram { let mut words = vec![ 0xBE85_0380, // s_mov_b32 s5, 0 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, @@ -86,7 +94,7 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { slot: 1, }], io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + rsrc2: 5 << 1 | lds.div_ceil(512) << 15, // 5 user SGPRs: s0..s4 threads: [threads, 1, 1], }), code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), @@ -226,10 +234,11 @@ fn copied_mask_keeps_both_numeric_words_inside_a_lane_branch() { eprintln!("four native wave64 low/high word readbacks passed"); } -#[test] -fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { - // thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd - // mantissas, so that additions round); all of them store the wave's sum +/// 64 threads in one console wave: thread t holds the 16-bit float with bits 0x3C00 + 37 t +/// (1.0 and up, with odd mantissas, so that additions round); all of them store the wave's sum +/// (`WaveActiveSum` of halves) to dword 0. With the console's sum (its tree) and the terms' +/// sum added in a row, which differs from it. +fn half_sum_program() -> (NativeProgram, u16, u16) { let mut words = vec![ 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 @@ -245,14 +254,6 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { 0x38 << 26 | 0x1C << 18, 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 ]); - let native = native(&words); - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); - let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - let mut copy = shader.dxil.clone(); - v.validate(&mut copy).expect("DXIL validation failed"); - } // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits // (to nearest, ties to even); values here are normal numbers let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); @@ -269,7 +270,20 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); } let in_a_row = terms.iter().copied().reduce(add).unwrap(); - assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order"); + (native(&words), tree[0], in_a_row) +} + +#[test] +fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { + let (native, tree, in_a_row) = half_sum_program(); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + assert_ne!(tree, in_a_row, "these terms tell the tree from another order"); let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let Ok(host) = Host::new(false) else { eprintln!("no SM 6.6 hardware device; not run"); @@ -296,8 +310,8 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { ) .unwrap_or_else(|e| panic!("dispatch failed: {e}")); // (the high half is lane 0's term's: zero) - assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]); - eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); + assert_eq!(out[0][0], u32::from(tree), "tree {tree:#x}, in a row {in_a_row:#x}"); + eprintln!("ran on the hardware device: the sum {tree:#x} of the console's tree"); } /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 @@ -572,3 +586,715 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() } eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); } + +/// The console's prefix over per-wave totals (a 512-thread scan): each console wave past the +/// first sums the totals of the waves before it from LDS in a loop that only its lanes run, +/// and `v_readfirstlane` copies the running sum, made from scalars and LDS alone, back into an +/// SGPR. Every lane holds the same sum there, so each host wave reads its own first lane: no +/// exchange, which could not meet inside the loop. +#[test] +fn a_first_lane_read_of_a_scalar_built_sum_inside_a_lane_loop_takes_the_host_waves_own() { + let mut native = native_of( + &[ + 0x2C0E_0086, // v_lshrrev_b32 v7, 6, v0 (the console wave of the thread) + 0x7E10_0280, // v_mov_b32 v8, 0 + 0xBE80_047E, // s_mov_b64 s[0:1], exec + 0x7DAA_0E80, // v_cmpx_ne_u32 exec, 0, v7 + 0xBF88_0014, // s_cbranch_execz past the loop + 0xBE82_047E, // s_mov_b64 s[2:3], exec + 0xBE86_047E, // s_mov_b64 s[6:7], exec + 0xBE92_0380, // s_mov_b32 s18, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xBF82_0003, // s_branch to the body + 0xBF80_0000, // (padding) + 0x87FE_0610, // s_and_b64 exec, s[16:17], s[6:7] + 0x7E22_0508, // v_readfirstlane_b32 s17, v8 + 0x8F10_8212, // s_lshl_b32 s16, s18, 2 + 0x8112_8112, // s_add_i32 s18, s18, 1 + 0x7E10_0210, // v_mov_b32 v8, s16 + 0xD8D8_0000, 0x0800_0008, // ds_read_b32 v8, v8 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x4A10_1011, // v_add_nc_u32 v8, s17, v8 + 0xBE90_047E, // s_mov_b64 s[16:17], exec + 0x7DA4_0E12, // v_cmpx_eq_u32 exec, s18, v7 + 0xBF80_0000, // s_nop 0 + 0x8A86_7E06, // s_andn2_b64 s[6:7], s[6:7], exec + 0xBF85_FFF2, // s_cbranch_scc1 back + 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + 0x7E0C_0308, // v_mov_b32 v6, v8 + 0xE070_0000, 0x0002_0600, // buffer_store_dword v6, v0, s[8:11], s0 + ], + true, + 512, + ); + if let StageIo::Cs(cs) = &mut native.io { + cs.rsrc2 |= 1 << 15; // 128 dwords of LDS + } + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + lower::take_needs(); + let shader = lowered(&native, &p, &HashSet::new()).expect("a scalar-built first-lane read"); + assert!(lower::take_needs().is_empty()); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } +} + +/// `ds_add_u32` of a negated value (and `ds_sub_u32`): host compilers turn an atomic addition +/// of `0 - x` on group-shared memory into a subtraction DXIL does not have, and NVIDIA's +/// driver and WARP then refuse the pipeline (E_OUTOFMEMORY; compute 7f61193d2c0e5f22). The +/// lowering makes it a compare-exchange loop instead. 32 threads each take 1 from 64. +#[test] +fn an_lds_addition_of_a_negated_value_is_a_compare_exchange_loop() { + for (atomic, name) in [(0xD800_0000u32, "ds_add_u32 of 0 - 1"), (0xD804_0000, "ds_sub_u32 of 0 - 1 (adds)")] { + let words = [ + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x7E08_02C0, // v_mov_b32 v4, 64 + 0xD834_0000, 0x0000_0403, // ds_write_b32 v3, v4 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBF8A_0000, // s_barrier + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0x4C02_0A80, // v_sub_nc_u32 v1, 0, v5 + atomic, 0x0000_0103, // ds_add_u32 / ds_sub_u32 v3, v1 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBF8A_0000, // s_barrier + 0xD8D8_0000, 0x0600_0003, // ds_read_b32 v6, v3 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16 | 6 << 8, // buffer_store_dword v6, off, s[8:11], 0 + ]; + let mut native = native_of(&words, false, 32); + if let StageIo::Cs(cs) = &mut native.io { + cs.rsrc2 |= 1 << 15; // 128 dwords of LDS + } + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_for_width(&native, &p, &HashSet::new(), 32).expect(name); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = on_the_card(&shader, [0, 0]) else { return }; + // ds_sub of -1 adds 1 per thread + let expected = if name.starts_with("ds_add") { 32 } else { 96 }; + assert_eq!(got, expected, "{name}"); + } +} + +/// One console wave of 64 threads, thread t holding t + 1. A branch on s0 (the wave's) picks +/// `WaveActiveMax` (s0 not 0) or `WaveActiveMin`, and the two reductions share their end: +/// each arm saves EXEC and reduces up to the read of lane 32, the join reads lane 0 and +/// restores EXEC (`deferred_tiled:CS_WaterTransmittanceOpticalDepthProcessing`, 0xb3c-0xbe0). +/// Neither block holds a whole section; `v_permlanex16_b32` lowered on its own reads the lanes +/// the host has, so the translation is the one with the join's code in each arm +/// ([`ir::whole_sections`]), where each section is whole. +#[test] +fn two_reductions_that_share_their_end_translate_as_two_sections() { + // an arm: save EXEC, the identity `init`, then `op` over the wave up to lane 32's read + let arm = |init: u32, op: u32| { + let mut w = vec![ + 0xBE8C_25C1, // s_or_saveexec_b64 s[12:13], -1 + 0x7E04_02FF, + init, // v_mov_b32 v2, init + 0xD501_0002, + 0x0032_0902, // v_cndmask_b32 v2, v2, v4, s[12:13] + ]; + for dpp in [0xDE54_C102, 0x9360_1202, 0x0009_2402] { + w.extend([op << 25 | 0x0004_04E9, dpp]); // v__f32 v2, v2, v2 dpp8:[...] + } + w.extend([ + op << 25 | 0x0004_04FA, + 0xFF09_4002, // v__f32 v2, v2, v2 row_mirror bound_ctrl:1 + 0xD778_0003, + 0x0201_0102, // v_permlanex16_b32 v3, v2, 0, 0 + op << 25 | 0x0004_0503, // v__f32 v2, v3, v2 + 0xD760_000E, + 0x0001_4102, // v_readlane_b32 s14, v2, 32 + op << 25 | 0x0004_040E, // v__f32 v2, s14, v2 + ]); + w + }; + let mut words = vec![ + 0x7E08_0D00, // v_cvt_f32_u32 v4, v0 + 0x0608_08F2, // v_add_f32 v4, 1.0, v4 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0014, // s_cbranch_scc1 to the minimum + ]; + words.extend(arm(0xFF80_0000, 0x10)); // the maximum from -inf + words.push(0xBF82_0013); // s_branch to the join + words.extend(arm(0x7F80_0000, 0x0F)); // the minimum from +inf + words.extend([ + 0xD760_000E, + 0x0001_0102, // v_readlane_b32 s14, v2, 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x7E00_020E, // v_mov_b32 v0, s14 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + // the section starts in the arms and ends in the join; afterwards each block holds whole ones + let sections = |p: &ir::Program| (0..p.blocks.len()).map(|b| super::wave::sections(p, b).len()).sum::(); + assert_eq!(sections(&p), 0); + let q = ir::whole_sections(&p).expect("sections to join"); + assert_eq!(sections(&q), 2); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let st_q = structure::structure(&q).expect("structure"); + let io_q = io::raise(&q, &native).expect("io::raise"); + let res_q = resource::track(&q, &native.layout, native.stage, Some(&st_q)).expect("track"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let joined = super::emit_any(&c, &native, &q, &st_q, &io_q, &res_q); + let shader = super::emit(&c, &native, &p, &st, &io, &res); + lower::TEST_HOST_WAVE.set(was); + let shader = shader.expect("emit"); + let joined = joined.expect("the joined sections"); + assert!(shader.dxil == joined.dxil, "the split sections' translation was taken"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (s0, expected) in [(1u32, 64.0f32), (0, 1.0)] { + let Some(got) = on_the_card(&shader, [s0, 0]) else { return }; + assert_eq!(f32::from_bits(got), expected, "s0 = {s0}"); + } + eprintln!("ran on the hardware device: the maximum or the minimum over the console's 64 lanes"); +} + +/// One console wave of 64 threads summing doubles over the lanes below s0 as the title's +/// water volumetrics count their lanes (`water_shading:CS_TransmissionVolumetrics`, +/// 0x5c4-0x68c): `v_add_f64` of each dword pair moved by DPP, `v_permlanex16` and lane 32, +/// the sum moved to s[20:21] and taken back as a float (`v_cvt_f32_f64`). The terms here are +/// the thread index as a double (`v_cvt_f64_f32`), so the sum is s0 (s0 - 1) / 2. +#[test] +fn a_wave_sum_of_doubles_is_the_consoles() { + let mut words = vec![ + 0x7E3E_0D00, // v_cvt_f32_u32 v31, v0 + 0x7E3A_211F, // v_cvt_f64_f32 v[29:30], v31 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_046A, // s_mov_b64 s[12:13], vcc + 0xBE90_25C1, // s_or_saveexec_b64 s[16:17], -1 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x8792_100C, // s_and_b64 s[18:19], s[12:13], s[16:17] + 0xD501_0002, + 0x004A_3B02, // v_cndmask_b32 v2, v2, v29, s[18:19] + 0xD501_0003, + 0x004A_3D03, // v_cndmask_b32 v3, v3, v30, s[18:19] + ]; + // v_mov_b32 v4, v2 / v5, v3 with each DPP pattern, then v_add_f64 v[2:3], v[4:5], v[2:3] + for (code, dpp) in [(0xE9, 0xDE54_C100), (0xE9, 0x9360_1200), (0xE9, 0x0009_2400), (0xFA, 0xFF09_4000)] { + words.extend([0x7E08_0200 | code, dpp | 2, 0x7E0A_0200 | code, dpp | 3, 0xD564_0002, 0x0002_0504]); + } + words.extend([ + 0xD778_0004, + 0x0201_0102, // v_permlanex16_b32 v4, v2, 0, 0 + 0xD778_0005, + 0x0201_0103, // v_permlanex16_b32 v5, v3, 0, 0 + 0xD564_0002, + 0x0002_0504, // v_add_f64 v[2:3], v[4:5], v[2:3] + 0xD760_0012, + 0x0001_4102, // v_readlane_b32 s18, v2, 32 + 0xD760_0013, + 0x0001_4103, // v_readlane_b32 s19, v3, 32 + 0xD564_0002, + 0x0002_0412, // v_add_f64 v[2:3], s[18:19], v[2:3] + 0xD760_0012, + 0x0001_0102, // v_readlane_b32 s18, v2, 0 + 0xD760_0013, + 0x0001_0103, // v_readlane_b32 s19, v3, 0 + 0xBE94_0312, // s_mov_b32 s20, s18 + 0xBE95_0313, // s_mov_b32 s21, s19 + 0xBEFE_0410, // s_mov_b64 exec, s[16:17] + 0x7E00_1E14, // v_cvt_f32_f64 v0, s[20:21] + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + // the section leaves the sum's two dwords in s20 and s21 + let block = (0..p.blocks.len()).find(|&b| !super::wave::sections(&p, b).is_empty()).expect("a section"); + let sums = super::wave::sections(&p, block) + .into_values() + .flat_map(|s| s.shapes.into_values()) + .filter(|s| matches!(s, super::wave::Shape::Sum64 { .. })) + .count(); + assert!(sums >= 2, "{sums} dwords of 64-bit sums"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let shader = super::emit(&c, &native, &p, &st, &io, &res); + lower::TEST_HOST_WAVE.set(was); + let shader = shader.expect("emit"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for s0 in [64u32, 40, 33, 1, 0] { + let Some(got) = on_the_card(&shader, [s0, 0]) else { return }; + let want = (s0 * s0.saturating_sub(1) / 2) as f32; + assert_eq!(f32::from_bits(got), want, "the lanes below {s0}"); + } + eprintln!("ran on the hardware device: the sums of doubles over the console's 64 lanes"); +} + +// ---- the paired form: a host wave of 32 for each console wave, two lanes a thread ---- + +// Operands as the hardware numbers them: SGPR n is n, VCC 106 (its high dword 107), EXEC 126, +// an inline integer n 128 + n (-1: 193), a literal (the next dword) 255, VGPR n 256 + n. +const VCC: u32 = 106; +const EXEC: u32 = 126; +const LIT: u32 = 255; + +const fn v(n: u32) -> u32 { + 256 + n +} + +const fn k(n: u32) -> u32 { + 128 + n +} + +const fn sop1(op: u32, sdst: u32, src0: u32) -> u32 { + 0xBE80_0000 | sdst << 16 | op << 8 | src0 +} + +const fn sop2(op: u32, sdst: u32, src0: u32, src1: u32) -> u32 { + 0x8000_0000 | op << 23 | sdst << 16 | src1 << 8 | src0 +} + +/// A branch by `imm` dwords from the next instruction (or `s_barrier`, `imm` 0). +const fn sopp(op: u32, imm: i16) -> u32 { + 0xBF80_0000 | op << 16 | imm as u16 as u32 +} + +const fn vop1(op: u32, vdst: u32, src0: u32) -> u32 { + 0x7E00_0000 | vdst << 17 | op << 9 | src0 +} + +const fn vop2(op: u32, vdst: u32, src0: u32, vsrc1: u32) -> u32 { + op << 25 | vdst << 17 | vsrc1 << 9 | src0 +} + +const fn vopc(op: u32, src0: u32, vsrc1: u32) -> u32 { + 0x7C00_0000 | op << 17 | vsrc1 << 9 | src0 +} + +const fn vop3(op: u32, dst: u32, src0: u32, src1: u32) -> [u32; 2] { + [0xD400_0000 | op << 16 | dst, src0 | src1 << 9] +} + +const fn ds(op: u32, vdst: u32, addr: u32, data: u32, offset: u32) -> [u32; 2] { + [0xD800_0000 | op << 18 | offset, vdst << 24 | data << 8 | addr] +} + +/// `buffer_store_dword v, v, s[8:11], 0 offen offset:` +const fn store(data: u32, addr: u32, offset: u32) -> [u32; 2] { + [0xE070_1000 | offset, 0x8002_0000 | data << 8 | addr] +} + +/// `v` stored as each thread's dwords of the UAV, the thread's index (v0) times 16 on. +fn stores(regs: [u32; 4]) -> Vec { + let mut w = vec![vop2(0x1A, 15, k(4), 0)]; // v_lshlrev_b32 v15, 4, v0 + for (n, r) in regs.into_iter().enumerate() { + w.extend(store(r, 15, 4 * n as u32)); + } + w +} + +/// `native` in the paired form on a host of 32-lane waves, validated by `dxil.dll` when +/// present. Where no other form gives the host the program (each still asks for 64-lane +/// waves, or fails), it is also what [`super::emit`] gives it. +fn paired(native: &NativeProgram) -> HostShader { + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let others = super::emit_forms(&c, native, &p, &st, &io, &res); + let shader = super::paired(&c, native, &p, &io, &res); + let chosen = super::emit(&c, native, &p, &st, &io, &res); + lower::TEST_HOST_WAVE.set(was); + let (shader, wave) = shader.expect("the paired form"); + assert_eq!(wave, Some(32)); + if !matches!(others, Ok((_, wave)) if wave != Some(64)) { + assert_eq!(chosen.expect("emit").dxil, shader.dxil, "emit's choice"); + } + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + shader +} + +/// `shader` on the hardware device: one group, root constants `s0..s3`, a raw UAV of `dwords` +/// zeroed dwords, which come back; None (and a line) without a device that takes it. +fn run_paired(shader: &HostShader, constants: [u32; 4], dwords: u32) -> Option> { + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program: {e}; not run"); + return None; + } + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=3) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = constants[d as usize]; + } + } + let mut out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(dwords)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out.swap_remove(0)) +} + +/// Panics at the first dword of `got` that is not the console's (`want`), naming the thread +/// and which of its four dwords. +fn same_as_console(got: &[u32], want: &[u32]) { + assert_eq!(got.len(), want.len()); + if let Some(n) = (0..want.len()).find(|&n| got[n] != want[n]) { + panic!("thread {}, dword {}: {:#x}, the console's {:#x}", n / 4, n % 4, got[n], want[n]); + } +} + +/// One console wave of 64 threads with 256 bytes of LDS. The even lanes write their dword in +/// one arm of a per-lane branch; the odd lanes theirs in the other arm, then, in that arm and +/// with no barrier, read their mirror lane's (63 - n, an even lane's); the even lanes read +/// theirs (an odd lane's) after the join. Then lanes 5 and 40 are read (`v_readlane_b32`), the +/// lanes holding more than 250 are counted (`s_bcnt1_i32_b64` of the compare's mask) and +/// counted below each lane (`v_mbcnt_lo/hi`): each of these takes lanes of both halves. +#[test] +fn paired_lanes_share_lds_and_lanes_across_halves_without_barriers() { + let mut w = vec![vop2(0x1A, 1, k(2), 0)]; // v_lshlrev_b32 v1, 2, v0: this lane's dword + w.extend(vop3(0x169, 2, v(0), k(7))); // v_mul_lo_u32 v2, v0, 7 + w.extend([ + vop2(0x26, 5, k(63), 0), // v_sub_nc_u32 v5, 63, v0: the mirror lane + vop2(0x1A, 5, k(2), 5), // v_lshlrev_b32 v5, 2, v5: its dword + vop2(0x1B, 3, k(1), 0), // v_and_b32 v3, 1, v0 + vopc(0xC2, k(0), 3), // v_cmp_eq_u32 vcc, 0, v3: the even lanes + sop1(0x24, 12, VCC), // s_and_saveexec_b64 s[12:13], vcc + sopp(0x08, 4), // s_cbranch_execz past the even lanes' arm + vop2(0x25, 4, LIT, 2), // v_add_nc_u32 v4, 100, v2 + 100, + ]); + w.extend(ds(0x0D, 0, 1, 4, 0)); // ds_write_b32 v1, v4 + w.extend([ + sop2(0x15, EXEC, 12, EXEC), // s_andn2_b64 exec, s[12:13], exec: the odd lanes + sopp(0x08, 6), // s_cbranch_execz past their arm + vop2(0x25, 4, LIT, 2), // v_add_nc_u32 v4, 200, v2 + 200, + ]); + w.extend(ds(0x0D, 0, 1, 4, 0)); // ds_write_b32 v1, v4 + w.extend(ds(0x36, 6, 5, 0, 0)); // ds_read_b32 v6, v5: an even lane's, from the other arm + w.extend([ + sop1(0x04, EXEC, 12), // s_mov_b64 exec, s[12:13] + sop1(0x24, 12, VCC), // s_and_saveexec_b64 s[12:13], vcc: the even lanes again + ]); + w.extend(ds(0x36, 6, 5, 0, 0)); // ds_read_b32 v6, v5: an odd lane's + w.push(sop1(0x04, EXEC, 12)); // s_mov_b64 exec, s[12:13] + w.extend(vop3(0x360, 14, v(6), k(5))); // v_readlane_b32 s14, v6, 5 + w.extend(vop3(0x360, 15, v(6), k(40))); // v_readlane_b32 s15, v6, 40 + w.extend([ + sop2(0x00, 14, 14, 15), // s_add_u32 s14, s14, s15 + vopc(0xC1, LIT, 6), // v_cmp_lt_u32 vcc, 250, v6 + 250, + sop1(0x10, 16, VCC), // s_bcnt1_i32_b64 s16, vcc + ]); + w.extend(vop3(0x365, 7, VCC, k(0))); // v_mbcnt_lo_u32_b32 v7, vcc_lo, 0 + w.extend(vop3(0x366, 7, VCC + 1, v(7))); // v_mbcnt_hi_u32_b32 v7, vcc_hi, v7 + w.extend([ + vop1(0x01, 9, 14), // v_mov_b32 v9, s14 + vop1(0x01, 10, 16), // v_mov_b32 v10, s16 + ]); + w.extend(stores([6, 9, 10, 7])); + let shader = paired(&native_with(&w, true, 64, 256)); + // the console: lane n's dword is 7n + 100 (even n) or 7n + 200, and lane n reads 63 - n's + let dword = |n: u32| 7 * n + if n.is_multiple_of(2) { 100 } else { 200 }; + let read: Vec = (0..64).map(|n| dword(63 - n)).collect(); + let big = (0..64).filter(|&n| read[n] > 250).fold(0u64, |m, n| m | 1 << n); + assert!(big as u32 != 0 && big >> 32 != 0, "lanes of both halves counted"); + let want: Vec = (0..64) + .flat_map(|n| [read[n], read[5] + read[40], big.count_ones(), (big & ((1 << n) - 1)).count_ones()]) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = run_paired(&shader, [0; 4], 256) else { return }; + same_as_console(&got, &want); + eprintln!("ran on the hardware device: LDS, lane reads and masks across the halves as on the console"); +} + +/// Two console waves of 64 in a group of 128 (two host waves of 32, 512 bytes of LDS). In +/// each, lane 0 zeroes the wave's dword of LDS; every lane loops (lane & 3) + 1 + wave times, +/// adding its lane number to its sum and 1 to the wave's dword each round (`ds_add_u32`; the +/// loop's branch is the wave's: it goes round while some lane is left); after the loop each +/// lane reads the wave's total, with no barrier; lanes 40-63 read their first lane's sum +/// (`v_readfirstlane_b32`: lane 40, an upper lane), then lanes 20-63 (lane 20, a lower one, +/// though upper lanes have one too); past the barrier, each lane reads the other wave's total. +#[test] +fn paired_lanes_loop_apart_and_meet_the_other_wave_at_the_barrier() { + let mut w = vec![ + vop2(0x16, 1, k(6), 0), // v_lshrrev_b32 v1, 6, v0: the console wave + vop2(0x1B, 2, k(63), 0), // v_and_b32 v2, 63, v0: the lane in it + vop2(0x1A, 11, k(2), 1), // v_lshlrev_b32 v11, 2, v1: the wave's dword + vop1(0x01, 12, k(0)), // v_mov_b32 v12, 0 + sop1(0x04, 22, EXEC), // s_mov_b64 s[22:23], exec + vopc(0xD2, k(0), 2), // v_cmpx_eq_u32 exec, 0, v2: lane 0 + ]; + w.extend(ds(0x0D, 0, 11, 12, 0)); // ds_write_b32 v11, v12 + w.extend([ + sop1(0x04, EXEC, 22), // s_mov_b64 exec, s[22:23] + vop2(0x1B, 3, k(3), 2), // v_and_b32 v3, 3, v2 + vop2(0x25, 3, k(1), 3), // v_add_nc_u32 v3, 1, v3 + vop2(0x25, 3, v(1), 3), // v_add_nc_u32 v3, v1, v3: the rounds + vop1(0x01, 4, k(0)), // v_mov_b32 v4, 0 + vop1(0x01, 13, k(1)), // v_mov_b32 v13, 1 + sop1(0x04, 20, EXEC), // s_mov_b64 s[20:21], exec + vop2(0x25, 4, v(2), 4), // loop: v_add_nc_u32 v4, v2, v4 + ]); + w.extend(ds(0x00, 0, 11, 13, 0)); // ds_add_u32 v11, v13 + w.extend([ + vop2(0x25, 3, 193, 3), // v_add_nc_u32 v3, -1, v3 + vopc(0xC5, k(0), 3), // v_cmp_ne_u32 vcc, 0, v3 + sop2(0x0F, EXEC, EXEC, VCC), // s_and_b64 exec, exec, vcc + sopp(0x09, -7), // s_cbranch_execnz loop + sop1(0x04, EXEC, 20), // s_mov_b64 exec, s[20:21] + ]); + w.extend(ds(0x36, 5, 11, 0, 0)); // ds_read_b32 v5, v11: the wave's total + w.extend([ + sop1(0x04, 24, EXEC), // s_mov_b64 s[24:25], exec + vopc(0xD1, k(39), 2), // v_cmpx_lt_u32 exec, 39, v2: lanes 40-63 + vop1(0x02, 6, v(4)), // v_readfirstlane_b32 s6, v4 + sop1(0x04, EXEC, 24), // s_mov_b64 exec, s[24:25] + vopc(0xD1, k(19), 2), // v_cmpx_lt_u32 exec, 19, v2: lanes 20-63 + vop1(0x02, 7, v(4)), // v_readfirstlane_b32 s7, v4 + sop1(0x04, EXEC, 24), // s_mov_b64 exec, s[24:25] + vop1(0x01, 6, 6), // v_mov_b32 v6, s6 + vop1(0x01, 9, 7), // v_mov_b32 v9, s7 + 0xD400_0000 | 0x346 << 16 | 6, // v_lshl_add_u32 v6, v9, 16, v6 + v(9) | k(16) << 9 | v(6) << 18, + sopp(0x0A, 0), // s_barrier + vop2(0x1D, 14, k(4), 11), // v_xor_b32 v14, 4, v11: the other wave's dword + ]); + w.extend(ds(0x36, 7, 14, 0, 0)); // ds_read_b32 v7, v14 + w.extend(stores([4, 5, 6, 7])); + let shader = paired(&native_with(&w, true, 128, 512)); + let rounds = |wave: u32, lane: u32| (lane & 3) + 1 + wave; + let total = |wave: u32| (0..64).map(|lane| rounds(wave, lane)).sum::(); + let first = |wave: u32, lane: u32| lane * rounds(wave, lane); + let want: Vec = (0..128) + .flat_map(|t| { + let (wave, lane) = (t / 64, t % 64); + [first(wave, lane), total(wave), first(wave, 20) << 16 | first(wave, 40), total(1 - wave)] + }) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = run_paired(&shader, [0; 4], 512) else { return }; + same_as_console(&got, &want); + eprintln!("ran on the hardware device: two console waves, their loops and LDS as on the console"); +} + +/// One console wave: `ds_bpermute_b32` from the mirror lane; a DPP row shift whose row mask +/// leaves rows 0 and 3 alone (rows 2 and 3 are lanes 32-63: rows are counted in console lanes); a +/// `ds_swizzle_b32` swapping the two 16-lane rows of each 32 lanes; `v_writelane_b32` of s0 +/// into lane 45. +#[test] +fn paired_lanes_permute_shift_and_write_lanes_of_both_halves() { + let mut w = vop3(0x169, 1, v(0), k(3)).to_vec(); // v_mul_lo_u32 v1, v0, 3 + w.extend([ + vop2(0x25, 1, k(1), 1), // v_add_nc_u32 v1, 1, v1 + vop2(0x26, 2, k(63), 0), // v_sub_nc_u32 v2, 63, v0 + vop2(0x1A, 2, k(2), 2), // v_lshlrev_b32 v2, 2, v2: the mirror lane's address + ]); + w.extend(ds(0xB3, 3, 2, 1, 0)); // ds_bpermute_b32 v3, v2, v1 + w.extend([ + vop1(0x01, 4, LIT), // v_mov_b32 v4, 1000 + 1000, + vop1(0x01, 4, 0xFA), // v_mov_b32 v4, v1 row_shr:1 row_mask:0x6 bank_mask:0xf + 0x6 << 28 | 0xF << 24 | 0x111 << 8 | 1, + ]); + w.extend(ds(0x35, 5, 1, 0, 0x401F)); // ds_swizzle_b32 v5, v1 offset:swizzle(BITMASK_PERM, xor 16) + w.push(vop1(0x01, 6, v(0))); // v_mov_b32 v6, v0 + w.extend(vop3(0x361, 6, 0, k(45))); // v_writelane_b32 v6, s0, 45 + w.extend(stores([3, 4, 5, 6])); + let shader = paired(&native_with(&w, true, 64, 0)); + let s0 = 0xABCD_1234; + let x = |n: u32| 3 * n + 1; + let want: Vec = (0..64) + .flat_map(|n| { + let shifted = if matches!(n >> 4, 1 | 2) && n & 15 != 0 { x(n - 1) } else { 1000 }; + let swizzled = x(n & 32 | (n & 31) ^ 16); + [x(63 - n), shifted, swizzled, if n == 45 { s0 } else { n }] + }) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = run_paired(&shader, [s0, 0, 0, 0], 256) else { return }; + same_as_console(&got, &want); + eprintln!("ran on the hardware device: permutes, row masks, swizzles and lane writes as on the console"); +} + +/// [`program`]'s wave OR inside a per-lane branch, in the paired form: the OR of both halves' +/// lanes, whichever take the branch; nothing stored when none does. +#[test] +fn paired_lanes_or_a_wave_inside_a_lane_branch() { + for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] { + let shader = paired(&program(skip)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let cases = [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1), (0, 0)]; + for (below, expected) in cases { + let Some(got) = on_the_card(&shader, [below, 0]) else { return }; + assert_eq!(got, expected, "{name}: {below} threads in the branch"); + } + } + eprintln!("ran on the hardware device: the OR of both halves in every case"); +} + +/// One console wave of 64 threads, thread t holding the bit `1 << (t >> 1)`: the threads below +/// s0 OR theirs over the wave inside `if (t < s0) { ... }` ([`super::wave::WAVE_OR_V7_TO_S7`] +/// into s7, which holds 0x77 before), and every thread stores s7 after the branch: the wave's +/// OR, or 0x77 when no thread took the branch and the wave skipped it. A wave-wide value used +/// past a per-lane branch, as the title's tile classification and light clustering programs +/// use theirs: no form in two host waves takes it (they would meet inside the branch, and the +/// skip cannot be left out: s7 would no longer keep 0x77), and the approximate form, each host +/// wave a wave of its own, gives each half its own OR, 0x77 to the upper half while s0 <= 32. +/// The title's 39 such programs ran approximate; [`super::emit`] now gives the paired form. +#[test] +fn a_wave_value_used_past_a_lane_branch_takes_the_paired_form_not_an_approximate_one() { + let mut w = vec![ + sop1(0x03, 7, LIT), // s_mov_b32 s7, 0x77 + 0x77, + vop1(0x01, 5, k(1)), // v_mov_b32 v5, 1 + vop2(0x16, 6, k(1), 0), // v_lshrrev_b32 v6, 1, v0 + vop2(0x1A, 7, v(6), 5), // v_lshlrev_b32 v7, v6, v5 + vopc(0xC4, 0, 0), // v_cmp_gt_u32 vcc, s0, v0 + sop1(0x24, 12, VCC), // s_and_saveexec_b64 s[12:13], vcc + sopp(0x08, 20), // s_cbranch_execz past the OR + ]; + w.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + w.extend([ + sop1(0x04, EXEC, 12), // s_mov_b64 exec, s[12:13] + vop1(0x01, 8, 7), // v_mov_b32 v8, s7 + ]); + w.extend(stores([8, 7, 6, 0])); + let native = native_with(&w, true, 64, 0); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let pairs = super::paired(&c, &native, &p, &io, &res); + let chosen = super::emit(&c, &native, &p, &st, &io, &res); + // (as before: the paired form only where no other form takes the program) + let off = super::TEST_PAIRS.replace(Some(false)); + let approximate = super::emit(&c, &native, &p, &st, &io, &res); + super::TEST_PAIRS.set(off); + lower::TEST_HOST_WAVE.set(was); + let (pairs, wave) = pairs.expect("the paired form"); + assert_eq!(wave, Some(32)); + let (chosen, approximate) = (chosen.expect("emit"), approximate.expect("an approximate form")); + assert!(chosen.dxil == pairs.dxil, "emit's choice is not the paired form"); + assert!(approximate.dxil != pairs.dxil, "without the paired form, emit gives it anyway"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = chosen.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // the console: every thread stores the OR of the threads below s0, or 0x77 with none + let want = |s0: u32| -> Vec { + let or = (0..64u32).filter(|&t| t < s0).fold(0u32, |m, t| m | 1 << (t >> 1)); + let s7 = if s0 == 0 { 0x77 } else { or }; + (0..64u32).flat_map(|t| [s7, 1 << (t >> 1), t >> 1, t]).collect() + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for s0 in [64u32, 40, 33, 32, 10, 1, 0] { + let Some(got) = run_paired(&chosen, [s0, 0, 0, 0], 256) else { return }; + same_as_console(&got, &want(s0)); + } + // each half on its own: with s0 = 10 the upper half took no branch and kept 0x77 + let Some(halves) = run_paired(&approximate, [10, 0, 0, 0], 256) else { return }; + assert_eq!((want(10)[0], want(10)[4 * 40]), (0x1F, 0x1F)); + assert_eq!((halves[0], halves[4 * 40]), (0x1F, 0x77), "the approximate form's lanes 0 and 40"); + eprintln!("ran on the hardware device: the wave's OR past the branch in every lane, not each half's"); +} + +/// [`half_sum_program`] in the paired form: each half's tree over its 32 lanes, then the two +/// halves' sums, the console's last addition. +#[test] +fn paired_lanes_sum_halves_as_the_consoles_tree() { + let (native, tree, _) = half_sum_program(); + let shader = paired(&native); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = on_the_card(&shader, [0, 0]) else { return }; + assert_eq!(got, u32::from(tree)); + eprintln!("ran on the hardware device: the sum {tree:#x} of the console's tree"); +} + +/// The lens-flare scans' allocation (`lens_flares:CS_ScanMip1`, 0x5c0-0x61c): in a branch +/// of the lanes below s0, the first lane adds the wave's count times a size (s1) to a +/// counter, and each lane takes base + below × size with `v_mad_u32_u24`. That is the +/// idiom a host wave may run alone ([`super::idiom::wave_local`]): each half reserves its own +/// count's slots. The same with the count where the base goes is not. +#[test] +fn an_allocation_in_units_of_a_size_is_the_idiom() { + let program = |base: u32| -> Vec { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0016, // s_cbranch_execz past the allocation + 0xBE82_047E, // s_mov_b64 s[2:3], exec + 0xBE84_147E, // s_ff1_i32_b64 s4, exec + 0xD765_0004, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v4, -1, 0 + 0xD766_0004, + 0x0002_08C1, // v_mbcnt_hi_u32_b32 v4, -1, v4: the lane + 0xBE86_047E, // s_mov_b64 s[6:7], exec + 0x7DA4_0804, // v_cmpx_eq_u32 exec, s4, v4: the first lane + 0xBE82_1002, // s_bcnt1_i32_b64 s2, s[2:3]: the count + 0x7E02_0201, // v_mov_b32 v1, s1: the size + 0x160A_0202, // v_mul_u32_u24 v5, s2, v1 + 0x7E16_0280, // v_mov_b32 v11, 0 + 0xE0C8_6000, + 0x8002_050B, // buffer_atomic_add v5, v11, s[8:11], 0 idxen glc + 0xBEFE_0406, // s_mov_b64 exec, s[6:7] + 0xD765_0004, + 0x0001_007E, // v_mbcnt_lo_u32_b32 v4, exec_lo, 0 + 0xD766_0004, + 0x0002_087F, // v_mbcnt_hi_u32_b32 v4, exec_hi, v4: the lanes below + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5: the base + 0xD543_0006, + 0x0002_0304 | base << 18, // v_mad_u32_u24 v6, v4, v1, s + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + S_ENDPGM, + ]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() + }; + let idiom = |code: &[u8]| { + let p = ir::build(code, true, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + super::idiom::wave_local(&p, &st) + }; + assert_eq!(idiom(&program(5)), Ok(())); + assert!(idiom(&program(2)).is_err(), "the count as the base"); +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c6d0..146163107d 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -123,6 +123,27 @@ impl Inst { } } +thread_local! { + /// See [`with_shared_slots`]. + static SHARED_SLOTS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with programs built so that a register pair parked in two lanes of a VGPR moves +/// as a pair wherever its save or restore comes together, also where the lower lane holds a +/// single scalar at other times ([`unspill`] otherwise moves every half alone then). Each +/// save and restore keeps its meaning either way (a pair move is the two moves at once, where +/// nothing in between sees the difference); what changes is that a parked lane mask then comes +/// back as the mask it is. `PS_VoxelizeVisiblity` parks a lane mask in lanes 3 and 4 of v56 and +/// later a single scalar in lane 3: its mask came back as two scalars, a mask the +/// structurisation cannot see into ("an opaque lane mask"). A retry ([`crate::emit::emit`]), +/// so that the programs that translate as they are keep their form. +pub fn with_shared_slots(f: impl FnOnce() -> R) -> R { + let was = SHARED_SLOTS.replace(true); + let r = f(); + SHARED_SLOTS.set(was); + r +} + /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). @@ -245,7 +266,9 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result = Vec::new(); + // ([`with_shared_slots`]) the upper lanes' parks that move with a lower one + let mut taken: Vec = Vec::new(); + let shared = SHARED_SLOTS.get(); for &(reg, lane) in &slots { if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { continue; @@ -396,8 +422,12 @@ fn unspill( let mut distinct: Vec = partners.iter().flatten().copied().collect(); distinct.sort_unstable(); distinct.dedup(); - if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + let found = partners.iter().flatten().count(); + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() + || shared && found > 0 && distinct.len() == found + { pairs.push((reg, lane)); + taken.extend(distinct); } } // Codes for the parked scalars: the trap temporaries (108..=123), then @@ -450,7 +480,8 @@ fn unspill( continue; }; let Some(slot) = code_of(reg, lane) else { return Vec::new() }; - if pairs.contains(&(reg, lane)) { + let alone = shared && (pairs.contains(&(reg, lane)) && partner(i).is_none() || lane > 0 && pairs.contains(&(reg, lane - 1)) && !taken.contains(&i)); + if pairs.contains(&(reg, lane)) && !alone { let Some(j) = partner(i) else { return Vec::new() }; // A save moves the pair where its second half is saved; a // restore where its first half is restored. @@ -458,7 +489,7 @@ fn unspill( let (dst, src) = if save { (slot, code) } else { (code, slot) }; edits.push((at, Some((true, dst, src)))); edits.push((gone, None)); - } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + } else if lane > 0 && pairs.contains(&(reg, lane - 1)) && !alone { // the upper half of a pair: moved with the lower } else { let (dst, src) = if save { (slot, code) } else { (code, slot) }; @@ -580,6 +611,161 @@ pub(crate) fn thread_edges( Ok(rename(blocks, p.wave64, p.vgprs)) } +/// Each of `joins` copied for every way into it but the first, each copy entered from its own +/// predecessor and left as the join is: a value the join merged from its ways in is one +/// value in each copy. Every instruction still runs once on each path. A loop header (a +/// block with a way in from later in reverse postorder) is left as it is. `None` if nothing +/// changes. +pub(crate) fn split_joins(p: &Program, joins: &[usize]) -> Option { + let order = reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + let mut any = false; + for &join in joins { + let mut preds = p.blocks[join].preds.clone(); + preds.dedup(); + if preds.len() < 2 || preds.iter().any(|&q| index[q] >= index[join]) { + continue; + } + for &pred in &preds[1..] { + let target = blocks.len(); + blocks.push(blocks[join].clone()); + match &mut blocks[pred].exit { + Exit::Jump(t) => *t = target, + Exit::Branch { taken, not_taken } => { + if *taken == join { + *taken = target; + } + if *not_taken == join { + *not_taken = target; + } + } + _ => unreachable!("a way into a join"), + } + } + any = true; + } + if !any { + return None; + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// The program with each whole-wave section (`s_or_saveexec -1` up to the restore of the +/// saved mask, `emit::wave`) that a jump splits in one block: the block the section starts +/// in, when it jumps to the block that restores the mask, takes that block's code and exit +/// (a copy where other ways lead there too). The compiler shares the end of two sections +/// whose start a branch chooses (`cond ? WaveActiveMax(x) : WaveActiveMin(x)` in the title's +/// water optical depth: each arm reduces up to the read of lane 32, the join reads lane 0 +/// and restores), and a section is followed within one block. Every instruction still runs +/// once on each path. A join that is a loop header is left as it is. `None` if nothing +/// changes. +pub(crate) fn whole_sections(p: &Program) -> Option { + use crate::gfx10::{Fields, Operand}; + /// The saved mask's scalar code if `inst` starts a section: EXEC becomes every lane + /// (`s_or_saveexec -1`, `s_nand_saveexec 0`). + fn start(inst: &Inst) -> Option { + let all = match inst.name() { + "s_or_saveexec_b64" | "s_or_saveexec_b32" => Operand::Const(193), + "s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Operand::Const(128), + _ => return None, + }; + match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + src, + .. + } if src.first() == Some(&all) => Some(*code), + _ => None, + } + } + let order = reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + // (block, the join whose code it takes) + let mut fuse = Vec::new(); + for &b in &order { + let block = &p.blocks[b]; + let Exit::Jump(join) = block.exit else { continue }; + // the last section start of the block, unless its restore is in the block too + let Some((at, code)) = block + .insts + .iter() + .enumerate() + .rev() + .find_map(|(i, inst)| start(inst).map(|c| (i, c))) + else { + continue; + }; + let saved = block.insts[at].write(Reg::S(code)); + let restores = |i: &Inst, held: Option| { + i.write(Reg::S(EXEC)).is_some() && i.read(Reg::S(code)).is_some_and(|v| Some(v) == held) + }; + if block.insts[at + 1..].iter().any(|i| restores(i, saved)) { + continue; + } + let z = &p.blocks[join]; + if join == b || z.preds.iter().any(|&q| index[q] >= index[join]) { + continue; + } + // what the saved register holds in the join: the value itself, or a join of it + let held = match z.phis.iter().find(|phi| phi.reg == Reg::S(code)) { + Some(phi) => { + let from_b = z.preds.iter().position(|&q| q == b).map(|k| phi.args[k]); + if from_b != saved { + continue; + } + Some(phi.value) + } + None => saved, + }; + // the join's first write of EXEC is the restore, and nothing before it writes the + // saved register + let first = z + .insts + .iter() + .position(|i| i.write(Reg::S(EXEC)).is_some() || i.write(Reg::S(code)).is_some()); + if first.is_some_and(|k| restores(&z.insts[k], held)) { + fuse.push((b, join)); + } + } + if fuse.is_empty() { + return None; + } + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + for &(b, join) in &fuse { + if blocks[b].insts.last().is_some_and(|i| i.name() == "s_branch") { + blocks[b].insts.pop(); + } + let tail = p.blocks[join].insts.clone(); + blocks[b].insts.extend(tail); + blocks[b].exit = p.blocks[join].exit; + } + // a join whose every way in took its code is left: nothing reaches it + for &(_, join) in &fuse { + if p.blocks[join].preds.iter().all(|q| fuse.contains(&(*q, join))) { + blocks[join].insts.clear(); + blocks[join].exit = Exit::End; + } + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + /// The program without its early-outs: an `s_cbranch_execz` to a block that /// only ends the program (`if (!inBounds) return;`, the outermost branch of /// most compute programs) is left out, so the lanes that would have left @@ -1607,6 +1793,33 @@ mod tests { assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); } + #[test] + fn a_split_join_gives_each_way_in_its_own_copy() { + let code = [ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0002, // s_cbranch_scc1 -> s_mov_b32 s2, 0 + 0xB002_0092, // s_movk_i32 s2, 0x92 + 0xBF82_0001, // s_branch -> the join + 0xBE82_0380, // s_mov_b32 s2, 0 + 0x7E02_0202, // v_mov_b32 v1, s2 (the join) + S_ENDPGM, + ]; + let p = build_words(&code, false); + let join = p.blocks.iter().position(|b| b.preds.len() == 2).expect("a join"); + assert_eq!(p.blocks[join].phis.len(), 1, "s2 differs by the way in"); + let q = split_joins(&p, &[join]).expect("split"); + // two blocks read s2 into v1, neither through a phi + let reads: Vec<&Block> = q + .blocks + .iter() + .filter(|b| b.insts.first().is_some_and(|i| i.name() == "v_mov_b32")) + .collect(); + assert_eq!(reads.len(), 2); + assert!(reads.iter().all(|b| b.preds.len() == 1 && b.phis.is_empty())); + // a block with one way in is left as it is + assert!(split_joins(&q, &[0]).is_none()); + } + #[test] fn joins_get_phis_only_where_values_differ() { let code = [ @@ -1788,4 +2001,53 @@ mod tests { assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4))); assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs"); } + + /// `PS_VoxelizeVisiblity`'s parking (0xa18-0xa38, 0xe44-0xe4c, 0x2df8, 0x3184): a lane + /// mask parked in lanes 3 and 4 of v56 and taken back to make EXEC, later a single scalar + /// parked in lane 3. Built as it is, the mask comes back as two scalars, which the + /// structurisation cannot see into; with [`with_shared_slots`] it comes back as the pair + /// it is, and EXEC as the compare's lanes. + #[test] + fn a_mask_parked_in_lanes_another_scalar_shares_comes_back_whole_with_shared_slots() { + let writelane = |lane: u32, s: u32| [0xD761_0038, s | (128 + lane) << 9]; // v_writelane_b32 v56, s, lane + let readlane = |s: u32, lane: u32| [0xD760_0000 | s, (256 + 56) | (128 + lane) << 9]; // v_readlane_b32 s, v56, lane + let mut w = vec![ + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBEA2_046A, // s_mov_b64 s[34:35], vcc + ]; + w.extend(writelane(3, 34)); + w.extend(writelane(4, 35)); + w.push(0xBEA2_0480); // s_mov_b64 s[34:35], 0 + w.extend(readlane(34, 3)); + w.extend(readlane(35, 4)); + let restore = 4 * (w.len() - 4) as u64; // (the first restore's offset) + w.extend([ + 0xBE82_2422, // s_and_saveexec_b64 s[2:3], s[34:35] + 0x7E02_0281, // v_mov_b32 v1, 1 + 0xBEFE_0402, // s_mov_b64 exec, s[2:3] + ]); + w.extend(writelane(3, 1)); + w.push(0xBE81_0380); // s_mov_b32 s1, 0 + w.extend(readlane(1, 3)); + w.push(S_ENDPGM); + let code: Vec = w.iter().flat_map(|w| w.to_le_bytes()).collect(); + let at = |p: &Program| { + let i = p.blocks.iter().flat_map(|b| &b.insts).find(|i| i.machine.offset as u64 == restore).expect("the restore"); + i.name() + }; + let alone = build(&code, true, 64).unwrap(); + assert_eq!(at(&alone), "s_mov_b32"); + let shared = with_shared_slots(|| build(&code, true, 64)).unwrap(); + assert_eq!(at(&shared), "s_mov_b64"); + let opaque = |p: &Program| { + let st = crate::structure::structure(p).unwrap(); + let v1 = p.blocks.iter().enumerate().flat_map(|(b, blk)| blk.insts.iter().enumerate().map(move |(i, inst)| (b, i, inst))); + let (b, i, _) = v1.into_iter().find(|(_, _, inst)| inst.name() == "v_mov_b32").expect("the guarded move"); + let guard = st.guards[b][i].expect("a guard"); + st.bools.support(guard).iter().any(|a| matches!(a, crate::structure::Atom::Opaque(_))) + }; + // (built alone, this branch may already see the compare's mask: only the shared build + // is checked) + assert!(!opaque(&shared), "the pair is the compare's mask"); + } } diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index 74838d0588..affb2ab02c 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -59,12 +59,17 @@ translation_inputs! { "emit/bitcode/census.rs", "emit/bitcode/opt.rs", "emit/container.rs", + "emit/descriptor_data.rs", + "emit/float64.rs", "emit/guest_address.rs", + "emit/idiom.rs", "emit/intersect.rs", + "emit/link.rs", "emit/lower.rs", "emit/mod.rs", "emit/own_bits.rs", "emit/packed_mask.rs", + "emit/pops.rs", "emit/rect.rs", "emit/sampler.rs", "emit/shader.rs", @@ -89,10 +94,13 @@ translation_inputs! { mod source_tests { use std::path::{Path, PathBuf}; - // host.rs consumes finished DXIL to create or run host pipelines. The + // host.rs consumes finished DXIL to create or run host pipelines. + // native_build.rs only writes containers: what it writes is hashed as + // any container is, so it cannot change a translation kept on disk. The // remaining modules are only compiled by the Windows execution tests. const OUTSIDE_TRANSLATION: &[&str] = &[ "emit/cube_lod_tests.rs", + "emit/descriptor_tests.rs", "emit/diff_tests.rs", "emit/helper_lane_tests.rs", "emit/host.rs", @@ -101,6 +109,7 @@ mod source_tests { "emit/valu_tests.rs", "emit/waterfall_tests.rs", "emit/wave64_tests.rs", + "native_build.rs", ]; #[test] diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 4c267e17c7..ec8402c7ee 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -71,6 +71,11 @@ use crate::ShaderError::{self, Malformed}; use crate::dxbc::{u32_at, u64_at}; +/// Programs handed to us compiled, outside a container, and a container for them. +#[path = "native_build.rs"] +mod build; +pub use build::{console_compute_container, console_compute_container_rooted}; + const XDAT_OFFSET: usize = 0x18; const MAX_XDAT_ENTRIES: usize = 64; const KIND_NATIVE: u32 = 0x0d; diff --git a/crates/victory-shader/src/native_build.rs b/crates/victory-shader/src/native_build.rs new file mode 100644 index 0000000000..77784943ce --- /dev/null +++ b/crates/victory-shader/src/native_build.rs @@ -0,0 +1,915 @@ +//! Console programs that reach us compiled already, outside a container, +//! and the container that holds such a program as the title's own do. +//! +//! A title can make a pipeline from a program it has put in its own memory +//! (device methods 0x218 for compute, 0x1c8 for graphics). Such a program +//! comes as its code, a block of registers and a resource table. The table, +//! as observed (the title's mip generation programs, against their +//! containers): +//! +//! ```text +//! +0x00 u32 kind (bit 10: 8 bytes more of header), u32 size of the rest +//! (from +0x0c, or +0x14), u32, u32 ..., the last u32 of the header +//! `n << 16 | 0x440` (n is not always the count of 0x41 entries: 11 +//! for 12 seen, so the entries are told apart by their tag) +//! entries of 0x20 bytes from the end of the header, 0x41 ones first: +//! 0x41 a descriptor the program reads: u32 0x41, u32 root type << 8 | +//! resource type (0 SRV, 1 sampler, 2 CBV, 3 UAV), u32 table offset +//! (dwords), u32 shader register, u32 stride (bytes; 0 for a CBV, +//! 4 for an image), u32 root slot << 16 | first user-data dword << 8 +//! | descriptor dwords, then u32 -1, u32 0 +//! 0x42 a table range (not read: the 0x41 entries name the same ranges) +//! 0x43 the program's 128-bit hash, last +//! ``` +//! +//! The user-data dword is the one byte that agrees across a table: the +//! root slots take the dwords from 4 on in their order, one each but two +//! for a root descriptor, which the program's `COMPUTE_PGM_RSRC2` user-SGPR +//! count covers, and a fixed sampler 0. The u32 before it is 0x10 or 0x20 +//! for buffer SRVs (a structured stride), which no user-SGPR count covers. +//! +//! Root type 0 is root constants (resource type 2): the program reads them +//! as values straight from its user SGPRs (`v_mul_f32 v7, s5, v7`), so the +//! descriptor dwords byte is their size in bytes. They give a root parameter +//! and no used resource, as nothing is loaded through them. +//! +//! Root type 1 is a root descriptor, a 64-bit buffer address in two user +//! SGPRs (descriptor dwords 2). Seen as an SRV (`t1`, user data 7 and 8, +//! the next slot at 9), which the program makes a buffer descriptor around +//! and loads through: `s_mov_b32 s20, s7`, `s_mov_b32 s21, s8`, +//! `s_mov_b32 s22, -1`, `s_mov_b32 s23, 0x31016fac`, then +//! `s_buffer_load_dword s27, s[20:23], null`. It is a root parameter of two +//! SGPRs and a used resource, as the title's containers give one. +//! +//! The registers of a compute program, 0x1c bytes: u32 flags (bit 5: 32 +//! lanes, as the container record's flags), u32, u32, u16 x3 thread-group +//! size and u16 whose bit 4 is set for a program of 32 lanes, u32 +//! `COMPUTE_PGM_RSRC1`, u32 `COMPUTE_PGM_RSRC2`. The flags' bit 5 is clear +//! in every 0x218 program seen; the programs with that u16 at 0x10 move +//! `exec_lo` alone, keep scalars in `vcc_hi` and use VGPRs up to the 32-lane +//! count of `COMPUTE_PGM_RSRC1` (v143 of 18 granules), and the others move +//! the whole `exec` and stay within the 64-lane count. + +use super::{ + ABSENT, CS_RSRC2, CS_THREADS, ComputeIo, ENTRY_SIZE, MAX_UNPACKED, FSSM_HEADER, FSSM_VERSION, GRAPHICS_SLOT_COUNT, HwStage, + KIND_NATIVE, NativeProgram, RECORD_COUNTS, RECORD_FLAGS, RECORD_LAYOUT, RECORD_REGS, + RECORD_SIZE, RECORD_USED, ResourceType, RootParam, RootType, SLOTS, StageIo, UsedResource, + XBCH_HEADER, XBCH_VERSION, XDAT_OFFSET, +}; +use crate::ShaderError::{self, Malformed}; +use crate::dxbc::u32_at; +use crate::{FourCC, dxbc}; + +const S_CODE_END: u32 = 0xBF9F_0000; + +/// In the registers' depth word, above the depth: a program of 32 lanes. +const WAVE32_DEPTH_BIT: u32 = 0x10 << 16; + +/// The descriptors a console resource table names, and the root parameters +/// they come through (one per table range, and one per fixed sampler). +fn resources(table: &[u8]) -> Result<(Vec, Vec), ShaderError> { + let kind = u32_at(table, 0)?; + let header = if kind & 0x400 != 0 { 0x18 } else { 0x10 }; + let size = u32_at(table, 4)? as usize; + if table.len().checked_sub(header - 4) != Some(size) { + return Err(Malformed("resource table size disagrees")); + } + let (entries, tail) = table[header..].as_chunks::<0x20>(); + let Some((hash, entries)) = entries.split_last() else { + return Err(Malformed("missing resource table hash")); + }; + if !tail.is_empty() || u32_at(hash, 0)? != 0x43 { + return Err(Malformed("incomplete resource table")); + } + let count = entries.iter().take_while(|entry| super::le32(entry.as_slice(), 0) == 0x41).count(); + let (descriptors, ranges) = entries.split_at(count); + if ranges.iter().any(|entry| super::le32(entry, 0) != 0x42) { + return Err(Malformed("unexpected resource range")); + } + let (mut layout, mut used) = (Vec::new(), Vec::new()); + for entry in descriptors { + let word = |k: usize| u32::from_le_bytes(entry[4 * k..4 * k + 4].try_into().unwrap()); + let (types, offset, register, stride, packed) = + (word(1), word(2), word(3), word(4), word(5)); + let root = RootType::from_raw(types >> 8); + let slot = u8::try_from(packed >> 16).map_err(|_| Malformed("implausible root slot"))?; + let user_data = (packed >> 8) as u8; + if root == RootType::Constants { + let bytes = packed & 0xFF; + if bytes == 0 || !bytes.is_multiple_of(4) { + return Err(Malformed("implausible root constants size")); + } + layout.push(RootParam { + root, + table_offset_dwords: 0, + sgprs: bytes / 4, + base_register: register, + user_data, + slot, + }); + continue; + } + used.push(UsedResource { + kind: match types & 0xFF { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n as u8), + }, + root, + table_offset_dwords: offset, + lower_bound: register, + stride, + dwords: packed as u8, + user_data, + slot, + }); + let sgprs = match root { + RootType::Table => 1, + RootType::Descriptor => 2, + RootType::ImmediateSampler => 0, + _ => { + return Err(Malformed( + "a console resource table entry of a root type not seen yet", + )); + } + }; + layout.push(RootParam { + root, + table_offset_dwords: offset, + sgprs, + base_register: register, + user_data, + slot, + }); + } + Ok((layout, used)) +} + +/// The code without the `s_code_end` the title pads it with. +fn trimmed(code: &[u8]) -> &[u8] { + let mut end = code.len(); + while end >= 4 && u32_at(code, end - 4).ok() == Some(S_CODE_END) { + end -= 4; + } + &code[..end] +} + +/// A root parameter of a serialized root signature: what it is, the +/// user-data dwords it takes and its shader register. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct SerializedParam { + root: RootType, + dwords: u32, + register: u32, + /// A root SRV: taken only where the table places it itself. + srv: bool, +} + +/// `D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and +/// `D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED`. +const HEAPS_INDEXED: u32 = 0xC00; + +/// The parameters and flags of a serialized root signature (an `RTS0` +/// part, alone or in a container): a header of u32 version (1 to 3), +/// parameter count, parameter offset, sampler count, sampler offset and +/// flags, then per parameter u32 type, visibility and payload offset. A +/// table (0) takes one user-data dword, root constants (1) as many as their +/// count (the payload's third u32), a root CBV (2) two, a root SRV (3) two +/// as well (a captured table places one in dwords 7 and 8, the next slot +/// at 9). Root UAVs (4) are refused: no captured table places one. +fn root_signature(blob: &[u8]) -> Result<(Vec, u32), ShaderError> { + let rts0 = match crate::Container::parse(blob) { + Ok(c) => { + c.part(FourCC::RTS0) + .ok_or(Malformed("a root signature container without RTS0"))? + .data + } + Err(_) => blob, + }; + if !(1..=3).contains(&u32_at(rts0, 0)?) { + return Err(Malformed("unknown root signature version")); + } + let (count, at, flags) = (u32_at(rts0, 4)?, u32_at(rts0, 8)? as usize, u32_at(rts0, 20)?); + if count > 64 { + return Err(Malformed("implausible root parameter count")); + } + let params = (0..count as usize) + .map(|k| { + let entry = at + 12 * k; + let payload = u32_at(rts0, entry + 8)? as usize; + let kind = u32_at(rts0, entry)?; + let (root, dwords) = match kind { + 0 => (RootType::Table, 1), + 1 => (RootType::Constants, u32_at(rts0, payload + 8)?), + 2 | 3 => (RootType::Descriptor, 2), + 4 => { + return Err(Malformed("a root UAV, whose user data no capture places")); + } + _ => return Err(Malformed("unknown root parameter type")), + }; + let register = if root == RootType::Table { 0 } else { u32_at(rts0, payload)? }; + Ok(SerializedParam { root, dwords, register, srv: kind == 3 }) + }) + .collect::>()?; + Ok((params, flags)) +} + +/// The root parameters a resource table leaves out, from the root +/// signature the title passes with it: a 0x218 program reads user SGPRs +/// that no table entry names (`slot218-m007`: a descriptor loaded from +/// s[10:11] plus s9 << 5, with entries for dwords 4 to 6 only). +/// +/// Every captured table places the parameters from user-data dword 4 on, +/// in order, a table taking one dword, root constants their count, a root +/// CBV two (slot 0 at 4 even when unnamed, a root CBV at 7 taking 7 and 8, +/// the constants after it at 9), so the others are placed the same way. +/// Nothing is guessed: the program is refused when the table places a +/// parameter elsewhere, when a parameter is cut by the end of the +/// program's user SGPRs, and when user SGPRs are left past the parameters +/// (where a directly indexed heap would be, which no capture places). +fn completed( + layout: &[RootParam], + params: &[SerializedParam], + flags: u32, + user_sgprs: u32, +) -> Result, ShaderError> { + let mut at = Vec::with_capacity(params.len()); + let mut end = 4u32; + for p in params { + at.push(end); + end = end + .checked_add(p.dwords) + .ok_or(Malformed("implausible root constants size"))?; + } + let named = |k: usize| { + layout + .iter() + .filter(|l| l.root != RootType::ImmediateSampler) + .any(|l| usize::from(l.slot) == k) + }; + let agrees = layout + .iter() + .filter(|l| l.root != RootType::ImmediateSampler) + .all(|l| { + let k = usize::from(l.slot); + params.get(k).is_some_and(|p| p.root == l.root) && at[k] == u32::from(l.user_data) + }); + if !agrees { + return Err(Malformed( + "a resource table places a root parameter where its root signature does not", + )); + } + let mut out = layout.to_vec(); + for (k, p) in params.iter().enumerate() { + let (first, past) = (at[k], at[k] + p.dwords); + if named(k) || first >= user_sgprs { + continue; + } + if past > user_sgprs { + return Err(Malformed( + "a root parameter cut by the end of the program's user SGPRs", + )); + } + if p.srv { + // A root SRV the table does not name: what it is read as (and + // so its used resource) is not known. + return Err(Malformed("a root SRV the resource table does not place")); + } + out.push(RootParam { + root: p.root, + table_offset_dwords: 0, + sgprs: p.dwords, + base_register: p.register, + user_data: first as u8, + slot: k as u8, + }); + } + if end < user_sgprs { + return Err(Malformed(if flags & HEAPS_INDEXED != 0 { + "user SGPRs past the root parameters, where a directly indexed heap would be: no capture places it" + } else { + "user SGPRs past the root parameters" + })); + } + Ok(out) +} + +/// A compute program from its registers (0x1c bytes), resource table and +/// code, as the title hands them to device method 0x218. +fn console_compute( + registers: &[u8], + table: &[u8], + code: &[u8], +) -> Result { + if registers.len() < 0x1c { + return Err(Malformed("compute registers too short")); + } + let flags = u32_at(registers, 0)?; + let size = u32_at(registers, 0x0c)?; + // The depth is the low half of its word; the high half says 32 lanes. + let depth = u32_at(registers, 0x10)?; + let threads = [size & 0xFFFF, size >> 16, depth & 0xFFFF]; + let rsrc1 = u32_at(registers, 0x14)?; + let rsrc2 = u32_at(registers, 0x18)?; + if threads.contains(&0) + || threads[2] > 64 + || threads + .into_iter() + .try_fold(1u32, u32::checked_mul) + .is_none_or(|lanes| lanes > 1024) + { + return Err(Malformed("implausible thread-group size")); + } + let wave64 = flags & super::FLAG_WAVE32 == 0 && depth & WAVE32_DEPTH_BIT == 0; + // COMPUTE_PGM_RSRC1.VGPRS: granules of 4 (64 lanes) or 8 (32 lanes), less one. + let vgprs = ((rsrc1 & 0x3F) + 1) * if wave64 { 4 } else { 8 }; + if vgprs > 256 || !code.len().is_multiple_of(4) { + return Err(Malformed("invalid compute register count or code length")); + } + let (layout, used) = resources(table)?; + // COMPUTE_PGM_RSRC2.USER_SGPR: what the root parameters can name. + let user_sgprs = rsrc2 >> 1 & 0x1F; + if layout.iter().any(|p| u32::from(p.user_data) + p.sgprs > user_sgprs) { + return Err(Malformed("a resource table names user data the program does not have")); + } + let code = trimmed(code); + if code.is_empty() { + return Err(Malformed("no code")); + } + Ok(NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: vgprs as u16, + layout, + used, + io: StageIo::Cs(ComputeIo { rsrc2, threads }), + code: code.to_vec(), + }) +} + +fn root_raw(root: RootType) -> u32 { + match root { + RootType::Constants => 0, + RootType::Descriptor => 1, + RootType::Table => 3, + RootType::ImmediateSampler => 4, + RootType::ResourceHeap => 5, + RootType::SamplerHeap => 6, + RootType::Other(n) => n, + } +} + +fn kind_raw(kind: ResourceType) -> u8 { + match kind { + ResourceType::Srv => 0, + ResourceType::Sampler => 1, + ResourceType::Cbv => 2, + ResourceType::Uav => 3, + ResourceType::Other(n) => n, + } +} + +/// An internal shader container built from the three blocks in a native compute description. +pub fn console_compute_container( + registers: &[u8], + table: &[u8], + code: &[u8], +) -> Result, ShaderError> { + console_compute_container_rooted(registers, table, code, None) +} + +/// [`console_compute_container`], the program's layout completed from the +/// serialized root signature the description names ([`completed`]), or +/// refused when the signature cannot be read or places something no +/// capture shows. Without a signature, the table's layout alone, as +/// [`console_compute_container`]. +pub fn console_compute_container_rooted( + registers: &[u8], + table: &[u8], + code: &[u8], + root: Option<&[u8]>, +) -> Result, ShaderError> { + let mut program = console_compute(registers, table, code)?; + if let Some(root) = root + && let StageIo::Cs(cs) = &program.io + { + let (params, flags) = root_signature(root)?; + program.layout = completed(&program.layout, ¶ms, flags, cs.rsrc2 >> 1 & 0x1F)?; + } + compute_container(&program) +} + +/// A container holding `program` (a compute program) as the title's +/// containers hold theirs, for everything that reads programs from +/// containers: [`super::native_programs`] gives `program` back. +fn compute_container(program: &NativeProgram) -> Result, ShaderError> { + let StageIo::Cs(cs) = &program.io else { + return Err(Malformed("not a compute program")); + }; + let put32 = + |v: &mut Vec, at: usize, x: u32| v[at..at + 4].copy_from_slice(&x.to_le_bytes()); + let put64 = + |v: &mut Vec, at: usize, x: u64| v[at..at + 8].copy_from_slice(&x.to_le_bytes()); + // payload: slot count and record offsets, the record, its stage data, code, tables + let mut payload = vec![0u8; SLOTS.iter().map(|s| s.1).max().unwrap() + 8]; + put64(&mut payload, 0, GRAPHICS_SLOT_COUNT); + for (_, at) in SLOTS { + put64(&mut payload, at, ABSENT); + } + let record = payload.len(); + put64( + &mut payload, + super::SLOTS.iter().find(|s| s.0 == HwStage::Cs).unwrap().1, + record as u64, + ); + payload.resize(record + RECORD_SIZE as usize + CS_THREADS + 12, 0); + let stage = record + RECORD_SIZE as usize; + put32(&mut payload, stage + CS_RSRC2, cs.rsrc2); + for (k, n) in cs.threads.iter().enumerate() { + put32(&mut payload, stage + CS_THREADS + 4 * k, *n); + } + let code_at = payload.len(); + payload.extend_from_slice(&program.code); + let layout_at = payload.len(); + for p in &program.layout { + let mut e = [0u8; ENTRY_SIZE as usize]; + e[0..4].copy_from_slice(&root_raw(p.root).to_le_bytes()); + e[4..8].copy_from_slice(&p.table_offset_dwords.to_le_bytes()); + e[8..12].copy_from_slice(&p.sgprs.to_le_bytes()); + e[12..16].copy_from_slice(&p.base_register.to_le_bytes()); + e[16] = p.user_data; + e[17] = p.slot; + payload.extend_from_slice(&e); + } + let used_at = payload.len(); + for u in &program.used { + let mut e = [0u8; ENTRY_SIZE as usize]; + e[0] = kind_raw(u.kind); + e[1] = root_raw(u.root) as u8; + e[4..8].copy_from_slice(&u.table_offset_dwords.to_le_bytes()); + e[8..12].copy_from_slice(&u.lower_bound.to_le_bytes()); + e[12..16].copy_from_slice(&u.stride.to_le_bytes()); + e[16] = u.dwords; + e[17] = u.user_data; + e[18] = u.slot; + payload.extend_from_slice(&e); + } + put64(&mut payload, record, code_at as u64); + put64(&mut payload, record + 8, program.code.len() as u64); + put32( + &mut payload, + record + RECORD_FLAGS, + if program.wave64 { + 0 + } else { + super::FLAG_WAVE32 + }, + ); + put64(&mut payload, record + RECORD_LAYOUT, layout_at as u64); + put64(&mut payload, record + RECORD_USED, used_at as u64); + put32( + &mut payload, + record + RECORD_COUNTS, + program.layout.len() as u32, + ); + put32( + &mut payload, + record + RECORD_COUNTS + 4, + program.used.len() as u32, + ); + put32(&mut payload, record + RECORD_REGS, u32::from(program.vgprs)); + // FSSM, then XBCH around its zlib stream + let mut fssm = b"FSSM".to_vec(); + fssm.extend(FSSM_VERSION.to_le_bytes()); + fssm.extend((payload.len() as u64).to_le_bytes()); + debug_assert_eq!(fssm.len(), FSSM_HEADER); + fssm.extend(payload); + if fssm.len() as u64 > MAX_UNPACKED { + return Err(Malformed( + "native compute program exceeds the container size limit", + )); + } + let mut compressed = vec![0; zlib_rs::compress_bound(fssm.len())]; + let config = zlib_rs::DeflateConfig { + level: 0, + ..Default::default() + }; + let (stream, status) = zlib_rs::compress_slice(&mut compressed, &fssm, config); + if status != zlib_rs::ReturnCode::Ok { + return Err(Malformed("could not encode native compute program")); + } + let mut xbch = b"XBCH".to_vec(); + xbch.extend(XBCH_VERSION.to_le_bytes()); + xbch.extend((stream.len() as u64).to_le_bytes()); + xbch.extend((fssm.len() as u64).to_le_bytes()); + debug_assert_eq!(xbch.len(), XBCH_HEADER); + xbch.extend_from_slice(stream); + // the DXIL part: a header up to the index, the index of one entry, the blob + let mut dxil = vec![0u8; XDAT_OFFSET]; + dxil.extend_from_slice(b"XDAT"); + dxil.extend(1u32.to_le_bytes()); + dxil.extend(0x24u32.to_le_bytes()); + let blob_at = dxil.len() + 12; + dxil.extend(KIND_NATIVE.to_le_bytes()); + dxil.extend((blob_at as u32).to_le_bytes()); + dxil.extend((xbch.len() as u32).to_le_bytes()); + dxil.extend(xbch); + Ok(dxbc::build(&[(FourCC::DXIL, &dxil)])) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A synthetic table with a fixed + /// sampler and a table of an SRV, two UAVs and a CBV, then a range and + /// the hash. + fn table() -> Vec { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 5 << 16] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| { + for w in words { + t.extend(w.to_le_bytes()); + } + }; + entry([0x41, 0x401, 0, 3, 0, 0x0002_0004, u32::MAX, 0]); + entry([0x41, 0x300, 0, 9, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x303, 8, 2, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x303, 16, 3, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x302, 24, 1, 0, 0x404, u32::MAX, 0]); + entry([0x42, 0, 0, 9, 1, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + t + } + + fn registers() -> Vec { + [0u32, 0, 0, 8 << 16 | 8, 1, 3, 5 << 1] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect() + } + + #[test] + fn a_console_compute_program_reads_its_registers_and_table() { + let code = [0x7E00_0280u32, 0xBF81_0000, S_CODE_END, S_CODE_END]; + let code: Vec = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = console_compute(®isters(), &table(), &code).unwrap(); + assert!(p.wave64); + assert_eq!(p.vgprs, 16); + assert_eq!(p.code.len(), 8, "the s_code_end padding is left out"); + let StageIo::Cs(cs) = p.io else { panic!() }; + assert_eq!( + (cs.rsrc2, cs.threads, cs.user_sgprs()), + (5 << 1, [8, 8, 1], 5) + ); + assert_eq!(p.used.len(), 5); + assert_eq!( + p.used[2], + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 8, + lower_bound: 2, + stride: 4, + dwords: 8, + user_data: 4, + slot: 0, + } + ); + assert_eq!( + (p.used[0].kind, p.used[0].root, p.used[0].slot), + (ResourceType::Sampler, RootType::ImmediateSampler, 2) + ); + assert_eq!(p.layout[4].table_offset_dwords, 24); + } + + #[test] + fn incomplete_or_unknown_descriptions_are_refused() { + let t = table(); + let code = 0xBF81_0000u32.to_le_bytes(); + let regs = registers(); + for end in 0..t.len() { + assert!(console_compute(®s, &t[..end], &code).is_err()); + } + // Root constants of no size, an unknown tag, no hash. + for (offset, value) in [(t.len() - 64, 0x41u32), (24, 0x44), (t.len() - 32, 0x42)] { + let mut bad = t.clone(); + bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + assert!(console_compute(®s, &bad, &code).is_err()); + } + assert!(console_compute(®s, &t, &code[..3]).is_err()); + assert!(console_compute(®s, &t, &S_CODE_END.to_le_bytes()).is_err()); + let mut large = regs; + large[12..16].copy_from_slice(&(64u32 << 16 | 32).to_le_bytes()); + assert!(console_compute(&large, &t, &code).is_err()); + } + + /// As a title's table (a program with seven user SGPRs): a header count + /// one short of the 0x41 entries, two root slots whose entries name + /// user-data dwords 4 and 5, structured buffer SRVs of a 16-byte stride. + #[test] + fn entries_name_their_user_data_and_stride_as_a_title_does() { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 2 << 16 | 0x440] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| t.extend(words.iter().flat_map(|w| w.to_le_bytes())); + entry([0x41, 0x401, 0, 0, 0, 2 << 16 | 4, u32::MAX, 0]); + entry([0x41, 0x300, 0x130, 0x48, 0x10, 0x404, u32::MAX, 0]); + entry([0x41, 0x303, 0x28, 0x16, 4, 1 << 16 | 0x508, u32::MAX, 0]); + entry([0x42, 0, 0xc_0001, 0x48, 0, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + let mut regs = registers(); + regs[0x18..0x1c].copy_from_slice(&(7u32 << 1).to_le_bytes()); + let code = 0xBF81_0000u32.to_le_bytes(); + let p = console_compute(®s, &t, &code).unwrap(); + let named: Vec<_> = p.used.iter().map(|u| (u.slot, u.user_data, u.stride)).collect(); + assert_eq!(named, [(2, 0, 0), (0, 4, 16), (1, 5, 4)]); + assert_eq!(p.layout.iter().map(|l| l.user_data).collect::>(), [0, 4, 5]); + // Five user SGPRs do not reach dword 5. + regs[0x18..0x1c].copy_from_slice(&(5u32 << 1).to_le_bytes()); + assert!(console_compute(®s, &t, &code).is_err()); + } + + /// A title's gamma pass: a UAV table in dword 4 and one root constant + /// in dword 5, read as a value; and a depth word whose high half is not + /// the depth but says 32 lanes. + #[test] + fn root_constants_are_a_root_parameter_and_the_depth_its_low_half() { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 2 << 16 | 0x440] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| t.extend(words.iter().flat_map(|w| w.to_le_bytes())); + entry([0x41, 0x303, 0, 0x37, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x002, 0, 0x1f6, 0, 1 << 16 | 0x504, u32::MAX, 0]); + entry([0x42, 0, 0x2_0101, 0x37, 1, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + let mut regs = registers(); + regs[0x0c..0x10].copy_from_slice(&(1u32 << 16 | 32).to_le_bytes()); + regs[0x10..0x14].copy_from_slice(&0x0010_0001u32.to_le_bytes()); + regs[0x18..0x1c].copy_from_slice(&0x98cu32.to_le_bytes()); + let code = 0xBF81_0000u32.to_le_bytes(); + let p = console_compute(®s, &t, &code).unwrap(); + let StageIo::Cs(cs) = p.io else { panic!() }; + assert_eq!(cs.threads, [32, 1, 1]); + // 0x10 above the depth: 32 lanes, VGPRs in granules of 8. + assert!(!p.wave64); + assert_eq!(p.vgprs, 32); + assert_eq!(p.used.len(), 1, "constants are not a resource read"); + assert_eq!( + p.layout[1], + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0x1f6, + user_data: 5, + slot: 1, + } + ); + } + + /// As a title's table: a table in dword 4, a root SRV (t1) in dwords 5 + /// and 6, its 64-bit address, then a root constant in dword 7 (slot 2: + /// the root SRV's two dwords push it one past 4 + 2). + #[test] + fn a_root_descriptor_takes_two_user_data_dwords() { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 3 << 16 | 0x440] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| t.extend(words.iter().flat_map(|w| w.to_le_bytes())); + entry([0x41, 0x303, 0, 7, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x100, 0, 1, 0, 1 << 16 | 0x502, u32::MAX, 0]); + entry([0x41, 0x002, 0, 0x1f6, 0, 2 << 16 | 0x704, u32::MAX, 0]); + entry([0x42, 0, 0xa_0101, 7, 0, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + let mut regs = registers(); + regs[0x18..0x1c].copy_from_slice(&(8u32 << 1).to_le_bytes()); + let code = 0xBF81_0000u32.to_le_bytes(); + let p = console_compute(®s, &t, &code).unwrap(); + assert_eq!( + p.layout[1], + RootParam { + root: RootType::Descriptor, + table_offset_dwords: 0, + sgprs: 2, + base_register: 1, + user_data: 5, + slot: 1, + } + ); + assert_eq!( + p.used[1], + UsedResource { + kind: ResourceType::Srv, + root: RootType::Descriptor, + table_offset_dwords: 0, + lower_bound: 1, + stride: 0, + dwords: 2, + user_data: 5, + slot: 1, + } + ); + assert_eq!(p.used.len(), 2, "constants are not a resource read"); + let c = compute_container(&p).unwrap(); + let c = crate::Container::parse(&c).unwrap(); + assert_eq!( + super::super::native_programs(c.part(FourCC::DXIL).unwrap().data).unwrap(), + vec![p] + ); + // Six user SGPRs hold the address's low half only (without the + // constant, the root SRV the last entry). + regs[0x18..0x1c].copy_from_slice(&(6u32 << 1).to_le_bytes()); + t.drain(0x58..0x78); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + assert!(console_compute(®s, &t, &code).is_err()); + regs[0x18..0x1c].copy_from_slice(&(7u32 << 1).to_le_bytes()); + assert!(console_compute(®s, &t, &code).is_ok()); + } + + #[test] + fn short_header_wave32_and_multiblock_code_round_trip() { + let mut t = table(); + t.drain(8..16); + t[..4].copy_from_slice(&3u32.to_le_bytes()); + let mut regs = registers(); + regs[..4].copy_from_slice(&super::super::FLAG_WAVE32.to_le_bytes()); + let code = vec![0; 65536]; + let p = console_compute(®s, &t, &code).unwrap(); + assert!(!p.wave64); + assert_eq!(p.vgprs, 32); + let bytes = console_compute_container(®s, &t, &code).unwrap(); + let c = crate::Container::parse(&bytes).unwrap(); + assert_eq!( + super::super::native_programs(c.part(FourCC::DXIL).unwrap().data).unwrap(), + vec![p] + ); + } + + /// A serialized root signature (version 1.1): per parameter its type and + /// payload (register, space, and for root constants their count). + fn rts0(params: &[(u32, [u32; 3])], flags: u32) -> Vec { + let n = params.len() as u32; + let mut words = vec![2, n, 24, 0, 24 + 24 * n, flags]; + for (k, (kind, _)) in params.iter().enumerate() { + words.extend([*kind, 0, 24 + 12 * n + 12 * k as u32]); + } + for (_, payload) in params { + words.extend(payload); + } + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// As the title's `slot218-m007`: tables in user-data dwords 4 and 5 and + /// a root constant in 6 named, eleven user SGPRs. + fn named() -> Vec { + let p = |root, user_data, sgprs, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + vec![ + p(RootType::Table, 4, 1, 0), + p(RootType::Table, 5, 1, 1), + p(RootType::Constants, 6, 1, 2), + ] + } + + #[test] + fn a_root_signature_completes_what_the_table_leaves_out() { + // m007's eleven user SGPRs: three constants in 7 to 9 would leave + // dword 10 to a heap. + let params = [(0, [0; 3]), (0, [0; 3]), (1, [0x1f5, 0, 1]), (1, [0x1f6, 0, 3])]; + let (four, flags) = root_signature(&rts0(¶ms, 0)).unwrap(); + let layout = completed(&named(), &four, flags, 10).unwrap(); + assert_eq!(&layout[..3], named().as_slice()); + assert_eq!( + layout[3..], + [RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 3, + base_register: 0x1f6, + user_data: 7, + slot: 3, + }] + ); + // Without the user SGPRs for it, nothing more. + assert_eq!(completed(&named(), &four, flags, 7).unwrap(), named()); + let refused = |r: Result, ShaderError>| match r { + Err(Malformed(why)) => why, + r => panic!("{r:?}"), + }; + // A user SGPR past the parameters: a heap, whose place is not guessed. + let (_, heaps) = root_signature(&rts0(¶ms, 0x400)).unwrap(); + assert!(refused(completed(&named(), &four, heaps, 11)).contains("directly indexed heap")); + assert_eq!( + refused(completed(&named(), &four, 0, 11)), + "user SGPRs past the root parameters" + ); + // Constants cut by the end of the user SGPRs. + assert!(refused(completed(&named(), &four, 0, 8)).contains("cut by the end")); + // A table that places a parameter elsewhere, or names another type. + let mut moved = named(); + moved[2].user_data = 7; + assert!(refused(completed(&moved, &four, 0, 10)).contains("places a root parameter")); + let (tables, _) = root_signature(&rts0(&[(0, [0; 3]); 4], 0)).unwrap(); + assert!(refused(completed(&named(), &tables, 0, 10)).contains("places a root parameter")); + // Root UAVs, which no table places, and short blobs. + assert!(root_signature(&rts0(&[(4, [0; 3])], 0)).is_err()); + assert!(root_signature(&rts0(¶ms, 0)[..20]).is_err()); + } + + /// A root SRV is taken where the table places it itself (as the title's + /// t1 in dwords 5 and 6 after a table in 4), and refused where only the + /// signature names it. + #[test] + fn a_root_srv_is_taken_only_where_the_table_places_it() { + let p = |root, user_data, sgprs, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let table = vec![p(RootType::Table, 4, 1, 0), p(RootType::Descriptor, 5, 2, 1)]; + let (srv, flags) = root_signature(&rts0(&[(0, [0; 3]), (3, [1, 0, 0])], 0)).unwrap(); + assert!(srv[1].srv); + assert_eq!(completed(&table, &srv, flags, 7).unwrap(), table); + // The same signature with only the table named: the root SRV is not + // taken from the signature alone. + let refused = completed(&table[..1], &srv, flags, 7); + assert!(matches!(refused, Err(Malformed(why)) if why.contains("root SRV"))); + } + + #[test] + fn the_container_holds_what_the_root_signature_adds() { + let mut regs = registers(); + regs[0x18..0x1c].copy_from_slice(&(10u32 << 1).to_le_bytes()); + let code = 0xBF81_0000u32.to_le_bytes(); + // A table entry in dword 4 for slot 0; the signature's root CBV and + // constants follow, the second table being slot 1 at 5. + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 1 << 16 | 0x440] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| t.extend(words.iter().flat_map(|w| w.to_le_bytes())); + entry([0x41, 0x303, 0, 2, 4, 0x408, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + let root = rts0(&[(0, [0; 3]), (0, [0; 3]), (2, [3, 0, 0]), (1, [7, 0, 2])], 0); + let root = dxbc::build(&[(FourCC::RTS0, &root)]); + let bytes = console_compute_container_rooted(®s, &t, &code, Some(&root)).unwrap(); + let c = crate::Container::parse(&bytes).unwrap(); + let p = super::super::native_programs(c.part(FourCC::DXIL).unwrap().data).unwrap(); + let placed: Vec<_> = p[0].layout.iter().map(|l| (l.root, l.slot, l.user_data, l.sgprs)).collect(); + assert_eq!( + placed, + [ + (RootType::Table, 0, 4, 1), + (RootType::Table, 1, 5, 1), + (RootType::Descriptor, 2, 6, 2), + (RootType::Constants, 3, 8, 2), + ] + ); + // Without a signature, the table alone; one that cannot be read is + // refused. + let plain = console_compute_container_rooted(®s, &t, &code, None).unwrap(); + assert_eq!(plain, console_compute_container(®s, &t, &code).unwrap()); + assert!(console_compute_container_rooted(®s, &t, &code, Some(b"RTS0")).is_err()); + } + + #[test] + fn its_container_gives_the_program_back() { + let code: Vec = [0x7E00_0280u32, 0xBF81_0000] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = console_compute(®isters(), &table(), &code).unwrap(); + let container = compute_container(&p).unwrap(); + let c = crate::Container::parse(&container).unwrap(); + let back = super::super::native_programs(c.part(FourCC::DXIL).unwrap().data).unwrap(); + assert_eq!(back, vec![p]); + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 2b6edd4652..25ddc85429 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -402,6 +402,8 @@ struct Tracer<'a> { origin: Vec, /// See [`Resources::lane_copied`]. lane_copied: std::cell::RefCell>, + /// Set when [`Self::made_raw`] took a descriptor for its load's. + raw: std::cell::Cell, lanes: Option<&'a Structured>, /// While set, [`Self::sum`] keeps the first-lane read of an index as /// the computed term instead of what the lanes hold. @@ -475,6 +477,7 @@ impl<'a> Tracer<'a> { inputs, origin: Vec::new(), lane_copied: Default::default(), + raw: Default::default(), lanes, read_first_lane: Default::default(), meets: Default::default(), @@ -1124,7 +1127,22 @@ impl<'a> Tracer<'a> { .ok_or("a descriptor not in SGPRs")?; // Only the lanes that reach the access read the descriptor. let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); - self.classify(&words, &mut Vec::new(), &mut known) + self.raw.set(false); + let source = self.classify(&words, &mut Vec::new(), &mut known)?; + // A structured buffer made raw has no stride and no format: an index + // would add nothing and a format read would read a raw dword, where + // the load's descriptor would not. + if self.raw.get() { + let by_byte = match inst.fields { + Fields::Buffer { idxen, .. } => !idxen && !inst.name().contains("format"), + Fields::Smem { .. } => true, + _ => false, + }; + if !by_byte { + return Err("a structured buffer made raw, read by index or format"); + } + } + Ok(source) } /// The source of a descriptor's words; `joins` are the phi blocks @@ -1171,6 +1189,10 @@ impl<'a> Tracer<'a> { if let Some(source) = self.loaded(words) { return Ok(source); } + if let Some(source) = self.made_raw(words) { + self.raw.set(true); + return Ok(source); + } if let [lo, hi, Term::Const(w2), Term::Const(w3)] = *words { let (mut hi, mut bits) = (hi, 0); while let Term::Value(v) = hi @@ -2088,6 +2110,49 @@ impl<'a> Tracer<'a> { }) } + /// A structured buffer descriptor the console compiler makes raw, to + /// read the buffer by byte: dword 0 as loaded, dword 1 with the stride + /// cleared (`s_and_b32` by 0xc000ffff), dword 2 the record count times + /// the stride (`s_mul_i32` by `s_max_u32` of `s_bfe_u32` of dword 1, + /// 14 bits at 16, and 1), dword 3 with `OOB_SELECT` raw (`s_or_b32` of + /// 0x30000000, after an `s_and_b32` by 0xcfffffff or not). The memory + /// and its size in bytes are the load's, and the host's buffer views + /// are raw already: the load stands for it, as long as no access reads + /// it by index or format ([`Self::descriptor`]). + fn made_raw(&self, words: &[Term]) -> Option { + let &[w0, Term::Value(w1), Term::Value(w2), Term::Value(w3)] = words else { + return None; + }; + // The other operand of an SOP2 that wrote `v` from it and `k`. + let with = |v: Value, name: &str, k: u32| match self.sop2(v, &[name])?.1 { + [x, Term::Const(c)] | [Term::Const(c), x] if c == k => Some(x), + _ => None, + }; + let value = |t: Term| match t { + Term::Value(v) => Some(v), + Term::Const(_) => None, + }; + let x1 = with(w1, "s_and_b32", 0xC000_FFFF)?; + let mut x3 = with(w3, "s_or_b32", 0x3000_0000)?; + if let Some(x) = value(x3).and_then(|v| with(v, "s_and_b32", 0xCFFF_FFFF)) { + x3 = x; + } + let (_, [a, b]) = self.sop2(w2, &["s_mul_i32"])?; + let is_stride = |t: Term| { + value(t) + .and_then(|v| with(v, "s_max_u32", 1)) + .and_then(value) + .and_then(|v| with(v, "s_bfe_u32", 0x000E_0010)) + == Some(x1) + }; + let x2 = match (is_stride(a), is_stride(b)) { + (_, true) => a, + (true, false) => b, + (false, false) => return None, + }; + self.loaded(&[w0, x1, x2, x3]) + } + /// A descriptor the code keeps per lane: every dword of `words` is the /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled /// from SGPRs. The console compiler does this to a descriptor loaded on @@ -2264,7 +2329,7 @@ impl Tracer<'_> { let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + self.spilled(inst.read(Reg::V(reg))?, constant_operand(lane)?, &mut Vec::new()) .ok() .flatten() } @@ -2298,7 +2363,7 @@ impl Tracer<'_> { if inst.name() != "v_writelane_b32" { return Err(()); } - if lane_of(*at).ok_or(())? != lane { + if constant_operand(*at).ok_or(())? != lane { return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); } match *value { @@ -2314,8 +2379,8 @@ impl Tracer<'_> { } } -/// A lane select given as a constant. -fn lane_of(op: Operand) -> Option { +/// An inline or literal constant operand. +fn constant_operand(op: Operand) -> Option { match op { Operand::Const(c) => inline(c), Operand::Literal(x) => Some(x), @@ -2331,16 +2396,21 @@ fn copy_source(inst: &Inst, k: usize) -> Option { if inst.name() == "s_movk_i32" { return Some(Moved::Const(i32::from((*imm)? as i16) as u32)); } + if inst.name() == "s_bfm_b32" && k == 0 { + let [width, shift] = src.as_slice() else { return None }; + let width = constant_operand(*width)? & 31; + let shift = constant_operand(*shift)? & 31; + return Some(Moved::Const(((1u32 << width) - 1) << shift)); + } let src = src.first()?; match (inst.name(), *src) { ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => { inst.read(Reg::S(code + k as u8)).map(Moved::Value) } ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)), - ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)), + // A literal used by a 64-bit bitwise instruction is zero extended. + ("s_mov_b32" | "s_mov_b64", Operand::Literal(x)) => Some(Moved::Const(if k == 0 { x } else { 0 })), ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const), - // shortcut: only the one-operand ways the compiler makes a constant - // that has no inline form; fold more if descriptors need it. ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())), ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)), // 64-bit inline integers are sign-extended. @@ -2453,6 +2523,25 @@ pub(crate) mod tests { ); } + #[test] + fn a_constant_bitmask_can_supply_a_static_sampler_word() { + let r = track_words( + &[ + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xBE88_0480, // s_mov_b64 s[8:9], 0 + 0xBE8A_04FF, 0x8000_0001, // s_mov_b64 s[10:11], literal + 0x9209_8385, // s_bfm_b32 s9, 5, 3 + 0xF080_0F08, 0x0040_0002, // image_sample using s[8:11] as its sampler + S_ENDPGM, + ], + &[param(Table, 2, 1)], + HwStage::Ps, + ); + let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler).unwrap(); + assert_eq!(sampler.source, Source::Constant(vec![0, 0xf8, 0x8000_0001, 0])); + } + #[test] fn root_descriptors_are_built_in_code() { let r = track_words( @@ -2795,6 +2884,74 @@ pub(crate) mod tests { ); } + /// A structured buffer made raw as the title's 0x218 programs do + /// (`slot218-m005`, `m006`, `m008`), then `last` (an access through it), + /// with `count` the third dword times what `s_mul_i32` reads. + fn made_raw(count: u32, last: [u32; 2]) -> Vec { + vec![ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0101, + 0xFA00_0000, // s_load_dwordx4 s[4:7], s[2:3], null + 0x9388_FF05, + 0x000E_0010, // s_bfe_u32 s8, s5, 0xe0010 + 0x8488_8108, // s_max_u32 s8, s8, 1 + 0x8707_FF07, + 0xCFFF_FFFF, // s_and_b32 s7, s7, 0xcfffffff + count, // s_mul_i32 s6, s6, ... + 0x8807_FF07, + 0x3000_0000, // s_or_b32 s7, s7, 0x30000000 + 0x8705_FF05, + 0xC000_FFFF, // s_and_b32 s5, s5, 0xc000ffff + last[0], + last[1], + S_ENDPGM, + ] + } + + const MUL_BY_STRIDE: u32 = 0x9306_0806; // s_mul_i32 s6, s6, s8 + const BY_BYTE: [u32; 2] = [0xE030_1034, 0x8001_0100]; // buffer_load_dword v1, v0, s[4:7], 0 offen offset:52 + + #[test] + fn a_structured_buffer_made_raw_is_its_load() { + let code = made_raw(MUL_BY_STRIDE, BY_BYTE); + let r = track_words(&code, &[param(Table, 9, 1)], HwStage::Ps); + assert_eq!(r.scalar, [((0, 2), at(0, 0))]); + assert_eq!( + r.descriptors[0].source, + Source::Loaded { + load: (0, 2), + first: 0 + } + ); + } + + #[test] + fn a_structured_buffer_made_raw_read_by_index_or_changed_otherwise_fails() { + let fails = |code: Vec| { + let code: Vec = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err() + }; + // Stride 0 drops an index the load's descriptor would scale. + let by_index = [0xE030_2000, 0x8001_0100]; // buffer_load_dword v1, v0, s[4:7], 0 idxen + assert_eq!( + fails(made_raw(MUL_BY_STRIDE, by_index)), + ShaderError::Unsupported { + offset: 0x38, + what: "a structured buffer made raw, read by index or format" + } + ); + // A record count times something else than the stride is another size. + assert_eq!( + fails(made_raw(0x9306_0A06, BY_BYTE)), // s_mul_i32 s6, s6, s10 + ShaderError::Unsupported { + offset: 0x38, + what: "a descriptor changed after loading" + } + ); + } + #[test] fn untraceable_addresses_fail_with_a_reason() { let code: Vec = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3] diff --git a/docs/d3d12-shader-preload.md b/docs/d3d12-shader-preload.md new file mode 100644 index 0000000000..2e74bc623d --- /dev/null +++ b/docs/d3d12-shader-preload.md @@ -0,0 +1,17 @@ +# Direct3D 12 checks and shader preload + +Choose **DexNom Runtime (Preload and Play)** from the Start menu after running Setup, or run this command from PowerShell. + +```powershell +& "$env:LOCALAPPDATA\DexNom Runtime\victory-warm.exe" --play +``` + +The console shows progress while the runtime scans the installed archives. It caches supported shader translations and compute pipelines, reusing compatible entries. The game starts once the scan finishes and reports at least one successful translation. If the scan fails or finds no translatable shaders, the console displays the error and the log path. The same launcher lock covers both steps, and both use the same settings and cache. + +The preload log is identified by `logs/latest-warm.txt`. Once the game starts, `logs/latest.txt` points to the same log. The offline pass reports individual refusals and graphics pipelines are created as the game supplies their draw state. + +Pipeline preload checks for a Direct3D 12 device with Shader Model 6.6 before scanning archives. The runtime also respects the reported shader-visible view heap limit. It uses one million descriptors below Resource Binding Tier 3. A Tier 3 adapter can use a larger heap when the runtime and driver support it. [Direct3D 12 hardware tiers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-support) · [Descriptor heap limit query](https://github.com/microsoft/DirectX-Specs/blob/master/d3d/VulkanOn12.md#sampler-descriptor-heap-size-increase) + +## Verification + +On the RTX 5060, Direct3D 12 reported Resource Binding Tier 3 and a maximum of 1,000,000 shader-visible view descriptors. The runtime selected that size. A test using 52 local compute shaders translated 49, created 47 compute pipelines, and reported the remaining refusals. Launcher tests verified that preloading ran first, that both phases shared the same lock and settings, and that failure or an empty scan stopped the launch. diff --git a/docs/nvidia-rtx5060.md b/docs/nvidia-rtx5060.md new file mode 100644 index 0000000000..cefe06f5ec --- /dev/null +++ b/docs/nvidia-rtx5060.md @@ -0,0 +1,77 @@ +# RTX 5060 wave-size diagnosis + +The Series X profile reached the opening credits on an RTX 5060 (Windows driver `32.0.16.2124`, Windows build `26300.9974`). The original session ran DexNom commit `2e01ab4`. D3D12 reported 32 lanes for both `WaveLaneCountMin` and `WaveLaneCountMax`. [Microsoft's D3D12 options reference](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_feature_data_d3d12_options1) + +## Compute pipeline refusals + +The third session logged `0x80070057` for these six compute pipelines. A separate run of `victory translate --pipelines --list --validate` on the same PC validated the DXIL for all six with the Windows SDK validator. All six still declare a fixed wave size of 64 after translation. The tool now detects the host's maximum automatically, reports the wave-size mismatch, and created pipelines for all 12 comparison shaders selected from successful creations in the same log. + +| Compute shader hash | Refused in session 3 (UTC) | +| --- | --- | +| `369cbe906ea72764` | 18:12:02 | +| `02384a60fda6f2d0` | 18:13:26 | +| `2da4beb386509b77` | 18:13:54 | +| `2cc4c197ee29e291` | 18:13:58 | +| `5dc3b25986622949` | 18:19:27 | +| `6f225b641c5b0708` | 18:19:28 | + +The runtime now records the adapter name and PCI IDs and skips creation of compute pipelines that declare a wave size above the device's reported maximum. This makes skipped dispatches easier to trace. A wave32 implementation still needs to preserve the order of shared-memory reads and writes inside branches. For groups of multiple console waves, any synchronization that uses a group barrier also needs every thread in the group to participate. Earlier experiments with `VICTORY_WAVE_WIDE=1` reported device loss on another NVIDIA system. [RTX 3060 Ti report](https://github.com/DexNom/VIctory/pull/14) · [RTX 4070 report](https://github.com/DexNom/VIctory/pull/15) + +To repeat the offline check from a diagnostics build, substitute the archive from your local game installation: + +```powershell +$env:VICTORY_TRANSLATE_ONLY = '369cbe906ea72764,02384a60fda6f2d0,2da4beb386509b77,2cc4c197ee29e291,5dc3b25986622949,6f225b641c5b0708,13dfdd3b1136e407' +& .\target\x86_64-pc-windows-msvc\release\victory.exe translate --pipelines --validate --list --jobs 1 'D:\Path\To\Game\shaders.rpf' +``` + +## Frame time and termination + +The third session started with an existing pipeline library of about 87 MB. The screenshots show roughly 1–2 FPS during the opening credits. One late log sample recorded 1,633.9 ms per frame, including 1,035.5 ms of preparation, 253.8 ms of readback, and 17.0 ms of GPU execution. The runtime also reached its texture budget and reported recurring failures to rebase 12-byte typed buffer views. The effect of those view failures on the image remains unmeasured. + +At 18:21:19 UTC, about 9 min 19 s after launch, multiple threads in the title hit the same breakpoint and the process exited with `0x80000003`. The causal link between the missing compute pipelines and the breakpoint remains unverified. + +For a controlled test of upload workers and parallel preludes, use the same save and scene with equally warmed caches. Set both variables before starting the launcher so its child process inherits them. + +```powershell +$env:VICTORY_PARALLEL_PRELUDES = '1' +$env:VICTORY_FILL_WORKERS = '4' +& "$env:LOCALAPPDATA\DexNom Runtime\victory-play.exe" +``` + +## Independent validation on RTX 4060 + +On 25 November 2026, GitHub contributor `molodayamama` reported a clean test merge into `2e01ab4` on a GeForce RTX 4060 8 GB with Windows 10 22H2 and Agility SDK 1.614.1 from PR #12. The contributor reported passing the fixed-wave-size regression, all seven wave64 tests, and all 188 `victory-gpu` library tests. The four `xtask` tests also passed, and Clippy reported zero warnings with both default and all features. The contributor ran these checks without game files. The game-specific wave32 lowering remains open. [GitHub test report](https://github.com/DexNom/VIctory/pull/16#issuecomment-7171554003) + +## In-game retest on RTX 5060 + +The diagnostics build at PR commit `1ae3b85` ran with the Series X profile, experimental RT off, copied saves, and a separate cache. Both upload options were set before launch (`VICTORY_FILL_WORKERS=4` and `VICTORY_PARALLEL_PRELUDES=1`). Scripted Enter presses passed the start screen. The pipeline library was effectively cold at 3,006 bytes, so the loading times are unsuitable for comparison with the earlier warm-cache session. + +The runtime identified the NVIDIA GeForce RTX 5060 (PCI `10de:2d05`) and reported a 32-lane maximum. It logged explicit `required=64 max=32` refusals in game for `02384a60fda6f2d0`, `369cbe906ea72764`, and `2da4beb386509b77`. Rendering continued after all three refusals. + +The title then terminated during intro prestreaming after about 2 min 21 s from launcher startup (1 min 51 s on the game's clock, frame 943). It attempted a null write and exited with `0xc0000005`. The fault offset `+0x23cf683` and the next two image-relative stack offsets `+0x2215c35` and `+0x2215eca` match the pre-PR crash in the second session. The log contains no DXGI device removal for this run. This test confirms the wave-width diagnostics in game. The cause of the recurring null write remains open. + +## Integration run with PRs #1, #7, #9 and #12 + +The integration build combined `a902405` (AVX2 buffer comparison and merge), `3ac8713` (DXIL handle optimization and a pipeline wait ceiling), `83e78b9` (texture streaming, DirectStorage staging and indirect draws), and `999fd75` (optional Agility SDK) with PR #16 at `1ae3b85`. The combined source built in release with diagnostics. [PR #1](https://github.com/DexNom/VIctory/pull/1) · [PR #7](https://github.com/DexNom/VIctory/pull/7) · [PR #9](https://github.com/DexNom/VIctory/pull/9) · [PR #12](https://github.com/DexNom/VIctory/pull/12) + +The test used a separate profile with copied saves, `VICTORY_LOG=trace`, DRED requested, and a foreground PowerShell log. Windows reported that the D3D12 debug layer was unavailable (`0x887A002D`). This run used the system D3D12 runtime on Windows 11. The optional GPU texture detiler from PR #9 and experimental ray tracing were off. + +PR #7 reports the stack offsets from the earlier `0xc0000005` null-write crash as the title's 30-second GPU watchdog. It caps pipeline waiting based on the time since the previous Present. This integration run went from the menu into the introduction and did not reproduce that null write. One loading sample took about 25.2 s, including 8.3 s of preparation, 8.1 s of which was spent on copies. Cold pipeline creation and trace logging make these samples unsuitable for judging frame-rate changes. A single combined run cannot isolate the contribution of any one PR. + +The integration run ultimately crashed after about **13 min 18 s** from launch, at 20:46:10 local time. The crash report gives 13 min 16 s on the title's clock, frame 1260, with the introduction in `Prestream` and `Paused: Yes`. Seven threads hit an unhandled `0x80000003` breakpoint at image offset `+0x63966f`. The next four image-relative stack offsets, `+0x3e54ad0`, `+0x257035e`, `+0x221c29c` and `+0x2215eca`, match the third launch on `2e01ab4`. The last reported sample rendered 550 draws per frame at 1.63 s per frame, with zero pipelines still being built in that sample. The log reports all six known wave64 refusals and contains no DXGI device removal or DirectStorage request failure. The reason the title hit this breakpoint remains unverified. + +The follow-up for PR #16 checks the required fixed wave size against both limits reported by the D3D12 device. Offline translation can still be configured to target another wave width, while the pipeline check uses the actual device's range. [DirectX WaveSize validation rules](https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html) + +## Warm-cache retest and pipeline wait accounting + +The follow-up used the same PR heads for #1, #7, #9 and #12, a separate copy of the save data, the existing integration cache, and a visible PowerShell window with `VICTORY_LOG=info`. The Series X profile, the system D3D12 runtime, `VICTORY_FILL_WORKERS=4` and `VICTORY_PARALLEL_PRELUDES=1` were used for both launches. Experimental RT and GPU detiling stayed off. + +The earlier trace run's title report shows `INSTANCE_LIST: 45000/45000`. The warm-cache reference at integration commit `98c516d` loaded a 172,589,936-byte pipeline library and ran for about 6 min 48 s. It exited with `0x80000003` at `+0x5149aec` during intro prestreaming, frame 1944, with `INSTANCE_LIST` again at `45000/45000`. These are the two breakpoint offsets documented upstream under similar pool pressure. No DXGI device removal was logged. The reference recorded 36 samples with at least 500 draws per frame, with a median of 2,768.4 ms per frame. [Upstream pool report](https://github.com/Marvisak/VIctory/issues/698) + +The reference also logged a seventh wave64 refusal, `6b82bc7d22016cb5`. An offline RTX 5060 test of the seven refused shaders and one control validated all eight DXIL containers. The control created its pipeline. Each of the seven fixed wave64 shaders was outside the device's reported range of `32..=32`. + +The follow-up commit `6b5a888` corrects the loading-allowance accounting for host pipeline waits. Sequential waits count against the same frame budget, and overlapping waits in the default shared window count once. Outstanding waits are still accounted for if another frame starts first. The two regression cases reproduce the sequential and overlapping examples in the discussion of PR #7. Ten focused tests passed on PR #16 by itself, and twelve passed in the integration build with PR #7's ceiling since the previous Present. [Accounting report on PR #7](https://github.com/DexNom/VIctory/pull/7#issuecomment-7171115239) + +The corrected integration build `00b26e5` used `VICTORY_PIPELINE_WAIT_MS=500` to exercise the loading allowance and loaded a 208,756,190-byte pipeline library. The tester reached interactive gameplay, where the movement and camera prompts were visible at 10 min 44 s, and deliberately closed the window after about 10 min 53 s. The title exceeded the one-second suspend deadline and the runtime exited with code `0`. No title exception or DXGI device removal was logged before closure. Across 89 samples with at least 500 draws, the median was 570.9 ms per frame. The last three reported samples were approximately 249–290 ms per frame with about 5,000 draws. + +The corrected run logged an eighth fixed wave64 refusal, `926c46bab3b86bd6`. A repeat of the offline test with all eight shaders and the same control validated all nine DXIL containers. The control created its pipeline. The two live runs started with different pipeline libraries and wait settings, so the observed difference in frame time cannot be assigned to the accounting patch. The intrinsic cause of the pool exhaustion and support for the remaining wave64 shaders are still open. diff --git a/docs/pixel-shader-pops.md b/docs/pixel-shader-pops.md new file mode 100644 index 0000000000..74ccb61681 --- /dev/null +++ b/docs/pixel-shader-pops.md @@ -0,0 +1,42 @@ +# Primitive ordering in ten refused pixel shaders + +The Windows shader-preload run reported 13 translation refusals. Ten were distinct pixel shaders in one alpha-cutout/tint family. The other three were compute shaders addressed by [PR #35](https://github.com/DexNom/VIctory/pull/35). + +The identifiers below are the 16-character BLAKE3 prefixes used in the VIctory log. The instruction offsets are relative to the start of the native shader code. + +| Shader container hash | Previously reported branch | POPS setup | +| --- | --- | --- | +| `c1dacd75698a5db8` | `0x2dbc` | `0x2d8c` | +| `f0296ce9fbe481cb` | `0x2dbc` | `0x2d8c` | +| `a76619e2dcb45652` | `0x2dbc` | `0x2d8c` | +| `aafcf40b30b9df18` | `0x2dbc` | `0x2d8c` | +| `8c5ae9ea0f2158eb` | `0x2dbc` | `0x2d8c` | +| `c94ff21793ffd81e` | `0x2dbc` | `0x2d8c` | +| `09cee52e3ebbdf51` | `0x3014` | `0x2fe4` | +| `5ac9e7769a54e90c` | `0x3014` | `0x2fe4` | +| `1b1bee1ab00a82b5` | `0x3014` | `0x2fe4` | +| `bb3f113d13bd2788` | `0x3014` | `0x2fe4` | + +All ten decode the overlap bit and wave IDs from `s18`, configure `HW_REG_POPS_PACKER`, poll `src_pops_exiting_wave_id`, and send `MSG_ORDERED_PS_DONE` after the ordered section. Those `s18` fields match the documented `COLLISION_WAVEID` input. The ordered section contains texture reads and writes. [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [Mesa driver documentation](https://docs.mesa3d.org/drivers/amd/hw/pops.html) + +The DXIL emitter now reports `primitive-ordered pixel shading (POPS)` at the first recognized ordering instruction, before generic scalar lowering. The detection uses decoded GFX10 instructions and applies to the pixel stage. A synthetic test covers the packer write, volatile wave-ID source, completion message, and ordered termination. + +On an RTX 5060 with driver 621.24, a filtered release run matched all ten hashes. The installed preload build reported ten generic SGPR errors. The patched build reported ten POPS errors at the setup offsets in the table. Both emitted zero DXIL for this set. All 11 tests in `emit::barycentric_tests` passed. A D3D12 feature query on the RTX 5060 returned `ROVsSupported = true`. + +Supporting the full family requires tracing the UAV accesses inside the ordered section, proving the coordinates and ordering are representable by D3D12 rasterizer-ordered views, and accounting for ordering between lanes of the same guest wave before removing its synchronization. An overlapping-fragment test should verify the order-dependent read/modify/write results. [D3D12 rasterizer-ordered views](https://learn.microsoft.com/en-us/windows/win32/direct3d12/rasterizer-order-views) + +## Follow-up after the full preload + +With this PR applied to the [PR #47 preload launcher](https://github.com/DexNom/VIctory/pull/47), the cold scan translated 25,745 shaders and created 2,699 compute pipelines in 735 s. It reported ten POPS and three compute translation refusals, plus 32 compute pipeline refusals. The game launched and exited after 7 min 34 s during intro `Prestream`, at frame 1508. The breakpoint was `0x80000003` at `+0x5149aec`. The crash report showed `INSTANCE_LIST` at 45,000/45,000. The game phase contains none of the ten pixel hashes and has no D3D12 device-removal error. [Preload report](https://github.com/DexNom/VIctory/pull/47#issuecomment-7175433123) · [Upstream issue #698](https://github.com/Marvisak/VIctory/issues/698) + +The follow-up checks control flow from the POPS packer write to an explicit completion instruction. A filtered rerun found a path to an ordinary exit before explicit completion in every shader in the table. Six diagnostics point to `0x305c` and four to `0x32b4`. This identifies an ordering case a ROV lowering would have to handle. DXIL emission for the ten remains 0/10. + +The emitter now accepts an immediate zero that clears the inactive packer enable bit in a pixel shader without ordered operations. A synthetic test compares the emitted DXIL with an otherwise identical shader. The active protocol and the exit that bypasses completion have separate regression coverage. + +## D3D12 translation of the ten shaders + +The emitter reads the POPS enable flag from pixel-stage metadata and marks heap UAV handles as rasterizer ordered. It uses the guest layout to identify the collision SGPR and seeds distinct synthetic wave IDs so the shader does not wait for a GFX10 wave. D3D12 ROV accesses supply the ordering. The DXIL feature flags reflect the ROV handles that survive optimization. A pixel format without active POPS still uses the previous diagnostic, and direct root UAVs in active POPS shaders remain unsupported. [Upstream ROV work](https://github.com/Marvisak/VIctory/pull/2490) · [Collision seed](https://github.com/Marvisak/VIctory/pull/2395) · [Feature flags](https://github.com/Marvisak/VIctory/pull/2610) + +On the RTX 5060, each hash in the table was tested individually. All ten emitted DXIL, declared the ROV feature, passed the Windows SDK validator, and created a D3D12 graphics pipeline with a generated vertex shader. A separate `warm` run with an empty cache translated all ten with zero refusals. All 14 pixel tests passed, including a synthetic ordered texture store. In-game output and overlapping-fragment rendering remain unverified. + +A later RTX 5060 integration run combined the POPS change at `64255cf` with the compute builder fixes from [PR #35](https://github.com/DexNom/VIctory/pull/35) and the preload launcher from [PR #47](https://github.com/DexNom/VIctory/pull/47). Preload translated 25,758 shaders with zero translation refusals. D3D12 created 2,704 compute pipelines and refused 30. Those compute pipeline failures are tracked in the preload report on PR #47. diff --git a/docs/preload-progress-rtx-5060.md b/docs/preload-progress-rtx-5060.md new file mode 100644 index 0000000000..41ef866a1c --- /dev/null +++ b/docs/preload-progress-rtx-5060.md @@ -0,0 +1,18 @@ +# Live progress during shader preload + +`victory warm` reports the shaders checked, shaders translated, and compute pipelines created at each 2,000-shader boundary. It also reports the first completion after each 15-second interval. The `warm` summary remains the completion signal for Preload and Play. + +## Windows x64 on RTX 5060 + +The 25 November 2026 test combined the local gameplay integration `00b26e5` with the preload launcher from [PR #47](https://github.com/DexNom/VIctory/pull/47), the POPS follow-up from [PR #50](https://github.com/DexNom/VIctory/pull/50) at `33c05ba`, and the progress change. The runtime used a cold isolated cache and `VICTORY_PIPELINE_WAIT_MS=500`. + +| Elapsed | Shaders checked | Translated | Compute pipelines | +| ---: | ---: | ---: | ---: | +| 150 s | 22,005 | 21,995 | 627 | +| 300 s | 22,431 | 22,421 | 1,053 | +| 630 s | 23,937 | 23,927 | 2,539 | +| 653 s | 25,758 | 25,745 | 2,699 | + +Preload exited with code 0 and launched the game. There were 13 translation refusals and 32 compute pipeline refusals in preload. Ten of the translation refusals were POPS pixel shaders. The game phase logged seven compute pipeline refusals for a fixed 64-lane wave size on the 32-lane adapter. + +The game confirmed the 500 ms base wait and exited with code 0 after a window close roughly 6 min 15 s after launch. The requested suspend exceeded its one-second deadline. The game log contains no instance of the earlier `0x80000003` breakpoint, D3D12 device removal, or any of the ten POPS hashes. The session ended before the 7 min 34 s point at which the previous cold run crashed, so stability beyond that point and interactive gameplay remain unverified on this build. diff --git a/docs/rtx5060-compute-pipeline-refusals.md b/docs/rtx5060-compute-pipeline-refusals.md new file mode 100644 index 0000000000..41a7f15e2d --- /dev/null +++ b/docs/rtx5060-compute-pipeline-refusals.md @@ -0,0 +1,66 @@ +# RTX 5060 compute pipeline refusals + +## Combined build + +On 26 November 2026, the combined build `3adcc40` translated all 25,758 shaders in 83 s with its populated cache. Direct3D 12 created 2,704 compute pipelines and refused 30. The adapter reports 32-lane waves. + +The 30 inputs were tested separately from the game using `translate --list --validate --pipelines`. The Windows SDK validator accepted all 30 DXIL modules in both configurations. + +| Translator setting | Pipelines created | Wave-size refusals | Other refusals | +| --- | ---: | ---: | ---: | +| Default | 0 | 29 | 1 | +| `VICTORY_WAVE_WIDE=1` | 22 | 7 | 1 | + +The combined build used Preload and Play from [PR #47](https://github.com/DexNom/VIctory/pull/47), the compute builder changes from [PR #35](https://github.com/DexNom/VIctory/pull/35), and the POPS translation from [PR #50](https://github.com/DexNom/VIctory/pull/50). In PowerShell, set `VICTORY_FILL_WORKERS`, `VICTORY_PARALLEL_PRELUDES`, and `VICTORY_PIPELINE_WAIT_MS` before invoking the launcher so it inherits the values. + +The seven shaders that still require wave64 have thread groups of 128 to 1,024 threads and use local shared memory. The current two-wave fallback declines that multi-wave path. Creation of the other 22 pipelines verifies that the driver accepts their DXIL. The code records previous GPU hangs with some of the broad wave-wide fallbacks, so this experiment was limited to pipeline creation. [Upstream wave32 issue](https://github.com/Marvisak/VIctory/issues/2220) + +[PR #40](https://github.com/DexNom/VIctory/pull/40) is related work on an automatic wave-wide fallback. Its report includes two of the shaders in this comparison. + +`7f61193d2c0e5f22` repeatedly returns `0x8007000E` on the RTX 5060, including when compiled alone with optimization masks `0`, `1`, `3`, `15`, `31`, and `47`, or with default optimization. The SDK validator accepts its DXIL. The WARP smoke test reports waves of four lanes and stops at the wave-size check before creating a pipeline. + +## Upstream comparison + +The upstream prototype at `b3efa1c` creates five of the eight pipelines that still fail with `VICTORY_WAVE_WIDE=1` on the RTX 5060: + +| Shader hash | Combined build with wave-wide emulation | Upstream prototype | +| --- | --- | --- | +| `2da4beb386509b77` | Requires wave64 | Descriptor tracing refuses this shader | +| `3b02415f67c6b0d8` | Requires wave64 | Pipeline created | +| `1d434307d981352a` | Requires wave64 | Pipeline created | +| `22338086ea4c5364` | Requires wave64 | Pipeline created | +| `02384a60fda6f2d0` | Requires wave64 | Pipeline created | +| `6832a9da15c2e584` | Requires wave64 | Multi-wave lowering still refuses this shader | +| `6b82bc7d22016cb5` | Requires wave64 | Multi-wave lowering still refuses this shader | +| `7f61193d2c0e5f22` | D3D12 returns `0x8007000E` | Pipeline created | + +The native metadata for `6832a9da15c2e584` and `6b82bc7d22016cb5` specifies 1,024 threads and 32,768 bytes of shared memory per group. The upstream synchronization state adds 4,480 bytes, bringing both to 37,248 bytes and exceeding the emitter's 32 KiB limit. The four recovered wave64 shaders fit within that limit. + +The comparison uses the complete upstream prototype. Its final patch does not apply directly to `3adcc40`, whose emitter has a different layout and synchronization path. The `0x8007000E` result depends on the translator build tested here. The comparison does not identify the exact change that fixes it. [Multi-wave upstream work](https://github.com/Marvisak/VIctory/pull/2214) + +## Experimental conversion port + +The upstream prototype alone creates 22 pipelines on the 30-shader set. It gains five pipelines over the combined build with wave-wide emulation and loses five that require `v_cvt_f32_f64`: + +- `926c46bab3b86bd6` +- `6871d6e4b3ac9a10` +- `5dc3b25986622949` +- `6f225b641c5b0708` +- `a10179ab7eda0dc3` + +The isolated worktree `target/wave64-2214-check` ports the existing IEEE 754 double-to-float lowering from the combined build. Its targeted test passed for normal values, rounding ties, subnormals, infinities, NaNs, and input sign modifiers. A rerun of the 30 shaders with just this port still created 22 pipelines. The five listed shaders then reached a missing whole-wave reduction. + +Adding the existing double-precision reduction made `5dc3b25986622949` and `6f225b641c5b0708` pass DXIL validation and pipeline creation. The final run created **24 of the 30 pipelines** and reproduced six refusals: + +| Shader hash | Refusal in the experimental build | +| --- | --- | +| `2da4beb386509b77` | Descriptor tracing at `0x4d0` | +| `6832a9da15c2e584` | Shared memory budget for the 1,024-thread group | +| `6b82bc7d22016cb5` | Shared memory budget for the 1,024-thread group | +| `926c46bab3b86bd6` | Lane mask used as data at `0x4258` | +| `a10179ab7eda0dc3` | Lane mask used as data at `0x778c` | +| `6871d6e4b3ac9a10` | Lane mask used as data at the image store at `0x4eb4` | + +The prototype recovers five pipelines that the combined wave-wide path still refused. That combined path created the three lane-mask pipelines in the table, leaving three shaders that failed in both builds. + +The five targeted `console_waves` tests passed in the experimental build, including dispatch checks for several waves per group, divergent branches, loops, and shared memory barriers. The 30 title shaders were evaluated through pipeline creation only. The test launcher and its runtime settings were left as installed.