From e149088bd0eea5f329e0b166c3f61acb5f71ebd8 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 20 Nov 2026 22:05:59 -0800 Subject: [PATCH] CLI: --device returns, as the way to compile for a runtime's device 06a35ed9e4 deleted `--device ` (a ReproDevice: a device description and a policy) on the premise that only a runtime's FALLBACK bundle would write that file and none does. The premise missed what the option reproduces: metal2vulkan-runtime compiles with the device's description restricted to the features it enables and with the identity pointer and handle domains (crates/metal2vulkan-runtime/src/device.rs, `translator`), while `--profile` always compiles with the default domains (DevicePolicy::UNTRUSTED). So `--profile` cannot reproduce a refusal the runtime meets, and `--device` is the command line's one way to: a lane's whole-library translation of a guest library (job m3-max-61778) ran through it hours before the deletion landed. This restores 06a35ed9e4's code as it was: ReproDevice (new, to_json, from_json), the command line's DeviceFile and `--device`, its usage and help lines and the cli test a_device_file_takes_the_place_of_a_profile. The docs say what it is for now, not a runtime's bundle: repro.rs's module doc no longer says a runtime may write a bundle (none does), the ReproDevice doc and the help text name a runtime's compile device and the default domains a profile takes, and the README's command-line section says the same. The module stays gated on `cli`, its only user. Verified: m3-max-61797 (msi) at 26ef12d7a3 (this change on 36e763e80e): clippy -p metal2vulkan --all-targets with all features, with none and with serde alone, -D warnings, all 0; rustdoc -D warnings 0; the cli binary's 9 tests pass, a_device_file_takes_the_place_of_a_profile among them. --- README.md | 6 +- crates/metal2vulkan/src/main.rs | 98 +++++++++++++++++++++++++------- crates/metal2vulkan/src/repro.rs | 40 ++++++++++++- crates/metal2vulkan/tests/cli.rs | 59 +++++++++++++++++++ 4 files changed, 178 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index f92df0dc2..a76cf8d95 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,11 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json - `--profile` is required: the crate ships no device description. Any Khronos profiles JSON works; [`crates/metal2vulkan-validation/profiles/`](crates/metal2vulkan-validation/profiles) has - examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. + examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. A profile compiles with the + default domains (`DevicePolicy::UNTRUSTED`). `--device FILE` takes its place with a device + description and policy as JSON (`{"description": ..., "policy": ...}`), which is how a runtime's + compile device is reproduced: metal2vulkan-runtime's is the description restricted to the + features it enables, with the identity pointer and handle domains. - Without `--function` it compiles the library's only kernel or vertex function. A kernel with `--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds `.tesc.spv` and `.tese.spv` modules; on a device without `tessellationShader` it answers diff --git a/crates/metal2vulkan/src/main.rs b/crates/metal2vulkan/src/main.rs index 064d11a35..d7c49ac53 100644 --- a/crates/metal2vulkan/src/main.rs +++ b/crates/metal2vulkan/src/main.rs @@ -3,7 +3,9 @@ //! the library's API (`Device::compile_compute_pipeline`, `compile_render_pipeline`, and //! `compile_tile_pipeline`). //! -//! Usage: `metal2vulkan [out.spv] --profile [options]`. +//! Usage: `metal2vulkan [out.spv] --profile [options]`, +//! or `--device ` in place of `--profile` (a device description and policy, such as a +//! runtime's compile device). //! A success prints a line containing `PASS`. Any failure prints `metal2vulkan: FALLBACK (why)` //! and exits with status 2; a failure after the inputs are read also writes a repro bundle //! (`metal2vulkan::repro`; `METAL2VULKAN_REPRO_DIR`, by default `$TMPDIR/metal2vulkan-repros`). @@ -29,13 +31,14 @@ use metal2vulkan::pipeline::{ SpecializationLayout, StageEntries, StageInputDescriptor, StageModule, StageSource, TileRenderPipelineDescriptor, VertexDescriptor, VertexInputState, }; -use metal2vulkan::repro::{shell_join, ReproBundle}; +use metal2vulkan::repro::{shell_join, ReproBundle, ReproDevice}; use metal2vulkan::{vk, Budget}; const USAGE: &str = "usage: metal2vulkan [out.spv] --profile [options]"; const HELP: &str = r#"usage: metal2vulkan [out.spv] --profile [options] + metal2vulkan [out.spv] --device [options] Compiles one pipeline of the input library for the device a Khronos profile describes, and writes its SPIR-V. A kernel writes out.spv; a render pipeline writes one module per stage, named by @@ -45,9 +48,14 @@ output is .vk.spv. A .ll input is assembled with llvm-a newer). options: - --profile FILE Khronos profiles JSON for the target device (required; the - repository's crates/metal2vulkan-validation/profiles/ holds examples) + --profile FILE Khronos profiles JSON for the target device (this or --device is + required; the repository's crates/metal2vulkan-validation/profiles/ + holds examples) --profile-name NAME the profile to read when FILE holds more than one + --device FILE the target device as a description and a policy: the JSON form of + metal2vulkan::device::DeviceDescription and DevicePolicy, + {"description": ..., "policy": ...}, in place of --profile (a + runtime's compile device; --profile takes the default domains) --function NAME the kernel or vertex function (default: the library's only one) --fragment NAME the fragment function of a render pipeline --constant ID:TYPE:VALUE function-constant value (repeatable): ID is an index or a name, TYPE a @@ -76,6 +84,29 @@ const DESCRIPTOR_FILES: [(&str, &str); 2] = [ ("--vertex-descriptor", "vertex-descriptor.json"), ]; +/// The device the command compiles for, as its file reads: a Khronos profiles document +/// (`--profile`), or a device description and policy (`--device`). +enum DeviceFile { + Profile(String), + Device(String), +} + +impl DeviceFile { + /// The device file's name in a repro bundle, and the options that name it there. + fn bundled(&self) -> (&'static str, [&'static str; 2], &[u8]) { + match self { + DeviceFile::Profile(json) => ( + "profile.json", + ["--profile", "profile.json"], + json.as_bytes(), + ), + DeviceFile::Device(json) => { + ("device.json", ["--device", "device.json"], json.as_bytes()) + } + } + } +} + /// What the command line asks for. #[derive(Default)] struct Args { @@ -83,6 +114,7 @@ struct Args { output: Option, profile: Option, profile_name: Option, + device: Option, function: Option, fragment: Option, constants: Vec<(String, FunctionConstantValue)>, @@ -96,7 +128,8 @@ struct Args { timeout: Option, emit_meta: Option, spirv_val: bool, - /// The options a repro bundle replays: every one but `--profile` and `--emit-meta`, with each descriptor file named as the bundle's copy of it + /// The options a repro bundle replays: every one but `--profile`, `--device` and + /// `--emit-meta`, with each descriptor file named as the bundle's copy of it /// ([`DESCRIPTOR_FILES`]). replay: Vec, } @@ -148,20 +181,27 @@ fn main() { let read = |path: &str| { fs::read_to_string(path).unwrap_or_else(|e| fail(&format!("cannot read {path}: {e}"))) }; - let Some(profile) = &args.profile else { - fail( + let device_file = match (&args.profile, &args.device) { + (Some(profile), None) => DeviceFile::Profile(read(profile)), + (None, Some(device)) => { + if args.profile_name.is_some() { + fail("--profile-name names a profile of --profile's document; --device has none"); + } + DeviceFile::Device(read(device)) + } + (Some(_), Some(_)) => fail("--profile and --device each name the device: give one"), + (None, None) => fail( "no --profile: name a Khronos profiles JSON for the target device (the repository's \ crates/metal2vulkan-validation/profiles/ holds examples, and the Vulkan SDK and \ - vulkaninfo --json produce more)", - ) + vulkaninfo --json produce more), or a device description and policy with --device", + ), }; - let profile = read(profile); let source = fs::read(&input).unwrap_or_else(|e| fail(&format!("cannot read {input}: {e}"))); let output = args .output .clone() .unwrap_or_else(|| default_output_path(&input)); - match run(&args, &source, &profile, &input, &output) { + match run(&args, &source, &device_file, &input, &output) { Ok(line) => println!("{line}"), Err(failure) => { if let Some(detail) = &failure.detail { @@ -171,7 +211,7 @@ fn main() { original: &original, input: &input, source: &source, - profile: &profile, + device_file: &device_file, args: &args, output: &output, }; @@ -188,14 +228,25 @@ fn main() { fn run( args: &Args, source: &[u8], - profile: &str, + device_file: &DeviceFile, input: &str, output: &str, ) -> Result { - let description = DeviceDescription::from_khronos_json(profile, args.profile_name.as_deref()) - .map_err(|e| Failure::detailed("profile not read", e.to_string()))?; - let device = Device::from_queries(description, DevicePolicy::default()) - .map_err(|e| Failure::detailed("profile refused", e.to_string()))?; + let device = match device_file { + DeviceFile::Profile(json) => { + let description = + DeviceDescription::from_khronos_json(json, args.profile_name.as_deref()) + .map_err(|e| Failure::detailed("profile not read", e.to_string()))?; + Device::from_queries(description, DevicePolicy::default()) + .map_err(|e| Failure::detailed("profile refused", e.to_string()))? + } + DeviceFile::Device(json) => { + let device = ReproDevice::from_json(json) + .map_err(|e| Failure::detailed("device not read", e))?; + Device::from_queries(device.description, device.policy) + .map_err(|e| Failure::detailed("device refused", e.to_string()))? + } + }; let assembled; let bitcode: &[u8] = if input.ends_with(".ll") { assembled = assemble(source)?; @@ -693,6 +744,10 @@ fn parse_args(args: &[String]) -> Args { parsed.profile = Some(value()); replayed = false; } + "--device" => { + parsed.device = Some(value()); + replayed = false; + } "--profile-name" => parsed.profile_name = Some(value()), "--function" => parsed.function = Some(value()), "--fragment" => parsed.fragment = Some(value()), @@ -943,22 +998,23 @@ struct Bundle<'a> { original: &'a [String], input: &'a str, source: &'a [u8], - profile: &'a str, + device_file: &'a DeviceFile, args: &'a Args, output: &'a str, } impl Bundle<'_> { - /// A bundle (`metal2vulkan::repro`) holding the input, the profile, the descriptor files, + /// A bundle (`metal2vulkan::repro`) holding the input, the device file, the descriptor files, /// the command that replays the failure on them, and why it failed, under /// `METAL2VULKAN_REPRO_DIR` or `$TMPDIR/metal2vulkan-repros`. fn write(&self, failure: &Failure) -> Result { let base = metal2vulkan::env_vars::repro_dir() .map(PathBuf::from) .unwrap_or_else(|| env::temp_dir().join("metal2vulkan-repros")); + let (device_name, device_options, device_bytes) = self.device_file.bundled(); let mut bundle = ReproBundle::new(repro_input_name(self.input), self.source) - .file("profile.json", self.profile.as_bytes().to_vec()) - .options(["--profile", "profile.json"]); + .file(device_name, device_bytes.to_vec()) + .options(device_options); let descriptors = [&self.args.stage_input, &self.args.vertex_descriptor]; for (path, (_, name)) in descriptors.into_iter().zip(DESCRIPTOR_FILES) { // A descriptor file that cannot be read is the failure the bundle records: its replay diff --git a/crates/metal2vulkan/src/repro.rs b/crates/metal2vulkan/src/repro.rs index 39868f58d..def93e1ed 100644 --- a/crates/metal2vulkan/src/repro.rs +++ b/crates/metal2vulkan/src/repro.rs @@ -2,9 +2,10 @@ //! `metal2vulkan` command line, which writes one for a failure after it read its inputs, under //! `METAL2VULKAN_REPRO_DIR` (`env_vars`). Not consumer API: the binary's, hidden as `env_vars` is. //! -//! A bundle holds the input (`input.metallib`, `input.air`, `input.ll` or `input.bin`), the -//! profile (`profile.json`, which `--profile` reads), the descriptor files the command names -//! (`stage-input.json`, `vertex-descriptor.json`), the command (`repro-command.txt`, and `repro.sh`, which runs it from +//! A bundle holds the input (`input.metallib`, `input.air`, `input.ll` or `input.bin`), the device +//! file (`profile.json`, which `--profile` reads, or `device.json`, which `--device` reads: a +//! [`ReproDevice`]), the descriptor files the command names (`stage-input.json`, +//! `vertex-descriptor.json`), the command (`repro-command.txt`, and `repro.sh`, which runs it from //! the bundle's directory) and `failure.txt`: why it failed, and each part of the request the //! command does not replay ([`ReproBundle::unreplayed`]). //! @@ -21,6 +22,39 @@ use std::sync::atomic::{AtomicU64, Ordering}; use sha2::{Digest, Sha256}; use crate::cache::Hash256; +use crate::device::{DeviceDescription, DevicePolicy}; + +/// The device a command compiles for, as `device.json` holds it and the command line's `--device` +/// reads it: a description and a policy, which build the same `Device` (`Device::from_queries`). +/// A runtime's compile device is one: metal2vulkan-runtime's is the device's description +/// restricted to the features it enables, with the identity pointer and handle domains, which a +/// Khronos profile read by `--profile` (the default domains) does not reproduce. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ReproDevice { + pub description: DeviceDescription, + pub policy: DevicePolicy, +} + +impl ReproDevice { + /// The device of `description` and `policy`. + pub fn new(description: DeviceDescription, policy: DevicePolicy) -> ReproDevice { + ReproDevice { + description, + policy, + } + } + + /// The device's `device.json`. + pub fn to_json(&self) -> Result, String> { + serde_json::to_vec_pretty(self).map_err(|e| e.to_string()) + } + + /// The device a `device.json` holds. + pub fn from_json(json: &str) -> Result { + serde_json::from_str(json).map_err(|e| e.to_string()) + } +} /// One bundle, built in memory and written by [`write`](Self::write). #[derive(Clone, Debug)] diff --git a/crates/metal2vulkan/tests/cli.rs b/crates/metal2vulkan/tests/cli.rs index a03f3989c..88cbb9df7 100644 --- a/crates/metal2vulkan/tests/cli.rs +++ b/crates/metal2vulkan/tests/cli.rs @@ -15,6 +15,7 @@ use metal2vulkan::pipeline::{ ComputePipelineDescriptor, FunctionDescriptor, StageSource, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; +use metal2vulkan::repro::ReproDevice; use metal2vulkan::Budget; fn repo() -> &'static Path { @@ -457,3 +458,61 @@ fn a_bundle_carries_its_descriptor_files_and_replays_the_failure() { "{replayed}" ); } + +/// `--device` reads a device description and policy (`ReproDevice`'s JSON) in place of +/// `--profile`, and compiles the same pipeline the profile's device does; the +/// two together, or `--profile-name` with `--device`, are usage errors. +#[test] +fn a_device_file_takes_the_place_of_a_profile() { + let scratch = Scratch::new(); + let json = std::fs::read_to_string(profile("moltenvk-m3")).unwrap(); + let description = DeviceDescription::from_khronos_json(&json, None).unwrap(); + let device_file = scratch.join("device.json"); + std::fs::write( + &device_file, + ReproDevice::new(description, DevicePolicy::default()) + .to_json() + .unwrap(), + ) + .unwrap(); + let input = fixture("ob3_texture_array.air"); + let by_profile = scratch.join("profile.spv"); + let by_device = scratch.join("device.spv"); + for (output, flag, file) in [ + (&by_profile, "--profile", profile("moltenvk-m3")), + (&by_device, "--device", device_file.clone()), + ] { + let result = cli( + &scratch, + &[ + input.as_os_str(), + output.as_os_str(), + os(flag), + file.as_os_str(), + os("--no-spirv-val"), + ], + &[], + ); + assert!(result.status.success(), "{}", text(&result.stderr)); + } + assert_eq!( + std::fs::read(&by_profile).unwrap(), + std::fs::read(&by_device).unwrap() + ); + let profile_path = profile("moltenvk-m3"); + for extra in [ + [os("--profile"), profile_path.as_os_str()], + [os("--profile-name"), os("any")], + ] { + let mut args = vec![ + input.as_os_str(), + by_device.as_os_str(), + os("--device"), + device_file.as_os_str(), + ]; + args.extend(extra); + let result = cli(&scratch, &args, &[]); + assert_eq!(result.status.code(), Some(2), "{}", text(&result.stderr)); + assert!(text(&result.stderr).contains("--device")); + } +}