diff --git a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs index 8a6566503..b0968351c 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs @@ -23,6 +23,15 @@ //! state's first pipeline prints every field; a later one prints the fields that differ from the //! state's closest earlier pipeline (the one with the fewest differing fields), each as //! `old -> new` with the parts both share elided. +//! - **The descriptor.** A state's first line also names what the state was made from +//! (`descriptor:`, `StateDescriptor::logged`): each function's name, the SHA-256 of its bitcode +//! (`FunctionInfo::air_hash`; a precompiled function's key) and the constant values it was made +//! with, each color attachment's format, blend and write mask, the depth and stencil formats, +//! and the raster samples: enough to make the same state again from the same library. +//! - **The SPIR-V.** With `METAL2VULKAN_DUMP_PIPELINES` naming a directory, each pipeline's +//! modules are written there ([`dump`]), one file per module named by the hash the line prints +//! it by (`.spv`), each once; a write that fails is named in the line. Setting it turns +//! the log on too, so the lines that name the files are there. //! - **MoltenVK's split.** Where the device's driver is MoltenVK and its performance tracking is //! on (`MVK_CONFIG_PERFORMANCE_TRACKING=1`), the line adds what MoltenVK's own statistics //! (`vkGetPerformanceStatisticsMVK`) gained during the creation, per activity: SPIR-V to MSL, @@ -39,7 +48,7 @@ //! made it), then the `link`; else the whole `pipeline`'s driver making, its record loaded or //! missed. The translation of the state's functions is not in it: a variant is translated //! before any of its pipelines is made, on the program's thread. -//! - **Bounded, and off by default.** Nothing is kept or measured while the variable is unset. +//! - **Bounded, and off by default.** Nothing is kept or measured while the variables are unset. //! With it set, each state keeps the fields of its last [`HISTORY`] pipelines, and nothing //! else changes: the same pipelines are made, from the same keys, at the same points. //! - **Numbered where the making begins** (the owner's HITCH rule 1). A pipeline's number and the @@ -57,6 +66,8 @@ use metal2vulkan::vk::{DriverId, ShaderStage}; use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, VecDeque}; use std::hash::{Hash, Hasher}; +use std::io::Write; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -74,10 +85,49 @@ const HELPER_GUARD_STRATEGY: &str = "fragment.helper-guard"; /// The census name of a fragment function's calls an identity shuffle follows. const HELPER_FENCE_STRATEGY: &str = "fragment.helper-fence"; -/// Whether the log is on: read once, at the first state made. +/// Whether the log is on: read once, at the first state made. The SPIR-V dump turns it on too. pub(crate) fn enabled() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(metal2vulkan::env_vars::log_pipelines) + *ON.get_or_init(|| metal2vulkan::env_vars::log_pipelines() || dump_dir().is_some()) +} + +/// The directory the pipelines' SPIR-V is written into (`METAL2VULKAN_DUMP_PIPELINES`), read +/// once. +fn dump_dir() -> Option<&'static Path> { + static DIR: OnceLock> = OnceLock::new(); + DIR.get_or_init(|| metal2vulkan::env_vars::dump_pipelines().map(PathBuf::from)) + .as_deref() +} + +/// Write each of `pipeline`'s modules into the dump directory, where one is set, as +/// `.spv` (`spirv` holding each stage's [`spirv_hash`], in its stages' order), each once: +/// a module already there is left as it is. Where a write fails, the line's note of it. +fn dump(pipeline: &RenderPipeline, spirv: &[u64]) -> Option { + let dir = dump_dir()?; + let written = std::fs::create_dir_all(dir).and_then(|()| { + for (i, module) in pipeline.stages.iter().enumerate() { + let hash = spirv + .get(i) + .copied() + .unwrap_or_else(|| spirv_hash(&module.spirv)); + let path = dir.join(format!("{hash:016x}.spv")); + let opened = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path); + let mut file = match opened { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + }; + let bytes: Vec = module.spirv.iter().flat_map(|w| w.to_le_bytes()).collect(); + file.write_all(&bytes)?; + } + Ok(()) + }); + written + .err() + .map(|error| format!("; SPIR-V dump into {} failed: {error}", dir.display())) } thread_local! { @@ -183,6 +233,8 @@ static BEGUN: AtomicU64 = AtomicU64::new(0); pub(crate) struct StateLog { /// How the line names the state. name: String, + /// What the state was made from, as its first line names it (`StateDescriptor::logged`). + descriptor: String, /// The fields of its pipelines made so far, the latest last, at most [`HISTORY`]. made: Mutex>, /// Its pipelines made so far. @@ -193,9 +245,13 @@ pub(crate) struct StateLog { type Fields = BTreeMap; impl StateLog { - /// The log of a state labelled `label` whose functions are `functions`, numbered now; `None` - /// while the log is off. - pub(crate) fn new(label: Option<&str>, functions: &[String]) -> Option { + /// The log of a state labelled `label` whose functions are `functions`, made from what + /// `descriptor` names, numbered now; `None` while the log is off. + pub(crate) fn new( + label: Option<&str>, + functions: &[String], + descriptor: impl FnOnce() -> String, + ) -> Option { if !enabled() { return None; } @@ -203,6 +259,7 @@ impl StateLog { let label = label.map_or_else(String::new, |label| format!(" {label:?}")); Some(StateLog { name: format!("state {number}{label} ({})", functions.join(", ")), + descriptor: descriptor(), made: Mutex::new(VecDeque::new()), count: AtomicU64::new(0), }) @@ -230,8 +287,16 @@ impl StateLog { ) -> Line { let number = self.count.fetch_add(1, Ordering::Relaxed) + 1; let fields = fields(variant, pipeline, key, spirv); + let dumped = dump(pipeline, spirv).unwrap_or_default(); let mut made = lock(&self.made); - let described = describe(&fields, &made, number); + let described = match number { + 1 => format!( + "; descriptor: {}{}{dumped}", + self.descriptor, + describe(&fields, &made, number) + ), + _ => format!("{}{dumped}", describe(&fields, &made, number)), + }; if made.len() == HISTORY { made.pop_front(); } diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 0473bbaff..acbf3271a 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -400,9 +400,9 @@ pub(crate) enum StateDescriptor { } impl StateDescriptor { - /// Its functions' names, in pipeline order (`stage_name`). - fn function_names(&self) -> Vec { - let stages: Vec<&StageSource> = match self { + /// Its functions, in pipeline order. + fn stages(&self) -> Vec<&StageSource> { + match self { StateDescriptor::Vertex(descriptor) => std::iter::once(&descriptor.vertex) .chain(&descriptor.fragment) .collect(), @@ -412,8 +412,61 @@ impl StateDescriptor { .chain(std::iter::once(&descriptor.mesh)) .chain(&descriptor.fragment) .collect(), + } + } + + /// Its functions' names, in pipeline order (`stage_name`). + fn function_names(&self) -> Vec { + self.stages().into_iter().map(stage_name).collect() + } + + /// What the pipeline creation log names a state of this descriptor by + /// (`creation_log.rs`): each function's name, the SHA-256 of its bitcode + /// (`FunctionInfo::air_hash`; a precompiled function's key) and the constant values it was + /// made with, by index and by name, each as its type and its bytes; each color attachment's + /// format, blend and write mask; the depth and stencil formats; and the raster samples. + fn logged(&self) -> String { + let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::(); + let functions: Vec = self + .stages() + .into_iter() + .map(|source| match source { + StageSource::Function(descriptor) => { + let info = descriptor.function.info(); + let constants = &descriptor.constants; + let values: Vec = (constants.by_index.iter()) + .map(|(index, value)| { + format!("{index}: {:?} {}", value.ty, hex(&value.bytes)) + }) + .chain(constants.by_name.iter().map(|(name, value)| { + format!("{name}: {:?} {}", value.ty, hex(&value.bytes)) + })) + .collect(); + format!( + "`{}` air {} constants {{{}}}", + info.name, + hex(&info.air_hash), + values.join(", ") + ) + } + StageSource::Compiled(compiled) => format!("{:?}", compiled.key()), + }) + .collect(); + let colors: Vec = (self.color_attachments().iter().enumerate()) + .filter_map(|(index, color)| { + color.map(|a| format!("{index}: {:?} {}", a.pixel_format, blend_text(&a))) + }) + .collect(); + let (depth, stencil) = match self { + StateDescriptor::Vertex(d) => (d.depth_format, d.stencil_format), + StateDescriptor::Mesh(d) => (d.depth_format, d.stencil_format), }; - stages.into_iter().map(stage_name).collect() + format!( + "functions [{}]; colors [{}]; depth {depth:?}; stencil {stencil:?}; raster samples {}", + functions.join("; "), + colors.join("; "), + self.raster_sample_count() + ) } /// A draw of a state of this descriptor at color `index`, in words for a notice: its @@ -434,18 +487,7 @@ impl StateDescriptor { .copied() .flatten(); let state = match color { - Some(a) if a.blending_enabled => format!( - "color {index} blended: color {:?} {:?} {:?}, alpha {:?} {:?} {:?}, write mask \ - {:?}", - a.source_rgb_blend_factor, - a.rgb_blend_operation, - a.destination_rgb_blend_factor, - a.source_alpha_blend_factor, - a.alpha_blend_operation, - a.destination_alpha_blend_factor, - a.write_mask - ), - Some(a) => format!("color {index} unblended, write mask {:?}", a.write_mask), + Some(a) => format!("color {index} {}", blend_text(&a)), None => format!("no color {index}"), }; format!("a draw of {function} ({state})") @@ -1987,7 +2029,9 @@ impl GraphicsState { let at_bind_views = AtBindViews::new(device, &base.shared_pipeline().interface); let log = match warming { true => None, - false => StateLog::new(label.as_deref(), &descriptor.function_names()), + false => StateLog::new(label.as_deref(), &descriptor.function_names(), || { + descriptor.logged() + }), }; Ok(GraphicsState(Arc::new_cyclic(|state| { // The state holds its ID's slot, which lists it among the states an indirect render @@ -2704,6 +2748,24 @@ fn mesh_descriptor_key(device: &Device, d: &MeshPipelineDescriptor) -> PipelineK } /// A stage's function name, or the compile key of a stage compiled already. +/// A color attachment's blend state, in words: its operation and factors for color and alpha, or +/// unblended, and its write mask, as the descriptor states them. +fn blend_text(a: &ColorAttachmentDescriptor) -> String { + match a.blending_enabled { + true => format!( + "blended: color {:?} {:?} {:?}, alpha {:?} {:?} {:?}, write mask {:?}", + a.source_rgb_blend_factor, + a.rgb_blend_operation, + a.destination_rgb_blend_factor, + a.source_alpha_blend_factor, + a.alpha_blend_operation, + a.destination_alpha_blend_factor, + a.write_mask + ), + false => format!("unblended, write mask {:?}", a.write_mask), + } +} + fn stage_name(source: &StageSource) -> String { match source { StageSource::Function(descriptor) => descriptor.function.info().name.to_string(), diff --git a/crates/metal2vulkan-runtime/src/tests/kept_variants.rs b/crates/metal2vulkan-runtime/src/tests/kept_variants.rs index 494ac92d3..489eead82 100644 --- a/crates/metal2vulkan-runtime/src/tests/kept_variants.rs +++ b/crates/metal2vulkan-runtime/src/tests/kept_variants.rs @@ -43,7 +43,7 @@ use std::time::{Duration, Instant}; const STATES: usize = 64; /// The library of the owned fixture `name` on `device`. -fn library(device: &Device, name: &str) -> Library { +pub(super) fn library(device: &Device, name: &str) -> Library { let ll = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../metal2vulkan-validation/fixtures/public/engine") .join(format!("{name}.ll")); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index fa36f4c53..9ff9b426c 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -374,6 +374,8 @@ mod pending_audit_device; mod pending_rebind; mod pipeline; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod pipeline_dump; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod pipeline_wait_order; #[cfg(unix)] mod pixel_format_info; diff --git a/crates/metal2vulkan-runtime/src/tests/pipeline_dump.rs b/crates/metal2vulkan-runtime/src/tests/pipeline_dump.rs new file mode 100644 index 000000000..4c4721a3f --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/pipeline_dump.rs @@ -0,0 +1,203 @@ +//! The pipeline creation log's descriptor and its SPIR-V dump (`pipeline/creation_log.rs`, +//! `METAL2VULKAN_LOG_PIPELINES`, `METAL2VULKAN_DUMP_PIPELINES`), on the device the cfg selects. A +//! child process of this test binary ([`dump_child`]) makes one render pipeline state of the owned +//! fixture `unspecialized_stage_functions`, its fragment function made with a constant and its +//! color blended, which makes its predicted `VkPipeline` at its creation +//! (`PipelineWaitPolicy::Exact`). With the dump directory set and the log variable unset, the +//! state's first line names each function, its bitcode's SHA-256 and its constant's type and +//! bytes, and the color's format, blend and write mask, and the directory holds each module the +//! line names, as `.spv`, of the words the line counts, and SPIR-V modules alone. With the dump variable empty and the +//! log variable unset, the child prints no line and writes no file. +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). + +use super::blit_holds::{exact_waits_device, Scratch}; +use super::kept_variants::library; +use crate::PipelineOptions; +use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues}; +use metal2vulkan::metal::{BlendFactor, DataType, PixelFormat}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use std::collections::BTreeSet; +use std::ffi::OsStr; +use std::path::Path; +use std::process::Command; + +/// The dump directory's variable. +const DUMP: &str = "METAL2VULKAN_DUMP_PIPELINES"; + +/// The log's variable. +const LOG: &str = "METAL2VULKAN_LOG_PIPELINES"; + +/// Where the child writes what the parent checks the line against: each function's name and its +/// bitcode's SHA-256, one per line. +const FACTS: &str = "M2V_PIPELINE_DUMP_FACTS"; + +/// What a line of the log starts with. +const LINE: &str = "metal2vulkan: pipeline creation: "; + +/// Run [`dump_child`] in `cwd` with `dump` as the dump variable and the log variable unset, its +/// facts written to `facts`: its stderr. +fn child(cwd: &Path, dump: &OsStr, facts: &Path) -> String { + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tests::pipeline_dump::dump_child", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .current_dir(cwd) + .env(DUMP, dump) + .env_remove(LOG) + .env(FACTS, facts) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert!(output.status.success(), "the child failed: {stderr}"); + stderr +} + +/// The files in `dir`, by name. +fn files(dir: &Path) -> BTreeSet { + std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect() +} + +/// With the dump directory set, the state's first line names its descriptor, and the directory +/// holds every module the lines name; with the dump variable empty and the log unset, no line and +/// no file (the module docs). +#[test] +fn the_log_names_the_descriptor_and_the_dump_holds_each_module() { + let scratch = Scratch::new("pipeline-dump"); + let (on, off) = (scratch.0.join("on"), scratch.0.join("off")); + std::fs::create_dir_all(&on).unwrap(); + std::fs::create_dir_all(&off).unwrap(); + let dir = scratch.0.join("dump"); + let facts = scratch.0.join("facts"); + + let stderr = child(&on, dir.as_os_str(), &facts); + let lines: Vec<&str> = stderr.lines().filter(|l| l.starts_with(LINE)).collect(); + let first = lines + .iter() + .find(|l| l.contains("; descriptor: ")) + .unwrap_or_else(|| panic!("no state's first line: {stderr}")); + let facts = std::fs::read_to_string(&facts).unwrap(); + for function in facts.lines() { + let (name, air) = function.split_once(' ').unwrap(); + assert!( + first.contains(&format!("`{name}` air {air} constants {{")), + "the line names {name} and its bitcode: {first}" + ); + } + for named in [ + "constants {fragment_tint: Float 00004040}", + "colors [0: BGRA8Unorm blended: color One Add OneMinusSourceAlpha, alpha One Add \ + OneMinusSourceAlpha, write mask ", + "; depth None; stencil None; raster samples 1", + ] { + assert!(first.contains(named), "the line names {named:?}: {first}"); + } + // Every module a line names in full (` ( words)`) is in the directory, of its + // words, and the directory holds SPIR-V modules alone. + let mut named = BTreeSet::new(); + for line in &lines { + for (at, _) in line.match_indices("spirv VK_SHADER_STAGE_") { + let field = &line[at..]; + let value = &field[field.find(": ").unwrap() + 2..]; + let Some((hash, rest)) = value.split_at_checked(16) else { + continue; + }; + let Some(words) = rest + .strip_prefix(" (") + .and_then(|rest| rest.split_once(" words)")) + .and_then(|(words, _)| words.parse::().ok()) + else { + continue; + }; + if !hash.chars().all(|c| c.is_ascii_hexdigit()) { + continue; + } + let bytes = std::fs::read(dir.join(format!("{hash}.spv"))).unwrap(); + assert_eq!( + bytes.len(), + words * 4, + "{hash}.spv holds the module's words" + ); + named.insert(format!("{hash}.spv")); + } + } + assert!( + named.len() >= 2, + "the lines name the stages' modules: {first}" + ); + let dumped = files(&dir); + assert!(named.is_subset(&dumped), "{named:?} among {dumped:?}"); + for file in &dumped { + let bytes = std::fs::read(dir.join(file)).unwrap(); + assert!(file.ends_with(".spv"), "{file}: a module's file"); + assert_eq!(bytes[..4], 0x0723_0203u32.to_le_bytes(), "{file} is SPIR-V"); + } + println!( + "PIPELINE-DUMP: {} line(s), {} module(s) dumped; first: {first}", + lines.len(), + dumped.len() + ); + + let stderr = child(&off, OsStr::new(""), &scratch.0.join("facts-off")); + assert!( + !stderr.lines().any(|l| l.starts_with(LINE)), + "no line with the log off: {stderr}" + ); + assert!(files(&off).is_empty(), "no file with the dump off"); +} + +/// The child of [`the_log_names_the_descriptor_and_the_dump_holds_each_module`], run as its own +/// process: makes one state (the module docs) and writes its functions' names and their bitcode's +/// SHA-256 to the file the parent names. +#[test] +#[ignore = "a child process of the_log_names_the_descriptor_and_the_dump_holds_each_module"] +fn dump_child() { + let facts = std::env::var_os(FACTS).expect("the parent names the facts' file"); + let scratch = Scratch::new("pipeline-dump-child"); + let device = exact_waits_device(&scratch.0); + let library = library(&device, "unspecialized_stage_functions"); + let vertex = library + .new_function_with_name("unspecialized_vertex_free") + .unwrap(); + let tint = FunctionConstantValue::new(DataType::Float, 3.0f32.to_le_bytes().to_vec()); + let fragment = library + .new_function_with_name_constant_values( + "unspecialized_fragment", + &FunctionConstantValues::defaults().with_name("fragment_tint", tint), + ) + .unwrap(); + let (vertex, fragment) = (vertex.function_descriptor(), fragment.function_descriptor()); + let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::(); + let written: String = [&vertex, &fragment] + .iter() + .map(|d| { + format!( + "{} {}\n", + d.function.info().name, + hex(&d.function.info().air_hash) + ) + }) + .collect(); + std::fs::write(facts, written).unwrap(); + let mut descriptor = RenderPipelineDescriptor::new(StageSource::Function(vertex)); + descriptor.fragment = Some(StageSource::Function(fragment)); + let mut color = ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm); + color.blending_enabled = true; + color.source_rgb_blend_factor = BlendFactor::One; + color.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha; + color.source_alpha_blend_factor = BlendFactor::One; + color.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha; + descriptor.color_attachments[0] = Some(color); + let state = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + drop(state); + drop(device); +} diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index 37acf544d..219f66d21 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -145,7 +145,7 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan-air/src/lib.rs", compile), ("metal2vulkan/src/cache/digest.rs", "the content digest, which defines the artifact rather than acting on it"), ("metal2vulkan/src/cache/mod.rs", "the plan's specialization and variant keys, whose values the plan digest holds, and RUNTIME_VERSION itself, which cannot be among the sources it versions"), - ("metal2vulkan/src/env_vars.rs", "the operational variables' accessors: the runtime reads only METAL2VULKAN_LOG_PIPELINES, METAL2VULKAN_LOG_MEMORY, METAL2VULKAN_LOG_SHADOWS, METAL2VULKAN_LOG_PASSES and METAL2VULKAN_PENDING_AUDIT, default-off diagnostics that print and change no run"), + ("metal2vulkan/src/env_vars.rs", "the operational variables' accessors: the runtime reads only METAL2VULKAN_LOG_PIPELINES, METAL2VULKAN_DUMP_PIPELINES, METAL2VULKAN_LOG_MEMORY, METAL2VULKAN_LOG_SHADOWS, METAL2VULKAN_LOG_PASSES and METAL2VULKAN_PENDING_AUDIT, default-off diagnostics that print (and write the pipelines' SPIR-V into the dump directory) and change no run"), ("metal2vulkan/src/error/mod.rs", "the error vocabulary: the runtime's code decides which error a run reports, and a record keeps the error as reported"), ("metal2vulkan/src/library/mod.rs", compile), ("metal2vulkan/src/lower/access/imageblock.rs", compile), diff --git a/crates/metal2vulkan/src/env_vars.rs b/crates/metal2vulkan/src/env_vars.rs index 5b9e8603e..aef44d8c1 100644 --- a/crates/metal2vulkan/src/env_vars.rs +++ b/crates/metal2vulkan/src/env_vars.rs @@ -39,8 +39,11 @@ pub const REGISTRY: &[EnvVar] = &[ default: "unset (off)", effect: "metal2vulkan-runtime's diagnostics: one line per render VkPipeline a device \ makes, through the device's message sink or on stderr: its state, its key, the \ - key's fields that differ from the state's closest earlier pipeline, and the \ - creation's time, split by the making's parts (the digests, each library made \ + key's fields that differ from the state's closest earlier pipeline (a state's \ + first line also names the descriptor the state was made from: each function's \ + name, the SHA-256 of its bitcode and the constant values it was made with, each \ + color attachment's format, blend and write mask, the depth and stencil formats \ + and the raster samples), and the creation's time, split by the making's parts (the digests, each library made \ with its record loaded or missed or another caller's, the link) and by \ MoltenVK's activities where its performance tracking is on \ (MVK_CONFIG_PERFORMANCE_TRACKING=1); and once per reason, why a draw \ @@ -48,6 +51,15 @@ pub const REGISTRY: &[EnvVar] = &[ than a snapshot, and how many such draws the snapshot's area rule weighed at each \ share of their colors' pixels and texel bytes; set to anything but empty or 0", }, + EnvVar { + name: "METAL2VULKAN_DUMP_PIPELINES", + default: "unset (off)", + effect: "metal2vulkan-runtime's diagnostics: a directory (made where missing) each device \ + writes the SPIR-V modules of every render VkPipeline it makes into, one file per \ + module, `.spv`, the hash METAL2VULKAN_LOG_PIPELINES's lines name the \ + module by, each written once; setting it turns that log on too; empty or 0 is \ + off", + }, EnvVar { name: "METAL2VULKAN_LOG_MEMORY", default: "unset (off)", @@ -152,6 +164,14 @@ pub fn log_shadows() -> bool { .is_some_and(|value| !value.is_empty() && value != "0") } +/// The directory metal2vulkan-runtime writes its render pipelines' SPIR-V modules into +/// (`REGISTRY`), as set; `None` where unset, empty or `0`. A default-off diagnostic: it writes +/// files, and changes no pipeline. +pub fn dump_pipelines() -> Option { + std::env::var_os("METAL2VULKAN_DUMP_PIPELINES") + .filter(|value| !value.is_empty() && value != "0") +} + /// The textures metal2vulkan-runtime's pass log watches, as set (`REGISTRY`): a comma-separated /// list of `FORMAT:WIDTHxHEIGHT` the runtime parses, empty or `0` for none. A default-off /// diagnostic: it changes no pass, only what is printed. diff --git a/docs/API.md b/docs/API.md index 4f7d2e46a..93dfa455c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1638,7 +1638,12 @@ How a notice reaches you: With `METAL2VULKAN_LOG_PIPELINES` set, a device also logs one line per render `VkPipeline` it makes (id name `metal2vulkan-pipeline-creation`, `Info` severity), with where its time went: the wait for its turn, the digests that name its parts, each library (made by this making, from its -driver cache record or not, or another caller's) and the link; and, once per reason, why a draw +driver cache record or not, or another caller's) and the link; a state's first line also names +the descriptor it was made from (each function's name, the SHA-256 of its bitcode and the constant +values it was made with, each color attachment's format, blend and write mask, the depth and +stencil formats and the raster samples). With `METAL2VULKAN_DUMP_PIPELINES` naming a directory, a +device writes each such pipeline's SPIR-V modules there, one file per module named by the hash +the line prints it by (`.spv`), and the log is on too. And, once per reason, why a draw that reads its own pass's color attachment after a barrier took the split rather than a snapshot (id name `metal2vulkan-snapshot-fallback`, `Info` severity; `WorkCounts::reading_draws_snapshotted` counts those that took a snapshot), and now and then a count of the draws the snapshot's area rule