diff --git a/crates/metal2vulkan-validation/src/acceptance.rs b/crates/metal2vulkan-validation/src/acceptance.rs index 47cec702f..ec05e9c62 100644 --- a/crates/metal2vulkan-validation/src/acceptance.rs +++ b/crates/metal2vulkan-validation/src/acceptance.rs @@ -261,11 +261,6 @@ pub enum PipelineRequest { shape: BindShape, #[serde(default, skip_serializing_if = "Option::is_none")] dispatch: Option, - /// The kernel compiles as a device-replay variant (`LoweringInputs::replay_bindings`, - /// `variants::compile_replay_for_shape`): a replayed template's pipeline, its buffers read - /// through the slot table the replay's preprocess writes per command. - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - replay: bool, }, /// The L4 row `entry`, a `stage` function with the function-constant values `constants` /// (none, the default: Metal's undefined, the plain census's compile), built as [`row`] @@ -288,15 +283,6 @@ pub enum PipelineRequest { template: RenderTemplate, #[serde(default)] shape: Option, - /// With a `shape`, the form of the variant it decides the stages compile in - /// (`variants::DrawForm`): the plain one, or an executed render command's, the - /// large-buffer form the runtime's host step draws in or a draw replay's forms its GPU - /// form draws in. - #[serde( - default, - skip_serializing_if = "crate::candidate::engine::variants::DrawForm::is_bound" - )] - form: crate::candidate::engine::variants::DrawForm, }, /// `Device::compile_render_pipeline` of `vertex` and `fragment`, rasterization enabled, from /// the Metal oracle's descriptor `template`: the engine candidate's draw of a case and its @@ -716,14 +702,13 @@ fn compile_counted( Ok::<_, Error>(function) }; let budget = Budget::with_deadline(deadline); - let render = - |descriptor: &RenderPipelineDescriptor, shape: Option<&BindShape>, form| match shape { - None => device.compile_render_pipeline(descriptor, &budget), - Some(shape) => crate::candidate::engine::variants::compile_render_for_shape( - device, descriptor, shape, form, &budget, - ) - .map(|(pipeline, _)| pipeline), - }; + let render = |descriptor: &RenderPipelineDescriptor, shape: Option<&BindShape>| match shape { + None => device.compile_render_pipeline(descriptor, &budget), + Some(shape) => crate::candidate::engine::variants::compile_render_for_shape( + device, descriptor, shape, &budget, + ) + .map(|(pipeline, _)| pipeline), + }; Ok(match request { PipelineRequest::Compute { entry, constants } => { let kernel = function( @@ -743,26 +728,25 @@ fn compile_counted( function: kernel, shape, dispatch, - replay, } => { - use crate::candidate::engine::variants; let kernel = function(0, Stage::Kernel, kernel, linked(0))?; - let compile = match replay { - true => variants::compile_replay_for_shape, - false => variants::compile_compute_for_shape, - }; - let (pipeline, _) = compile(device, &kernel, shape, dispatch.as_ref(), &budget)?; + let (pipeline, _) = crate::candidate::engine::variants::compile_compute_for_shape( + device, + &kernel, + shape, + dispatch.as_ref(), + &budget, + )?; AcceptancePipeline::Compute(Box::new(pipeline)) } PipelineRequest::VertexDraw { function: vertex, template, shape, - form, } => { let vertex = function(0, Stage::Vertex, vertex, linked(0))?; let descriptor = template.descriptor(StageSource::Function(vertex), None)?; - AcceptancePipeline::Render(Box::new(render(&descriptor, shape.as_ref(), *form)?)) + AcceptancePipeline::Render(Box::new(render(&descriptor, shape.as_ref())?)) } PipelineRequest::Draw { vertex, @@ -776,11 +760,7 @@ fn compile_counted( StageSource::Function(vertex), Some(StageSource::Function(fragment)), )?; - AcceptancePipeline::Render(Box::new(render( - &descriptor, - shape.as_ref(), - crate::candidate::engine::variants::DrawForm::Bound, - )?)) + AcceptancePipeline::Render(Box::new(render(&descriptor, shape.as_ref())?)) } PipelineRequest::MeshDraw { object, @@ -1648,7 +1628,6 @@ mod tests { }, shape: BindShape::default(), dispatch: None, - replay: false, }; let library = |names: &[&str]| LinkedLibrary { functions: names.iter().map(|name| (*name).to_owned()).collect(), @@ -1715,7 +1694,6 @@ mod tests { function: function("k", 2), shape: BindShape::default(), dispatch: None, - replay: false, }; assert_eq!(kernel.linked_ranges(), vec![Range { start: 1, end: 3 }]); assert_eq!(kernel.libraries(), 3); @@ -1723,7 +1701,6 @@ mod tests { function: function("v", 1), template, shape: None, - form: crate::candidate::engine::variants::DrawForm::Bound, }; assert_eq!(vertex.linked_ranges(), vec![Range { start: 1, end: 2 }]); let row = PipelineRequest::Compute { diff --git a/crates/metal2vulkan-validation/src/authored_compile.rs b/crates/metal2vulkan-validation/src/authored_compile.rs index ee861a02e..b354bc84a 100644 --- a/crates/metal2vulkan-validation/src/authored_compile.rs +++ b/crates/metal2vulkan-validation/src/authored_compile.rs @@ -10,13 +10,10 @@ //! //! - **The request.** A case is admitted and prepared by the executor's own device-free half //! (`engine::prepare_compile`: its run's preparation, except that an object or mesh case, whose -//! mesh render pipeline the executor does not draw, is prepared to compile it), and every -//! pipeline a run compiles before it reads device output -//! comes from `engine::case_compiles`: the case's own, and on a device where the device -//! replay runs, each registered replay variant. Each compiles in a compile worker (the 20-s and -//! 500-MiB per-attempt ceilings, a process-group kill). The pipelines of host-replayed commands -//! are compiled for bind shapes the producer's records decide on the device, so they are counted -//! per case and profile as uncovered, never compiled here; the count is part of the cell. +//! mesh render pipeline the executor does not draw, is prepared to compile it), and the one +//! pipeline a run compiles before it reads device output, the case's own, comes from +//! `engine::case_compile`. It compiles in a compile worker (the 20-s and 500-MiB per-attempt +//! ceilings, a process-group kill). //! - **The bounds.** Each case is admitted, prepared, and compiled in its own case worker //! ([`CaseWorkers`]) under the 500-MiB ceiling, so the census's process holds only the //! committed cases and their cells; `jobs` cases run at once, each case's compiles one at a time. @@ -47,8 +44,7 @@ use crate::candidate::engine::artifact::CaseArtifact; use crate::candidate::engine::{ - case_compiles, prepare_compile, CompileFailure, CompileSubject, PreparedCase, - ENGINE_EXECUTOR_ABI, + case_compile, prepare_compile, CompileFailure, PreparedCase, ENGINE_EXECUTOR_ABI, }; use crate::case::AuthoredCase; use crate::check::admission::{admit, ExecutionRequest, ExecutorError, NotSupported}; @@ -445,7 +441,7 @@ pub trait CaseCompiler: Sync { } /// The executor's admission and compile preparation ([`prepare_compile`]) of `case` over the -/// corpus at `root`, then every pipeline [`case_compiles`] lists for each of `devices`, each in a +/// corpus at `root`, then the pipeline [`case_compile`] plans for each of `devices`, each in a /// compile worker of `worker`: one cell per device, in order. pub fn compile_case( root: &Path, @@ -648,63 +644,31 @@ pub fn serve_if_requested() { )) } -/// `prepared` compiled on `device`: each pipeline of [`case_compiles`] in order, stopping at the -/// first that does not compile, as the executor's run stops, and the digest of what a run there -/// executes when every one compiled: each compile's, and the device replay's preprocess module -/// where the device replay runs its variants, as the executor's run records them; none when the -/// host replay runs any command buffer there. +/// `prepared` compiled on `device`: the pipeline of [`case_compile`], and the digest of what a run +/// there executes when it compiled, as the executor's run records it. pub fn compile_prepared( prepared: &PreparedCase, worker: &CompileWorker, device: &WorkerDevice, ) -> CellResult { - let planned = match case_compiles(prepared, device) { + let planned = match case_compile(prepared, device) { Ok(planned) => planned, Err(error) => return CellResult::decided(executor_outcome(error, FailureClass::Case)), }; + let mut artifact = CaseArtifact::default(); + let (result, measured) = planned.compile(worker, device, &mut artifact); let mut cell = CellResult { outcome: Ok(CellOutcome::Compiled), - host_replayed: planned.host_replayed, - compiles: 0, + host_replayed: 0, + compiles: 1, cost: Cost::default(), artifact: None, }; - let mut artifact = CaseArtifact::default(); - for compile in &planned.compiles { - let (result, measured) = compile.compile(worker, device, &mut artifact); - cell.compiles += 1; - cell.cost.add(measured.as_ref()); - if let Err(failure) = result { - cell.outcome = compile_outcome(failure).map_err(|failure| CellFailure { - detail: match compile.subject { - CompileSubject::Case => failure.detail, - CompileSubject::ReplayVariant { - token, - threads_per_group, - } => format!( - "the replay variant of pipeline token {token} for {threads_per_group:?}: {}", - failure.detail - ), - }, - ..failure - }); - return cell; - } + cell.cost.add(measured.as_ref()); + match result { + Ok(()) => cell.artifact = artifact.sha256(), + Err(failure) => cell.outcome = compile_outcome(failure), } - let replays = planned - .compiles - .iter() - .any(|compile| matches!(compile.subject, CompileSubject::ReplayVariant { .. })); - if replays { - if let Err(error) = artifact.record_replay_module(device.device()) { - cell.outcome = executor_outcome(error, FailureClass::Tool); - return cell; - } - } - if planned.host_replayed > 0 { - artifact.record_uncovered(); - } - cell.artifact = artifact.sha256(); cell } diff --git a/crates/metal2vulkan-validation/src/candidate.rs b/crates/metal2vulkan-validation/src/candidate.rs index 290c71543..bdd3c07e9 100644 --- a/crates/metal2vulkan-validation/src/candidate.rs +++ b/crates/metal2vulkan-validation/src/candidate.rs @@ -172,13 +172,6 @@ mod platform { &crate::worker::compile::WorkerDevice, &metal2vulkan::bind::BindShape, ) -> Result, - _children: impl FnMut( - &crate::worker::compile::WorkerDevice, - u64, - &metal2vulkan::bind::BindShape, - &super::engine::ChildCommand, - ) -> Result, - _registered: &[metal2vulkan::bind::ReplayVariant], ) -> super::engine::RunAttempt { super::engine::RunAttempt::of(Err( "candidate execution is supported only on Linux and macOS".into(), @@ -193,12 +186,6 @@ mod platform { &crate::worker::compile::WorkerDevice, &metal2vulkan::bind::BindShape, ) -> Result, - _children: impl FnMut( - &crate::worker::compile::WorkerDevice, - u64, - &metal2vulkan::bind::BindShape, - &super::engine::ChildCommand, - ) -> Result, ) -> super::engine::RunAttempt { super::engine::RunAttempt::of(Err( "candidate execution is supported only on Linux and macOS".into(), diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index addacae05..96077b045 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -14,8 +14,8 @@ //! ([`linked_modules`]). Each element of a texture array is the texture at its own Metal slot //! ([`resources::bound_textures`]), and an argument-buffer buffer of either executor is a used //! resource whose address its owner holds ([`argument_buffers`]); an argument-buffer texture is a -//! used texture whose resource id its owner holds, a member of the plan's heap, and a command -//! buffer an opaque id in its owner. Nothing about the layout is re-derived here. +//! used texture whose resource id its owner holds, a member of the plan's heap. Nothing about the +//! layout is re-derived here. //! //! Safety and evidence rules, in the order they apply: //! @@ -40,7 +40,6 @@ use crate::acceptance::{LinkedLibrary, PipelineRequest, RequestFunction}; use crate::c3::{VenueProfile, Venues, VENUE_PROFILE}; -use crate::case::indirect_commands::CommandBufferResource; use crate::case::out_of_bounds::{OutOfBoundsResource, OutOfBoundsTarget}; use crate::case::{ ArgumentBufferSamplerResource, AuthoredCase, OutputSelection, SamplerResource, Stage, @@ -77,7 +76,7 @@ use crate::worker::WorkerFailure; use base64::Engine as _; use metal2vulkan::bind::{ BindShape, BindState, BoundBuffer, BufferRanges, Dispatch, DrawCall, ExecutionStatus, - ReplayVariant, StageTable, StatusReport, + StageTable, StatusReport, }; use metal2vulkan::cache::Hash256; use metal2vulkan::device::DeviceProfile; @@ -114,8 +113,8 @@ pub mod variants; pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v207"; /// One kernel case in the terms the binder takes: what this executor supports of an -/// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures, command -/// buffers and pipeline states, textures, texture arrays, samplers, threadgroup lengths, function +/// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures, +/// textures, texture arrays, samplers, threadgroup lengths, function /// constants, a `dispatchThreads` grid, and a buffer, argument-buffer buffer, texture or /// argument-buffer texture output). #[derive(Clone, Debug, PartialEq, Eq)] @@ -146,16 +145,6 @@ pub struct ComputeCase { /// argument samplers, so the plan's sampler arrays hold it and the function's sampler table /// finds it. pub argument_buffer_samplers: BTreeMap<(u32, u32), ArgumentBufferSamplerResource>, - /// Each pipeline state, by `(owner Metal index, field offset)`: the case's token for it, the - /// word the owner holds at the field ([`argument_buffers::embed_objects`]). The product reads - /// the word only as an encoder's operand, the pipeline a command records. - pub objects: BTreeMap<(u32, u32), u64>, - /// Each command buffer, by `(owner Metal index, field offset)`: its record storage is the - /// argument-buffer buffer at the key ([`ComputeCase::argument_buffer_buffers`]), initialized - /// under its descriptor, at its ID's records address rather than its own, and its owner holds - /// its ID ([`records_ids`]); the run checks its final records - /// ([`argument_buffers::validate_records`]). - pub command_buffers: BTreeMap<(u32, u32), CommandBufferResource>, /// Each bound texture (initial contents included), by Metal texture index: the case's textures /// and each element of its texture arrays at its own slot ([`resources::bound_textures`]). pub textures: BTreeMap, @@ -171,7 +160,7 @@ pub struct ComputeCase { pub out_of_bounds: Vec, /// The bound each driver creation of the case's own pipeline is held to /// (`budgets::creation_within`): the case's declared one (`AuthoredCase::creation_bound`), or - /// the shared ceiling. An executed command's pipelines, its templates', keep the ceiling. + /// the shared ceiling. pub creation_bound: Duration, } @@ -283,6 +272,10 @@ pub fn compute_case(case: &AuthoredCase) -> Result { } require_case_families(case)?; for (present, what) in [ + ( + !case.command_buffers.is_empty() || !case.pipeline_states.is_empty(), + "an indirect command buffer or a pipeline state in an argument buffer", + ), (case.depth_stencil.is_some(), "a depth/stencil attachment"), (!case.vertex_inputs.is_empty(), "vertex inputs"), (case.draw.is_some() || case.tessellation.is_some(), "draws"), @@ -391,7 +384,7 @@ pub fn compute_case(case: &AuthoredCase) -> Result { return Err(gap(&format!("buffer {binding} bound twice"))); } } - let mut argument_buffer_buffers = + let argument_buffer_buffers = argument_buffers::embed(&mut buffers, &resources.argument_buffer_buffers) .map_err(|error| gap(&error))?; let argument_buffer_textures = @@ -400,13 +393,6 @@ pub fn compute_case(case: &AuthoredCase) -> Result { let argument_buffer_samplers = argument_buffers::embed_samplers(&mut buffers, &case.argument_buffer_samplers) .map_err(|error| gap(&error))?; - let objects = argument_buffers::embed_objects( - &mut buffers, - &mut argument_buffer_buffers, - &case.command_buffers, - &case.pipeline_states, - ) - .map_err(|error| gap(&error))?; let textures = resources::bound_textures(&resources.textures, &resources.texture_arrays) .map_err(|error| gap(&error))?; let mut samplers = BTreeMap::new(); @@ -426,8 +412,6 @@ pub fn compute_case(case: &AuthoredCase) -> Result { argument_buffer_buffers, argument_buffer_textures, argument_buffer_samplers, - objects: objects.pipeline_tokens, - command_buffers: objects.command_buffers, textures, samplers, threadgroup_lengths, @@ -458,10 +442,8 @@ pub fn compute_case(case: &AuthoredCase) -> Result { /// check keeps a case mapped without the checker to the same rule. (The compute executor binds /// device buffer arrays, [`compute_case`]. Both executors bind argument-buffer buffers, /// [`argument_buffers`], and texture arrays, each element the texture at its slot, -/// [`resources::bound_textures`], argument-buffer textures and command buffers, each command buffer -/// its record storage, and pipeline states, each its token in its owner; the compute executor -/// executes a kernel case's commands. Visible-function references are no resource: the case's -/// function links them, [`linked_modules`].) +/// [`resources::bound_textures`], and argument-buffer textures and samplers. Visible-function +/// references are no resource: the case's function links them, [`linked_modules`].) pub fn require_case_families(case: &AuthoredCase) -> Result<(), NotSupported> { crate::executor_contract::require_executor( &crate::executor_contract::case_requirements(case), @@ -601,13 +583,6 @@ pub fn sampler_ids(case: &ComputeCase) -> Result, Stri argument_buffers::sampler_ids(case.argument_buffer_samplers.keys().copied()) } -/// The `gpuResourceID` of each command buffer of `case`, by its key, in key order -/// ([`argument_buffers::records_ids`]): the word its owner holds, which the product resolves to its -/// record storage. -pub fn records_ids(case: &ComputeCase) -> Result, String> { - argument_buffers::records_ids(case.command_buffers.keys().copied()) -} - /// A bound buffer's addresses: the Metal `gpuAddress` the guest sees and the host Vulkan device /// address when the buffer has one. With device addresses an allocation's guest address is its /// device address, read as a signed number, moved up by [`BufferAddress::GUEST_OFFSET`] @@ -755,8 +730,6 @@ pub fn runs_through_runtime(case: &ComputeCase) -> bool { argument_buffer_buffers: _, argument_buffer_textures: _, argument_buffer_samplers: _, - objects, - command_buffers, textures: _, samplers: _, threadgroup_lengths: _, @@ -765,12 +738,10 @@ pub fn runs_through_runtime(case: &ComputeCase) -> bool { out_of_bounds: _, creation_bound: _, } = case; - objects.is_empty() - && command_buffers.is_empty() - && matches!( - dispatch, - Dispatch::Threads { .. } | Dispatch::Threadgroups { .. } - ) + matches!( + dispatch, + Dispatch::Threads { .. } | Dispatch::Threadgroups { .. } + ) } /// The bytes of each buffer a run through the runtime binds, by Metal index, as the Metal oracle @@ -957,8 +928,8 @@ pub struct RuntimeKernel<'a> { /// every field the mapping fills is named here, so a new one is decided when it is added. pub fn runs_render_through_runtime(case: &graphics::RenderCase) -> bool { let graphics::RenderCase { - vertex, - fragment, + vertex: _, + fragment: _, vertex_buffers: _, color_targets: _, depth_stencil, @@ -973,27 +944,12 @@ pub fn runs_render_through_runtime(case: &graphics::RenderCase) -> bool { companion: _, raster_sample_count: _, } = case; - let bound = |function: &graphics::RenderFunction| { - let graphics::StageResources { - buffers: _, - argument_buffer_buffers: _, - argument_buffer_textures: _, - argument_buffer_samplers: _, - objects, - command_buffers, - textures: _, - samplers: _, - } = &function.resources; - objects.is_empty() && command_buffers.is_empty() - }; // The runtime renders into no separate depth and stencil textures in one pass // (`Gap::RenderPass` of `DepthStencilViews`), which the oracle makes of an attachment of both. let one_aspect = |attachment: &LiteralDepthStencil| { attachment.depth.is_none() || attachment.stencil.is_none() }; - bound(vertex) - && fragment.as_ref().is_none_or(bound) - && depth_stencil.as_ref().is_none_or(one_aspect) + depth_stencil.as_ref().is_none_or(one_aspect) && *render_target_array_length == 0 && matches!( (assembly, draw), @@ -1331,148 +1287,10 @@ pub fn compute_request<'a>( function: linking(&case.entry, &case.constants, linked), shape: shape.clone(), dispatch: Some(case.dispatch), - replay: false, }; (request, with_linked(&[library], linked)) } -/// The verdict of a device replay whose preprocess refused commands for `faults`, `what` naming the -/// command buffer. The product's typed limits refuse the row (`not_supported{bind}`): no registered -/// variant has the command's pipeline and lengths and the threadgroup size of one of its regions -/// (its own, or an edge's), the command has more regions than the execution records, its grid -/// exceeds `2^32 - 1` threads, or a merged draw replay's commands draw `2^62` vertices or more, -/// where the host replay of v72 ran the command. Every other reason -/// fails it, as the host replay failed: the records passed the host contract's decode before the -/// replay (`validate_records`: no encoding fault, malformed record, draw, missing pipeline, or -/// state set while inherited), every allocation of the run is resident and the execution's capacity -/// is the storage's, so an encoding, record, action, pipeline, buffers, or range fault is a case -/// the host replay fails too (a dynamic stride) or a preprocess that disagrees with the host -/// contract. -pub fn replay_fault_verdict(what: &str, faults: metal2vulkan::bind::ReplayFaults) -> ExecutorError { - use metal2vulkan::bind::ReplayFaults as F; - let names = [ - (F::ENCODING, "encoding"), - (F::ACTION, "a draw"), - (F::PIPELINE, "pipeline"), - (F::BUFFERS, "buffers"), - (F::VARIANT, "no registered variant"), - (F::GROUP_COUNT, "a grid past 2^32 - 1 threads"), - (F::RECORD, "a malformed record"), - (F::RANGE, "a command past the storage's capacity"), - (F::REGIONS, "more regions than the execution records"), - (F::BARRIER, "a set barrier between draws"), - (F::VERTICES, "a merged draw of 2^62 vertices or more"), - ]; - let named: Vec<&str> = names - .iter() - .filter(|(bit, _)| faults.contains(*bit)) - .map(|(_, name)| *name) - .collect(); - let reasons = format!("{:#x}: {}", faults.0, named.join(", ")); - let limits = F::VARIANT.0 | F::GROUP_COUNT.0 | F::REGIONS.0 | F::VERTICES.0; - if faults.0 != 0 && faults.0 & !limits == 0 { - NotSupported::Bind(format!( - "{what}: the device replay dispatched nothing for command(s) the registered variants \ - do not run ({reasons})" - )) - .into() - } else { - ExecutorError::Failed(format!( - "{what}: the device replay refused command(s) the host contract admits or a run \ - cannot bind ({reasons}); the output is not evidence" - )) - } -} - -/// The dispatch of a device-replay variant for a threadgroup of `threads_per_group` threads: -/// indirect, its group counts the replay's arguments, so it plans on the pipeline variant every -/// such dispatch runs on (`dispatch_variant`). The arguments' buffer is the replay's scratch, which -/// no plan names. -pub fn replay_dispatch(threads_per_group: [u32; 3]) -> Dispatch { - Dispatch::ThreadgroupsIndirect { - indirect: metal2vulkan::bind::IndirectRef::new(0, 0), - threads_per_group, - } -} - -/// The compile request for the device-replay variant of the template `case` (its dispatch a -/// [`replay_dispatch`]) for the bind shape `shape`, which binds no kernel buffer: -/// [`compute_request`] with `replay` set, so the kernel compiles with -/// `LoweringInputs::replay_bindings`. -pub fn replay_request<'a>( - library: &RowSource<'a>, - linked: &[LinkedModule], - case: &ComputeCase, - shape: &BindShape, -) -> (PipelineRequest, Vec>) { - let request = PipelineRequest::BoundCompute { - function: linking(&case.entry, &case.constants, linked), - shape: shape.clone(), - dispatch: Some(case.dispatch), - replay: true, - }; - (request, with_linked(&[library], linked)) -} - -/// One allocation of a compute run that a replayed command may bind or reach through a pointer, by -/// what it holds. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RunAllocation { - /// The case buffer at this Metal index. - Buffer(u32), - /// The argument-buffer buffer at this key (its owner's index and field offset). - ArgumentBuffer((u32, u32)), -} - -/// Every allocation of `case`'s run that a replayed command may bind or reach, in the order the -/// run lists them, each its token in the device replay's resident set ([`replay_resident`]): -/// each case buffer, then each argument-buffer buffer, -/// with the length the guest sees (not the padding). The compute executor's run lists its -/// allocations by it, and the authored compile census its variants' resident set. -pub fn run_allocations(case: &ComputeCase) -> Vec<(RunAllocation, u64)> { - case.buffers - .iter() - .map(|(&index, bytes)| (RunAllocation::Buffer(index), bytes.len() as u64)) - .chain( - case.argument_buffer_buffers - .iter() - .map(|(&key, bytes)| (RunAllocation::ArgumentBuffer(key), bytes.len() as u64)), - ) - .collect() -} - -/// The bind state the device replay's variants start from: each of `allocations` (its address and -/// the length the guest sees; its token its position) resident for reading and writing, as the -/// Metal oracle's `useResource` makes every allocation of the run resident. -pub fn replay_resident( - allocations: impl IntoIterator, -) -> Result { - let mut resident = BindState::default(); - for (token, (address, length)) in allocations.into_iter().enumerate() { - resident.used_resources.push(argument_buffers::used_buffer( - token, - length as usize, - address, - RenderStages::empty(), - )?); - } - Ok(resident) -} - -/// The bind state the registered replay variant `variant` is compiled and planned for: `resident` -/// ([`replay_resident`]) with the variant's threadgroup lengths and no kernel buffer. -pub fn replay_variant_state(resident: &BindState, variant: &ReplayVariant) -> BindState { - let mut state = resident.clone(); - let mut table = StageTable::default(); - for (slot, &length) in variant.threadgroup_memory_lengths.iter().enumerate() { - if length != 0 { - table.threadgroup_lengths.insert(slot as u32, length); - } - } - state.stages.insert(ShaderStage::Kernel, table); - state -} - /// The source of `case`'s generated companion, when it has one: its opaque AIR text, which the /// compile worker assembles. pub fn companion_source(case: &graphics::RenderCase) -> Option> { @@ -1511,7 +1329,6 @@ pub fn render_request<'a>( function: own(&case.vertex), template, shape: Some(shape.clone()), - form: variants::DrawForm::Bound, }; Ok((request, with_linked(&[library], linked))) } @@ -1719,15 +1536,11 @@ pub fn compute_shape( } /// The synthetic guest address of each argument-buffer buffer of `case`, by its key -/// ([`argument_buffers::synthetic_addresses`]): a command buffer's record storage at its records -/// address ([`records_ids`]), every other buffer at its [`BufferAddress::synthetic_used`]. +/// ([`argument_buffers::synthetic_addresses`]): its [`BufferAddress::synthetic_used`]. pub fn synthetic_used_addresses( case: &ComputeCase, ) -> Result, String> { - argument_buffers::synthetic_addresses( - case.argument_buffer_buffers.keys().copied(), - &records_ids(case)?, - ) + argument_buffers::synthetic_addresses(case.argument_buffer_buffers.keys().copied()) } /// A binder refusal as the executor reports it: an `Unsupported` is the product's typed outcome, @@ -1803,357 +1616,6 @@ pub struct PreparedCase { mapped: Mapped, /// The libraries the case's own function links ([`linked_modules`]). linked: Vec, - /// The template of each pipeline token the case's executed commands may run, as the - /// executor's context replays them ([`replay_templates`]). - templates: BTreeMap, -} - -/// A pipeline template an executed command may run: its checked case (by id in -/// [`CheckedCase::pipeline_templates`]), mapped, and the libraries it links. -pub struct ReplayTemplate { - case_id: String, - mapped: TemplateCase, - linked: Vec, -} - -/// What a replayed command runs: a compute command's dispatch, or a render command's draw of -/// `primitive`; or, for the device replay, the template's replay variant for a threadgroup of -/// `threads_per_group` threads, which every command selecting it dispatches indirectly; or, for -/// the device replay of render commands, the render template's draw replay variant, `merged` into -/// one draw or drawn once per command, which every command of the execution draws indirectly. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ChildCommand { - Dispatch(Dispatch), - Draw { - draw: DrawCall, - primitive: crate::case::Primitive, - }, - ReplayVariant { - threads_per_group: [u32; 3], - }, - DrawReplay { - merged: bool, - }, -} - -/// A template compiled for one replayed command: a compute pipeline for a dispatch, and for a -/// draw the template's render case (with the command's draw) and its pipeline. -pub enum CompiledChild { - Compute(Box), - Render(Box, Box), -} - -/// A replay template's case in the terms of the executor that runs it: a compute template a -/// dispatch runs, or a render template a draw runs. -#[derive(Clone, Debug)] -pub enum TemplateCase { - Compute(Box), - Render(Box), -} - -/// The template of each pipeline token an executed command of `checked`'s case may select: each -/// pipeline state's and each execution's parent pipeline's, by token, of a family some executed -/// command buffer runs. A compute template is mapped only when compute commands execute, a render -/// template only when render commands do, as the checker requires of render templates only then -/// (`check::check_render_replay_templates`): a command never selects a template of the other -/// family, so such a literal is no template here. A replayed compute template binds buffers and -/// threadgroup memory only; a replayed render template is a -/// rasterization-disabled vertex function (which the checker requires) that binds buffers only, -/// with no vertex input. A template with any other resource of its own refuses the case, before -/// any device ([`ToolingRequirement::ReplayedTemplateResources`]), and so does an object or mesh -/// template, whose mesh draw the executor does not draw -/// ([`ToolingRequirement::MeshRenderPipeline`]). -pub fn replay_templates( - checked: &CheckedCase, -) -> Result, ExecutorError> { - let case = &checked.primary.case; - let executed = || { - case.command_buffers - .iter() - .filter(|command| command.execute.is_some()) - }; - let executes_compute = executed().any(|command| !command.is_render()); - let executes_render = executed().any(|command| command.is_render()); - let parents = executed().filter_map(|command| { - let template = command.execute.as_ref()?.pipeline.as_ref()?; - Some((template.token, &template.case_id)) - }); - let mut templates = BTreeMap::new(); - for (token, case_id) in case - .pipeline_states - .iter() - .map(|state| (state.token, &state.case_id)) - .chain(parents) - { - let template = checked - .pipeline_templates - .get(case_id) - .ok_or_else(|| format!("pipeline template {case_id} was not checked"))?; - let executes_family = match template.case.stage { - Stage::Kernel => executes_compute, - Stage::Vertex | Stage::Fragment | Stage::Object | Stage::Mesh => executes_render, - }; - if !executes_family { - continue; - } - let mapped = match template.case.stage { - Stage::Kernel => { - let mapped = compute_case(&template.case)?; - let replayable = mapped.textures.is_empty() - && mapped.samplers.is_empty() - && mapped.argument_buffer_buffers.is_empty() - && mapped.argument_buffer_textures.is_empty() - && mapped.argument_buffer_samplers.is_empty() - && mapped.objects.is_empty(); - if !replayable { - return Err(NotSupported::Requirements( - [ToolingRequirement::ReplayedTemplateResources].into(), - ) - .into()); - } - TemplateCase::Compute(Box::new(mapped)) - } - Stage::Vertex | Stage::Fragment => { - let mapped = graphics::render_case( - &template.case, - &template.interface, - template.entry_ll(), - template.companion.as_ref(), - )?; - let resources = &mapped.vertex.resources; - // An index buffer or an out-of-bounds target is the template's own draw's; the - // replayed draw is the command's, which binds neither. - let replayable = mapped.fragment.is_none() - && mapped.companion.is_none() - && mapped.vertex_buffers.is_empty() - && mapped.index_buffer.is_none() - && mapped.out_of_bounds.is_empty() - && mapped.depth_stencil.is_none() - && matches!(mapped.assembly, graphics::Assembly::Primitives(_)) - && resources.textures.is_empty() - && resources.samplers.is_empty() - && resources.argument_buffer_buffers.is_empty() - && resources.argument_buffer_textures.is_empty() - && resources.argument_buffer_samplers.is_empty() - && resources.objects.is_empty() - && resources.command_buffers.is_empty(); - if !replayable { - return Err(NotSupported::Requirements( - [ToolingRequirement::ReplayedTemplateResources].into(), - ) - .into()); - } - TemplateCase::Render(Box::new(mapped)) - } - Stage::Object | Stage::Mesh => { - return Err(NotSupported::Requirements( - [ToolingRequirement::MeshRenderPipeline].into(), - ) - .into()) - } - }; - templates.insert( - token, - ReplayTemplate { - case_id: case_id.clone(), - mapped, - linked: linked_modules(&template.linked_functions)?, - }, - ); - } - Ok(templates) -} - -/// The variants the device replay registers for `case`'s executed compute commands, deduplicated in -/// a fixed order: each compute template of `templates` with the threadgroup size of its own -/// dispatch and its threadgroup lengths, and each dispatch the host encodes into an executed -/// compute command buffer with its pipeline (its own, or the execution's parent pipeline where the -/// commands inherit it), threadgroup lengths, and the threadgroup size of each of its regions (its -/// own, and a thread grid's edges, which run the remaining threads, [`region_sizes`]). Where an -/// executed compute command buffer has a command in its range whose action the host does not -/// encode, the producer may encode a thread grid of any size, so each compute template also -/// registers every edge size of its own threadgroup size (each size no larger on any axis, -/// [`edge_sizes`]), in token order, while the variants stay within the product's -/// `MAX_REPLAY_VARIANTS`; a template whose edges do not fit keeps its own size, and a ragged -/// command of it faults `VARIANT`. Registration is the consumer's: a command that selects another -/// variant dispatches nothing, and the run fails on its replay fault. A template threadgroup length -/// at an index no record holds is the executor's refusal. -pub fn replay_variants( - case: &ComputeCase, - templates: &BTreeMap, -) -> Result, ExecutorError> { - use crate::case::indirect_commands::HostAction; - const LENGTHS: usize = crate::air::reflect::THREADGROUP_BUFFER_ARGUMENT_COUNT_USIZE; - let lengths = |entries: &mut dyn Iterator| { - let mut out = [0u32; LENGTHS]; - for (index, length) in entries { - *out.get_mut(index as usize).ok_or_else(|| { - NotSupported::NotImplemented(format!( - "engine candidate: a replayed threadgroup length at index {index}" - )) - })? = length; - } - Ok::<_, ExecutorError>(out) - }; - let mut registered = std::collections::BTreeSet::new(); - // Each compute template's own variant, in token order. - let mut own = Vec::new(); - for (&token, template) in templates { - let TemplateCase::Compute(mapped) = &template.mapped else { - continue; - }; - let threads_per_group = match mapped.dispatch { - Dispatch::Threadgroups { - threads_per_group, .. - } - | Dispatch::Threads { - threads_per_group, .. - } - | Dispatch::ThreadgroupsIndirect { - threads_per_group, .. - } => threads_per_group, - other => { - return Err(NotSupported::NotImplemented(format!( - "engine candidate: a replayed template's dispatch {other:?}" - )) - .into()) - } - }; - let lengths = lengths(&mut mapped.threadgroup_lengths.iter().map(|(&i, &l)| (i, l)))?; - registered.insert((token, threads_per_group, lengths)); - own.push((token, threads_per_group, lengths)); - } - let mut gpu_encoded = false; - for command in case.command_buffers.values() { - let Some(execution) = command.execute.as_ref().filter(|_| !command.is_render()) else { - continue; - }; - let [start, end] = command.execution_range; - gpu_encoded |= (start..end).any(|index| { - !command - .commands - .iter() - .any(|host| host.index == index && host.action.is_some()) - }); - let parent = execution.pipeline.as_ref().map(|template| template.token); - for host in &command.commands { - let sizes = match host.action { - Some(HostAction::DispatchThreadgroups { - threads_per_threadgroup, - .. - }) => vec![threads_per_threadgroup], - Some(HostAction::DispatchThreads { - grid, - threads_per_threadgroup, - }) => region_sizes(grid, threads_per_threadgroup), - Some( - HostAction::DrawPrimitives { .. } - | HostAction::DrawIndexedPrimitives { .. } - | HostAction::DrawPatches { .. }, - ) - | None => continue, - }; - let token = if command.inherit_pipeline_state { - parent - } else { - host.pipeline - }; - let Some(token) = token else { - continue; - }; - let lengths = lengths( - &mut host - .threadgroup_memory_lengths - .iter() - .map(|l| (l.index, l.length)), - )?; - registered.extend(sizes.into_iter().map(|size| (token, size, lengths))); - } - } - if gpu_encoded { - let most = metal2vulkan::bind::MAX_REPLAY_VARIANTS as usize; - for (token, threads_per_group, lengths) in own { - let count: u64 = threads_per_group.iter().map(|&a| u64::from(a)).product(); - if count > most as u64 { - continue; - } - let edges: Vec<_> = edge_sizes(threads_per_group) - .into_iter() - .map(|size| (token, size, lengths)) - .filter(|variant| !registered.contains(variant)) - .collect(); - if registered.len() + edges.len() <= most { - registered.extend(edges); - } - } - } - registered - .into_iter() - .map(|(token, threads_per_group, lengths)| { - let pipeline = std::num::NonZeroU64::new(token) - .ok_or("a replayed pipeline token of 0 names no pipeline")?; - Ok(ReplayVariant::new(pipeline, threads_per_group, lengths)) - }) - .collect() -} - -/// The regions a device replay of `commands` commands over `variants` registered variants records -/// per command: `MAX_REPLAY_REGIONS`, or as many as keep its dispatches, `commands * regions * -/// variants`, within `MAX_REPLAY_DISPATCHES`. So every range executor v92 ran (one dispatch per -/// command and variant, at most 16,384 x 64 = 2^20) still runs, and a command that needs more -/// regions than a long range records is a typed `REGIONS` fault, never a refused range. Both of the -/// device replay's paths record the same regions. -pub(crate) fn replay_regions(commands: u32, variants: usize) -> u32 { - use metal2vulkan::bind::{MAX_REPLAY_DISPATCHES, MAX_REPLAY_REGIONS}; - let per_region = u64::from(commands.max(1)) * (variants.max(1) as u64); - let fit = MAX_REPLAY_DISPATCHES / per_region; - u32::try_from(fit.min(u64::from(MAX_REPLAY_REGIONS))) - .expect("at most MAX_REPLAY_REGIONS") - .max(1) -} - -/// The threadgroup sizes of the regions of a thread grid `grid` in threadgroups of `local`: per -/// axis, the whole threadgroups' size where the grid holds one, and the remaining threads where it -/// is not a multiple. A grid with a zero axis runs nothing and needs no variant; it registers -/// `local`, as a host-encoded dispatch always has. -pub fn region_sizes(grid: [u32; 3], local: [u32; 3]) -> Vec<[u32; 3]> { - if grid.contains(&0) || local.contains(&0) { - return vec![local]; - } - let axis = |i: usize| { - let mut sizes = Vec::with_capacity(2); - if grid[i] >= local[i] { - sizes.push(local[i]); - } - if !grid[i].is_multiple_of(local[i]) { - sizes.push(grid[i] % local[i]); - } - sizes - }; - let (xs, ys, zs) = (axis(0), axis(1), axis(2)); - let mut out = Vec::with_capacity(xs.len() * ys.len() * zs.len()); - for &z in &zs { - for &y in &ys { - for &x in &xs { - out.push([x, y, z]); - } - } - } - out -} - -/// Every threadgroup size an edge of a thread grid in threadgroups of `local` can run: each size of -/// 1 to `local`'s threads on every axis, `local` itself among them. -pub fn edge_sizes(local: [u32; 3]) -> Vec<[u32; 3]> { - let mut out = Vec::new(); - for z in 1..=local[2] { - for y in 1..=local[1] { - for x in 1..=local[0] { - out.push([x, y, z]); - } - } - } - out } /// An admitted case in the terms of the executor that runs it (boxed: the two differ in size). @@ -2182,7 +1644,7 @@ pub fn prepare_case( /// [`prepare_case`] for the authored compile census (`authored_compile`): a case whose only stop /// is the mesh render pipeline the executor does not draw /// ([`ToolingRequirement::MeshRenderPipeline`]) is prepared too, its draw mapped -/// ([`mesh::mesh_case`]), so [`case_compiles`] lists the pipeline a run of it would compile. A +/// ([`mesh::mesh_case`]), so [`case_compile`] plans the pipeline a run of it would compile. A /// run's preparation refuses such a case before any device, its device worker's included. pub fn prepare_compile( device: DeviceType, @@ -2219,33 +1681,17 @@ fn prepare( )?)), }; let linked = linked_modules(&checked.primary.linked_functions)?; - let templates = replay_templates(&checked)?; Ok(PreparedCase { device, checked, mapped, linked, - templates, }) } -/// What one compile of [`case_compiles`] builds. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CompileSubject { - /// The case's own pipeline: its kernel's, or its draw's with its generated companion. - Case, - /// The device-replay variant of the compute template of pipeline token `token` for a - /// threadgroup of `threads_per_group` threads. - ReplayVariant { - token: u64, - threads_per_group: [u32; 3], - }, -} - -/// One pipeline a run of a prepared case compiles, with the request and libraries the executor +/// The one pipeline a run of a prepared case compiles, with the request and libraries the executor /// builds for it. pub struct CaseCompile<'a> { - pub subject: CompileSubject, pipeline: PlannedPipeline<'a>, } @@ -2278,7 +1724,7 @@ impl CaseCompile<'_> { ) -> (Result<(), CompileFailure>, Option) { let mut record = |pipeline: &dyn artifact::Planned, shape| { artifact - .record(self.subject, pipeline, device.device(), shape) + .record(pipeline, device.device(), shape) .map_err(CompileFailure::Artifact) }; match &self.pipeline { @@ -2304,121 +1750,33 @@ impl CaseCompile<'_> { } } -/// Every pipeline a run of `prepared` compiles on `device` before it reads any device output, in -/// the order the run compiles them, and how many of its executed command buffers compile what no -/// device-free compile builds there. -pub struct CaseCompiles<'a> { - pub compiles: Vec>, - /// The executed command buffers (with a non-empty execution range) whose commands' pipelines no - /// device-free compile builds on this device: a render command buffer, whose host replay - /// compiles each command's pipeline for the bind shape of the records the producer writes on - /// the device, and whose draw replay (`platform::compute::draw_replay`) compiles its - /// template's variant for the bind state of the execution's encoder; and a compute one the host - /// replay runs, where the product sets no device replay up or the case registers no variant. - pub host_replayed: usize, -} - -/// The pipelines a run of `prepared` compiles on `device` before it reads any device output, -/// with the requests the executor builds for them: the case's own pipeline ([`compute_request`] for -/// the bind shape [`compute_shape`] gives, or [`render_request`] with its generated companion for -/// [`graphics::render_shape`]'s), and, where the device replay runs an executed compute command -/// buffer (the product sets it up on `device` and the case registers variants), each registered -/// variant (`replay_variant_request` for the bind state [`replay_variant_state`] of the run's -/// resident allocations, [`run_allocations`]). The bind shapes depend on the device only through -/// whether it has device addresses, which the executor reads from what its context enabled and this -/// from `device`'s description: the same fact for an opened device, whose description is restricted -/// to what was enabled; and through its profile's range limits (`BufferRanges::of`), which both -/// read from the device's profile. The authored compile census compiles these on each committed profile; the -/// executor builds the same requests through [`compile_case`], [`compile_render_case`], and -/// `compile_child`. -pub fn case_compiles<'a>( +/// The pipeline a run of `prepared` compiles on `device` before it reads any device output, with +/// the request the executor builds for it: the case's own pipeline ([`compute_request`] for the +/// bind shape [`compute_shape`] gives, [`render_request`] with its generated companion for +/// [`graphics::render_shape`]'s, or a mesh draw's, `mesh::mesh_request`). The bind shapes depend +/// on the device only through whether it has device addresses, which the executor reads from what +/// its context enabled and this from `device`'s description: the same fact for an opened device, +/// whose description is restricted to what was enabled; and through its profile's range limits +/// (`BufferRanges::of`), which both read from the device's profile. The authored compile census +/// compiles it on each committed profile; the executor builds the same request through +/// [`compile_case`] and [`compile_render_case`]. +pub fn case_compile<'a>( prepared: &'a PreparedCase, device: &WorkerDevice, -) -> Result, ExecutorError> { +) -> Result, ExecutorError> { use metal2vulkan::device::VkFeature; let addressed = device.description().has(VkFeature::BufferDeviceAddress); let ranges = BufferRanges::of(device.device().profile().limits()); - let executed = |command: &CommandBufferResource| { - command.execute.is_some() && command.execution_range[0] != command.execution_range[1] - }; let library = RowSource::of_row(&prepared.checked.primary.source); let linked = prepared.linked.as_slice(); - let mut compiles = Vec::new(); - let mut host_replayed = 0; - match &prepared.mapped { + let pipeline = match &prepared.mapped { Mapped::Compute(compute) => { - let registered = replay_variants(compute, &prepared.templates)?; let shape = compute_shape(compute, addressed, ranges).map_err(ExecutorError::Failed)?; let (request, libraries) = compute_request(&library, linked, compute, &shape); - compiles.push(CaseCompile { - subject: CompileSubject::Case, - pipeline: PlannedPipeline::Compute { - request, - libraries, - shape, - }, - }); - // Whether the product sets the device replay up on this device, asked only of a case - // whose executed compute commands could take it (`device_replay::replay_commands`). - let mut set_up = None; - let mut on_device = false; - for command in compute.command_buffers.values().filter(|c| executed(c)) { - if command.is_render() || registered.is_empty() { - host_replayed += 1; - continue; - } - let runs = match set_up { - Some(runs) => runs, - None => { - let runs = - match metal2vulkan::bind::replay_preprocess_module(device.device()) { - Ok(_) => true, - Err(Error::Unsupported(_)) => false, - Err(error) => return Err(product_refusal(&error)), - }; - set_up = Some(runs); - runs - } - }; - if runs { - on_device = true; - } else { - host_replayed += 1; - } - } - if on_device { - let resident = - replay_resident(run_allocations(compute).into_iter().enumerate().map( - |(token, (_, length))| { - let address = BufferAddress::synthetic_used(token as u32); - ( - BufferAddress { - host: Some(address.guest), - ..address - }, - length, - ) - }, - )) - .map_err(ExecutorError::Failed)?; - for variant in ®istered { - let token = variant.pipeline.get(); - let threads_per_group = variant.threads_per_threadgroup; - let shape = replay_variant_state(&resident, variant).shape(); - let (request, libraries) = - replay_variant_request(prepared, token, threads_per_group, &shape)?; - compiles.push(CaseCompile { - subject: CompileSubject::ReplayVariant { - token, - threads_per_group, - }, - pipeline: PlannedPipeline::Compute { - request, - libraries, - shape, - }, - }); - } + PlannedPipeline::Compute { + request, + libraries, + shape, } } Mapped::Render(render) => { @@ -2427,18 +1785,11 @@ pub fn case_compiles<'a>( let companion = companion_source(render); let (request, libraries) = render_request(&library, companion.as_ref(), linked, render, &shape)?; - compiles.push(CaseCompile { - subject: CompileSubject::Case, - pipeline: PlannedPipeline::Render { - request, - libraries, - shape, - }, - }); - host_replayed = render - .command_buffers() - .filter(|(_, command)| executed(command)) - .count(); + PlannedPipeline::Render { + request, + libraries, + shape, + } } Mapped::Mesh(mesh) => { let shape = mesh::mesh_shape(mesh, addressed, ranges)?; @@ -2447,20 +1798,14 @@ pub fn case_compiles<'a>( .as_ref() .map(|generated| RowSource::Text(Cow::Owned(generated.air_text(Spelling::Opaque)))); let (request, libraries) = mesh::mesh_request(&library, companion, mesh, &shape)?; - compiles.push(CaseCompile { - subject: CompileSubject::Case, - pipeline: PlannedPipeline::Render { - request, - libraries, - shape, - }, - }); + PlannedPipeline::Render { + request, + libraries, + shape, + } } - } - Ok(CaseCompiles { - compiles, - host_replayed, - }) + }; + Ok(CaseCompile { pipeline }) } /// The device worker's half of [`execute_prepared`] (`worker::device`): admit and prepare `input`'s @@ -2583,7 +1928,6 @@ fn prepare_on_device(input: &DeviceInput) -> Result<(PreparedCase, CompileWorker /// records what it compiled, by content ([`artifact::CaseArtifact`]). fn run_on_context(prepared: &PreparedCase, worker: &CompileWorker) -> RunAttempt { let case = &prepared.checked.primary.case; - let templates = &prepared.templates; // The worker assembles a row that retains no bitcode (a public fixture), and a companion. let library = RowSource::of_row(&prepared.checked.primary.source); let linked = &prepared.linked; @@ -2601,43 +1945,19 @@ fn run_on_context(prepared: &PreparedCase, worker: &CompileWorker) -> RunAttempt } } let artifact = RefCell::new(artifact::CaseArtifact::default()); - // Each executed command's template, compiled for the command's bind shape and dispatch or - // draw. - let children = - |target: &WorkerDevice, token: u64, shape: &BindShape, command: &ChildCommand| { - let compiled = compile_child(prepared, worker, target, (token, shape, command))?; - record_child( - &mut artifact.borrow_mut(), - target, - (token, shape, command), - &compiled, - )?; - Ok(compiled) - }; let mut attempt = match &prepared.mapped { - Mapped::Compute(compute) => { - let registered = match replay_variants(compute, templates) { - Ok(registered) => registered, - Err(error) => return RunAttempt::of(Err(error)), - }; - super::platform::execute_engine( - prepared.device, - &case.case_id, - compute, - |target, shape| { - let compiled = compile_case(worker, target, &library, linked, compute, shape)?; - artifact.borrow_mut().record( - CompileSubject::Case, - &compiled, - target.device(), - shape, - )?; - Ok(compiled) - }, - children, - ®istered, - ) - } + Mapped::Compute(compute) => super::platform::execute_engine( + prepared.device, + &case.case_id, + compute, + |target, shape| { + let compiled = compile_case(worker, target, &library, linked, compute, shape)?; + artifact + .borrow_mut() + .record(&compiled, target.device(), shape)?; + Ok(compiled) + }, + ), Mapped::Render(render) => { let companion = companion_source(render); super::platform::execute_engine_render( @@ -2654,15 +1974,11 @@ fn run_on_context(prepared: &PreparedCase, worker: &CompileWorker) -> RunAttempt render, shape, )?; - artifact.borrow_mut().record( - CompileSubject::Case, - &compiled, - target.device(), - shape, - )?; + artifact + .borrow_mut() + .record(&compiled, target.device(), shape)?; Ok(compiled) }, - children, ) } // A run's preparation refuses a mesh case before it maps (`prepare_case`); only the @@ -2682,135 +1998,6 @@ fn run_on_context(prepared: &PreparedCase, worker: &CompileWorker) -> RunAttempt attempt } -/// Record a compiled child in the run's artifact: a device-replay variant by its subject, with the -/// preprocess module the device replay runs it under; a host replay's pipeline (for a record a -/// producer wrote on the device) and a draw replay's variant (for the bind state of the execution's -/// encoder) as ones the census cannot compile. -fn record_child( - artifact: &mut artifact::CaseArtifact, - target: &WorkerDevice, - (token, shape, command): (u64, &BindShape, &ChildCommand), - compiled: &CompiledChild, -) -> Result<(), ExecutorError> { - match (command, compiled) { - (&ChildCommand::ReplayVariant { threads_per_group }, CompiledChild::Compute(compiled)) => { - artifact.record( - CompileSubject::ReplayVariant { - token, - threads_per_group, - }, - compiled.as_ref(), - target.device(), - shape, - )?; - artifact.record_replay_module(target.device()) - } - _ => { - artifact.record_uncovered(); - Ok(()) - } - } -} - -/// Compile the template of `token` for one command the case executes, in `worker`, for the bind -/// shape `shape`: a compute template for a dispatch, with the command's dispatch, or its replay -/// variant; a render template for a draw, with the command's draw (its class stays the template's -/// own, as Metal compiles it), or its draw replay variant for an execution's commands. A token -/// without a template, or a template of the other family, fails the run. -fn compile_child( - prepared: &PreparedCase, - worker: &CompileWorker, - target: &WorkerDevice, - (token, shape, command): (u64, &BindShape, &ChildCommand), -) -> Result { - let template = prepared.templates.get(&token).ok_or_else(|| { - ExecutorError::Failed(format!( - "an executed command's pipeline token {token} names no template" - )) - })?; - let source = RowSource::of_row(&prepared.checked.pipeline_templates[&template.case_id].source); - // A render template's vertex function alone, its variant in `form`. - let render_child = |child: graphics::RenderCase, form: variants::DrawForm| { - let (mut request, libraries) = - render_request(&source, None, &template.linked, &child, shape)?; - let PipelineRequest::VertexDraw { form: formed, .. } = &mut request else { - return Err(ExecutorError::Failed( - "an executed command's render template has a fragment stage".into(), - )); - }; - *formed = form; - let compiled = compile_render(worker, target, &request, &libraries)?; - Ok(CompiledChild::Render(Box::new(child), Box::new(compiled))) - }; - match (&template.mapped, command) { - (TemplateCase::Compute(mapped), ChildCommand::Dispatch(dispatch)) => { - let child = ComputeCase { - dispatch: *dispatch, - ..(**mapped).clone() - }; - compile_case(worker, target, &source, &template.linked, &child, shape) - .map(|c| CompiledChild::Compute(Box::new(c))) - } - (TemplateCase::Compute(_), &ChildCommand::ReplayVariant { threads_per_group }) => { - let (request, libraries) = - replay_variant_request(prepared, token, threads_per_group, shape)?; - compile_request(worker, target, &libraries, &request) - .map(|c| CompiledChild::Compute(Box::new(c))) - } - // In the large-buffer form, as the runtime's host step draws an executed render command. - (TemplateCase::Render(mapped), &ChildCommand::Draw { draw, .. }) => { - let child = graphics::RenderCase { - draw, - ..(**mapped).clone() - }; - render_child(child, variants::DrawForm::Large) - } - // In a draw replay's form, as the runtime's GPU form draws an execution's commands - // (`platform::compute::draw_replay`). - (TemplateCase::Render(mapped), &ChildCommand::DrawReplay { merged }) => { - let form = match merged { - true => variants::DrawForm::Merged, - false => variants::DrawForm::Replay, - }; - render_child((**mapped).clone(), form) - } - _ => Err(ExecutorError::Failed(format!( - "an executed command's pipeline token {token} names a template of the other command \ - family" - ))), - } -} - -/// The compile of the device-replay variant of the compute template of pipeline token `token` for -/// a threadgroup of `threads_per_group` threads, bound as `shape`: the template's case with a -/// [`replay_dispatch`], and [`replay_request`]'s request and libraries for it. The executor's -/// compile of a variant ([`compile_child`]) and the authored compile census ([`case_compiles`]) -/// build it here. A token without a template, or with a render template, fails the run. -fn replay_variant_request<'a>( - prepared: &'a PreparedCase, - token: u64, - threads_per_group: [u32; 3], - shape: &BindShape, -) -> Result<(PipelineRequest, Vec>), ExecutorError> { - let template = prepared.templates.get(&token).ok_or_else(|| { - ExecutorError::Failed(format!( - "an executed command's pipeline token {token} names no template" - )) - })?; - let TemplateCase::Compute(mapped) = &template.mapped else { - return Err(ExecutorError::Failed(format!( - "an executed command's pipeline token {token} names a template of the other command \ - family" - ))); - }; - let source = RowSource::of_row(&prepared.checked.pipeline_templates[&template.case_id].source); - let child = ComputeCase { - dispatch: replay_dispatch(threads_per_group), - ..(**mapped).clone() - }; - Ok(replay_request(&source, &template.linked, &child, shape)) -} - /// [`execute_case`] of a case [`prepare_case`] accepted: the device half in a device worker /// (`run_on_device`), the comparison and the row here. Without generated commands /// (`candidate::run_without_generated_commands`) the row is compared and returned but not stored: diff --git a/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs b/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs index b7ac23535..274e7f0d7 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/argument_buffers.rs @@ -16,26 +16,15 @@ //! that resource id ([`used_texture`]): a heap member, which the plan writes into every heap //! array whose class holds it and enters in each stage's handle table, so a handle loaded from //! the field finds its element; -//! - a command buffer is its `gpuResourceID` in the owner, a small integer of its own -//! ([`records_ids`]), and its record storage an argument-buffer buffer at the guest address the -//! product resolves that ID at (`records_address`, [`records_storage`]), which the product's -//! encoder writes each command through, and which the run checks as the host contract decodes it -//! ([`embed_objects`], [`validate_records`]); //! - a sampler is its `gpuResourceID` in the owner and an argument sampler of the bind state with //! that id ([`embed_samplers`], [`sampler_ids`]): the plan writes it into each sampler array //! and enters it in each stage's sampler table, so a sampler loaded from the field finds its -//! element; -//! - a pipeline state is the case's token for it in the owner and nothing else: the product reads -//! the field's word only as an encoder's operand and refuses every other use of the handle and -//! every access but the handle load that may reach the field's bytes (`ArgumentBufferObjects`), -//! so no observation depends on it but through the records, and the binder has no class for one. +//! element. use super::resources; use super::BufferAddress; -use crate::case::indirect_commands::{CommandBufferResource, PipelineResource}; use crate::case::{ArgumentBufferSamplerResource, TextureType}; use crate::literal::{LiteralArgumentBufferBuffer, LiteralArgumentBufferTexture, LiteralTexture}; -use metal2vulkan::bind::indirect_commands::{records_address, RECORDS_ID_LIMIT}; use metal2vulkan::bind::{ArgumentSampler, BoundTexture, ResourceClass, UsedResource}; use metal2vulkan::metal::{RenderStages, ResourceUsage}; use std::collections::BTreeMap; @@ -146,91 +135,6 @@ pub fn embed_samplers( Ok(embedded) } -/// The indirect-command objects of a function whose bound buffers are `buffers`: its command -/// buffers `commands` and pipeline states `pipelines`, each owner grown with zeros to cover the -/// object's 8-byte field. -/// -/// - A command buffer is its record storage (`HostRecordsV1`, initialized under the case's -/// descriptor, capacity, and inheritance, [`CommandBufferResource::initialize_records`]), an -/// argument-buffer buffer added to `embedded` at its key, at its records address -/// ([`records_storage`]) and a used buffer the resident set reaches there ([`used_buffer`]); -/// its owner holds its ID ([`records_ids`], [`field_words`]), which the product resolves to -/// that address to write each command through it. The result names each one by its key, for -/// [`validate_records`] after the run. -/// - A pipeline state is the case's token for it, the word a command's pipeline field holds and -/// the replay's key for the compiled template; the product reads the field's word only as an -/// encoder's operand. -/// -/// A key authored twice, or one that an argument-buffer buffer of `embedded` also names, is -/// refused. -pub fn embed_objects( - buffers: &mut BTreeMap>, - embedded: &mut BTreeMap>, - commands: &[CommandBufferResource], - pipelines: &[PipelineResource], -) -> Result { - let mut objects = EmbeddedObjects::default(); - for command in commands { - let key = (command.buffer_binding, command.field_offset); - cover(buffers, key, "command buffer")?; - let mut storage = vec![0; command.record_storage_bytes()?]; - command.initialize_records(&mut storage)?; - if embedded.insert(key, storage).is_some() - || objects - .command_buffers - .insert(key, command.clone()) - .is_some() - { - return Err(format!("command buffer {}+{} bound twice", key.0, key.1)); - } - } - for pipeline in pipelines { - let key = (pipeline.buffer_binding, pipeline.field_offset); - cover(buffers, key, "pipeline state")?; - if embedded.contains_key(&key) - || objects - .pipeline_tokens - .insert(key, pipeline.token) - .is_some() - { - return Err(format!("pipeline state {}+{} bound twice", key.0, key.1)); - } - } - Ok(objects) -} - -/// A function's indirect-command objects ([`embed_objects`]). -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct EmbeddedObjects { - /// Each command buffer, by key: its record storage is the argument-buffer buffer at the key. - pub command_buffers: BTreeMap, - /// Each pipeline state's token, by key: the word its owner holds at the field. - pub pipeline_tokens: BTreeMap, -} - -/// Check each command buffer of `commands` in its final record storage (`finals`, the -/// argument-buffer buffers' bytes after the run, by key) as the host contract decodes it -/// ([`CommandBufferResource::validated_records`]): a fault flag the product's encoder set (a -/// write its descriptor policy refuses, which Metal leaves undefined and whose guarded setter the -/// oracle faults too), a header the run changed, or a record the contract does not decode fails -/// the run. -pub fn validate_records<'a, K: Ord + Copy + std::fmt::Debug + 'a>( - commands: impl Iterator, - finals: &BTreeMap>, -) -> Result<(), String> { - for (key, command) in commands { - let bytes = finals - .get(&key) - .ok_or_else(|| format!("command buffer {key:?} has no final records"))?; - // Decoding validates every record, not only the execution range it then selects. - command - .validated_records(bytes) - .map(|_| ()) - .map_err(|error| format!("command buffer {key:?}: {error}"))?; - } - Ok(()) -} - /// The synthetic `gpuResourceID` of the used resource whose consumer token is `token`: nonzero /// (a handle table never enters id 0, the null entry) and distinct per token. pub fn resource_id(token: u32) -> u64 { @@ -273,29 +177,6 @@ pub fn argument_samplers<'a, K>( .collect() } -/// The `gpuResourceID` of each command buffer `keys` (in order), by key: Metal's is a small -/// integer, the lowest an indirect command buffer does not hold, so the run's command buffers, made -/// in this order, take 1, 2, and on, each below `RECORDS_ID_LIMIT`. -pub fn records_ids(keys: impl Iterator) -> Result, String> { - keys.zip(1u64..) - .map(|(key, id)| { - (id < RECORDS_ID_LIMIT) - .then_some((key, id)) - .ok_or_else(|| "too many command buffers".into()) - }) - .collect() -} - -/// The addresses of the record storage of the command buffer whose ID is `id`, its host device -/// address `host`: its guest address is the one the product resolves the ID at (`records_address`), -/// whether or not the allocation has a device address of its own. -pub fn records_storage(id: u64, host: Option) -> BufferAddress { - BufferAddress { - guest: records_address(id), - host, - } -} - /// The consumer token of each argument-buffer texture `keys` (in order) of a case whose /// argument-buffer buffers number `buffers`: its position after them, so the buffers keep theirs. pub fn texture_tokens( @@ -314,40 +195,24 @@ pub fn texture_tokens( } /// The 8 bytes Metal's argument encoder writes at each member's field, as a little-endian word -/// by key: each argument-buffer buffer's guest address (`buffers`), but a command buffer's ID -/// where `buffers` holds its record storage (`records`, [`records_ids`]; the storage at its -/// [`records_storage`] address), each argument-buffer texture's [`resource_id`] (`textures`, by -/// consumer token), each argument-buffer sampler's id (`samplers`, [`sampler_ids`]), and each -/// pipeline state's token (`objects`, [`embed_objects`]). A key named by two members, a command -/// buffer without its record storage, and record storage away from its ID's address are refused. +/// by key: each argument-buffer buffer's guest address (`buffers`), each argument-buffer +/// texture's [`resource_id`] (`textures`, by consumer token), and each argument-buffer sampler's +/// id (`samplers`, [`sampler_ids`]). A key named by two members is refused. pub fn field_words( buffers: &BTreeMap, - records: &BTreeMap, textures: &BTreeMap, samplers: &BTreeMap, - objects: impl Iterator, ) -> Result, String> { let mut words = BTreeMap::new(); - for (key, &id) in records { - let storage = buffers - .get(key) - .ok_or_else(|| format!("command buffer {key:?} has no record storage"))?; - if storage.guest != records_address(id) { - return Err(format!( - "command buffer {key:?}'s record storage is not at its ID {id}'s address" - )); - } - } let members = buffers .iter() - .map(|(&key, address)| (key, records.get(&key).copied().unwrap_or(address.guest))) + .map(|(&key, address)| (key, address.guest)) .chain( textures .iter() .map(|(&key, &token)| (key, resource_id(token))), ) - .chain(samplers.iter().map(|(&key, &id)| (key, id))) - .chain(objects); + .chain(samplers.iter().map(|(&key, &id)| (key, id))); for (key, word) in members { if words.insert(key, word).is_some() { return Err(format!("argument-buffer field {key:?} holds two members")); @@ -429,21 +294,14 @@ pub fn used_texture( } /// The guest address of each argument-buffer buffer of `keys` (in token order) on a device -/// without device addresses, by key: a command buffer's record storage (`records`, its ID by key, -/// [`records_ids`]) at its [`records_storage`] address, every other buffer at its -/// [`BufferAddress::synthetic_used`]. +/// without device addresses, by key: its [`BufferAddress::synthetic_used`]. pub fn synthetic_addresses( keys: impl Iterator, - records: &BTreeMap, ) -> Result, String> { keys.enumerate() .map(|(token, key)| { let token = u32::try_from(token).map_err(|_| "too many argument-buffer buffers")?; - let address = match records.get(&key) { - Some(&id) => records_storage(id, None), - None => BufferAddress::synthetic_used(token), - }; - Ok((key, address)) + Ok((key, BufferAddress::synthetic_used(token))) }) .collect() } diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs index 9f3981323..fcae98e57 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact.rs @@ -1,22 +1,19 @@ //! What an engine run executed, by content. //! -//! Every pipeline a run compiles before it reads device output (the case's own, and each -//! device-replay variant, the compiles [`super::case_compiles`] lists) contributes one compile -//! digest: its subject, the pipeline's content digest (`ComputePipeline::content_digest`, every -//! field but the cache identity), the content digest of the binding plan the run makes of it for -//! its bind shape (`BindingPlan::content_digest`, or the refusal of that plan). A run that replays -//! its compute commands on the device adds the preprocess module's words. The case's artifact is -//! the SHA-256 over those, in subject order, so the order the run compiled them in does not enter. +//! The pipeline a run compiles before it reads device output (the case's own, the compile +//! [`super::case_compile`] plans) contributes one compile digest: its subject (`case`), the +//! pipeline's content digest (`ComputePipeline::content_digest`, every field but the cache +//! identity), the content digest of the binding plan the run makes of it for its bind shape +//! (`BindingPlan::content_digest`, or the refusal of that plan). The case's artifact is the +//! SHA-256 over the compile digests, by subject. //! //! The executor records it ([`ExecutedArtifact`]) with the product's //! `cache::RUNTIME_VERSION`; the authored compile census computes it the same way, device-free, -//! for each committed profile; C3's currency compares the two. A pipeline a host replay compiles -//! for a record a producer wrote on the device is one the census cannot compile (`uncovered`): a -//! run that compiled any has no artifact digest, and its row stays on its build. +//! for each committed profile; C3's currency compares the two. use std::collections::BTreeMap; -use metal2vulkan::bind::{replay_preprocess_module, BindShape, BindingPlan}; +use metal2vulkan::bind::{BindShape, BindingPlan}; use metal2vulkan::cache::Hash256; use metal2vulkan::device::Device; use metal2vulkan::error::BindError; @@ -24,7 +21,6 @@ use metal2vulkan::pipeline::{ComputePipeline, RenderPipeline}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use super::CompileSubject; use crate::check::admission::ExecutorError; /// What a run executed, by content: recorded in an engine row's census and in a refusal the run @@ -32,12 +28,12 @@ use crate::check::admission::ExecutorError; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ExecutedArtifact { - /// The product's `cache::RUNTIME_VERSION`: what its runtime (instantiation, the device - /// replay, status decoding) does with a compiled pipeline. + /// The product's `cache::RUNTIME_VERSION`: what its runtime (instantiation, status decoding) + /// does with a compiled pipeline. pub runtime_version: u32, /// Lowercase hex SHA-256 over the compile digests of every pipeline the run compiled before /// it read device output ([`CaseArtifact`]); `None` when it compiled none (a refusal at the - /// first compile) or compiled one the census cannot (a host replay's). + /// first compile). #[serde(default, skip_serializing_if = "Option::is_none")] pub sha256: Option, } @@ -87,39 +83,25 @@ impl Planned for RenderPipeline { } } -/// A compile's subject as the artifact names it. -fn subject_label(subject: CompileSubject) -> String { - match subject { - CompileSubject::Case => "case".into(), - CompileSubject::ReplayVariant { - token, - threads_per_group: [x, y, z], - } => format!("replay-variant/{token}/{x}x{y}x{z}"), - } -} +/// The subject of the case's own compile, as the artifact names it. +const CASE: &str = "case"; /// The digests of what one run compiled before it read device output, by subject. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CaseArtifact { parts: BTreeMap, - /// The run compiled a pipeline the census cannot (a host replay's). - uncovered: bool, } -/// The subject of the device replay's preprocess module. -const REPLAY_MODULE: &str = "replay-preprocess-module"; - impl CaseArtifact { - /// Record the compile of `subject`: `pipeline` planned for `shape` on `device`. A plan the binder refuses is part of the digest as its refusal. - /// A subject compiled twice (a variant the run asked for again) must be the same compile. + /// Record the case's compile: `pipeline` planned for `shape` on `device`. A plan the binder + /// refuses is part of the digest as its refusal. Compiled twice, it must be the same compile. pub fn record( &mut self, - subject: CompileSubject, pipeline: &dyn Planned, device: &Device, shape: &BindShape, ) -> Result<(), ExecutorError> { - let label = subject_label(subject); + let label = CASE.to_owned(); let mut h = Sha256::new(); h.update(b"metal2vulkan C3 compile digest v1\0"); put(&mut h, label.as_bytes()); @@ -139,34 +121,6 @@ impl CaseArtifact { self.insert(label, h.finalize().into()) } - /// Record the device replay's preprocess module for `device`, which a run that replays on the - /// device executes beside its compiled pipelines: its words, requirements, limits, and layout. - /// Once per artifact: the module is the device's alone. - pub fn record_replay_module(&mut self, device: &Device) -> Result<(), ExecutorError> { - if self.parts.contains_key(REPLAY_MODULE) { - return Ok(()); - } - let module = replay_preprocess_module(device).map_err(|error| { - ExecutorError::Failed(format!("the device replay's preprocess module: {error}")) - })?; - let mut h = Sha256::new(); - h.update(b"metal2vulkan C3 replay preprocess module v1\0"); - h.update((module.spirv.len() as u64).to_le_bytes()); - for word in module.spirv.iter() { - h.update(word.to_le_bytes()); - } - put(&mut h, format!("{:?}", module.requirements).as_bytes()); - put(&mut h, format!("{:?}", module.limits).as_bytes()); - put(&mut h, format!("{:?}", module.layout).as_bytes()); - self.insert(REPLAY_MODULE.into(), h.finalize().into()) - } - - /// Note that the run compiled a pipeline the census cannot (a host replay's, for a record a - /// producer wrote on the device): the artifact then has no digest. - pub fn record_uncovered(&mut self) { - self.uncovered = true; - } - fn insert(&mut self, label: String, digest: Hash256) -> Result<(), ExecutorError> { match self.parts.insert(label.clone(), digest) { Some(earlier) if earlier != digest => Err(ExecutorError::Failed(format!( @@ -176,10 +130,9 @@ impl CaseArtifact { } } - /// The case's artifact digest, lowercase hex: `None` when nothing was recorded, or when the - /// run compiled a pipeline the census cannot. + /// The case's artifact digest, lowercase hex: `None` when nothing was recorded. pub fn sha256(&self) -> Option { - if self.parts.is_empty() || self.uncovered { + if self.parts.is_empty() { return None; } let mut h = Sha256::new(); diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index f2126cfe5..136a06aee 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -27,16 +27,12 @@ fn a_case_artifact_is_its_parts_by_subject() { } ); - let variant = subject_label(CompileSubject::ReplayVariant { - token: 3, - threads_per_group: [32, 1, 1], - }); - assert_eq!(variant, "replay-variant/3/32x1x1"); + let other = "another".to_owned(); let mut a = CaseArtifact::default(); a.insert("case".into(), digest(1)).unwrap(); - a.insert(variant.clone(), digest(2)).unwrap(); + a.insert(other.clone(), digest(2)).unwrap(); let mut b = CaseArtifact::default(); - b.insert(variant.clone(), digest(2)).unwrap(); + b.insert(other.clone(), digest(2)).unwrap(); b.insert("case".into(), digest(1)).unwrap(); assert_eq!(a.sha256(), b.sha256()); assert_eq!(a.sha256().unwrap().len(), 64); @@ -48,18 +44,9 @@ fn a_case_artifact_is_its_parts_by_subject() { let mut c = CaseArtifact::default(); c.insert("case".into(), digest(1)).unwrap(); - assert_ne!( - a.sha256(), - c.sha256(), - "a missing variant moves the artifact" - ); - c.insert(variant, digest(3)).unwrap(); - assert_ne!(a.sha256(), c.sha256(), "a moved variant moves the artifact"); - - // A run that compiled a host replay's pipeline has no digest, whatever else it compiled. - a.record_uncovered(); - assert_eq!(a.sha256(), None); - assert_eq!(a.executed().sha256, None); + assert_ne!(a.sha256(), c.sha256(), "a missing part moves the artifact"); + c.insert(other, digest(3)).unwrap(); + assert_ne!(a.sha256(), c.sha256(), "a moved part moves the artifact"); } /// The record's JSON: the runtime version always, the digest when there is one, nothing else. @@ -129,7 +116,7 @@ fn the_runtime_sources_are_the_committed_ones() { let compile = "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests"; let values = "the compiled pipeline's value types; the artifact digests their values"; - let spirv = "the SPIR-V builder: at run time it builds the device replay's preprocess module, whose words the artifact digests"; + let spirv = "the SPIR-V builder: at run time it builds only the device replay's preprocess module, which no engine run executes"; let packed = "compile-time translation, reached only through lower/arith/pack.rs's pack and unpack intrinsics, which the compile emits; the runtime's YCbCr write takes that file's sRGB encode (srgb_encode), which reaches none of it"; let not_runtime = BTreeMap::from([ ("metal2vulkan-air/src/abi/mod.rs", compile), diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs index 05b16fc30..ff21d3fef 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics.rs @@ -15,7 +15,7 @@ //! oracle's slots ([`vertex_input_slots`]), the oracle's 1×1 `R8Unorm` color attachment as API //! scaffolding, and the case's buffers, textures (texture-array elements at their slots), //! samplers, argument-buffer buffers ([`super::argument_buffers`]), and argument-buffer textures -//! and command buffers bound to the vertex stage; +//! and samplers bound to the vertex stage; //! - a fragment case draws through its generated passthrough vertex companion, with the case's //! resources bound to the fragment stage and its render targets attached; //! - a vertex case observed through its position or a varying draws into its generated observer @@ -37,7 +37,6 @@ use super::{ function_constants, require_case_families, resources, select_range, views_told_apart, BufferAddress, }; -use crate::case::indirect_commands::CommandBufferResource; use crate::case::out_of_bounds::OutOfBoundsTarget; use crate::case::{ ArgumentBufferSamplerResource, AttributeFormat, AuthoredCase, OutputSelection, Primitive, @@ -85,14 +84,6 @@ pub struct StageResources { /// Each argument-buffer sampler, by `(owner Metal index, field offset)`: an argument sampler /// whose id its owner holds at the field. pub argument_buffer_samplers: BTreeMap, - /// Each pipeline state, by `(owner Metal index, field offset)`: the case's token for it, the - /// word its owner holds at the field ([`argument_buffers::embed_objects`]). - pub objects: BTreeMap, - /// Each command buffer, by `(owner Metal index, field offset)`: its record storage is the - /// argument-buffer buffer at the key, at its ID's records address, and its owner holds its ID - /// ([`records_ids`]); the run checks its final records - /// ([`argument_buffers::validate_records`]). - pub command_buffers: BTreeMap, /// Each bound texture (texture-array elements included, each element at its own slot, /// [`resources::bound_textures`]) with its initial contents. pub textures: BTreeMap, @@ -309,32 +300,6 @@ impl RenderCase { }) } - /// Each pipeline state of each stage with its token, by `(stage, owner, field offset)`, in - /// stage order. - pub fn objects(&self) -> impl Iterator + '_ { - self.stages().flat_map(|(stage, function)| { - function - .resources - .objects - .iter() - .map(move |(&(owner, field), &word)| ((stage, owner, field), word)) - }) - } - - /// Each command buffer of each stage, by `(stage, owner, field offset)`, in stage order: its - /// record storage is the argument-buffer buffer at the same key. - pub fn command_buffers( - &self, - ) -> impl Iterator { - self.stages().flat_map(|(stage, function)| { - function - .resources - .command_buffers - .iter() - .map(move |(&(owner, field), command)| ((stage, owner, field), command)) - }) - } - /// The stage of the generated companion's function, which links nothing: the vertex stage of a /// passthrough vertex, the fragment stage of an observer fragment, none without a companion /// (a render case's is never a mesh render pipeline's stages, which [`render_case`] refuses). @@ -677,14 +642,20 @@ pub fn stage_output( } /// What the case's own function binds, from its literals `literal`: its buffers (an argument -/// buffer's owner covering each pointer field), its argument buffers' members, the pipeline states -/// and command buffers its argument buffers hold, its textures (texture-array elements each at its -/// own slot) and samplers. The one mapping a render case's and a mesh case's own stage share. +/// buffer's owner covering each pointer field), its argument buffers' members, its textures +/// (texture-array elements each at its own slot) and samplers. The one mapping a render case's and +/// a mesh case's own stage share. A case with an indirect command buffer or a pipeline state in an +/// argument buffer is not mapped (`NotImplemented`). pub fn stage_resources( case: &AuthoredCase, literal: &LiteralResources, ) -> Result { let gap = |what: &str| NotSupported::NotImplemented(format!("engine candidate: {what}")); + if !case.command_buffers.is_empty() || !case.pipeline_states.is_empty() { + return Err( + gap("an indirect command buffer or a pipeline state in an argument buffer").into(), + ); + } let mut resources = StageResources::default(); for buffer in &literal.buffers { if resources @@ -704,15 +675,6 @@ pub fn stage_resources( resources.argument_buffer_samplers = argument_buffers::embed_samplers(&mut resources.buffers, &case.argument_buffer_samplers) .map_err(|error| gap(&error))?; - let objects = argument_buffers::embed_objects( - &mut resources.buffers, - &mut resources.argument_buffer_buffers, - &case.command_buffers, - &case.pipeline_states, - ) - .map_err(|error| gap(&error))?; - resources.objects = objects.pipeline_tokens; - resources.command_buffers = objects.command_buffers; resources.textures = resources::bound_textures(&literal.textures, &literal.texture_arrays) .map_err(|error| gap(&error))?; for sampler in &case.samplers { @@ -875,25 +837,6 @@ pub fn topology_class(primitive: Primitive) -> metal::PrimitiveTopologyClass { primitive.topology_class() } -/// Whether a replayed draw of `primitive` is one the template compiled for `assembly` defines: -/// Metal compiles a render template for its own draw's topology class, so a draw of another class -/// (a GPU-encoded one; the checker refuses a host-encoded one) fails the run, and a patch template -/// is not replayed. -pub fn replayed_draw_in_class(assembly: &Assembly, primitive: Primitive) -> Result<(), String> { - match assembly { - Assembly::Primitives(compiled) - if topology_class(*compiled) == topology_class(primitive) => - { - Ok(()) - } - Assembly::Primitives(compiled) => Err(format!( - "a replayed draw of {primitive:?} is outside the topology class of its template, \ - compiled for {compiled:?}" - )), - Assembly::Patches { .. } => Err("a replayed draw's template draws patches".into()), - } -} - /// The Vulkan input assembly of a draw's primitive, the consumer's pipeline state within the /// class the pipeline was compiled for: its topology and whether it restarts primitives, as the /// product maps Metal's primitive type (`metal::state::input_assembly`). @@ -1200,22 +1143,11 @@ pub fn texture_tokens(case: &RenderCase) -> Result Result, String> { - argument_buffers::synthetic_addresses( - case.argument_buffer_buffers().map(|(key, _)| key), - &records_ids(case)?, - ) -} - -/// The `gpuResourceID` of each command buffer of `case`, by `(stage, owner, field offset)`, in -/// stage order ([`argument_buffers::records_ids`]): the word its owner holds, which the product -/// resolves to its record storage. The stages' command buffers share one space, as Metal's do. -pub fn records_ids(case: &RenderCase) -> Result, String> { - argument_buffers::records_ids(case.command_buffers().map(|(key, _)| key)) + argument_buffers::synthetic_addresses(case.argument_buffer_buffers().map(|(key, _)| key)) } /// The `BindShape` the render executor binds `case` with on a device that has device addresses diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs index e23f3d1ec..da59112e7 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs @@ -583,7 +583,6 @@ pub(crate) fn draw_request<'a>( function: function(&case.vertex), template: render_template(case), shape: Some(shape.clone()), - form: crate::candidate::engine::variants::DrawForm::Bound, }, vec![libraries.vertex], ), @@ -1276,14 +1275,7 @@ fn render_cases_bind_argument_buffer_buffers_and_texture_arrays() { listed.desc, resources::argument_sampler_descriptor(&members.argument_buffer_samplers[0]) ); - let words = field_words( - &embedded, - &BTreeMap::new(), - &tokens, - &samplers, - std::iter::empty(), - ) - .unwrap(); + let words = field_words(&embedded, &tokens, &samplers).unwrap(); assert_eq!( words, BTreeMap::from([ diff --git a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs index fd332d7e1..ef53f9dac 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/mesh.rs @@ -247,8 +247,7 @@ impl MeshTemplate { /// apart and classing lengths under `ranges` ([`views_told_apart`]), so its plan is the runtime's /// of the same binds. What the compile worker compiles the draw for /// (`variants::compile_mesh_for_shape`). -/// A case whose own function takes an argument buffer, a command buffer or a pipeline state is not -/// built here (`NotImplemented`). +/// A case whose own function takes an argument buffer is not built here (`NotImplemented`). pub fn mesh_shape( mesh: &MeshCase, addressed: bool, @@ -259,9 +258,7 @@ pub fn mesh_shape( let resources = &function.resources; if !(resources.argument_buffer_buffers.is_empty() && resources.argument_buffer_textures.is_empty() - && resources.argument_buffer_samplers.is_empty() - && resources.command_buffers.is_empty() - && resources.objects.is_empty()) + && resources.argument_buffer_samplers.is_empty()) { return Err(NotSupported::NotImplemented( "engine candidate: a device-free compile of a mesh draw whose function takes an \ diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index 9e843c90c..9b6968f5c 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -392,40 +392,14 @@ fn the_cases_own_function_links_and_its_libraries_follow_the_stages() { function: linking(&kernel.entry), shape: shape.clone(), dispatch: Some(kernel.dispatch), - replay: false, } ); assert_eq!(given, expected_libraries(&[&case])); - // A plain request's serialization names no replay, so it reads back as before. let json = serde_json::to_value(&request).unwrap(); - assert!(json.to_string().find("\"replay\"").is_none(), "{json}"); assert_eq!( serde_json::from_value::(json).unwrap(), request ); - // The device-replay variant's request: the same function and libraries, the variant's indirect - // dispatch, and the replay input, which its serialization carries. - let variant = ComputeCase { - dispatch: replay_dispatch([8, 1, 1]), - ..kernel.clone() - }; - let (replayed, given) = replay_request(&case, &linked, &variant, &shape); - assert_eq!( - replayed, - PipelineRequest::BoundCompute { - function: linking(&kernel.entry), - shape: shape.clone(), - dispatch: Some(replay_dispatch([8, 1, 1])), - replay: true, - } - ); - assert_eq!(given, expected_libraries(&[&case])); - let json = serde_json::to_value(&replayed).unwrap(); - assert!(json.to_string().contains("\"replay\":true"), "{json}"); - assert_eq!( - serde_json::from_value::(json).unwrap(), - replayed - ); assert_eq!( request.linked_ranges(), [std::ops::Range { start: 1, end: 3 }] @@ -440,7 +414,6 @@ fn the_cases_own_function_links_and_its_libraries_follow_the_stages() { function: linking("shade"), template: graphics::render_template(&vertex_case), shape: Some(shape.clone()), - form: crate::candidate::engine::variants::DrawForm::Bound, } ); assert_eq!(given, expected_libraries(&[&case])); @@ -728,14 +701,8 @@ fn arrays_and_argument_buffers_map_onto_the_binder() { ); // The owner is created holding the pointer, little endian, at its field. - let fields = argument_buffers::field_words( - &embedded, - &BTreeMap::new(), - &BTreeMap::new(), - &BTreeMap::new(), - std::iter::empty(), - ) - .unwrap(); + let fields = + argument_buffers::field_words(&embedded, &BTreeMap::new(), &BTreeMap::new()).unwrap(); let owner_bytes = |index| argument_buffers::owner_bytes(&mapped.buffers, index, &fields); let owner = owner_bytes(0).unwrap(); assert_eq!(&owner[..4], &[0xab; 4]); @@ -1045,8 +1012,6 @@ fn the_binder_plans_the_executors_state() { argument_buffer_buffers: BTreeMap::new(), argument_buffer_textures: BTreeMap::new(), argument_buffer_samplers: BTreeMap::new(), - objects: BTreeMap::new(), - command_buffers: BTreeMap::new(), textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), @@ -1205,327 +1170,6 @@ fn committed_command_buffer_and_pipeline_state_cases_refuse_by_their_requirement } } -/// A replayed draw runs only in its template's topology class (Metal compiled the template for it), -/// whatever primitive of that class the record names; another class fails the run, as a record the -/// GPU encoded with a draw its template does not define. -#[test] -fn a_replayed_draw_stays_in_its_templates_topology_class() { - use crate::case::Primitive; - use graphics::{replayed_draw_in_class, Assembly}; - let points = Assembly::Primitives(Primitive::Point); - assert_eq!(replayed_draw_in_class(&points, Primitive::Point), Ok(())); - let error = replayed_draw_in_class(&points, Primitive::Triangle).unwrap_err(); - assert!(error.contains("outside the topology class"), "{error}"); - let strips = Assembly::Primitives(Primitive::TriangleStrip); - assert_eq!(replayed_draw_in_class(&strips, Primitive::Triangle), Ok(())); - assert!(replayed_draw_in_class(&strips, Primitive::LineStrip).is_err()); - let lines = Assembly::Primitives(Primitive::Line); - assert_eq!(replayed_draw_in_class(&lines, Primitive::LineStrip), Ok(())); -} - -/// A device replay records as many regions per command as keep its dispatches within the -/// product's bound, so a range executor v92 ran is never refused for its length: 3,971 commands of -/// 33 variants take all eight regions, 3,972 take seven (eight would be `TooManyDispatches`), and -/// Metal's most, 16,384 commands of 64 variants, one. -#[test] -fn a_long_replay_records_the_regions_its_dispatch_bound_holds() { - use metal2vulkan::bind::BindState; - use metal2vulkan::bind::{replay_preprocess, ReplayExecution, ReplayRefusal}; - use metal2vulkan::bind::{MAX_REPLAY_DISPATCHES, MAX_REPLAY_REGIONS}; - use metal2vulkan::error::BindError; - use std::num::NonZeroU64; - let path = crate::engine::profiles_dir().join("gate-lavapipe.json"); - let text = std::fs::read_to_string(path).unwrap(); - let description = DeviceDescription::from_khronos_json(&text, None).unwrap(); - let device = Device::from_queries(description, DevicePolicy::RESIDENT_TABLES).unwrap(); - let variants = |n: u32| -> Vec { - (1..=n) - .map(|x| ReplayVariant::new(NonZeroU64::new(7).unwrap(), [x, 1, 1], [0; 31])) - .collect() - }; - let run = |count: u32, registered: &[ReplayVariant], regions: u32| { - let mut execution = ReplayExecution::new(count, 0, count); - execution.regions = regions; - replay_preprocess(&device, &BindState::default(), &execution, registered).map(|_| ()) - }; - for (count, n, regions) in [ - (1, 1, MAX_REPLAY_REGIONS), - (3_971, 33, 8), - (3_972, 33, 7), - (16_384, 64, 1), - ] { - let registered = variants(n); - assert_eq!( - replay_regions(count, registered.len()), - regions, - "{count} x {n}" - ); - let dispatches = u64::from(count) * u64::from(n) * u64::from(regions); - assert!(dispatches <= MAX_REPLAY_DISPATCHES, "{count} x {n}"); - run(count, ®istered, regions).unwrap_or_else(|e| panic!("{count} x {n}: {e:?}")); - } - // Eight regions at the boundary are the refusal the chosen count avoids. - let registered = variants(33); - assert!(matches!( - run(3_972, ®istered, MAX_REPLAY_REGIONS), - Err(BindError::InvalidReplay { - reason: ReplayRefusal::TooManyDispatches { .. } - }) - )); -} - -/// A device replay's fault refuses the row (`not_supported{bind}`) only when every reason is one of -/// the product's typed limits (no registered variant, a grid past `2^32 - 1` threads, more regions -/// than the execution records); any other reason, alone or beside them, fails the row, as the host -/// replay fails a dynamic stride, and as a preprocess that -/// disagrees with the host decode must. The verdict names the reasons. -#[test] -fn a_replay_fault_refuses_the_row_only_for_the_products_typed_limits() { - use metal2vulkan::bind::ReplayFaults as F; - let limits = [F::VARIANT, F::GROUP_COUNT, F::REGIONS]; - let others = [ - F::ENCODING, - F::ACTION, - F::PIPELINE, - F::BUFFERS, - F::RECORD, - F::RANGE, - ]; - let refused = |faults: u32| match replay_fault_verdict("command buffer (0, 0)", F(faults)) { - ExecutorError::NotSupported(NotSupported::Bind(why)) => Ok(why), - ExecutorError::Failed(why) => Err(why), - other => panic!("{other:?}"), - }; - for bit in limits { - let why = refused(bit.0).unwrap_or_else(|why| panic!("{bit:?} failed: {why}")); - assert!(why.starts_with("command buffer (0, 0): "), "{why}"); - } - let all_limits = limits.iter().fold(0, |all, bit| all | bit.0); - let why = refused(all_limits).unwrap_or_else(|why| panic!("{why}")); - assert!( - why.contains( - "no registered variant, a grid past 2^32 - 1 threads, more regions than the \ - execution records" - ), - "{why}" - ); - for bit in others { - let why = refused(bit.0).expect_err("fails the row"); - assert!(why.contains(&format!("{:#x}", bit.0)), "{why}"); - refused(bit.0 | F::VARIANT.0).expect_err("fails the row beside a limit"); - } - // A fault bit with no reason is no typed limit. - refused(0).expect_err("fails the row"); -} - -/// An executed command buffer of `descriptor`'s family with no commands, no parent pipeline, and -/// no parent buffers: what `replay_templates` reads of it is that it executes, and its family. -fn executed_command_buffer( - descriptor: crate::case::indirect_commands::CommandDescriptor, -) -> crate::case::indirect_commands::CommandBufferResource { - crate::case::indirect_commands::CommandBufferResource { - buffer_binding: 0, - field_offset: 16, - capacity: 1, - execution_range: [0, 1], - inherit_pipeline_state: false, - inherit_buffers: false, - descriptor, - commands: vec![], - execute: Some(crate::case::indirect_commands::Execution { - pipeline: None, - buffers: vec![], - vertex_buffers: vec![], - fragment_buffers: vec![], - object_buffers: vec![], - mesh_buffers: vec![], - }), - } -} - -/// A compute command buffer's descriptor, for [`executed_command_buffer`]. -fn compute_commands() -> crate::case::indirect_commands::CommandDescriptor { - crate::case::indirect_commands::CommandDescriptor::Compute { - dispatch: crate::case::indirect_commands::ComputeDispatch::Both, - max_buffer_bind_count: 1, - max_threadgroup_memory_bind_count: 0, - support_dynamic_attribute_stride: false, - } -} - -/// The templates the replay maps are of the families the case's executed command buffers run. The -/// committed case over a fragment template's and a kernel template's pipeline states -/// (`pipeline-states-beside-the-data-of-two-stages`), given an executed compute command buffer, -/// maps only the kernel template: no compute command selects the fragment one, which the checker -/// and the oracle accept beside compute commands. Given an executed render command buffer instead, -/// the fragment template is the one mapped, and refused: it is no rasterization-disabled vertex -/// function. -#[test] -fn replay_templates_map_only_the_families_executed_commands_run() { - use crate::case::indirect_commands::CommandDescriptor; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let case = CorpusStore::new(&root) - .read_all_cases() - .unwrap() - .into_iter() - .find(|case| case.name == "pipeline-states-beside-the-data-of-two-stages") - .expect("the committed public case"); - let request = ExecutionRequest::EngineCandidate { - device: DeviceType::Cpu, - }; - let mut checked = admit(&root, case, request) - .unwrap_or_else(|error| panic!("{error}")) - .into_checked_for(request) - .unwrap(); - let stages = checked - .pipeline_templates - .values() - .map(|template| template.case.stage) - .collect::>(); - assert!(stages.contains(&Stage::Fragment) && stages.contains(&Stage::Kernel)); - // Not executing commands, the case selects no template. - assert!(replay_templates(&checked).unwrap().is_empty()); - checked - .primary - .case - .command_buffers - .push(executed_command_buffer(compute_commands())); - let templates = replay_templates(&checked).unwrap_or_else(|error| panic!("{error}")); - let kernel_token = checked - .primary - .case - .pipeline_states - .iter() - .find(|state| checked.pipeline_templates[&state.case_id].case.stage == Stage::Kernel) - .unwrap() - .token; - assert_eq!( - templates.keys().copied().collect::>(), - [kernel_token] - ); - assert!(matches!( - templates[&kernel_token].mapped, - TemplateCase::Compute(_) - )); - checked.primary.case.command_buffers[0] = executed_command_buffer(CommandDescriptor::Render { - draws: crate::case::indirect_commands::RenderDraws::default(), - max_vertex_buffer_bind_count: 1, - max_fragment_buffer_bind_count: 0, - max_object_buffer_bind_count: 0, - max_mesh_buffer_bind_count: 0, - support_dynamic_attribute_stride: false, - }); - let error = replay_templates(&checked).err().unwrap(); - assert!( - matches!(&error, ExecutorError::NotSupported(NotSupported::Requirements(requirements)) - if requirements.contains(&ToolingRequirement::ReplayedTemplateResources)), - "{error}" - ); -} - -/// The mirror and the mixed run of -/// [`replay_templates_map_only_the_families_executed_commands_run`]. Beside render commands only -/// (`gpu-encoded-draws-run-the-inherited-vertex-buffers`), a kernel pipeline-state literal that -/// binds beyond buffers (`pipeline-states-beside-the-data-of-two-stages`'s kernel template with a -/// sampler added) is no template: no render command selects it, so it is skipped, not refused. -/// Once compute commands execute too, it is a template, and refused. With its buffers only, the -/// mixed run maps both families, each token to its own. -#[test] -fn replay_templates_skip_another_familys_literal_and_map_both_families_of_a_mixed_run() { - use crate::case::{SamplerAddressMode, SamplerFilter, SamplerMipFilter, SamplerResource}; - let root = metal2vulkan_devtools::validation_dir().join("corpus"); - let cases = CorpusStore::new(&root).read_all_cases().unwrap(); - let request = ExecutionRequest::EngineCandidate { - device: DeviceType::Cpu, - }; - let checked_case = |name: &str| { - let case = cases - .iter() - .find(|case| case.name == name) - .unwrap_or_else(|| panic!("the committed public case {name}")) - .clone(); - admit(&root, case, request) - .unwrap_or_else(|error| panic!("{name}: {error}")) - .into_checked_for(request) - .unwrap() - }; - let mut checked = checked_case("gpu-encoded-draws-run-the-inherited-vertex-buffers"); - assert!(checked - .primary - .case - .command_buffers - .iter() - .all(|command| command.execute.is_none() || command.is_render())); - let render = replay_templates(&checked).unwrap_or_else(|error| panic!("{error}")); - assert!(!render.is_empty()); - assert!(render - .values() - .all(|template| matches!(template.mapped, TemplateCase::Render(_)))); - - let mut beside = checked_case("pipeline-states-beside-the-data-of-two-stages"); - let mut literal = beside - .primary - .case - .pipeline_states - .iter() - .find(|state| beside.pipeline_templates[&state.case_id].case.stage == Stage::Kernel) - .cloned() - .unwrap(); - let mut kernel = beside.pipeline_templates.remove(&literal.case_id).unwrap(); - assert!(kernel.case.samplers.is_empty()); - kernel.case.samplers.push(SamplerResource { - binding: 0, - address_mode: SamplerAddressMode::ClampToEdge, - min_filter: SamplerFilter::Nearest, - mag_filter: SamplerFilter::Nearest, - mip_filter: SamplerMipFilter::NotMipmapped, - normalized_coordinates: true, - }); - let token = render.keys().max().unwrap() + 1; - literal.token = token; - let case_id = literal.case_id.clone(); - checked.pipeline_templates.insert(case_id.clone(), kernel); - checked.primary.case.pipeline_states.push(literal); - - // Render commands only: the kernel literal is skipped, not refused. - let skipped = replay_templates(&checked).unwrap_or_else(|error| panic!("{error}")); - assert_eq!( - skipped.keys().collect::>(), - render.keys().collect::>() - ); - - // Compute commands execute too: the literal is a template, and it binds beyond buffers. - checked - .primary - .case - .command_buffers - .push(executed_command_buffer(compute_commands())); - let error = replay_templates(&checked).err().unwrap(); - assert!( - matches!(&error, ExecutorError::NotSupported(NotSupported::Requirements(requirements)) - if requirements.contains(&ToolingRequirement::ReplayedTemplateResources)), - "{error}" - ); - - // With its buffers only, the mixed run maps both families. - checked - .pipeline_templates - .get_mut(&case_id) - .unwrap() - .case - .samplers - .pop(); - let both = replay_templates(&checked).unwrap_or_else(|error| panic!("{error}")); - assert_eq!( - both.keys().copied().collect::>(), - render.keys().copied().chain([token]).collect::>() - ); - assert!(matches!(both[&token].mapped, TemplateCase::Compute(_))); - for token in render.keys() { - assert!(matches!(both[token].mapped, TemplateCase::Render(_))); - } -} - /// An allocation's guest address names a buffer whatever device address it has: NVIDIA's lie /// below 2^32 (a vertex buffer at 0x5020000 on an RTX 3090), where a guest address equal to it /// was a nil buffer's offset to a record, and RADV's sign-extended upper half @@ -1575,8 +1219,6 @@ fn plain_kernel() -> ComputeCase { argument_buffer_buffers: BTreeMap::new(), argument_buffer_textures: BTreeMap::new(), argument_buffer_samplers: BTreeMap::new(), - objects: BTreeMap::new(), - command_buffers: BTreeMap::new(), textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::from([(0, 64)]), @@ -1597,8 +1239,8 @@ fn plain_kernel() -> ComputeCase { /// by threads or threadgroups and observing a buffer, a texture, an argument-buffer member or /// nothing, a 32-bit float depth or a multisampled texture among its textures (which the run /// fills by a draw), a cube array among them, and its out-of-bounds targets among them -/// (`platform::runtime_bounds`); a case with anything else (a pipeline state in an argument -/// buffer, an indirect dispatch) stays on the executor's own context. +/// (`platform::runtime_bounds`); a case with an indirect dispatch stays on the executor's own +/// context. #[test] fn a_plain_kernel_case_and_only_one_runs_through_the_runtime() { use crate::case::{ @@ -1688,8 +1330,6 @@ fn a_plain_kernel_case_and_only_one_runs_through_the_runtime() { }; assert!(runs_through_runtime(&case)); } - let mut object = plain.clone(); - object.objects.insert((1, 0), 7); let depth = LiteralTexture { format: TextureFormat::Depth32Float, bytes: vec![0; 64], @@ -1716,16 +1356,14 @@ fn a_plain_kernel_case_and_only_one_runs_through_the_runtime() { ..plain.clone() }; assert!(runs_through_runtime(&bounded)); - let others = [ - object, - ComputeCase { - dispatch: replay_dispatch([2, 1, 1]), - ..plain.clone() + let indirect = ComputeCase { + dispatch: Dispatch::ThreadgroupsIndirect { + indirect: metal2vulkan::bind::IndirectRef::new(0, 0), + threads_per_group: [2, 1, 1], }, - ]; - for other in &others { - assert!(!runs_through_runtime(other), "{other:?}"); - } + ..plain.clone() + }; + assert!(!runs_through_runtime(&indirect), "{indirect:?}"); } /// The runtime draws a vertex or fragment case of any sample count, its own stage's buffers, diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs index 7d3df1371..b7d505456 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests/argument_buffer_members.rs @@ -184,14 +184,7 @@ fn argument_buffer_members_are_written_into_their_owner() { } // The owner holds, at each field, the word Metal's argument encoder writes there. - let fields = field_words( - &embedded, - &BTreeMap::new(), - &tokens, - &BTreeMap::new(), - std::iter::empty(), - ) - .unwrap(); + let fields = field_words(&embedded, &tokens, &BTreeMap::new()).unwrap(); let owner = owner_bytes(&mapped.buffers, 0, &fields).unwrap(); let word = |at: usize| u64::from_le_bytes(owner[at..at + 8].try_into().unwrap()); assert_eq!(&owner[..8], &[0xab, 0xab, 0xab, 0xab, 0, 0, 0, 0]); @@ -206,14 +199,7 @@ fn argument_buffer_members_are_written_into_their_owner() { assert_eq!(ids.len(), 64); assert!(!ids.contains(&0)); // A field named by two members, overlapping fields, and a field past the owner are refused. - assert!(field_words( - &embedded, - &BTreeMap::new(), - &BTreeMap::from([((0, 8), 1)]), - &BTreeMap::new(), - std::iter::empty() - ) - .is_err()); + assert!(field_words(&embedded, &BTreeMap::from([((0, 8), 1)]), &BTreeMap::new(),).is_err()); let overlapping = BTreeMap::from([((0, 8), 1), ((0, 12), 2)]); assert!(owner_bytes(&mapped.buffers, 0, &overlapping).is_err()); assert!(owner_bytes(&mapped.buffers, 0, &BTreeMap::from([((0, 32), 1)])).is_err()); @@ -337,11 +323,9 @@ fn an_argument_buffer_texture_is_the_heap_member_its_owner_names() { }; assert_eq!(bytes.len(), bytes_len as usize); let fields = field_words( - &BTreeMap::new(), &BTreeMap::new(), &texture_tokens(&mapped).unwrap(), &BTreeMap::new(), - std::iter::empty(), ) .unwrap(); let owner = owner_bytes(&mapped.buffers, 0, &fields).unwrap(); @@ -427,11 +411,9 @@ fn an_argument_buffer_sampler_maps_by_its_field() { shared.argument_buffer_textures[0].field_offset = 8; let mapped = map_kernel(&shared).unwrap(); assert!(field_words( - &BTreeMap::new(), &BTreeMap::new(), &texture_tokens(&mapped).unwrap(), &sampler_ids(&mapped).unwrap(), - std::iter::empty(), ) .is_err()); } @@ -524,11 +506,9 @@ fn an_argument_buffer_sampler_is_the_sampler_table_entry_its_owner_names() { && write.source == WriteSource::Neutral(NeutralResource::Sampler { compare: false }))); let commands = plan.instantiate_dispatch(&state, &mapped.dispatch).unwrap(); let fields = field_words( - &BTreeMap::new(), &BTreeMap::new(), &texture_tokens(&mapped).unwrap(), &sampler_ids(&mapped).unwrap(), - std::iter::empty(), ) .unwrap(); let owner = owner_bytes(&mapped.buffers, 0, &fields).unwrap(); diff --git a/crates/metal2vulkan-validation/src/candidate/engine/variants.rs b/crates/metal2vulkan-validation/src/candidate/engine/variants.rs index 5aed77f55..86d233f91 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/variants.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/variants.rs @@ -24,7 +24,7 @@ //! shape): the whole loop runs under the worker's one deadline and memory limit, and the device //! process only plans the returned pipeline for the same shape. Everything here is device-free. -use metal2vulkan::bind::{draw_replay_vertex_layouts, BindShape, Dispatch, TextureShape}; +use metal2vulkan::bind::{BindShape, Dispatch, TextureShape}; use metal2vulkan::cache::VariantKey; use metal2vulkan::device::{Device, DeviceProfile}; use metal2vulkan::error::{Error, InternalError, InternalKind, RuntimeInput}; @@ -36,7 +36,6 @@ use metal2vulkan::pipeline::{ }; use metal2vulkan::pipeline::{SlotClass, SlotRef, Stage}; use metal2vulkan::Budget; -use serde::{Deserialize, Serialize}; /// Whether a pipeline compiled under `compiled` is the one `variant` asks for. pub fn compiled_for(compiled: &VariantKey, variant: &VariantKey) -> bool { @@ -126,26 +125,6 @@ pub fn compile_compute_for_shape( }) } -/// Compile `function` into the device-replay variant of a template for `device` under `budget`, for -/// the bind shape `shape` (which binds no kernel buffer) and the variant's indirect `dispatch`, as -/// [`compile_compute_for_shape`] does: under the key's kernel inputs with -/// `LoweringInputs::replay_bindings` set. Returns the pipeline and that key. -pub fn compile_replay_for_shape( - device: &Device, - function: &FunctionDescriptor, - shape: &BindShape, - dispatch: Option<&Dispatch>, - budget: &Budget, -) -> Result<(ComputePipeline, VariantKey), Error> { - compile_kernel_for_shape(device, shape, dispatch, |key| { - let mut inputs = key.lowering_inputs(Stage::Kernel); - inputs.replay_bindings = true; - let compiled = device.compile_function(function, &inputs, budget)?; - let descriptor = ComputePipelineDescriptor::new(StageSource::Compiled(compiled)); - device.compile_compute_pipeline(&descriptor, budget) - }) -} - /// [`compile_for_bind_state`] of a kernel pipeline `compile` builds under a key, settling on the /// variant the plan of `shape` asks for, or the one `dispatch` runs on when given (its plan's /// `dispatch_variant`). @@ -171,89 +150,21 @@ fn compile_kernel_for_shape( ) } -/// The form of the variant a render pipeline compiles in for what draws it -/// ([`compile_render_for_shape`]), as the runtime's draws take them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum DrawForm { - /// The variant the plan of the bind shape asks for: a case's draw. - #[default] - Bound, - /// Its large-buffer form (`VariantKey::large_buffer_form`): an executed render command's draw, - /// which the runtime's host step draws in that form. - Large, - /// Its draw replay variant (`VariantKey::replay_bindings`): an execution's commands drawn on - /// the device, one draw per command, every buffer from the command's slot table, as the - /// runtime's GPU form of an execution of GPU-written render commands draws them. - Replay, - /// Its merged draw replay variant (`VariantKey::replay_bindings` and `merged_draws`): an - /// execution's commands drawn on the device as one merged draw. - Merged, -} - -impl DrawForm { - /// Whether this is the plain form, which a request leaves unstated. - pub fn is_bound(&self) -> bool { - *self == DrawForm::Bound - } -} - /// Compile `descriptor` into a render pipeline for `device` under `budget` with the variant the /// bind shape `shape` decides ([`compile_for_bind_state`] over `Device::compile_render_variant`: -/// storage-texture formats of both stages, the plan's pulled vertex buffers) in `form`; returns -/// the pipeline and that key. In the large-buffer form, as the runtime's host step compiles an -/// executed render command's draw (`VariantKey::large_buffer_form` of the first pipeline's plan, -/// from its dependencies), the plan of the pipeline compiled under it settles on it where that key -/// covers the plan's. In a draw replay's forms the key is the plan's with `replay_bindings` (and -/// `merged_draws` for the merged one) set, as the runtime's state settles a replayed draw, the -/// plan's for `shape` with every fixed-function layout of the first pipeline compiled (the base) -/// named among those the draw pulls (`bind::draw_replay_vertex_layouts`); a layout of a stride set -/// per bind stays in fixed function, whose replay variant the product refuses. +/// storage-texture formats of both stages, the plan's pulled vertex buffers); returns the pipeline +/// and that key. pub fn compile_render_for_shape( device: &Device, descriptor: &RenderPipelineDescriptor, shape: &BindShape, - form: DrawForm, budget: &Budget, ) -> Result<(RenderPipeline, VariantKey), Error> { - let mut large_key: Option = None; - let mut replayed: Option = None; compile_for_bind_state( |slot| bound_format(shape, slot), device.profile(), |key| device.compile_render_variant(descriptor, key, budget), - |pipeline| { - // A draw replay pulls the base's fixed-function layouts (the first pipeline's). - let shape = match form { - DrawForm::Replay | DrawForm::Merged => &*replayed.get_or_insert_with(|| { - let mut replayed = shape.clone(); - replayed.far_vertex_buffers = - draw_replay_vertex_layouts(&pipeline.vertex_input).unwrap_or_default(); - replayed - }), - DrawForm::Bound | DrawForm::Large => shape, - }; - let plan = pipeline.plan(device, shape).ok()?; - match form { - DrawForm::Bound => Some(plan.variant), - DrawForm::Large => { - if let Some(key) = large_key.as_ref().filter(|key| key.covers(&plan.variant)) { - return Some(key.clone()); - } - let key = plan - .variant - .large_buffer_form(&pipeline.dependencies, shape); - large_key = Some(key.clone()); - Some(key) - } - DrawForm::Replay | DrawForm::Merged => { - let mut key = plan.variant; - key.replay_bindings = true; - key.merged_draws = form == DrawForm::Merged; - Some(key) - } - } - }, + |pipeline| Some(pipeline.plan(device, shape).ok()?.variant), ) } @@ -563,14 +474,8 @@ mod tests { resource_id: None, }, ); - let (_, key) = compile_render_for_shape( - &device, - &descriptor, - &state.shape(), - DrawForm::Bound, - &budget, - ) - .unwrap(); + let (_, key) = + compile_render_for_shape(&device, &descriptor, &state.shape(), &budget).unwrap(); let choice = storage_image_choice(PixelFormat::RGBA32Float, device.profile()).unwrap(); assert_eq!(key.storage_images.get(&slot), Some(&choice)); } diff --git a/crates/metal2vulkan-validation/src/candidate/platform.rs b/crates/metal2vulkan-validation/src/candidate/platform.rs index 50d246a69..f38fb56b2 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform.rs @@ -5,7 +5,6 @@ mod buffers; mod compute; mod device; mod enables; -mod generated_commands; mod graphics_pipeline; mod ignored_drivers; mod loader_word; diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute.rs index 1193f30be..79d515e67 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/compute.rs @@ -14,17 +14,15 @@ use super::device::{ refused_restriction, with_validated_context, RefusedRestriction, VulkanContext, }; use super::plan_resources::{padded, Guest, PlanResources, TextureKey}; -use crate::candidate::engine::argument_buffers::{ - field_words, owner_bytes, records_storage, validate_records, -}; +use crate::candidate::engine::argument_buffers::{field_words, owner_bytes}; use crate::candidate::engine::guards::{ embedded_guard_reach, guard_reach, with_escaped, GuardCount, GuardReach, }; use crate::candidate::engine::{ bind_refusal, bind_state, compute_shape, engine_fingerprint, out_of_bounds_run, - product_refusal, records_ids, resources, run_allocations, sampler_ids, select_output, - status_verdict, synthetic_used_addresses, texture_tokens, BufferAddress, ComputeCase, - ComputeOutput, ComputeRun, RunAllocation, RunAttempt, + product_refusal, resources, sampler_ids, select_output, status_verdict, + synthetic_used_addresses, texture_tokens, BufferAddress, ComputeCase, ComputeOutput, + ComputeRun, RunAttempt, }; use crate::case::out_of_bounds::OutOfBoundsResource; use crate::check::admission::{ExecutorError, NotSupported}; @@ -40,8 +38,8 @@ use ash::vk; use metal2vulkan::bind::BindingPlan; use metal2vulkan::bind::{BindShape, BufferRanges}; use metal2vulkan::bind::{ - DispatchCommands, DispatchRegion, ExecutionStatus, NeutralResource, PushHole, ReplayVariant, - RootTable, SamplerDescriptor, + DispatchCommands, DispatchRegion, ExecutionStatus, NeutralResource, PushHole, RootTable, + SamplerDescriptor, }; use metal2vulkan::device::VkFeature; use metal2vulkan::device::{Device, DeviceDescription, DeviceProfile}; @@ -52,43 +50,26 @@ use std::ffi::CString; use std::sync::Arc; use std::time::Duration; -mod device_replay; -mod draw_replay; -mod replay; -use crate::candidate::engine::{ChildCommand, CompiledChild}; -pub(super) use device_replay::{replay_commands, OnDevice, ReplayPath}; -pub(in crate::candidate) use replay::CompileChild; -pub(super) use replay::{Live, Replay}; - /// One region's push-constant writes: `(stages, offset, bytes)`, holes filled. type PushWrites = Vec<(vk::ShaderStageFlags, u32, Vec)>; /// Compile `case` for the device `device_type` opens with `compile` (given the opened device's /// description and policy, and the shape the dispatch binds, which decides the lowering inputs; it /// returns the pipeline), plan and execute its dispatch, and -/// read the status before the output. The commands of each executed command buffer run after it, -/// compiled with `children`: on the device over the `registered` replay variants where the product -/// sets the device replay up, by the host replay elsewhere. Every refusal is typed; only a device, -/// driver, or tool failure is `Failed`. A typed refusal after the device opened names that device +/// read the status before the output. Every refusal is typed; only a device, driver, or tool +/// failure is `Failed`. A typed refusal after the device opened names that device /// ([`RunAttempt::refused_on`]). pub fn execute_engine( device_type: DeviceType, case_id: &str, case: &ComputeCase, compile: impl FnOnce(&WorkerDevice, &BindShape) -> Result, - children: impl FnMut( - &WorkerDevice, - u64, - &BindShape, - &ChildCommand, - ) -> Result, - registered: &[ReplayVariant], ) -> RunAttempt { if let Some(refused) = refused_attempt(device_type, "engine-compute") { return refused; } with_validated_context(device_type, |context| { - let result = run(context, case_id, case, (compile, children), registered); + let result = run(context, case_id, case, compile); Ok(attempt(context, result, "engine-compute")) }) .unwrap_or_else(|error| RunAttempt::of(Err(ExecutorError::Failed(error)))) @@ -227,16 +208,7 @@ fn run( context: &VulkanContext, case_id: &str, case: &ComputeCase, - (compile, mut children): ( - impl FnOnce(&WorkerDevice, &BindShape) -> Result, - impl FnMut( - &WorkerDevice, - u64, - &BindShape, - &ChildCommand, - ) -> Result, - ), - registered: &[ReplayVariant], + compile: impl FnOnce(&WorkerDevice, &BindShape) -> Result, ) -> Result { let target = opened_device(context)?; let addressed = context @@ -274,17 +246,8 @@ fn run( case_id: case_id.into(), module_sha256: spv_sha256.clone(), }; - let mut compile_child = |token: u64, shape: &BindShape, command: &ChildCommand| { - children(&target, token, shape, command) - }; let executed = with_submission_label(label, || { - execute( - context, - device, - (&pipeline, &shape), - case, - (&mut compile_child, registered), - ) + execute(context, device, (&pipeline, &shape), case) }); // Every object of the run is destroyed by now, so destruction reports here too. let messages = context.take_messages(); @@ -302,23 +265,19 @@ fn run( let Executed { output, status, - children, escaped, - replayed, } = executed?; - // The census covers every module the run executed: the producer's, under the specialization - // its plan for the shape gives, and each replayed command's. + // The census covers the module the run executed, under the specialization its plan for the + // shape gives. let planned = pipeline.plan(device, &shape).ok(); - let mut modules = module_censuses( + let modules = module_censuses( std::slice::from_ref(&pipeline.stage), device.profile(), planned.as_ref(), )?; - modules.extend(children); let out_of_bounds = out_of_bounds.map(|run| with_escaped(run, &escaped)); let census = executed_census(context, modules, out_of_bounds); - let mut environment = environment(context, device, "engine-compute"); - command_replay(&mut environment, &replayed); + let environment = environment(context, device, "engine-compute"); Ok(ComputeRun { output, spv_sha256: Some(spv_sha256), @@ -354,15 +313,6 @@ pub(super) fn executed_census( } } -/// Record in `environment` which replay ran each executed command buffer, in key order -/// (`command_replay`, [`ReplayPath::name`]), where any ran. -pub(super) fn command_replay(environment: &mut serde_json::Value, replayed: &[ReplayPath]) { - if let (false, Some(object)) = (replayed.is_empty(), environment.as_object_mut()) { - let paths: Vec<&str> = replayed.iter().map(|path| path.name()).collect(); - object.insert("command_replay".into(), serde_json::json!(paths)); - } -} - /// The census of each module of a pipeline the run executed /// (`ModuleCensus::of_pipeline_modules_under`): its stages, compiled for the opened device's /// `profile`, with the containment encodings that profile gives them, and the precision notes that @@ -439,15 +389,12 @@ impl Drop for Objects<'_> { } } -/// What [`execute`] read after the run: the output, the status, the census of each module a -/// replayed command executed, the guard and padding bytes that changed around each guarded buffer, -/// by out-of-bounds target, and which replay ran each executed command buffer, in key order. +/// What [`execute`] read after the run: the output, the status, and the guard and padding bytes +/// that changed around each guarded buffer, by out-of-bounds target. struct Executed { output: Vec, status: metal2vulkan::bind::StatusReport, - children: Vec, escaped: BTreeMap, - replayed: Vec, } /// A buffer the run allocated, with its device address when the device has them. @@ -503,18 +450,15 @@ fn not_implemented(what: impl Into) -> ExecutorError { } /// Allocate the case's buffers (argument-buffer buffers first, so each owner is created with their -/// addresses, its textures' and samplers' resource ids, and its command buffers', [`field_words`], -/// [`owner_bytes`]), plan and instantiate its dispatch, create what every plan write names -/// (`plan_resources`: textures, argument-buffer textures, heap arrays, handle tables, samplers, and -/// neutrals included), record and submit it, wait, and read the status and then -/// the output ([`Executed`]). `compile` compiles the children the case's executed command -/// buffers dispatch, each in a compile worker: on the device, the `registered` replay variants. +/// addresses and its textures' and samplers' resource ids, [`field_words`], [`owner_bytes`]), plan +/// and instantiate its dispatch, create what every plan write names (`plan_resources`: textures, +/// argument-buffer textures, heap arrays, handle tables, samplers, and neutrals included), record +/// and submit it, wait, and read the status and then the output ([`Executed`]). fn execute( context: &VulkanContext, device: &Device, (pipeline, compiled_for): (&ComputePipeline, &BindShape), case: &ComputeCase, - (compile, registered): (&mut CompileChild<'_>, &[ReplayVariant]), ) -> Result { let addressed = context .enabled @@ -527,7 +471,6 @@ fn execute( None => Ok(synthetic), }; let synthetic_used = synthetic_used_addresses(case).map_err(ExecutorError::Failed)?; - let records = records_ids(case).map_err(ExecutorError::Failed)?; let mut embedded = BTreeMap::new(); let mut embedded_addresses = BTreeMap::new(); for (&key, bytes) in &case.argument_buffer_buffers { @@ -540,21 +483,14 @@ fn execute( vk::BufferUsageFlags::empty(), embedded_guard_reach(case, key), )?; - // A command buffer's record storage lies at its ID's records address. - let address = match records.get(&key) { - Some(&id) => records_storage(id, allocation.address), - None => own_guest(&allocation, synthetic_used[&key])?, - }; - embedded_addresses.insert(key, address); + embedded_addresses.insert(key, own_guest(&allocation, synthetic_used[&key])?); embedded.insert(key, allocation); } let tokens = texture_tokens(case).map_err(ExecutorError::Failed)?; let fields = field_words( &embedded_addresses, - &records, &tokens, &sampler_ids(case).map_err(ExecutorError::Failed)?, - case.objects.iter().map(|(&key, &word)| (key, word)), ) .map_err(ExecutorError::Failed)?; let mut buffers = BTreeMap::new(); @@ -580,23 +516,6 @@ fn execute( )) }) .collect::>()?; - // The commands the host encodes, written into their record storage before the producer runs, - // each buffer at its case buffer's guest address. - for (key, command) in &case.command_buffers { - if command.commands.is_empty() { - continue; - } - let storage = embedded - .get(key) - .ok_or_else(|| format!("command buffer {key:?} has no record storage"))?; - // SAFETY: the storage was created for this run and nothing has been submitted yet. - let mapped = unsafe { storage.buffer.map()? }; - command - .encode_host_records(mapped.bytes, |buffer| { - addresses.get(&buffer).map(|address| address.guest) - }) - .map_err(ExecutorError::Failed)?; - } let ranges = BufferRanges::of(device.profile().limits()); let state = bind_state(case, &addresses, &embedded_addresses, ranges).map_err(ExecutorError::Failed)?; @@ -695,7 +614,7 @@ fn execute( // A dispatch draws no patches and has no attachments. tessellation_factors: None, attachments: &BTreeMap::new(), - status: Some(status.buffer.buffer), + status: status.buffer.buffer, }, observed, )?; @@ -751,64 +670,11 @@ fn execute( .try_into() .expect("the status buffer holds ExecutionStatus::BYTES bytes"); let report = status_verdict(&status_bytes)?; - // Each command buffer's records as the host contract decodes them: an encoding fault fails the - // run. Then the commands the case executes run, over the run's allocations. - let mut records = BTreeMap::new(); - for &key in case.command_buffers.keys() { - let allocation = embedded - .get(&key) - .ok_or_else(|| format!("command buffer {key:?} has no record storage"))?; - let len = case.argument_buffer_buffers[&key].len(); - // SAFETY: as for the status buffer. - let bytes = unsafe { allocation.buffer.map()? }.bytes[..len].to_vec(); - records.insert(key, bytes); - } - validate_records( - case.command_buffers - .iter() - .map(|(&key, command)| (key, command)), - &records, - ) - .map_err(ExecutorError::Failed)?; - // Each allocation at its guest address and the length the guest sees (not the padding), in - // the run's order (`run_allocations`), which the device replay's resident set follows. - let live = run_allocations(case) - .into_iter() - .map(|(held, length)| { - let (address, allocation) = match held { - RunAllocation::Buffer(index) => (addresses[&index], &buffers[&index]), - RunAllocation::ArgumentBuffer(key) => (embedded_addresses[&key], &embedded[&key]), - }; - Live { - buffer: allocation.buffer.buffer, - address, - length, - } - }) - .collect::>(); - let (executed, replayed) = replay_commands( - context, - device, - case.command_buffers - .iter() - .map(|(&key, command)| (key, command)), - Replay { - live: &live, - records: &records, - addresses: &|_, buffer| addresses.get(&buffer).map(|address| address.guest), - compile, - }, - OnDevice { - registered, - storage: &|key| embedded.get(&key).and_then(|allocation| allocation.address), - writes: pipeline.interface.command_writes, - }, - )?; let mut finals = BTreeMap::new(); let mut escaped = BTreeMap::new(); for (&index, allocation) in &buffers { let len = case.buffers[&index].len(); - // SAFETY: as for the status buffer; every replayed command completed too. + // SAFETY: as for the status buffer. let bytes = unsafe { allocation.buffer.map()? }.bytes[..len].to_vec(); finals.insert(index, bytes); // SAFETY: as for the status buffer. @@ -872,9 +738,7 @@ fn execute( Ok(Executed { output, status: report, - children: executed, escaped, - replayed, }) } diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay.rs deleted file mode 100644 index b3fea4b0b..000000000 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay.rs +++ /dev/null @@ -1,986 +0,0 @@ -//! Device replay of executed compute commands in the engine compute executor. -//! -//! After the producer completed and every command buffer's records passed the host contract's -//! decode (as for the host replay, `validate_records`), each executed compute command buffer runs -//! its execution range on the device where the product sets the device replay up -//! (`replay_preprocess_module`: a device with device addresses) and the case registers a -//! variant: the records are never decoded to drive what runs. The consumer side is the -//! product's contract (`docs/API.md`, "GPU-encoded compute commands on the device"): -//! -//! - every registered variant ([`ReplayVariant`]: a compute template's pipeline token, threadgroup -//! size, and threadgroup lengths, `engine::replay_variants`) is compiled in a compile worker -//! with `LoweringInputs::replay_bindings` (`ChildCommand::ReplayVariant`), planned for a bind -//! state that sets its threadgroup lengths, binds no kernel buffer, and makes every allocation -//! of the run resident (as the oracle's `useResource` does), and instantiated with -//! `BindingPlan::instantiate_replay`; -//! - one command buffer records the product's preprocess over the range (its scratch holding the -//! parameters, the resident root table with the sink filled, the variants, and the parent -//! encoder's state, as `replay_preprocess` states them, with the product's most regions per -//! command, `MAX_REPLAY_REGIONS`), a barrier, and then per command in range order, per region -//! (a ragged grid's edges and a group count's chunks past the device's limit), and per variant -//! `vkCmdDispatchIndirect` from the arguments of the command's region with the command's slot -//! table as the root table and the region's record as the region, a compute barrier between -//! commands; -//! - after the wait, the status: a replay fault (a command dispatched nothing) refuses the row -//! for the product's typed limits and fails it for every other reason -//! (`engine::replay_fault_verdict`); the census holds each variant once per command whose -//! arguments selected it in any region. -//! -//! Where the context enabled `VK_EXT_device_generated_commands` (`VulkanContext:: -//! generated_commands`), the variants are compiled first and the product's -//! `replay_preprocess_generated` sets up the generated-commands path: the same preprocess writes -//! each command's sequences and each possible segment's count in place of the arguments, and the -//! command buffer records one `vkCmdExecuteGeneratedCommandsEXT` per command of the range -//! ([`generated`]) in place of the dispatches. Where the product refuses that path -//! (`ReplayRefusal::GeneratedCommands`: a limit the device states, or variants that bind other -//! descriptors), K14c's dispatches run instead; the environment names which ran. -//! -//! A render command buffer runs on the device where the runtime's GPU form draws it -//! (`draw_replay`); one the shared rules send to the host step, a compute one on a device without -//! device addresses, and one of a case that registers no variant run the host replay -//! (`replay::execute_commands`). - -use super::draw_replay::{draw_commands, Drawing}; -use super::replay::{bound_table, execute_commands, require_enabled}; -use super::*; -use crate::candidate::engine::{ - replay_fault_verdict, replay_regions, replay_resident, replay_variant_state, -}; -use crate::case::indirect_commands::CommandBufferResource; -use metal2vulkan::bind::indirect_commands::{ - BufferStage, CommandRecord, Inheritance, RegisteredBuffer, StateSource, -}; -use metal2vulkan::bind::{ - replay_preprocess, replay_preprocess_generated, replay_preprocess_module, BindState, - BindingPlan, GeneratedLayout, GeneratedVariant, IndirectArgs, ReplayExecution, ReplayLayout, - ReplayPreprocessModule, ReplayRefusal, -}; -use metal2vulkan::error::BindError; - -mod generated; - -/// Which replay ran an executed command buffer. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(in crate::candidate::platform) enum ReplayPath { - /// The product's preprocess and indirect dispatches of the registered variants. - Device, - /// The product's preprocess and the generated-commands executions of its token stream. - Generated, - /// The host replay of the decoded records. - Host, - /// The product's draw replay preprocess and one indirect draw per command of the render - /// template's draw replay variant (`draw_replay`). - Draws, - /// The product's draw replay preprocess, its merge passes, and the merged draw of the render - /// template's merged variant (`draw_replay`). - MergedDraws, -} - -impl ReplayPath { - /// The name the candidate's environment records. - pub(in crate::candidate::platform) fn name(self) -> &'static str { - match self { - ReplayPath::Device => "device", - ReplayPath::Generated => "generated", - ReplayPath::Host => "host", - ReplayPath::Draws => "device-draws", - ReplayPath::MergedDraws => "merged-draws", - } - } -} - -/// What the device replay needs beyond the host replay's [`Replay`]: the variants the case -/// registers, the device address of each command buffer's record storage (its header), by key, -/// and what the functions of the case's own dispatch or draw may write into the records of every -/// command buffer of their kinds (`PipelineInterface::command_writes`: its encoder makes each -/// resident for writing, as the case runner's does). -pub(in crate::candidate::platform) struct OnDevice<'a, K> { - pub(in crate::candidate::platform) registered: &'a [ReplayVariant], - pub(in crate::candidate::platform) storage: &'a dyn Fn(K) -> Option, - pub(in crate::candidate::platform) writes: metal2vulkan::pipeline::CommandWrites, -} - -/// Execute each of `command_buffers` that the case executes, in key order: a compute command -/// buffer on the device ([`device_commands`]) where the product sets the device replay up and -/// `on_device` registers a variant, a render one on the device where the runtime's GPU form draws -/// it ([`draw_commands`]), every other one by the host replay ([`execute_commands`]). The census -/// of every module a command executed, and which replay ran each executed command buffer. -pub(in crate::candidate::platform) fn replay_commands<'c, K: Ord + Copy + std::fmt::Debug>( - context: &VulkanContext, - device: &Device, - command_buffers: impl IntoIterator, - replay: Replay<'_, '_, K>, - on_device: OnDevice<'_, K>, -) -> Result<(replay::Executed, Vec), ExecutorError> { - let Replay { - live, - records, - addresses, - compile, - } = replay; - let mut executed = Vec::new(); - let mut paths = Vec::new(); - // The preprocess module, built once: `None` where the product does not set the device replay - // up on this device (no device addresses). - let mut preprocess: Option> = None; - for (key, command) in command_buffers { - if command.execute.is_none() { - continue; - } - if command.is_render() { - let drawing = Drawing { - live, - addresses, - storage: (on_device.storage)(key), - writes: on_device.writes, - }; - if let Some((census, path)) = - draw_commands(context, device, (key, command), drawing, compile)? - { - executed.extend(census); - paths.push(path); - continue; - } - } - let module = if command.is_render() || on_device.registered.is_empty() { - None - } else { - if preprocess.is_none() { - preprocess = Some(preprocess_module(device)?); - } - preprocess.as_ref().and_then(Option::as_ref) - }; - match module { - Some(module) => { - let storage = (on_device.storage)(key).ok_or_else(|| { - format!("command buffer {key:?} has no record storage address") - })?; - let (census, path) = device_commands( - context, - device, - (key, command), - module, - Commands { - live, - addresses, - storage, - registered: on_device.registered, - }, - compile, - )?; - executed.extend(census); - paths.push(path); - } - None => { - executed.extend(execute_commands( - context, - device, - [(key, command)], - Replay { - live, - records, - addresses, - compile: &mut *compile, - }, - )?); - paths.push(ReplayPath::Host); - } - } - } - Ok((executed, paths)) -} - -/// The product's preprocess module for `device`, or `None` where the product states the device -/// replay unsupported (no device addresses): the host replay runs there. -fn preprocess_module(device: &Device) -> Result, ExecutorError> { - match replay_preprocess_module(device) { - Ok(module) => Ok(Some(module)), - Err(metal2vulkan::error::Error::Unsupported(_)) => Ok(None), - Err(error) => Err(product_refusal(&error)), - } -} - -/// What one command buffer's device replay runs over: the run's allocations `live`, the guest -/// address of each case buffer of the command buffer's owner (`addresses`, for the parent's -/// bindings), the record storage's device address `storage`, and the registered variants. -struct Commands<'a, K> { - live: &'a [Live], - addresses: &'a dyn Fn(K, u32) -> Option, - storage: u64, - registered: &'a [ReplayVariant], -} - -/// Replay the execution range of the command buffer `key` on the device: compile each registered -/// variant ([`prepare`]), set up the generated-commands path where the context enabled it and the -/// product sets it up ([`generated::Generated::create`]) or else each variant's dispatches -/// ([`Variant::create`]), upload the preprocess's scratch, record the preprocess and every -/// command's executions or indirect dispatches in one command buffer, submit, wait, and read the -/// status. The census of each variant once per command whose arguments (or sequences) selected -/// it, and which path ran. -fn device_commands( - context: &VulkanContext, - device: &Device, - (key, command): (K, &CommandBufferResource), - module: &ReplayPreprocessModule, - commands: Commands<'_, K>, - compile: &mut CompileChild<'_>, -) -> Result<(replay::Executed, ReplayPath), ExecutorError> { - let Commands { - live, - addresses, - storage, - registered, - } = commands; - let fail = |why: String| ExecutorError::Failed(format!("command buffer {key:?}: {why}")); - let Some(parent) = command - .parent_bindings(|buffer| addresses(key, buffer)) - .map_err(ExecutorError::Failed)? - else { - return Ok((Vec::new(), ReplayPath::Device)); - }; - let [start, end] = command.execution_range; - let count = end - .checked_sub(start) - .ok_or_else(|| fail("a reversed execution range".into()))?; - if count == 0 { - return Ok((Vec::new(), ReplayPath::Device)); - } - let addressed = context - .enabled - .features - .contains(&VkFeature::BufferDeviceAddress); - if !addressed { - return Err(fail( - "the device replay needs device addresses the context did not enable".into(), - )); - } - // Every allocation of the run is resident, as the oracle's `useResource` makes it. - let resident = replay_resident( - live.iter() - .map(|allocation| (allocation.address, allocation.length)), - ) - .map_err(ExecutorError::Failed)?; - let mut execution = ReplayExecution::new(command.capacity, start, count); - execution.inheritance = command.inheritance(); - execution.parent_pipeline = parent.pipeline; - // Commands that inherit the encoder's buffers bind its kernel buffers, each at its - // allocation's device address (`ReplayExecution::parent_buffers`). - if execution.inheritance.buffers == StateSource::Parent { - let buffers = live - .iter() - .map(|allocation| { - RegisteredBuffer::new(allocation, allocation.address.guest, allocation.length) - }) - .collect::, _>>() - .map_err(|error| fail(error.to_string()))?; - let encoder = Inheritance { - pipeline: StateSource::Parent, - buffers: StateSource::Parent, - }; - let empty = CommandRecord::default(); - let resolved = empty - .resolve_bindings(encoder, &parent) - .map_err(|error| fail(error.to_string()))?; - let (table, _) = - bound_table(&resolved, Stage::Kernel, BufferStage::Kernel, &buffers).map_err(fail)?; - execution.parent_buffers = table.buffers; - } - // As many regions per command as keep the range's dispatches within the product's bound. - execution.regions = replay_regions(count, registered.len()); - let k14c = || { - replay_preprocess(device, &resident, &execution, registered).map_err(|e| bind_refusal(&e)) - }; - // The generated-commands path needs the variants' plans and commands before the preprocess; - // K14c's path keeps its order, the preprocess's refusals first. - let dgc = context.generated_commands(); - let (pre, prepared) = match dgc { - Some(_) => { - let prepared = prepare_all(context, device, registered, &resident, compile)?; - let set_up = { - let generated: Vec> = - prepared.iter().map(Prepared::generated).collect(); - replay_preprocess_generated(device, &resident, &execution, registered, &generated) - }; - match set_up { - Ok(pre) => (pre, prepared), - Err(BindError::InvalidReplay { - reason: ReplayRefusal::GeneratedCommands { .. }, - }) => (k14c()?, prepared), - Err(error) => return Err(bind_refusal(&error)), - } - } - None => { - let pre = k14c()?; - ( - pre, - prepare_all(context, device, registered, &resident, compile)?, - ) - } - }; - let layout = pre.layout; - require_preprocess(context, module)?; - let stages: Vec = prepared.iter().map(|p| p.stage.clone()).collect(); - let mut replayed = match (dgc, &pre.generated, &layout.generated) { - (Some(dgc), Some(replay), Some(generated)) => Replayed::Generated( - Box::new(generated::Generated::create( - context, device, dgc, &prepared, replay, generated, - )?), - *generated, - ), - _ => { - let mut variants = Vec::with_capacity(prepared.len()); - for p in prepared { - variants.push(Variant::create(context, device, p)?); - } - Replayed::Dispatches(variants) - } - }; - - // The consumer's objects: the sink the resident root table names, the scratch, the status. - let sink = allocate( - context, - "device replay sink", - &[0; NeutralResource::SINK_BYTES as usize], - addressed, - vk::BufferUsageFlags::empty(), - )?; - let sink_address = sink.address.ok_or("the sink has no device address")?; - let scratch_bytes = scratch_bytes(&pre, sink_address)?; - // The generated path's preprocess memory, sized for the executions the layout states. - if let Replayed::Generated(generated, layout) = &mut replayed { - generated.reserve_preprocess(context, layout)?; - } - let scratch = allocate( - context, - "device replay scratch", - &scratch_bytes, - addressed, - vk::BufferUsageFlags::INDIRECT_BUFFER, - )?; - let scratch_address = match scratch.address { - // Every slot table and the resident root table are root tables: 16-aligned. - Some(address) if address % 16 == 0 => address, - other => { - return Err(fail(format!( - "the scratch's address {other:?} is not 16-aligned" - ))) - } - }; - let status = allocate( - context, - "device replay status", - &ExecutionStatus::initial(), - addressed, - vk::BufferUsageFlags::empty(), - )?; - let status_address = status.address.ok_or("the status has no device address")?; - let mut push = pre.push_constants.clone(); - for hole in &pre.push_holes { - let (offset, address) = match *hole { - PushHole::RootTableAddress { offset, .. } => { - (offset, scratch_address + layout.resident_offset) - } - PushHole::ExecutionStatusAddress { offset, .. } => (offset, status_address), - PushHole::CommandRecordsAddress { offset, .. } => (offset, storage), - other => return Err(not_implemented(format!("the push hole {other:?}"))), - }; - push.get_mut(offset as usize..offset as usize + 8) - .ok_or_else(|| fail(format!("the preprocess push bytes end before {offset}")))? - .copy_from_slice(&address.to_le_bytes()); - } - let mut objects = preprocess_objects(context, (&module.spirv, &module.layout), "preprocess")?; - record_and_submit( - context, - &mut objects, - &replayed, - Recorded { - layout: &layout, - group_count: pre.group_count, - push: &push, - scratch: scratch.buffer.buffer, - scratch_address, - status_address, - }, - )?; - // SAFETY: the submission completed (the fence signaled), and nothing else maps it. - let status_bytes: [u8; ExecutionStatus::BYTES] = unsafe { status.buffer.map()? }.bytes - [..ExecutionStatus::BYTES] - .try_into() - .expect("the status buffer holds ExecutionStatus::BYTES bytes"); - let report = ExecutionStatus::decode(&status_bytes); - if report.replay_fault { - return Err(replay_fault_verdict( - &format!("command buffer {key:?}"), - report.replay_faults, - )); - } - status_verdict(&status_bytes).map_err(|e| match e { - ExecutorError::Failed(why) => fail(why), - refused => refused, - })?; - // Each variant a command's arguments (or sequences) selected in any region (every group - // count nonzero), once per command. - // SAFETY: as for the status buffer. - let arguments = unsafe { scratch.buffer.map()? }; - let selected = |slot: u32, index: usize| -> Result { - let mut selected = false; - for region in 0..layout.regions { - let (variant, at) = match &replayed { - Replayed::Dispatches(_) => ( - index, - layout.argument_offset(slot, region, index as u32) as usize, - ), - Replayed::Generated(_, generated) => { - let at = generated.sequence_offset(slot, region); - let word = arguments - .bytes - .get(at as usize..at as usize + 4) - .ok_or_else(|| { - fail(format!("the sequences of command {slot} end early")) - })?; - let variant = u32::from_le_bytes(word.try_into().expect("four bytes")); - let at = at + u64::from(generated.dispatch_offset()); - (variant as usize, at as usize) - } - }; - if variant >= stages.len() { - return Err(fail(format!( - "a sequence of command {slot} selects variant {variant} of {}", - stages.len() - ))); - } - selected |= variant == index - && arguments - .bytes - .get(at..at + 12) - .ok_or_else(|| fail(format!("the arguments of command {slot} end early")))? - .as_chunks::<4>() - .0 - .iter() - .all(|word| *word != [0; 4]); - } - Ok(selected) - }; - let mut executed = Vec::new(); - for slot in 0..layout.slots { - for (index, stage) in stages.iter().enumerate() { - if selected(slot, index)? { - executed.extend(module_censuses( - std::slice::from_ref(stage), - device.profile(), - None, - )?); - } - } - } - drop(arguments); - drop(objects); - let path = match replayed { - Replayed::Dispatches(_) => ReplayPath::Device, - Replayed::Generated(..) => ReplayPath::Generated, - }; - Ok((executed, path)) -} - -/// What the replay records after the preprocess and its barrier: each variant's indirect -/// dispatches per command and region (K14c), or the generated-commands executions of the -/// preprocess's token stream, with its layout. -enum Replayed<'c> { - Dispatches(Vec>), - Generated(Box>, GeneratedLayout), -} - -/// Refuse the preprocess where the context did not enable what it requires. -fn require_preprocess( - context: &VulkanContext, - module: &ReplayPreprocessModule, -) -> Result<(), ExecutorError> { - let missing = unmet_requirements(context, &module.requirements); - if missing.is_empty() { - Ok(()) - } else { - Err(NotSupported::NotEnabled(missing).into()) - } -} - -/// The scratch's initial bytes: the parameters, the resident root table with its sink entry's -/// `host` field at `sink`, the resident roots' extents, the variants, and the parent's state, -/// each at its layout offset; the slot tables and arguments are the preprocess's to write. -fn scratch_bytes(pre: &metal2vulkan::bind::ReplayPreprocess, sink: u64) -> Result, String> { - let layout = pre.layout; - let len = usize::try_from(layout.bytes).map_err(|_| "the scratch exceeds the address space")?; - let mut bytes = vec![0u8; len]; - let mut resident = pre.resident.bytes.clone(); - let at = RootTable::SINK_HOST_OFFSET as usize; - resident - .get_mut(at..at + 8) - .ok_or("the resident root table has no sink entry")? - .copy_from_slice(&sink.to_le_bytes()); - // The generated path's variant templates, which its preprocess reads. - let templates = match (&pre.generated, &layout.generated) { - (Some(replay), Some(generated)) => Some((generated.templates_offset, &replay.templates)), - (None, None) => None, - _ => return Err("the preprocess states half of the generated-commands path".into()), - }; - for (offset, part) in [ - (layout.params_offset(), &pre.params), - (layout.resident_offset, &resident), - (layout.extents_offset, &pre.extents), - (layout.variants_offset, &pre.variants), - (layout.parent_offset, &pre.parent), - ] - .into_iter() - .chain(templates) - { - let offset = offset as usize; - bytes - .get_mut(offset..offset + part.len()) - .ok_or("a scratch section runs past the scratch")? - .copy_from_slice(part); - } - Ok(bytes) -} - -/// One registered variant, compiled, planned, and instantiated (no Vulkan object yet): its stage -/// module (for the census), its pipeline, its plan, and its replay commands. -struct Prepared { - stage: StageModule, - pipeline: ComputePipeline, - plan: BindingPlan, - commands: DispatchCommands, - /// What a failure of this variant names. - name: String, -} - -impl Prepared { - /// The variant as the generated-commands path binds it. - fn generated(&self) -> GeneratedVariant<'_> { - GeneratedVariant::new(&self.pipeline, &self.plan, &self.commands) - } - - fn fail(&self, why: String) -> ExecutorError { - ExecutorError::Failed(format!("{}: {why}", self.name)) - } - - /// The constant blob a write of the plan may read, by stage. - fn constant_blobs(&self) -> BTreeMap> { - self.pipeline - .stage - .constant_blob - .iter() - .map(|blob| (Stage::Kernel, blob.clone())) - .collect() - } - - /// What the plan's writes name: a variant binds no kernel buffer (each command's slot table - /// names its buffers), and its descriptor contents are its commands'. - fn resources<'c>( - &self, - context: &'c VulkanContext, - device: &Device, - ) -> Result, ExecutorError> { - PlanResources::create( - context, - device, - &self.plan.descriptors, - &Guest { - buffers: &BTreeMap::new(), - textures: &BTreeMap::new(), - status: None, - used_textures: &BTreeMap::new(), - samplers: &BTreeMap::new(), - // A generated-commands variant's state lists no argument sampler - // (`replay_variant_state`). - argument_samplers: &[], - constant_blobs: &self.constant_blobs(), - descriptor_ranges: &self.commands.descriptor_ranges, - descriptor_bytes: &self.commands.descriptor_bytes, - tessellation_factors: None, - attachments: &BTreeMap::new(), - }, - None, - ) - } -} - -/// Every registered variant, [`prepare`]d, in their order. -fn prepare_all( - context: &VulkanContext, - device: &Device, - registered: &[ReplayVariant], - resident: &BindState, - compile: &mut CompileChild<'_>, -) -> Result, ExecutorError> { - let mut prepared = Vec::with_capacity(registered.len()); - for variant in registered { - prepared.push(prepare(context, device, variant, resident, compile)?); - } - Ok(prepared) -} - -/// Compile `variant` in a compile worker for the bind state of `resident` with its threadgroup -/// lengths and no kernel buffer, plan it (no diagnostic), and instantiate it with -/// `instantiate_replay` (one region with the replay's indirect arguments and no root table). -fn prepare( - context: &VulkanContext, - device: &Device, - variant: &ReplayVariant, - resident: &BindState, - compile: &mut CompileChild<'_>, -) -> Result { - let token = variant.pipeline.get(); - let name = format!( - "the replay variant of pipeline token {token} for {:?}", - variant.threads_per_threadgroup - ); - let fail = |why: String| ExecutorError::Failed(format!("{name}: {why}")); - let state = replay_variant_state(resident, variant); - let shape = state.shape(); - let child = ChildCommand::ReplayVariant { - threads_per_group: variant.threads_per_threadgroup, - }; - let pipeline = match compile(token, &shape, &child)? { - CompiledChild::Compute(pipeline) => *pipeline, - CompiledChild::Render(..) => return Err(fail("the token names a render template".into())), - }; - require_enabled(context, &pipeline.requirements)?; - let plan = pipeline - .plan(device, &shape) - .map_err(|e| bind_refusal(&e))?; - if let Some(diagnostic) = plan.diagnostics.first() { - return Err(incompatible_binding(diagnostic)); - } - let commands = plan - .instantiate_replay(&state, variant.threads_per_threadgroup) - .map_err(|e| bind_refusal(&e))?; - let replayed = matches!( - commands.regions.as_slice(), - [region] if region.indirect == Some(IndirectArgs::Replay) - ); - if !replayed || commands.root_table.is_some() { - return Err(fail(format!( - "the binder instantiated {} region(s), not one replayed region without a root \ - table", - commands.regions.len() - ))); - } - Ok(Prepared { - stage: pipeline.stage.clone(), - pipeline, - plan, - commands, - name, - }) -} - -/// One registered variant set up for K14c's dispatches: its instantiated commands, its pipeline -/// (one region), its descriptor sets, and the objects behind them (the pipeline objects destroyed -/// before the plan's resources, a field declared after). -struct Variant<'c> { - commands: DispatchCommands, - sets: Vec, - objects: Objects<'c>, - resources: PlanResources<'c>, -} - -impl<'c> Variant<'c> { - /// Create the pipeline of `prepared` (with its own layout) and what its plan writes name. - fn create( - context: &'c VulkanContext, - device: &Device, - prepared: Prepared, - ) -> Result, ExecutorError> { - let mut resources = prepared.resources(context, device)?; - let Prepared { - pipeline, commands, .. - } = &prepared; - let layout = match LayoutObjects::create(&context.device, &pipeline.layout) { - Ok(layout) => layout, - Err(LayoutError::Shape(why) | LayoutError::Refused(why)) => { - return Err(prepared.fail(why)) - } - }; - let mut objects = Objects { - device: &context.device, - module: vk::ShaderModule::null(), - pipelines: Vec::new(), - command_pool: vk::CommandPool::null(), - fence: vk::Fence::null(), - layout, - }; - let module_info = vk::ShaderModuleCreateInfo::default().code(&pipeline.stage.spirv); - // SAFETY: `module_info` points at live SPIR-V words for the call. - objects.module = unsafe { context.device.create_shader_module(&module_info, None) } - .map_err(|error| format!("create shader module: {error}"))?; - // A replayed command's template: the shared ceiling (`ComputeCase::creation_bound`). - create_pipelines( - context, - &mut objects, - pipeline, - &commands.regions, - crate::budgets::PIPELINE_CREATION_CEILING, - )?; - let sets = resources.write_sets(context, &objects.layout)?; - Ok(Variant { - commands: prepared.commands, - sets, - objects, - resources, - }) - } -} - -/// An owned kernel's (`what`: a replay's preprocess, a merge pass) module of `spirv`, pipeline, and -/// layout (its own, `layout`: [`ReplayPreprocessModule::layout`] and the like), with the command -/// pool and fence of the replay's submission still to create. -pub(super) fn preprocess_objects<'c>( - context: &'c VulkanContext, - (spirv, layout): (&[u32], &metal2vulkan::pipeline::PipelineLayout), - what: &str, -) -> Result, ExecutorError> { - let layout = match LayoutObjects::create(&context.device, layout) { - Ok(layout) => layout, - Err(LayoutError::Shape(why) | LayoutError::Refused(why)) => { - return Err(ExecutorError::Failed(why)) - } - }; - let mut objects = Objects { - device: &context.device, - module: vk::ShaderModule::null(), - pipelines: Vec::new(), - command_pool: vk::CommandPool::null(), - fence: vk::Fence::null(), - layout, - }; - let module_info = vk::ShaderModuleCreateInfo::default().code(spirv); - // SAFETY: `module_info` points at live SPIR-V words for the call. - objects.module = unsafe { context.device.create_shader_module(&module_info, None) } - .map_err(|error| format!("create the {what}'s shader module: {error}"))?; - let entry = c"main"; - let stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(objects.module) - .name(entry); - let info = vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(objects.layout.pipeline_layout); - let clock = crate::budgets::CreationClock::start(); - // SAFETY: every pointer in `info` outlives the call; the result is destroyed with `objects`. - let created = unsafe { - context - .device - .create_compute_pipelines(vk::PipelineCache::null(), &[info], None) - } - .map_err(|(_, error)| format!("the driver refused the {what} pipeline: {error}"))?; - objects.pipelines.extend(created.first().copied()); - crate::budgets::creation_within_ceiling(&format!("the {what} pipeline"), clock.read())?; - Ok(objects) -} - -/// What the replay's command buffer records beyond the pipelines: the scratch's layout, buffer, -/// and address, the preprocess's group count and push bytes, and the status's address. -struct Recorded<'a> { - layout: &'a ReplayLayout, - group_count: [u32; 3], - push: &'a [u8], - scratch: vk::Buffer, - scratch_address: u64, - status_address: u64, -} - -/// Record the variants' uploads, the preprocess, its barrier, and per command in range order -/// either per region and per variant the variant's indirect dispatch from the arguments of the -/// command's region with the command's slot table and the region's record, or the command's -/// generated-commands execution ([`generated::record_executions`]); a compute barrier between -/// commands, a shader-to-host barrier at the end. Submit and wait under the hang protocol. -fn record_and_submit( - context: &VulkanContext, - objects: &mut Objects<'_>, - replayed: &Replayed<'_>, - recorded: Recorded<'_>, -) -> Result<(), ExecutorError> { - let Recorded { - layout, - group_count, - push, - scratch, - scratch_address, - status_address, - } = recorded; - let variants: &[Variant<'_>] = match replayed { - Replayed::Dispatches(variants) => variants, - Replayed::Generated(..) => &[], - }; - // A variant's push writes for a command's region: its slot table, its region record, and the - // status. Each is written as its dispatch is recorded, so what the recording holds stays one - // variant's writes whatever the range. - let writes = |variant: &Variant<'_>, slot: u32, region: u32| { - push_writes(&variant.commands, |hole| match *hole { - PushHole::RootTableAddress { offset, .. } => { - Ok((offset, scratch_address + layout.table_offset(slot))) - } - PushHole::ReplayRegionAddress { offset, .. } => { - Ok((offset, scratch_address + layout.region_offset(slot, region))) - } - PushHole::ExecutionStatusAddress { offset, .. } => Ok((offset, status_address)), - other => Err(not_implemented(format!("the push hole {other:?}"))), - }) - .map(|writes| writes.into_iter().next().unwrap_or_default()) - }; - // Every hole is one the recording fills, before anything is recorded. - for variant in variants { - writes(variant, 0, 0)?; - } - let device = &context.device; - let pool_info = vk::CommandPoolCreateInfo::default().queue_family_index(context.queue_family); - // SAFETY: the queue family is the context's. - objects.command_pool = unsafe { device.create_command_pool(&pool_info, None) } - .map_err(|error| format!("create command pool: {error}"))?; - let allocate_info = vk::CommandBufferAllocateInfo::default() - .command_pool(objects.command_pool) - .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(1); - // The pool is live; the buffer is freed with it. - let command = context - .allocate_command_buffers(&allocate_info) - .map_err(|error| format!("allocate command buffer: {error}"))?[0]; - // The generated path's executions read the token stream in their preprocessing stage too. - let (preprocess_stage, preprocess_read) = match replayed { - Replayed::Dispatches(_) => (vk::PipelineStageFlags::empty(), vk::AccessFlags::empty()), - Replayed::Generated(..) => (generated::PREPROCESS_STAGE, generated::PREPROCESS_READ), - }; - let preprocessed = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask( - vk::AccessFlags::INDIRECT_COMMAND_READ | vk::AccessFlags::SHADER_READ | preprocess_read, - ); - let between = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE); - let shader_to_host = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask(vk::AccessFlags::HOST_READ); - // SAFETY: every handle recorded is live until the fence signals; the buffer is recorded once. - unsafe { - device - .begin_command_buffer( - command, - &vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT), - ) - .map_err(|error| format!("begin command buffer: {error}"))?; - for variant in variants { - variant.resources.record_uploads(command); - } - if let Replayed::Generated(generated, _) = replayed { - generated.resources.record_uploads(command); - } - device.cmd_bind_pipeline( - command, - vk::PipelineBindPoint::COMPUTE, - objects.pipelines[0], - ); - device.cmd_push_constants( - command, - objects.layout.pipeline_layout, - vk::ShaderStageFlags::COMPUTE, - 0, - push, - ); - let [x, y, z] = group_count; - device.cmd_dispatch(command, x, y, z); - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::PipelineStageFlags::DRAW_INDIRECT - | vk::PipelineStageFlags::COMPUTE_SHADER - | preprocess_stage, - vk::DependencyFlags::empty(), - &[preprocessed], - &[], - &[], - ); - if let Replayed::Generated(generated, generated_layout) = replayed { - generated::record_executions( - device, - command, - generated, - generated_layout, - scratch_address, - &between, - )?; - } - if let Replayed::Dispatches(variants) = replayed { - for slot in 0..layout.slots { - if slot > 0 { - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::DependencyFlags::empty(), - &[between], - &[], - &[], - ); - } - for (index, variant) in variants.iter().enumerate() { - let pipeline_layout = variant.objects.layout.pipeline_layout; - if !variant.sets.is_empty() { - device.cmd_bind_descriptor_sets( - command, - vk::PipelineBindPoint::COMPUTE, - pipeline_layout, - 0, - &variant.sets, - &[], - ); - } - device.cmd_bind_pipeline( - command, - vk::PipelineBindPoint::COMPUTE, - variant.objects.pipelines[0], - ); - // A command's regions are one Metal dispatch: no barrier between them. - for region in 0..layout.regions { - for (stages, offset, bytes) in writes(variant, slot, region)? { - device.cmd_push_constants( - command, - pipeline_layout, - stages, - offset, - &bytes, - ); - } - device.cmd_dispatch_indirect( - command, - scratch, - layout.argument_offset(slot, region, index as u32), - ); - } - } - } - } - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::PipelineStageFlags::HOST, - vk::DependencyFlags::empty(), - &[shader_to_host], - &[], - &[], - ); - device - .end_command_buffer(command) - .map_err(|error| format!("end command buffer: {error}"))?; - objects.fence = device - .create_fence(&vk::FenceCreateInfo::default(), None) - .map_err(|error| format!("create completion fence: {error}"))?; - let commands = [command]; - let submit = [vk::SubmitInfo::default().command_buffers(&commands)]; - device - .queue_submit(context.queue, &submit, objects.fence) - .map_err(|error| format!("submit command buffer: {error}"))?; - } - context.wait_for_fence(objects.fence, "engine candidate device replay")?; - Ok(()) -} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs deleted file mode 100644 index cf6a395d3..000000000 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/device_replay/generated.rs +++ /dev/null @@ -1,465 +0,0 @@ -//! The device replay's generated-commands path in the engine compute executor: the consumer -//! side of the product's `replay_preprocess_generated` (`docs/API.md`, "With -//! `VK_EXT_device_generated_commands`"). -//! -//! - every variant's pipeline is created with the product's shared pipeline layout -//! (`GeneratedReplay::pipeline_layout`) and `VK_PIPELINE_CREATE_2_INDIRECT_BINDABLE_BIT_EXT`, -//! with its one region's specialization; the variants' descriptor sets are the first's (the -//! product refuses variants that bind other descriptors), written once; -//! - an indirect execution set holds the pipelines in variant order (the first is its initial -//! pipeline), and an indirect commands layout holds the product's three tokens at their offsets -//! with its stride; -//! - each command of the range has preprocess memory of its own, sized by -//! `vkGetGeneratedCommandsMemoryRequirementsEXT` for the most sequences its execution runs; -//! - after the preprocess and its barrier, the descriptor sets are bound once and, per command, a -//! barrier (as K14c's between commands), the initial pipeline, zeroed push constants (the tokens -//! write every byte), and `vkCmdExecuteGeneratedCommandsEXT` over its sequences with the count -//! the preprocess wrote ([`record_executions`]); -//! - the commands layout is made for explicit preprocessing, every command's execution is -//! preprocessed (`vkCmdPreprocessGeneratedCommandsEXT`) before the first runs, a barrier orders -//! those writes before the executions, and each runs preprocessed: no preprocessing follows an -//! execution, a form that runs right on every driver. - -use super::*; -use crate::candidate::platform::generated_commands::{ - Commands, Execution, ExecutionSetCreateInfo, ExecutionSetPipelineInfo, ExecutionSetToken, - GeneratedCommandsInfo, Handle, LayoutCreateInfo, LayoutToken, MemoryRequirementsInfo, - PushConstantToken, WriteExecutionSetPipeline, EXECUTION_SET_PIPELINES, INDIRECT_BINDABLE, - PREPROCESS_BUFFER, PREPROCESS_WRITE, TOKEN_DISPATCH, TOKEN_EXECUTION_SET, TOKEN_PUSH_CONSTANT, -}; -pub(super) use crate::candidate::platform::generated_commands::{ - PREPROCESS_READ, PREPROCESS_STAGE, -}; -use metal2vulkan::bind::GeneratedReplay; -use std::collections::btree_map::Entry; -use std::time::Duration; - -/// The generated-commands path's objects for one command buffer's range. Its own handles (the -/// execution set and commands layout before the pipelines they name, then the modules and the -/// preprocess memory) are destroyed first, then the shared layout and the plan's resources -/// (fields), as a K14c variant's are. -pub(super) struct Generated<'c> { - device: &'c ash::Device, - commands: Commands, - modules: Vec, - /// Each variant's pipeline, in variant order: the execution set's indices. - pipelines: Vec, - execution_set: Handle, - commands_layout: Handle, - /// The preprocess memory's buffer and allocation ([`Generated::reserve_preprocess`]). - preprocess: Option<(vk::Buffer, vk::DeviceMemory)>, - /// Each command's preprocess memory, by slot: its address and size (`(0, 0)` where the - /// device needs none). - reserved: Vec<(vk::DeviceAddress, vk::DeviceSize)>, - sets: Vec, - layout: LayoutObjects<'c>, - pub(super) resources: PlanResources<'c>, -} - -impl Drop for Generated<'_> { - fn drop(&mut self) { - // SAFETY: every handle was created on `device` by this replay and is destroyed once; the - // replay waited for its submission (under the hang protocol) before returning normally. - unsafe { - if self.execution_set != 0 { - self.commands.destroy_execution_set(self.execution_set); - } - if self.commands_layout != 0 { - self.commands.destroy_commands_layout(self.commands_layout); - } - for pipeline in &self.pipelines { - self.device.destroy_pipeline(*pipeline, None); - } - for module in &self.modules { - self.device.destroy_shader_module(*module, None); - } - if let Some((buffer, memory)) = self.preprocess { - self.device.destroy_buffer(buffer, None); - self.device.free_memory(memory, None); - } - } - } -} - -fn fail(why: impl std::fmt::Display) -> ExecutorError { - ExecutorError::Failed(format!("the generated-commands replay: {why}")) -} - -impl<'c> Generated<'c> { - /// Set up the generated-commands path of the `prepared` variants (in their order) as the - /// product's `replay` and `layout` state it: the shared layout, the first variant's - /// descriptor sets, each variant's indirect-bindable pipeline, the execution set, and the - /// indirect commands layout. The preprocess memory waits for - /// [`reserve_preprocess`](Generated::reserve_preprocess). - pub(super) fn create( - context: &'c VulkanContext, - device: &Device, - commands: Commands, - prepared: &[Prepared], - replay: &GeneratedReplay, - layout: &GeneratedLayout, - ) -> Result, ExecutorError> { - let first = prepared.first().ok_or_else(|| fail("no variant"))?; - let shared = match LayoutObjects::create(&context.device, &replay.pipeline_layout) { - Ok(shared) => shared, - Err(LayoutError::Shape(why) | LayoutError::Refused(why)) => return Err(fail(why)), - }; - // The variants bind alike (the product refuses others): the first's resources and sets - // are every variant's. - let resources = first.resources(context, device)?; - let mut generated = Generated { - device: &context.device, - commands, - modules: Vec::with_capacity(prepared.len()), - pipelines: Vec::with_capacity(prepared.len()), - execution_set: 0, - commands_layout: 0, - preprocess: None, - reserved: Vec::new(), - sets: Vec::new(), - layout: shared, - resources, - }; - generated.sets = generated.resources.write_sets(context, &generated.layout)?; - for variant in prepared { - let [region] = variant.commands.regions.as_slice() else { - return Err(variant.fail("not one replayed region".into())); - }; - let module_info = - vk::ShaderModuleCreateInfo::default().code(&variant.pipeline.stage.spirv); - // SAFETY: `module_info` points at live SPIR-V words for the call. - let module = unsafe { context.device.create_shader_module(&module_info, None) } - .map_err(|error| format!("create shader module: {error}"))?; - generated.modules.push(module); - let (pipeline, took) = bindable_pipeline( - context, - module, - generated.layout.pipeline_layout, - &variant.pipeline, - region, - )?; - generated.pipelines.push(pipeline); - crate::budgets::creation_within_ceiling("the compute pipeline", took)?; - } - let count = u32::try_from(generated.pipelines.len()).map_err(fail)?; - let pipeline_info = ExecutionSetPipelineInfo::new(generated.pipelines[0], count); - // SAFETY: `pipeline_info` and the initial pipeline are live for the call. - generated.execution_set = - unsafe { commands.create_execution_set(&ExecutionSetCreateInfo::new(&pipeline_info)) } - .map_err(|error| fail(format!("create the indirect execution set: {error}")))?; - // The initial pipeline is index 0; the others go at their variant's index. - let writes: Vec = (1..count) - .map(|index| WriteExecutionSetPipeline::new(index, generated.pipelines[index as usize])) - .collect(); - if !writes.is_empty() { - // SAFETY: nothing has used the set yet; every written pipeline is live. - unsafe { commands.update_execution_set(generated.execution_set, &writes) }; - } - let set_token = ExecutionSetToken { - kind: EXECUTION_SET_PIPELINES, - shader_stages: vk::ShaderStageFlags::COMPUTE, - }; - let push_token = PushConstantToken { - update_range: vk::PushConstantRange { - stage_flags: vk::ShaderStageFlags::COMPUTE, - offset: 0, - size: layout.push_bytes, - }, - }; - let tokens = [ - LayoutToken::new( - TOKEN_EXECUTION_SET, - std::ptr::from_ref(&set_token).cast(), - GeneratedLayout::INDEX_OFFSET, - ), - LayoutToken::new( - TOKEN_PUSH_CONSTANT, - std::ptr::from_ref(&push_token).cast(), - GeneratedLayout::PUSH_OFFSET, - ), - LayoutToken::new(TOKEN_DISPATCH, std::ptr::null(), layout.dispatch_offset()), - ]; - let info = LayoutCreateInfo::new(layout.stride, generated.layout.pipeline_layout, &tokens); - // SAFETY: `info`, its tokens, and their data are live for the call. - generated.commands_layout = unsafe { commands.create_commands_layout(&info) } - .map_err(|error| fail(format!("create the indirect commands layout: {error}")))?; - Ok(generated) - } - - /// Reserve each command's preprocess memory: `vkGetGeneratedCommandsMemoryRequirementsEXT` - /// for the most sequences its execution runs ([`GeneratedLayout::max_sequences`], asked once - /// per distinct count), each at its alignment in one buffer of preprocess usage. No two - /// executions share any of it. - pub(super) fn reserve_preprocess( - &mut self, - context: &VulkanContext, - layout: &GeneratedLayout, - ) -> Result<(), ExecutorError> { - let mut asked: BTreeMap = BTreeMap::new(); - let mut placed = Vec::with_capacity(layout.slots as usize); - let mut total = 0u64; - let mut alignment = 1u64; - let mut type_bits = u32::MAX; - for slot in 0..layout.slots { - let sequences = layout.max_sequences(slot); - let requirement = match asked.entry(sequences) { - Entry::Occupied(known) => *known.get(), - Entry::Vacant(new) => { - let info = MemoryRequirementsInfo::new( - self.execution_set, - self.commands_layout, - sequences, - ); - // SAFETY: the execution set and commands layout are live. - *new.insert(unsafe { self.commands.memory_requirements(&info) }) - } - }; - let align = requirement.alignment.max(1); - let at = total.next_multiple_of(align); - placed.push((at, requirement.size)); - total = at + requirement.size; - alignment = alignment.max(align); - if requirement.size != 0 { - type_bits &= requirement.memory_type_bits; - } - } - if total == 0 { - self.reserved = vec![(0, 0); placed.len()]; - return Ok(()); - } - let mut usage = vk::BufferUsageFlags2CreateInfoKHR::default() - .usage(PREPROCESS_BUFFER | vk::BufferUsageFlags2KHR::SHADER_DEVICE_ADDRESS); - let info = vk::BufferCreateInfo::default() - .size(total) - .sharing_mode(vk::SharingMode::EXCLUSIVE) - .push_next(&mut usage); - let device = self.device; - // SAFETY: `info` and its chain are live for the call. - let buffer = unsafe { device.create_buffer(&info, None) } - .map_err(|error| fail(format!("create the preprocess buffer: {error}")))?; - self.preprocess = Some((buffer, vk::DeviceMemory::null())); - // SAFETY: the buffer is live. - let requirements = unsafe { device.get_buffer_memory_requirements(buffer) }; - let memory_type = context - .memory_type( - requirements.memory_type_bits & type_bits, - vk::MemoryPropertyFlags::empty(), - ) - .map_err(fail)?; - let mut flags = - vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); - let allocation = vk::MemoryAllocateInfo::default() - .allocation_size(requirements.size) - .memory_type_index(memory_type) - .push_next(&mut flags); - // SAFETY: `allocation` and its chain are live for the call. - let memory = unsafe { device.allocate_memory(&allocation, None) } - .map_err(|error| fail(format!("allocate the preprocess memory: {error}")))?; - self.preprocess = Some((buffer, memory)); - // SAFETY: the buffer and memory are live, and the memory is of a type the buffer allows. - unsafe { device.bind_buffer_memory(buffer, memory, 0) } - .map_err(|error| fail(format!("bind the preprocess memory: {error}")))?; - let info = vk::BufferDeviceAddressInfo::default().buffer(buffer); - // SAFETY: the buffer was created with device-address usage and its memory is bound. - let address = unsafe { device.get_buffer_device_address(&info) }; - if address % alignment != 0 { - return Err(fail(format!( - "the preprocess buffer's address {address:#x} is not {alignment}-aligned" - ))); - } - self.reserved = placed - .into_iter() - .map(|(at, size)| { - if size == 0 { - (0, 0) - } else { - (address + at, size) - } - }) - .collect(); - Ok(()) - } -} - -/// `pipeline`'s compute pipeline for `region` in `module`, created with the shared `layout` and -/// `VK_PIPELINE_CREATE_2_INDIRECT_BINDABLE_BIT_EXT`, and how long its creation took. -fn bindable_pipeline( - context: &VulkanContext, - module: vk::ShaderModule, - layout: vk::PipelineLayout, - pipeline: &ComputePipeline, - region: &DispatchRegion, -) -> Result<(vk::Pipeline, Duration), ExecutorError> { - let entry = CString::new(pipeline.stage.entry_point.as_str()) - .map_err(|_| "entry point name contains NUL")?; - let map: Vec = region - .specialization - .entries - .iter() - .map(|&entry| entry.into()) - .collect(); - let spec = vk::SpecializationInfo::default() - .map_entries(&map) - .data(®ion.specialization.data); - let mut subgroup = vk::PipelineShaderStageRequiredSubgroupSizeCreateInfo::default() - .required_subgroup_size(region.required_subgroup_size.unwrap_or(0)); - let mut stage = vk::PipelineShaderStageCreateInfo::default() - .stage(vk::ShaderStageFlags::COMPUTE) - .module(module) - .name(&entry) - .flags(region.stage_flags.into()); - if !map.is_empty() { - stage = stage.specialization_info(&spec); - } - if region.required_subgroup_size.is_some() { - stage = stage.push_next(&mut subgroup); - } - let mut flags = vk::PipelineCreateFlags2CreateInfoKHR::default().flags(INDIRECT_BINDABLE); - let info = vk::ComputePipelineCreateInfo::default() - .stage(stage) - .layout(layout) - .push_next(&mut flags); - let clock = crate::budgets::CreationClock::start(); - // SAFETY: every pointer in `info` outlives the call; the caller destroys the result. - let created = unsafe { - context - .device - .create_compute_pipelines(vk::PipelineCache::null(), &[info], None) - } - .map_err(|(_, error)| { - fail(format!( - "the driver refused an indirect-bindable compute pipeline: {error}" - )) - })?; - let pipeline = created - .first() - .copied() - .ok_or_else(|| fail("the driver created no pipeline"))?; - Ok((pipeline, clock.read())) -} - -/// Record, after the preprocess and its barrier, the descriptor sets once and per command of -/// `layout` in range order: `between` (as K14c's between commands, from the second on), the -/// initial pipeline, zeroed push constants (the tokens write every byte of them), and the -/// command's `vkCmdExecuteGeneratedCommandsEXT` over its sequences in the scratch at -/// `scratch_address`, with the count the preprocess wrote and its own preprocess memory. A -/// command that starts no segment has the count 0: its execution runs nothing. The layout is made -/// for explicit preprocessing: the initial pipeline and zeroed push constants are bound first, -/// every command's execution is preprocessed -/// (`vkCmdPreprocessGeneratedCommandsEXT`) with that state, a barrier orders the preprocessing's -/// writes before the executions' preprocess and indirect reads, and each execution runs -/// preprocessed. A range whose preprocess memory was not reserved for every command records -/// nothing and fails. -/// -/// # Safety -/// `command` is recording on `device`, every object of `generated` is live until the submission -/// completes, and the scratch at `scratch_address` holds `layout`'s sections. -pub(super) unsafe fn record_executions( - device: &ash::Device, - command: vk::CommandBuffer, - generated: &Generated<'_>, - layout: &GeneratedLayout, - scratch_address: vk::DeviceAddress, - between: &vk::MemoryBarrier<'_>, -) -> Result<(), ExecutorError> { - if generated.reserved.len() != layout.slots as usize { - return Err(fail(format!( - "preprocess memory for {} of {} commands", - generated.reserved.len(), - layout.slots - ))); - } - let pipeline_layout = generated.layout.pipeline_layout; - let zeros = vec![0u8; layout.push_bytes as usize]; - // The state every preprocessing and execution takes: the execution set's initial pipeline and - // zeroed push constants (the tokens write every byte). An execution leaves the bound pipeline - // and push constants undefined. - let bind = || { - // SAFETY: the caller's contract. - unsafe { - device.cmd_bind_pipeline( - command, - vk::PipelineBindPoint::COMPUTE, - generated.pipelines[0], - ); - device.cmd_push_constants( - command, - pipeline_layout, - vk::ShaderStageFlags::COMPUTE, - 0, - &zeros, - ); - } - }; - // Each command's execution: its sequences, the count the preprocess wrote, and its own - // preprocess memory. - let execution = |slot: u32| { - let sequences = layout.max_sequences(slot); - Execution { - indirect: ( - scratch_address + layout.sequence_offset(slot, 0), - u64::from(layout.stride) * u64::from(sequences), - ), - preprocess: generated.reserved[slot as usize], - max_sequences: sequences, - count_address: scratch_address + layout.count_offset(slot), - } - }; - // SAFETY: the caller's contract; each command's preprocess memory is its own. - unsafe { - if !generated.sets.is_empty() { - device.cmd_bind_descriptor_sets( - command, - vk::PipelineBindPoint::COMPUTE, - pipeline_layout, - 0, - &generated.sets, - &[], - ); - } - bind(); - for slot in 0..layout.slots { - let execution = execution(slot); - let info = GeneratedCommandsInfo::new( - generated.execution_set, - generated.commands_layout, - &execution, - ); - generated.commands.preprocess(command, &info); - } - let preprocessed = vk::MemoryBarrier::default() - .src_access_mask(PREPROCESS_WRITE) - .dst_access_mask(vk::AccessFlags::INDIRECT_COMMAND_READ | PREPROCESS_READ); - device.cmd_pipeline_barrier( - command, - PREPROCESS_STAGE, - vk::PipelineStageFlags::DRAW_INDIRECT | PREPROCESS_STAGE, - vk::DependencyFlags::empty(), - &[preprocessed], - &[], - &[], - ); - for slot in 0..layout.slots { - if slot > 0 { - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::DependencyFlags::empty(), - std::slice::from_ref(between), - &[], - &[], - ); - } - bind(); - let execution = execution(slot); - let info = GeneratedCommandsInfo::new( - generated.execution_set, - generated.commands_layout, - &execution, - ); - generated.commands.execute_preprocessed(command, &info); - } - } - Ok(()) -} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs deleted file mode 100644 index ded3a177c..000000000 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/draw_replay.rs +++ /dev/null @@ -1,508 +0,0 @@ -//! Device replay of executed render commands in the engine executors: an execution of render -//! commands runs on the device where the runtime's GPU form draws it, by the rules both share -//! (`bind::replay`'s draw replay rules), so the executor compiles and draws what the runtime does, -//! and the records never return to the host to decide what runs. -//! -//! - **Which executions.** The rules decide from the case's facts alone, never from the records: -//! a range of commands of a buffer of draws of one primitive type alone under the encoder's -//! pipeline state, with their own buffers or the parent's where they inherit them -//! (`draw_replay_primitive_type`, `DrawReplay::inheritance`), from what the records -//! may hold: the host's setters' (`CommandBufferResource::host_writes`) and what the functions of -//! the case's own dispatch or draw may write where they write render commands -//! (`PipelineInterface::command_writes`, its `kinds`: a route reaches the buffers of its kind -//! alone, as the runtime's does; its encoder makes every command buffer resident for writing, as -//! the case runner's does); the inherited -//! state's functions (`draw_replay_state`) and attributes (`draw_replay_vertex_layouts`: the -//! variant pulls every fixed-function layout, `variants::compile_render_for_shape`), and its -//! draw instantiated in the variant's form (`draw_replay_draw`); and a device with device -//! addresses (`draw_replay_module`, `draw_replay_preprocess`). The runtime's rules of its own hold of every case the runner -//! makes: it passes no check, counts no visibility result, and its pass (the template's -//! scaffolding) reaches no tile memory and draws nothing before the execution. An execution a -//! rule keeps from the device, or whose variant, plan, draw or preprocess the product refuses, -//! runs the host replay (`replay::execute_commands`), as the runtime records it at its host step. -//! - **What runs.** The parent's render template's draw replay variant (`ChildCommand:: -//! DrawReplay`), compiled in a compile worker for the bind state of the execution's encoder (the -//! parent's vertex buffers bound, every allocation of the run resident in the vertex and fragment -//! stages, as the oracle's `useResource` makes them): merged into one draw where the commands -//! draw a list type or points and the merged form's rules hold (`draw_replay_merges`), else one -//! draw per command. One command buffer records the product's preprocess over the range (its -//! scratch holding the parameters, the resident root table of every allocation with the sink -//! filled, the extents, the parent's buffers and a merged replay's header), a merged replay's two -//! merge passes (`draw_merge_module`), then, in the template's pass, the variant's draws: per -//! command one `vkCmdDrawIndirect` of one draw at its arguments with its slot tables at the -//! variant's root-table holes, or the merged draw's two (`render::submit_replayed_draws`). -//! - **After the wait**, the status: a replay fault refuses the row for the product's typed limits -//! and fails it otherwise (`engine::replay_fault_verdict`), then the status verdict. The census -//! holds the variant once per execution. The artifact holds it as a pipeline the authored -//! compile census does not compile. - -use super::device_replay::{preprocess_objects, ReplayPath}; -use super::replay::{bound_table, require_enabled, Executed}; -use super::*; -use crate::candidate::engine::argument_buffers::used_buffer; -use crate::candidate::engine::graphics::RenderCase; -use crate::candidate::engine::{replay_fault_verdict, replay_resident}; -use crate::candidate::platform::render::{ - submit_replayed_draws, OwnedPass, ReplayedDraw, ReplayedDraws, -}; -use crate::case::indirect_commands::{authored_primitive, CommandBufferResource}; -use metal2vulkan::bind::indirect_commands::{ - BufferStage, CommandRecord, Inheritance, RegisteredBuffer, StateSource, -}; -use metal2vulkan::bind::{ - draw_merge_module, draw_replay_draw, draw_replay_merges, draw_replay_module, - draw_replay_preprocess, draw_replay_primitive_type, draw_replay_slots, draw_replay_state, - draw_replay_vertex_layouts, BindState, DrawCall, DrawCommands, DrawMergeModule, DrawReplay, - DrawReplayPreprocess, IndirectRef, MergePhase, -}; -use metal2vulkan::error::Error; -use metal2vulkan::metal::RenderStages; -use metal2vulkan::pipeline::{CommandWrites, RenderPipeline}; - -/// What one render command buffer's device replay runs over: the run's allocations `live`, the -/// guest address of each case buffer of the command buffer's owner (`addresses`, for the parent's -/// bindings), the record storage's device address (`storage`, none without device addresses), and -/// what the functions of the case's own dispatch or draw may write into the records of a buffer of -/// their kinds (`writes`). -pub(super) struct Drawing<'a, K> { - pub(super) live: &'a [Live], - pub(super) addresses: &'a dyn Fn(K, u32) -> Option, - pub(super) storage: Option, - pub(super) writes: CommandWrites, -} - -/// Replay the execution of render command buffer `key` on the device where the shared rules take -/// it (the module docs), compiling its variant with `compile`; `None` where they send it to the -/// host replay. The census of the variant that drew, and which form ran. -pub(super) fn draw_commands( - context: &VulkanContext, - device: &Device, - (key, command): (K, &CommandBufferResource), - drawing: Drawing<'_, K>, - compile: &mut CompileChild<'_>, -) -> Result, ExecutorError> { - let Drawing { - live, - addresses, - storage, - writes, - } = drawing; - let fail = |why: String| ExecutorError::Failed(format!("command buffer {key:?}: {why}")); - // The call's rules and the buffer's, from what the records may hold. - let [start, end] = command.execution_range; - let count = end - .checked_sub(start) - .ok_or_else(|| fail("a reversed execution range".into()))?; - let Some(execution) = command.execute.as_ref().filter(|_| count > 0) else { - return Ok(None); - }; - // The case's functions reach these records where they write render commands: a kernel that - // encodes dispatches writes no draw. - let writes = match writes.writes_kinds(CommandWrites::RENDER_COMMANDS) { - true => writes, - false => CommandWrites::NONE, - }; - let written = command.host_writes().map_err(fail)?.union(writes); - let types = command.descriptor.command_types(); - let inherits = command.inherit_pipeline_state; - let Ok(primitive_type) = draw_replay_primitive_type(types, inherits, written) else { - return Ok(None); - }; - let primitive = authored_primitive(primitive_type.as_raw()).ok_or_else(|| { - fail(format!( - "primitive type {primitive_type:?} is no Metal primitive" - )) - })?; - let token = (execution.pipeline.as_ref()) - .ok_or_else(|| fail("the commands inherit a pipeline the parent does not set".into()))? - .token; - // The device sets the draw replay up where it has device addresses. - let module = match draw_replay_module(device) { - Ok(module) => module, - Err(Error::Unsupported(_)) => return Ok(None), - Err(error) => return Err(product_refusal(&error)), - }; - let addressed = context - .enabled - .features - .contains(&VkFeature::BufferDeviceAddress); - let storage = match (addressed, storage) { - (true, Some(storage)) => storage, - _ => { - return Err(fail( - "the draw replay needs device addresses the context did not enable".into(), - )) - } - }; - let parent = command - .parent_bindings(|buffer| addresses(key, buffer)) - .map_err(ExecutorError::Failed)? - .ok_or_else(|| fail("an execution without its parent's state".into()))?; - - // The execution's encoder's bind state: its vertex buffers (the parent's), and every - // allocation of the run resident in the vertex and fragment stages, as the oracle's - // `useResource` makes it. No render template has a fragment stage. - let registered = live - .iter() - .map(|allocation| { - RegisteredBuffer::new(allocation, allocation.address.guest, allocation.length) - }) - .collect::, _>>() - .map_err(|error| ExecutorError::Failed(error.to_string()))?; - let encoder = Inheritance { - pipeline: StateSource::Parent, - buffers: StateSource::Parent, - }; - let empty = CommandRecord::default(); - let resolved = empty - .resolve_bindings(encoder, &parent) - .map_err(|error| fail(error.to_string()))?; - let (table, guest) = - bound_table(&resolved, Stage::Vertex, BufferStage::Vertex, ®istered).map_err(fail)?; - let mut state = BindState::default(); - state.stages.insert(Stage::Vertex, table.clone()); - for (token, allocation) in live.iter().enumerate() { - state.used_resources.push( - used_buffer( - token, - allocation.length as usize, - allocation.address, - RenderStages::VERTEX | RenderStages::FRAGMENT, - ) - .map_err(ExecutorError::Failed)?, - ); - } - // The preprocess's resident set: every allocation of the run, as the host step resolves a - // command's buffers in it; and the encoder's vertex buffers, which commands that inherit them - // bind (`draw_replay_preprocess`'s state). - let mut resident = replay_resident( - live.iter() - .map(|allocation| (allocation.address, allocation.length)), - ) - .map_err(ExecutorError::Failed)?; - resident.stages.insert(Stage::Vertex, table); - let mut replay = DrawReplay::new( - command.capacity, - start, - count, - vec![primitive_type.as_raw()], - ); - replay.inheritance = command.inheritance(); - - // One draw per command's variant first: its functions' facts are the state's, which decide - // whether the merged form may run at all, as the runtime's state decides it before it compiles - // the merged variant. Merged where the commands draw a list type or points and its rules hold. - let at = (context, device, &state, &resident); - let Some(per_command) = compiled(token, &state, false, compile)? else { - return Ok(None); - }; - let merges = draw_replay_merges(primitive_type) - && draw_replay_state(&per_command.1.graphics, true).is_ok(); - let merged = match merges { - true => match compiled(token, &state, true, compile)? { - Some(merged) => drawn(at, merged, &replay, true)?, - None => None, - }, - false => None, - }; - let variant = match merged { - Some(merged) => merged, - None => match drawn(at, per_command, &replay, false)? { - Some(variant) => variant, - None => return Ok(None), - }, - }; - - // The replay's objects: the sink the resident root table names, the scratch, the status, and - // the owned kernels' pipelines. - let Variant { - merged, - case, - pipeline, - plan, - commands, - pre, - } = variant; - let layout = pre.layout; - require_enabled(context, &module.requirements)?; - let sink = allocate( - context, - "draw replay sink", - &[0; NeutralResource::SINK_BYTES as usize], - addressed, - vk::BufferUsageFlags::empty(), - )?; - let sink_address = sink.address.ok_or("the sink has no device address")?; - let scratch = allocate( - context, - "draw replay scratch", - &scratch_bytes(&pre, sink_address)?, - addressed, - vk::BufferUsageFlags::INDIRECT_BUFFER, - )?; - let scratch_address = match scratch.address { - // Every slot table and the resident root table are root tables: 16-aligned. - Some(address) if address % 16 == 0 => address, - other => { - return Err(fail(format!( - "the scratch's address {other:?} is not 16-aligned" - ))) - } - }; - let status = allocate( - context, - "draw replay status", - &ExecutionStatus::initial(), - addressed, - vk::BufferUsageFlags::empty(), - )?; - let status_address = status.address.ok_or("the status has no device address")?; - let mut push = pre.push_constants.clone(); - for hole in &pre.push_holes { - let (offset, address) = match *hole { - PushHole::RootTableAddress { offset, .. } => { - (offset, scratch_address + layout.resident_offset) - } - PushHole::ExecutionStatusAddress { offset, .. } => (offset, status_address), - PushHole::CommandRecordsAddress { offset, .. } => (offset, storage), - other => return Err(fail(format!("the preprocess's push hole {other:?}"))), - }; - push.get_mut(offset as usize..offset as usize + 8) - .ok_or_else(|| fail(format!("the preprocess push bytes end before {offset}")))? - .copy_from_slice(&address.to_le_bytes()); - } - let mut kernels = vec![preprocess_objects( - context, - (&module.spirv, &module.layout), - "draw replay preprocess", - )?]; - let mut pushes = vec![(push, pre.group_count)]; - if let Some(sections) = layout.merged { - for phase in [MergePhase::Blocks, MergePhase::Starts] { - let module = draw_merge_module(device, phase).map_err(|e| product_refusal(&e))?; - require_enabled(context, &module.requirements)?; - kernels.push(preprocess_objects( - context, - (&module.spirv, &module.layout), - "draw merge pass", - )?); - let header = scratch_address + sections.header_offset; - pushes.push(( - DrawMergeModule::push_constants(header, status_address), - sections.group_count(), - )); - } - } - let passes: Vec = kernels - .iter() - .zip(pushes) - .map(|(kernel, (push, group_count))| OwnedPass { - pipeline: kernel.pipelines[0], - layout: kernel.layout.pipeline_layout, - push, - group_count, - }) - .collect(); - - // The draws: per command its arguments, after the push writes of its slot tables at the - // variant's root-table holes (the first command's the draw's own push writes carry); or the - // merged draw's two, its header at the variant's merged-draw hole. - let table = |hole: &PushHole, command: u32| match *hole { - PushHole::RootTableAddress { stages, .. } => { - let stages = vk::ShaderStageFlags::from(stages); - let offset = if stages == vk::ShaderStageFlags::VERTEX { - layout.vertex_table_offset(command) - } else if stages == vk::ShaderStageFlags::FRAGMENT { - layout.fragment_table_offset(command) - } else { - return None; - }; - Some(scratch_address + offset) - } - PushHole::MergedDrawAddress { .. } => { - (layout.merged).map(|sections| scratch_address + sections.header_offset) - } - _ => None, - }; - let draws: Vec = match layout.merged { - Some(sections) => (0..2) - .map(|index| ReplayedDraw { - push: Vec::new(), - arguments: sections.draw_offset(index), - }) - .collect(), - None => (0..layout.commands) - .map(|command| ReplayedDraw { - push: match command { - 0 => Vec::new(), - _ => (commands.push_holes.iter()) - .filter_map(|hole| match *hole { - PushHole::RootTableAddress { stages, offset } => { - let address = table(hole, command)?; - Some((stages.into(), offset, address.to_le_bytes().to_vec())) - } - _ => None, - }) - .collect(), - }, - arguments: layout.argument_offset(command, 0), - }) - .collect(), - }; - submit_replayed_draws( - context, - device, - (&case, primitive), - (&pipeline, &plan, &commands), - (&state, &guest), - (&status, &|hole: &PushHole| table(hole, 0)), - &ReplayedDraws { - passes: &passes, - scratch: scratch.buffer.buffer, - draws: &draws, - }, - ) - .map_err(|error| match error { - ExecutorError::Failed(why) => fail(why), - refused => refused, - })?; - // SAFETY: the submission completed (the fence signaled), and nothing else maps it. - let status_bytes: [u8; ExecutionStatus::BYTES] = unsafe { status.buffer.map()? }.bytes - [..ExecutionStatus::BYTES] - .try_into() - .map_err(|_| "the status buffer is shorter than ExecutionStatus")?; - let report = ExecutionStatus::decode(&status_bytes); - if report.replay_fault { - return Err(replay_fault_verdict( - &format!("command buffer {key:?}"), - report.replay_faults, - )); - } - status_verdict(&status_bytes).map_err(|error| match error { - ExecutorError::Failed(why) => fail(why), - refused => refused, - })?; - drop(kernels); - let census = module_censuses(&pipeline.stages, device.profile(), None)?; - let path = match merged { - true => ReplayPath::MergedDraws, - false => ReplayPath::Draws, - }; - Ok(Some((census, path))) -} - -/// The draw replay variant of the template of `token`, `merged` into one draw or not, compiled in -/// a compile worker for the shape of `state`: its template's case and pipeline; `None` where the -/// product refuses it, as the runtime's GPU form takes its host step where its state does not -/// settle the variant. -fn compiled( - token: u64, - state: &BindState, - merged: bool, - compile: &mut CompileChild<'_>, -) -> Result, ExecutorError> { - match compile(token, &state.shape(), &ChildCommand::DrawReplay { merged }) { - Ok(CompiledChild::Render(case, pipeline)) => Ok(Some((*case, *pipeline))), - Ok(CompiledChild::Compute(_)) => Err(ExecutorError::Failed(format!( - "an executed command's pipeline token {token} names a compute template for render \ - commands" - ))), - Err(ExecutorError::NotSupported(_)) => Ok(None), - Err(error) => Err(error), - } -} - -/// One form's variant ready to draw: its template's case and pipeline, the plan and the one -/// indirect draw instantiated for the encoder's bind state, and the replay's preprocess. -struct Variant { - merged: bool, - case: RenderCase, - pipeline: RenderPipeline, - plan: BindingPlan, - commands: DrawCommands, - pre: DrawReplayPreprocess, -} - -/// The `compiled` variant in its form (`merged` or one draw per command) where the shared rules -/// hold of it: the inherited state's (`draw_replay_state`), its plan for `state` (no diagnostic) -/// and its one indirect draw instantiated for it (`draw_replay_draw`), and the product's -/// preprocess of `replay` over `resident` with the slots its functions read; `None` where a rule -/// breaks or the product refuses the plan, the draw or the preprocess, as the runtime's GPU form -/// takes its host step. -fn drawn( - (context, device, state, resident): (&VulkanContext, &Device, &BindState, &BindState), - (case, pipeline): (RenderCase, RenderPipeline), - replay: &DrawReplay, - merged: bool, -) -> Result, ExecutorError> { - // Its attributes: none whose layout's stride is set per bind (the variant pulls the rest). - if draw_replay_state(&pipeline.graphics, merged).is_err() - || draw_replay_vertex_layouts(&pipeline.vertex_input).is_err() - { - return Ok(None); - } - require_enabled(context, &pipeline.requirements)?; - let Ok(plan) = pipeline.plan(device, &state.shape()) else { - return Ok(None); - }; - if let Some(diagnostic) = plan.diagnostics.first() { - return Err(incompatible_binding(diagnostic)); - } - let draw = DrawCall::Indirect { - indirect: IndirectRef::new(0, 0), - indexed: None, - }; - let Ok(commands) = plan.instantiate_draw(state, &draw) else { - return Ok(None); - }; - if draw_replay_draw(&commands, (&plan, &plan.variant), merged).is_err() { - return Ok(None); - } - let mut replay = replay.clone(); - (replay.vertex_slots, replay.fragment_slots) = draw_replay_slots(&pipeline.interface); - replay.merged = merged; - let Ok(pre) = draw_replay_preprocess(device, resident, &replay) else { - return Ok(None); - }; - Ok(Some(Variant { - merged, - case, - pipeline, - plan, - commands, - pre, - })) -} - -/// The scratch's initial bytes: the parameters, the resident root table with its sink entry's -/// `host` field at `sink`, the resident roots' extents, the parent's buffers, and a merged -/// replay's header, each at its layout offset; the slot tables and arguments (and a merged -/// replay's sections past its header) are the preprocess's and the passes' to write. -fn scratch_bytes(pre: &DrawReplayPreprocess, sink: u64) -> Result, String> { - let layout = pre.layout; - let len = usize::try_from(layout.bytes).map_err(|_| "the scratch exceeds the address space")?; - let mut bytes = vec![0u8; len]; - let mut resident = pre.resident.bytes.clone(); - let at = RootTable::SINK_HOST_OFFSET as usize; - resident - .get_mut(at..at + 8) - .ok_or("the resident root table has no sink entry")? - .copy_from_slice(&sink.to_le_bytes()); - let header = (layout.merged).map(|sections| (sections.header_offset, &pre.header)); - for (offset, part) in [ - (layout.params_offset(), &pre.params), - (layout.resident_offset, &resident), - (layout.extents_offset, &pre.extents), - (layout.parent_offset, &pre.parent), - ] - .into_iter() - .chain(header) - { - let offset = offset as usize; - bytes - .get_mut(offset..offset + part.len()) - .ok_or("a scratch section runs past the scratch")? - .copy_from_slice(part); - } - Ok(bytes) -} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs deleted file mode 100644 index 18555f66a..000000000 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute/replay.rs +++ /dev/null @@ -1,418 +0,0 @@ -//! Host replay of executed indirect commands in the engine executors. -//! -//! After the producer's dispatch or draw completed and its records decoded under the host -//! contract, each command buffer the case executes runs its execution range in order, one command -//! at a time: the command's state (or the parent encoder's, where the descriptor inherits it) -//! selects a compiled template by its pipeline token, and binds each buffer address to the -//! allocation of the run that holds it at its interior offset (`BufferBinding::resolve_buffer`). -//! A dispatch binds the command's kernel buffers and threadgroup lengths, and its template is -//! compiled for that bind shape and the command's dispatch; a draw binds the command's vertex -//! buffers, and its template (a rasterization-disabled vertex function, which the checker -//! requires of every render template an executed command may select) is compiled for that bind -//! shape, drawn with the command's primitive, counts, and base instance in a pass of its own -//! (`render::submit_draw_child`). Each child is compiled in a compile worker, planned, and -//! submitted over the run's own allocations, each waited for before the next (an ordering -//! Metal's barriers, and its render encoder's draw order, allow). A record whose pipeline has no -//! template, whose address no allocation holds, whose primitive type Metal does not define or is -//! outside its template's topology class, whose dynamic attribute stride, stage-in region, or -//! imageblock size no template reads, or whose bind the plan refuses or asks another variant for -//! fails the run: nothing is guessed. A draw's fragment buffers pass the record decode's index -//! policy (`CommandBuffer::decode`) and are neither resolved nor bound: no render template has a -//! fragment stage. - -use super::*; -use crate::candidate::engine::argument_buffers::used_buffer; -use crate::candidate::engine::{ChildCommand, CompiledChild}; -use crate::case::indirect_commands::{authored_primitive, CommandBufferResource}; -use metal2vulkan::bind::indirect_commands::{ - Action, BufferBinding, BufferStage, RegisteredBuffer, ResolvedBindings, -}; -use metal2vulkan::bind::{BindState, BoundBuffer, Dispatch, DrawCall, StageTable}; -use metal2vulkan::metal::RenderStages; - -/// One allocation of the run a replayed command may bind or reach through a pointer. -pub(in crate::candidate::platform) struct Live { - pub(in crate::candidate::platform) buffer: vk::Buffer, - pub(in crate::candidate::platform) address: BufferAddress, - pub(in crate::candidate::platform) length: u64, -} - -/// Compile the template of a pipeline token for a bind shape and a command, in a compile worker. -pub(in crate::candidate) type CompileChild<'a> = - dyn FnMut(u64, &BindShape, &ChildCommand) -> Result + 'a; - -/// What a replay executed: each child's module census, for the run's census. -pub(in crate::candidate::platform) type Executed = Vec; - -/// What a replay runs over: the run's allocations `live` (every case buffer and argument-buffer -/// buffer), the final records `records` (by command-buffer key), the guest -/// address of each case buffer of a command buffer's owner (`addresses`, by its key and the -/// buffer's Metal index, for the parent's bindings), and the compile of each child. -pub(in crate::candidate::platform) struct Replay<'a, 'b, K> { - pub(in crate::candidate::platform) live: &'a [Live], - pub(in crate::candidate::platform) records: &'a BTreeMap>, - pub(in crate::candidate::platform) addresses: &'a dyn Fn(K, u32) -> Option, - pub(in crate::candidate::platform) compile: &'a mut CompileChild<'b>, -} - -/// Execute each of `command_buffers` (by key, in key order: the order the case's identity sorts -/// them in, and the oracle's, `case::indirect_commands::executed_in_key_order`) that the case -/// executes, as `replay` states, on the context's device. -pub(in crate::candidate::platform) fn execute_commands<'c, K: Ord + Copy + std::fmt::Debug>( - context: &VulkanContext, - device: &Device, - command_buffers: impl IntoIterator, - replay: Replay<'_, '_, K>, -) -> Result { - let Replay { - live, - records, - addresses, - compile, - } = replay; - let mut executed = Vec::new(); - let executing = command_buffers - .into_iter() - .filter(|(_, command)| command.execute.is_some()) - .collect::>(); - if executing.is_empty() { - return Ok(executed); - } - let registered = live - .iter() - .map(|allocation| { - RegisteredBuffer::new(allocation, allocation.address.guest, allocation.length) - }) - .collect::, _>>() - .map_err(|error| ExecutorError::Failed(error.to_string()))?; - for (key, command) in executing { - let parent = match command - .parent_bindings(|buffer| addresses(key, buffer)) - .map_err(ExecutorError::Failed)? - { - Some(parent) => parent, - None => continue, - }; - let bytes = records - .get(&key) - .ok_or_else(|| format!("command buffer {key:?} has no final records"))?; - let decoded = command - .validated_records(bytes) - .map_err(ExecutorError::Failed)?; - let start = command.execution_range[0]; - for (offset, record) in decoded.enumerate() { - let index = start + offset as u32; - let what = format!("command {index} of command buffer {key:?}"); - let fail = |why: String| ExecutorError::Failed(format!("{what}: {why}")); - let resolved = record - .resolve_bindings(command.inheritance(), &parent) - .map_err(|error| fail(error.to_string()))?; - if record.stage_in_region != [0; 6] || record.imageblock_size != [0; 2] { - return Err(fail( - "a stage-in region or an imageblock size, which no replayed template reads" - .into(), - )); - } - let child = match record.action { - Action::Empty => continue, - Action::DispatchThreadgroups { grid, local_size } => { - ChildCommand::Dispatch(Dispatch::Threadgroups { - groups: grid, - threads_per_group: local_size, - }) - } - Action::DispatchThreads { grid, local_size } => { - ChildCommand::Dispatch(Dispatch::Threads { - threads: grid, - threads_per_group: local_size, - }) - } - Action::DrawPrimitives { - primitive_type, - vertex_start, - vertex_count, - instance_count, - base_instance, - } => ChildCommand::Draw { - draw: DrawCall::Primitives { - vertex_start, - vertex_count, - instance_count, - base_instance, - }, - primitive: authored_primitive(primitive_type).ok_or_else(|| { - fail(format!( - "primitive type {primitive_type} is no Metal primitive" - )) - })?, - }, - // The executor's context draws no index or patch buffer a record names, and no - // mesh draw. - Action::DrawIndexedPrimitives { .. } - | Action::DrawPatches { .. } - | Action::DrawIndexedPatches { .. } - | Action::DrawMeshThreadgroups { .. } - | Action::DrawMeshThreads { .. } => return Err(fail( - "an indexed, patch or mesh draw, which the executor's context does not replay" - .into(), - )), - }; - let token = resolved - .pipeline - .ok_or_else(|| fail("no pipeline".into()))? - .get(); - // A dispatch binds the command's kernel buffers and threadgroup lengths, a draw its - // vertex buffers (its template has no fragment stage). - let (stage, buffers, stages) = match child { - ChildCommand::Dispatch(_) => { - (Stage::Kernel, BufferStage::Kernel, RenderStages::empty()) - } - ChildCommand::Draw { .. } => ( - Stage::Vertex, - BufferStage::Vertex, - RenderStages::VERTEX | RenderStages::FRAGMENT, - ), - // A record's action is a dispatch or a draw, never a device replay's variant. - ChildCommand::ReplayVariant { .. } | ChildCommand::DrawReplay { .. } => { - return Err(fail( - "a host-replayed command runs no replay variant".into(), - )) - } - }; - let (table, guest) = - bound_table(&resolved, stage, buffers, ®istered).map_err(fail)?; - let mut state = BindState::default(); - state.stages.insert(stage, table); - // Every allocation of the run is resident, as the oracle's `useResource` makes it. - for (token, allocation) in live.iter().enumerate() { - state.used_resources.push( - used_buffer( - token, - allocation.length as usize, - allocation.address, - stages, - ) - .map_err(ExecutorError::Failed)?, - ); - } - let shape = state.shape(); - let stages = match (compile(token, &shape, &child)?, child) { - (CompiledChild::Compute(pipeline), ChildCommand::Dispatch(dispatch)) => { - require_enabled(context, &pipeline.requirements)?; - submit_child(context, device, &pipeline, &state, &dispatch, &guest) - .map_err(|error| refine(error, &fail))?; - vec![pipeline.stage.clone()] - } - (CompiledChild::Render(case, pipeline), ChildCommand::Draw { primitive, .. }) => { - require_enabled(context, &pipeline.requirements)?; - super::super::render::submit_draw_child( - context, device, &case, &pipeline, &state, primitive, &guest, - ) - .map_err(|error| refine(error, &fail))?; - pipeline.stages.clone() - } - _ => { - return Err(fail(format!( - "pipeline token {token} names a template of the other command family" - ))) - } - }; - executed.extend(super::module_censuses(&stages, device.profile(), None)?); - } - } - Ok(executed) -} - -/// A failed child's error, named for its command. -fn refine(error: ExecutorError, fail: &impl Fn(String) -> ExecutorError) -> ExecutorError { - match error { - ExecutorError::Failed(why) => fail(why), - other => other, - } -} - -/// Refuse a child whose requirements the context did not enable. -pub(super) fn require_enabled( - context: &VulkanContext, - requirements: &metal2vulkan::device::Requirements, -) -> Result<(), ExecutorError> { - let missing = unmet_requirements(context, requirements); - if missing.is_empty() { - Ok(()) - } else { - Err(NotSupported::NotEnabled(missing).into()) - } -} - -/// The bind table of `stage` from the command's resolved `buffers` bindings, each at the -/// allocation of `registered` that holds its address (at least one byte of it), and the -/// allocation each slot binds; for a dispatch, the command's nonzero threadgroup lengths too. A -/// dynamic attribute stride, which no replayed template reads (no template has stage inputs or -/// vertex inputs), or an address no allocation holds, is the command's failure. -pub(super) fn bound_table( - resolved: &ResolvedBindings<'_>, - stage: Stage, - buffers: BufferStage, - registered: &[RegisteredBuffer<'_, Live>], -) -> Result<(StageTable, BTreeMap), String> { - let mut table = StageTable::default(); - let mut guest = BTreeMap::new(); - for (slot, binding) in resolved.buffers(buffers).iter().enumerate() { - // A slot no setter set binds nothing; a nil buffer's (its offset below 2^32) binds - // nothing and reads no stride. - let Some(binding) = binding.filter(BufferBinding::names_buffer) else { - continue; - }; - if binding.attribute_stride.is_some() { - return Err(format!( - "buffer {slot} has a dynamic attribute stride, which no replayed template reads" - )); - } - let Some(found) = binding - .resolve_buffer(registered, 1) - .map_err(|error| format!("buffer {slot}: {error}"))? - else { - continue; - }; - let slot = slot as u32; - table.buffers.insert( - slot, - BoundBuffer::Buffer { - length: found.resource.length, - offset: found.offset, - gpu_address: found.resource.address.guest, - device_address: found.resource.address.host, - attribute_stride: None, - }, - ); - guest.insert( - SlotRef { - stage, - class: SlotClass::Buffer, - index: slot, - }, - found.resource.buffer, - ); - } - if stage == Stage::Kernel { - for (slot, &length) in resolved.threadgroup_memory_lengths.iter().enumerate() { - if length != 0 { - table.threadgroup_lengths.insert(slot as u32, length); - } - } - } - Ok((table, guest)) -} - -/// Plan `pipeline` for `state` (the plan must name no other variant and no neutral), create what -/// the plan names over the run's allocations `guest` (by slot), record and submit `dispatch`, -/// wait, and require a clean status. -fn submit_child( - context: &VulkanContext, - device: &Device, - pipeline: &ComputePipeline, - state: &BindState, - dispatch: &Dispatch, - guest: &BTreeMap, -) -> Result<(), ExecutorError> { - let addressed = context - .enabled - .features - .contains(&VkFeature::BufferDeviceAddress); - let shape = state.shape(); - let plan = pipeline - .plan(device, &shape) - .map_err(|e| bind_refusal(&e))?; - if let Some(diagnostic) = plan.diagnostics.first() { - return Err(incompatible_binding(diagnostic)); - } - let commands = plan - .instantiate_dispatch(state, dispatch) - .map_err(|e| bind_refusal(&e))?; - if commands.regions.iter().any(|r| r.indirect.is_some()) { - return Err(not_implemented("indirect dispatches")); - } - let status = allocate( - context, - "replayed command status", - &ExecutionStatus::initial(), - addressed, - vk::BufferUsageFlags::empty(), - )?; - let constant_blobs: BTreeMap> = pipeline - .stage - .constant_blob - .iter() - .map(|blob| (Stage::Kernel, blob.clone())) - .collect(); - let mut resources = PlanResources::create( - context, - device, - &plan.descriptors, - &Guest { - buffers: guest, - textures: &BTreeMap::new(), - status: Some(status.buffer.buffer), - used_textures: &BTreeMap::new(), - samplers: &BTreeMap::new(), - argument_samplers: &state.argument_samplers, - constant_blobs: &constant_blobs, - descriptor_ranges: &commands.descriptor_ranges, - descriptor_bytes: &commands.descriptor_bytes, - tessellation_factors: None, - attachments: &BTreeMap::new(), - }, - None, - )?; - let root = commands - .root_table - .as_ref() - .map(|table| upload_root_table(context, table, addressed)) - .transpose()?; - let regions = push_bytes(&commands, root.as_ref().map(|(table, _)| table), &status)?; - let layout = match LayoutObjects::create(&context.device, &pipeline.layout) { - Ok(layout) => layout, - Err(LayoutError::Shape(why) | LayoutError::Refused(why)) => { - return Err(ExecutorError::Failed(why)) - } - }; - let mut objects = Objects { - device: &context.device, - module: vk::ShaderModule::null(), - pipelines: Vec::new(), - command_pool: vk::CommandPool::null(), - fence: vk::Fence::null(), - layout, - }; - let module_info = vk::ShaderModuleCreateInfo::default().code(&pipeline.stage.spirv); - // SAFETY: `module_info` points at live SPIR-V words for the call. - objects.module = unsafe { context.device.create_shader_module(&module_info, None) } - .map_err(|error| format!("create shader module: {error}"))?; - // An executed command's template: the shared ceiling (`ComputeCase::creation_bound`). - let region_pipelines = create_pipelines( - context, - &mut objects, - pipeline, - &commands.regions, - crate::budgets::PIPELINE_CREATION_CEILING, - )?; - let sets = resources.write_sets(context, &objects.layout)?; - record_and_submit( - context, - &mut objects, - &resources, - &sets, - &commands.regions, - ®ions, - ®ion_pipelines, - )?; - // SAFETY: the submission completed (the fence signaled), and nothing else maps it. - let status_bytes: [u8; ExecutionStatus::BYTES] = unsafe { status.buffer.map()? }.bytes - [..ExecutionStatus::BYTES] - .try_into() - .expect("the status buffer holds ExecutionStatus::BYTES bytes"); - status_verdict(&status_bytes)?; - drop(objects); - drop(resources); - Ok(()) -} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/device.rs b/crates/metal2vulkan-validation/src/candidate/platform/device.rs index 522f9b012..66e24c787 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/device.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/device.rs @@ -379,9 +379,6 @@ pub(super) struct VulkanContext { /// The robustness features the context could not enable /// (`enables::Enables::unmet_robustness`): every run on the context is refused naming them. pub(super) unmet_robustness: BTreeSet, - /// Whether the context enabled `VK_EXT_device_generated_commands` with its - /// `deviceGeneratedCommands` ([`enables::enable_generated_commands`]). - pub(super) generated_commands: bool, /// What the runtime probe's context enabled beyond the engine's list /// ([`with_runtime_probe_context`]); `None` on every other context. pub(super) runtime_probe: Option, @@ -1832,7 +1829,6 @@ impl VulkanContext { restriction, hidden, unmet_robustness: enables.unmet_robustness, - generated_commands, runtime_probe, messenger, messages, @@ -1857,31 +1853,6 @@ impl VulkanContext { } } - /// `VK_EXT_device_generated_commands`'s commands, loaded through the loader's - /// `vkGetDeviceProcAddr`, which reads the device's loader word ([`LoaderWord`]): the word is - /// put back first. `None` where the context did not enable the extension (or a command does not - /// load). - #[expect( - clippy::disallowed_methods, - reason = "the one call site, after the loader word is put back" - )] - pub(super) fn generated_commands(&self) -> Option { - if !self.generated_commands { - return None; - } - let handle = self.device.handle(); - let load = |name: &CStr| { - // SAFETY: the device is live, its context is used by its own thread only, and the - // word is put back before each load. - unsafe { - self.loader_word.restore(); - self.instance.get_device_proc_addr(handle, name.as_ptr()) - } - }; - // SAFETY: each name is the extension's command of this device, which enabled it. - unsafe { super::generated_commands::Commands::load(handle, load) } - } - /// `vkGetMemoryHostPointerPropertiesEXT` (`VK_EXT_external_memory_host`), loaded through the /// loader's `vkGetDeviceProcAddr`, which reads the device's loader word ([`LoaderWord`]): the /// word is put back first. `None` where the context did not enable the extension (only the diff --git a/crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs b/crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs deleted file mode 100644 index 1ec493a22..000000000 --- a/crates/metal2vulkan-validation/src/candidate/platform/generated_commands.rs +++ /dev/null @@ -1,440 +0,0 @@ -//! `VK_EXT_device_generated_commands`, which `ash 0.38` (Vulkan 1.3.281) predates: the structures -//! and commands the device replay's generated-commands path uses (`compute::device_replay`), laid -//! out as the registry defines them (`vk.xml`, extension number 573: structure types -//! `1000572000 + n`). -//! -//! The executor's context loads the commands only where it enabled the extension -//! ([`Commands::load`]). Every commands layout is made for explicit preprocessing: each execution -//! is preprocessed apart ([`Commands::preprocess`]) and runs preprocessed -//! ([`Commands::execute_preprocessed`]), a form that runs right on every driver. - -use ash::vk; -use std::ffi::{c_void, CStr}; - -/// `VkIndirectExecutionSetEXT` and `VkIndirectCommandsLayoutEXT`: non-dispatchable handles. -pub(crate) type Handle = u64; - -const fn structure(n: i32) -> vk::StructureType { - vk::StructureType::from_raw(1_000_572_000 + n) -} - -/// `VK_INDIRECT_EXECUTION_SET_INFO_TYPE_PIPELINES_EXT`. -pub(crate) const EXECUTION_SET_PIPELINES: i32 = 0; -/// `VK_INDIRECT_COMMANDS_TOKEN_TYPE_EXECUTION_SET_EXT`, `..._PUSH_CONSTANT_EXT`, -/// `..._DISPATCH_EXT`. -pub(crate) const TOKEN_EXECUTION_SET: i32 = 0; -pub(crate) const TOKEN_PUSH_CONSTANT: i32 = 1; -pub(crate) const TOKEN_DISPATCH: i32 = 9; -/// `VK_PIPELINE_CREATE_2_INDIRECT_BINDABLE_BIT_EXT`. -pub(crate) const INDIRECT_BINDABLE: vk::PipelineCreateFlags2KHR = - vk::PipelineCreateFlags2KHR::from_raw(0x40_0000_0000); -/// `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT`. -pub(crate) const PREPROCESS_BUFFER: vk::BufferUsageFlags2KHR = - vk::BufferUsageFlags2KHR::from_raw(0x8000_0000); -/// `VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_EXT`: an execution of the layout -/// is preprocessed apart (`vkCmdPreprocessGeneratedCommandsEXT`) before it runs. -const LAYOUT_EXPLICIT_PREPROCESS: u32 = 0x1; -/// `VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_EXT`, `VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_EXT` and -/// `VK_ACCESS_COMMAND_PREPROCESS_WRITE_BIT_EXT` (the values of the `NV` names `ash` has). -pub(crate) const PREPROCESS_STAGE: vk::PipelineStageFlags = - vk::PipelineStageFlags::COMMAND_PREPROCESS_NV; -pub(crate) const PREPROCESS_READ: vk::AccessFlags = vk::AccessFlags::COMMAND_PREPROCESS_READ_NV; -pub(crate) const PREPROCESS_WRITE: vk::AccessFlags = vk::AccessFlags::COMMAND_PREPROCESS_WRITE_NV; - -/// `VkIndirectExecutionSetPipelineInfoEXT`. -#[repr(C)] -pub(crate) struct ExecutionSetPipelineInfo { - s_type: vk::StructureType, - p_next: *const c_void, - initial_pipeline: vk::Pipeline, - max_pipeline_count: u32, -} - -impl ExecutionSetPipelineInfo { - pub(crate) fn new(initial_pipeline: vk::Pipeline, max_pipeline_count: u32) -> Self { - ExecutionSetPipelineInfo { - s_type: structure(10), - p_next: std::ptr::null(), - initial_pipeline, - max_pipeline_count, - } - } -} - -/// `VkIndirectExecutionSetCreateInfoEXT` of the pipelines type (its `info` union holds -/// `pPipelineInfo`). -#[repr(C)] -pub(crate) struct ExecutionSetCreateInfo { - s_type: vk::StructureType, - p_next: *const c_void, - kind: i32, - pipeline_info: *const ExecutionSetPipelineInfo, -} - -impl ExecutionSetCreateInfo { - pub(crate) fn new(pipeline_info: &ExecutionSetPipelineInfo) -> Self { - ExecutionSetCreateInfo { - s_type: structure(3), - p_next: std::ptr::null(), - kind: EXECUTION_SET_PIPELINES, - pipeline_info, - } - } -} - -/// `VkWriteIndirectExecutionSetPipelineEXT`. -#[repr(C)] -pub(crate) struct WriteExecutionSetPipeline { - s_type: vk::StructureType, - p_next: *const c_void, - index: u32, - pipeline: vk::Pipeline, -} - -impl WriteExecutionSetPipeline { - pub(crate) fn new(index: u32, pipeline: vk::Pipeline) -> Self { - WriteExecutionSetPipeline { - s_type: structure(8), - p_next: std::ptr::null(), - index, - pipeline, - } - } -} - -/// `VkIndirectCommandsPushConstantTokenEXT`. -#[repr(C)] -pub(crate) struct PushConstantToken { - pub(crate) update_range: vk::PushConstantRange, -} - -/// `VkIndirectCommandsExecutionSetTokenEXT`. -#[repr(C)] -pub(crate) struct ExecutionSetToken { - pub(crate) kind: i32, - pub(crate) shader_stages: vk::ShaderStageFlags, -} - -/// `VkIndirectCommandsLayoutTokenEXT` (its `data` union is one pointer). -#[repr(C)] -pub(crate) struct LayoutToken { - s_type: vk::StructureType, - p_next: *const c_void, - kind: i32, - data: *const c_void, - offset: u32, -} - -impl LayoutToken { - pub(crate) fn new(kind: i32, data: *const c_void, offset: u32) -> Self { - LayoutToken { - s_type: structure(7), - p_next: std::ptr::null(), - kind, - data, - offset, - } - } -} - -/// `VkIndirectCommandsLayoutCreateInfoEXT`, made for explicit preprocessing -/// (`VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EXPLICIT_PREPROCESS_BIT_EXT`): each of its executions is -/// preprocessed apart ([`Commands::preprocess`]) and runs preprocessed -/// ([`Commands::execute_preprocessed`]). -#[repr(C)] -pub(crate) struct LayoutCreateInfo { - s_type: vk::StructureType, - p_next: *const c_void, - flags: u32, - shader_stages: vk::ShaderStageFlags, - indirect_stride: u32, - pipeline_layout: vk::PipelineLayout, - token_count: u32, - tokens: *const LayoutToken, -} - -impl LayoutCreateInfo { - pub(crate) fn new( - indirect_stride: u32, - pipeline_layout: vk::PipelineLayout, - tokens: &[LayoutToken], - ) -> Self { - LayoutCreateInfo { - s_type: structure(6), - p_next: std::ptr::null(), - flags: LAYOUT_EXPLICIT_PREPROCESS, - shader_stages: vk::ShaderStageFlags::COMPUTE, - indirect_stride, - pipeline_layout, - token_count: tokens.len() as u32, - tokens: tokens.as_ptr(), - } - } -} - -/// `VkGeneratedCommandsMemoryRequirementsInfoEXT`. -#[repr(C)] -pub(crate) struct MemoryRequirementsInfo { - s_type: vk::StructureType, - p_next: *const c_void, - execution_set: Handle, - commands_layout: Handle, - max_sequence_count: u32, - max_draw_count: u32, -} - -impl MemoryRequirementsInfo { - pub(crate) fn new(execution_set: Handle, commands_layout: Handle, sequences: u32) -> Self { - MemoryRequirementsInfo { - s_type: structure(2), - p_next: std::ptr::null(), - execution_set, - commands_layout, - max_sequence_count: sequences, - max_draw_count: 0, - } - } -} - -/// `VkGeneratedCommandsInfoEXT`. -#[repr(C)] -#[derive(Clone, Copy)] -pub(crate) struct GeneratedCommandsInfo { - s_type: vk::StructureType, - p_next: *const c_void, - shader_stages: vk::ShaderStageFlags, - execution_set: Handle, - commands_layout: Handle, - indirect_address: vk::DeviceAddress, - indirect_address_size: vk::DeviceSize, - preprocess_address: vk::DeviceAddress, - preprocess_size: vk::DeviceSize, - max_sequence_count: u32, - sequence_count_address: vk::DeviceAddress, - max_draw_count: u32, -} - -/// One execution's addresses and sizes. -pub(crate) struct Execution { - pub(crate) indirect: (vk::DeviceAddress, vk::DeviceSize), - pub(crate) preprocess: (vk::DeviceAddress, vk::DeviceSize), - pub(crate) max_sequences: u32, - pub(crate) count_address: vk::DeviceAddress, -} - -impl GeneratedCommandsInfo { - pub(crate) fn new(execution_set: Handle, commands_layout: Handle, e: &Execution) -> Self { - GeneratedCommandsInfo { - s_type: structure(4), - p_next: std::ptr::null(), - shader_stages: vk::ShaderStageFlags::COMPUTE, - execution_set, - commands_layout, - indirect_address: e.indirect.0, - indirect_address_size: e.indirect.1, - preprocess_address: e.preprocess.0, - preprocess_size: e.preprocess.1, - max_sequence_count: e.max_sequences, - sequence_count_address: e.count_address, - max_draw_count: 0, - } - } -} - -type CreateExecutionSet = unsafe extern "system" fn( - vk::Device, - *const ExecutionSetCreateInfo, - *const vk::AllocationCallbacks<'static>, - *mut Handle, -) -> vk::Result; -type DestroyHandle = - unsafe extern "system" fn(vk::Device, Handle, *const vk::AllocationCallbacks<'static>); -type UpdateExecutionSetPipeline = - unsafe extern "system" fn(vk::Device, Handle, u32, *const WriteExecutionSetPipeline); -type CreateCommandsLayout = unsafe extern "system" fn( - vk::Device, - *const LayoutCreateInfo, - *const vk::AllocationCallbacks<'static>, - *mut Handle, -) -> vk::Result; -type MemoryRequirements = unsafe extern "system" fn( - vk::Device, - *const MemoryRequirementsInfo, - *mut vk::MemoryRequirements2<'static>, -); -type Execute = - unsafe extern "system" fn(vk::CommandBuffer, vk::Bool32, *const GeneratedCommandsInfo); -type Preprocess = - unsafe extern "system" fn(vk::CommandBuffer, *const GeneratedCommandsInfo, vk::CommandBuffer); - -/// The extension's commands, loaded for one device. -#[derive(Clone, Copy)] -pub(crate) struct Commands { - device: vk::Device, - create_execution_set: CreateExecutionSet, - destroy_execution_set: DestroyHandle, - update_execution_set_pipeline: UpdateExecutionSetPipeline, - create_commands_layout: CreateCommandsLayout, - destroy_commands_layout: DestroyHandle, - memory_requirements: MemoryRequirements, - execute: Execute, - preprocess: Preprocess, -} - -impl Commands { - /// The commands of `device`, each from `load` (`vkGetDeviceProcAddr`); `None` when one is - /// missing. - /// - /// # Safety - /// `load` returns each name's command of `device`, which enabled the extension. - pub(crate) unsafe fn load( - device: vk::Device, - load: impl Fn(&CStr) -> vk::PFN_vkVoidFunction, - ) -> Option { - macro_rules! command { - ($name:literal, $ty:ty) => {{ - let f = load($name)?; - // SAFETY: the registry gives the command this signature. - unsafe { std::mem::transmute::(f) } - }}; - } - Some(Commands { - device, - create_execution_set: command!(c"vkCreateIndirectExecutionSetEXT", CreateExecutionSet), - destroy_execution_set: command!(c"vkDestroyIndirectExecutionSetEXT", DestroyHandle), - update_execution_set_pipeline: command!( - c"vkUpdateIndirectExecutionSetPipelineEXT", - UpdateExecutionSetPipeline - ), - create_commands_layout: command!( - c"vkCreateIndirectCommandsLayoutEXT", - CreateCommandsLayout - ), - destroy_commands_layout: command!(c"vkDestroyIndirectCommandsLayoutEXT", DestroyHandle), - memory_requirements: command!( - c"vkGetGeneratedCommandsMemoryRequirementsEXT", - MemoryRequirements - ), - execute: command!(c"vkCmdExecuteGeneratedCommandsEXT", Execute), - preprocess: command!(c"vkCmdPreprocessGeneratedCommandsEXT", Preprocess), - }) - } - - /// `vkCreateIndirectExecutionSetEXT`. - /// - /// # Safety - /// `info` and what it points at are valid for the call. - pub(crate) unsafe fn create_execution_set( - &self, - info: &ExecutionSetCreateInfo, - ) -> Result { - let mut out = 0; - // SAFETY: the caller's contract. - match unsafe { (self.create_execution_set)(self.device, info, std::ptr::null(), &mut out) } - { - vk::Result::SUCCESS => Ok(out), - error => Err(error), - } - } - - /// `vkDestroyIndirectExecutionSetEXT`. - /// - /// # Safety - /// No pending work uses `set`. - pub(crate) unsafe fn destroy_execution_set(&self, set: Handle) { - // SAFETY: the caller's contract. - unsafe { (self.destroy_execution_set)(self.device, set, std::ptr::null()) } - } - - /// `vkUpdateIndirectExecutionSetPipelineEXT`. - /// - /// # Safety - /// No submitted work references the written indices. - pub(crate) unsafe fn update_execution_set( - &self, - set: Handle, - writes: &[WriteExecutionSetPipeline], - ) { - // SAFETY: the caller's contract. - unsafe { - (self.update_execution_set_pipeline)( - self.device, - set, - writes.len() as u32, - writes.as_ptr(), - ) - } - } - - /// `vkCreateIndirectCommandsLayoutEXT`. - /// - /// # Safety - /// `info` and what it points at are valid for the call. - pub(crate) unsafe fn create_commands_layout( - &self, - info: &LayoutCreateInfo, - ) -> Result { - let mut out = 0; - // SAFETY: the caller's contract. - match unsafe { - (self.create_commands_layout)(self.device, info, std::ptr::null(), &mut out) - } { - vk::Result::SUCCESS => Ok(out), - error => Err(error), - } - } - - /// `vkDestroyIndirectCommandsLayoutEXT`. - /// - /// # Safety - /// No pending work uses `layout`. - pub(crate) unsafe fn destroy_commands_layout(&self, layout: Handle) { - // SAFETY: the caller's contract. - unsafe { (self.destroy_commands_layout)(self.device, layout, std::ptr::null()) } - } - - /// `vkGetGeneratedCommandsMemoryRequirementsEXT`. - /// - /// # Safety - /// `info`'s handles are live. - pub(crate) unsafe fn memory_requirements( - &self, - info: &MemoryRequirementsInfo, - ) -> vk::MemoryRequirements { - let mut out = vk::MemoryRequirements2::default(); - // SAFETY: the caller's contract. - unsafe { (self.memory_requirements)(self.device, info, &mut out) }; - out.memory_requirements - } - - /// `vkCmdPreprocessGeneratedCommandsEXT` of `info` into `command`, the state taken from - /// `command` itself. - /// - /// # Safety - /// `command` is recording, with the execution set's initial pipeline bound; `info`'s handles - /// and addresses are live until the work completes. - pub(crate) unsafe fn preprocess( - &self, - command: vk::CommandBuffer, - info: &GeneratedCommandsInfo, - ) { - // SAFETY: the caller's contract. - unsafe { (self.preprocess)(command, info, command) } - } - - /// `vkCmdExecuteGeneratedCommandsEXT` of commands [`preprocess`](Self::preprocess) wrote. - /// - /// # Safety - /// `command` is recording, with the execution set's initial pipeline bound; `info` was - /// preprocessed in `command`, with the same contents and the same state bound, a barrier - /// ordering that preprocessing's writes before this execution, and its handles and addresses - /// are live until the work completes. - pub(crate) unsafe fn execute_preprocessed( - &self, - command: vk::CommandBuffer, - info: &GeneratedCommandsInfo, - ) { - // SAFETY: the caller's contract. - unsafe { (self.execute)(command, vk::TRUE, info) } - } -} diff --git a/crates/metal2vulkan-validation/src/candidate/platform/plan_resources.rs b/crates/metal2vulkan-validation/src/candidate/platform/plan_resources.rs index a12d8acf2..758cc981f 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/plan_resources.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/plan_resources.rs @@ -112,9 +112,8 @@ pub(super) struct Guest<'a> { /// reads (framebuffer fetch), in `GENERAL`. A dispatch has none. pub(super) attachments: &'a BTreeMap, /// The run's `ExecutionStatus` buffer, which a stage binds on a device that does not address - /// buffers (`WriteSource::ExecutionStatus`). A device replay, which needs the addresses, - /// has none. - pub(super) status: Option, + /// buffers (`WriteSource::ExecutionStatus`). + pub(super) status: vk::Buffer, } /// What one descriptor write points at. @@ -406,17 +405,12 @@ impl<'a> PlanResources<'a> { whole(buffer) } // The run's status words, the ones every command of it writes. - WriteSource::ExecutionStatus => { - let status = guest - .status - .ok_or("the plan binds an execution status the run has none of")?; - Info::Buffer( - vk::DescriptorBufferInfo::default() - .buffer(status) - .offset(0) - .range(ExecutionStatus::BYTES as u64), - ) - } + WriteSource::ExecutionStatus => Info::Buffer( + vk::DescriptorBufferInfo::default() + .buffer(guest.status) + .offset(0) + .range(ExecutionStatus::BYTES as u64), + ), WriteSource::Texture { slot, view } => { let (image, layout) = self.image(TextureKey::Slot(*slot))?; let view = self.view(context, image, view)?; diff --git a/crates/metal2vulkan-validation/src/candidate/platform/render.rs b/crates/metal2vulkan-validation/src/candidate/platform/render.rs index 5fd3ee3ca..5f6f4d95b 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/render.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/render.rs @@ -43,25 +43,22 @@ use super::acceptance::{unmet_requirements, LayoutError, LayoutObjects}; use super::buffers::{create_host_buffer, HostBuffer}; use super::compute::{ - allocate, allocate_in, attempt, command_replay, environment, executed_census, - incompatible_binding, module_censuses, opened_device, refused_attempt, replay_commands, - upload_root_table, Allocation, CompileChild, Live, OnDevice, Replay, ReplayPath, + allocate, allocate_in, attempt, environment, executed_census, incompatible_binding, + module_censuses, opened_device, refused_attempt, upload_root_table, Allocation, }; use super::device::{with_validated_context, ExtendedDynamicState, VulkanContext}; use super::graphics_pipeline::{self, GraphicsError}; use super::plan_resources::{barrier, create_image, layers, Guest, PlanResources, TextureKey}; -use crate::candidate::engine::argument_buffers::{ - field_words, owner_bytes, records_storage, validate_records, -}; +use crate::candidate::engine::argument_buffers::{field_words, owner_bytes}; use crate::candidate::engine::graphics::{ self, stage_of, Assembly, ColorTarget, RenderCase, RenderFinals, RenderOutput, }; use crate::candidate::engine::guards::{declared_reach, with_escaped, GuardCount}; +use crate::candidate::engine::index_padding_agrees; use crate::candidate::engine::{ bind_refusal, draw_out_of_bounds_run, engine_fingerprint, resources, status_verdict, BufferAddress, ComputeRun, RunAttempt, }; -use crate::candidate::engine::{index_padding_agrees, ChildCommand, CompiledChild}; use crate::case::out_of_bounds::OutOfBoundsResource; use crate::check::admission::{ExecutorError, NotSupported}; use crate::executor_contract::multisample::AttachmentTransfer; @@ -73,8 +70,8 @@ use crate::literal::{LiteralDepthStencil, LiteralTexture}; use crate::worker::compile::WorkerDevice; use ash::vk; use metal2vulkan::bind::{ - BindShape, BindState, BindingPlan, BufferRanges, DrawCommands, ExecutionStatus, PushHole, - SamplerDescriptor, StatusReport, DRAW_ARGUMENT_BYTES, + BindShape, BufferRanges, DrawCommands, ExecutionStatus, PushHole, SamplerDescriptor, + StatusReport, }; use metal2vulkan::device::Device; use metal2vulkan::device::VkFeature; @@ -91,25 +88,18 @@ fn not_implemented(what: impl Into) -> ExecutorError { /// description and policy and the bind shape the draw binds, `graphics::render_shape`; the tools' /// compile worker; it returns the pipeline), plan and /// execute its draw, and read the status before the output. Every refusal is typed; only a device, -/// driver, or tool failure is `Failed`. `children` compiles the template each command the case -/// executes runs, in a compile worker. +/// driver, or tool failure is `Failed`. pub fn execute_engine_render( device_type: DeviceType, case_id: &str, case: &RenderCase, compile: impl FnOnce(&WorkerDevice, &BindShape) -> Result, - children: impl FnMut( - &WorkerDevice, - u64, - &BindShape, - &ChildCommand, - ) -> Result, ) -> RunAttempt { if let Some(refused) = refused_attempt(device_type, "engine-render") { return refused; } with_validated_context(device_type, |context| { - let result = run(context, case_id, case, (compile, children)); + let result = run(context, case_id, case, compile); Ok(attempt(context, result, "engine-render")) }) .unwrap_or_else(|error| RunAttempt::of(Err(ExecutorError::Failed(error)))) @@ -119,15 +109,7 @@ fn run( context: &VulkanContext, case_id: &str, case: &RenderCase, - (compile, mut children): ( - impl FnOnce(&WorkerDevice, &BindShape) -> Result, - impl FnMut( - &WorkerDevice, - u64, - &BindShape, - &ChildCommand, - ) -> Result, - ), + compile: impl FnOnce(&WorkerDevice, &BindShape) -> Result, ) -> Result { let target = opened_device(context)?; let addressed = context @@ -156,9 +138,6 @@ fn run( case_id: case_id.into(), module_sha256: spv_sha256.clone(), }; - let mut compile_child = |token: u64, shape: &BindShape, command: &ChildCommand| { - children(&target, token, shape, command) - }; // A pipeline whose vertex stage stores its slice clamped to the pass's pushed length, drawn // into a pass of at most one layer, the one-layer framebuffer every row draws into: the // layer's warning of its `Layer` write is a false alarm the sink withholds and counts. @@ -177,7 +156,6 @@ fn run( (pipeline, &shape), case, out_of_bounds.as_ref(), - &mut compile_child, ) }); let withheld = context.take_withheld(); @@ -198,21 +176,17 @@ fn run( output, status, escaped, - children, - replayed, } = executed?; - // Every stage module drawn, in the order `spv_sha256` hashes them, then each replayed - // command's, and the guard bytes each out-of-bounds target's run changed. + // Every stage module drawn, in the order `spv_sha256` hashes them, and the guard bytes each + // out-of-bounds target's run changed. let planned = pipeline.plan(device, &shape).ok(); - let mut modules = module_censuses(&pipeline.stages, device.profile(), planned.as_ref())?; - modules.extend(children); + let modules = module_censuses(&pipeline.stages, device.profile(), planned.as_ref())?; let census = executed_census( context, modules, out_of_bounds.map(|run| with_escaped(run, &escaped)), ); let mut environment = environment(context, device, "engine-render"); - command_replay(&mut environment, &replayed); super::device::record_withheld(&mut environment, withheld); Ok(ComputeRun { output, @@ -226,22 +200,18 @@ fn run( } /// Allocate the case's buffers (argument-buffer buffers first, so each owner is created with -/// their addresses, its textures' and samplers' resource ids, and its command buffers', -/// [`field_words`], -/// [`owner_bytes`]) and vertex buffers, write the commands the host encodes into their record storage, plan and instantiate -/// its draw, create what every plan write names (argument-buffer textures, heap arrays, and -/// handle tables included), the color targets, and the pipeline, record and submit the draw, -/// wait, read the status, check the records, execute the commands the case executes (`compile` -/// compiling each child in a compile worker), and read the output; with the guard and padding bytes -/// the draw changed around each out-of-bounds target (`out_of_bounds`), by target, and the census -/// of each module a replayed command executed. +/// their addresses and its textures' and samplers' resource ids, [`field_words`], [`owner_bytes`]) +/// and vertex buffers, plan and instantiate its draw, create what every plan write names +/// (argument-buffer textures, heap arrays, and handle tables included), the color targets, and the +/// pipeline, record and submit the draw, wait, read the status, and read the output; with the +/// guard and padding bytes the draw changed around each out-of-bounds target (`out_of_bounds`), by +/// target. fn execute( context: &VulkanContext, device: &Device, (pipeline, compiled_for): (&RenderPipeline, &BindShape), case: &RenderCase, out_of_bounds: Option<&OutOfBoundsRun>, - compile: &mut CompileChild<'_>, ) -> Result { let addressed = context .enabled @@ -259,7 +229,6 @@ fn execute( None => Ok(synthetic), }; let synthetic_used = graphics::synthetic_used_addresses(case).map_err(ExecutorError::Failed)?; - let records = graphics::records_ids(case).map_err(ExecutorError::Failed)?; let mut embedded: BTreeMap<(Stage, u32, u32), Allocation> = BTreeMap::new(); let mut embedded_addresses = BTreeMap::new(); for (key, bytes) in case.argument_buffer_buffers() { @@ -272,24 +241,13 @@ fn execute( addressed, vk::BufferUsageFlags::empty(), )?; - // A command buffer's record storage lies at its ID's records address. - let address = match records.get(&key) { - Some(&id) => records_storage(id, allocation.address), - None => own_guest(&allocation, synthetic_used[&key])?, - }; - embedded_addresses.insert(key, address); + embedded_addresses.insert(key, own_guest(&allocation, synthetic_used[&key])?); embedded.insert(key, allocation); } let tokens = graphics::texture_tokens(case).map_err(ExecutorError::Failed)?; let samplers = graphics::sampler_ids(case).map_err(ExecutorError::Failed)?; - let words = field_words( - &embedded_addresses, - &records, - &tokens, - &samplers, - case.objects(), - ) - .map_err(ExecutorError::Failed)?; + let words = + field_words(&embedded_addresses, &tokens, &samplers).map_err(ExecutorError::Failed)?; let mut buffers: BTreeMap<(Stage, u32), Allocation> = BTreeMap::new(); for (stage, function) in case.stages() { let resources = &function.resources; @@ -357,25 +315,6 @@ fn execute( Ok(((stage, index), address)) }) .collect::>()?; - // The guest address of a case buffer of the stage that owns a command buffer. - let case_address = |(stage, _, _): (Stage, u32, u32), buffer: u32| { - addresses.get(&(stage, buffer)).map(|a| a.guest) - }; - // The commands the host encodes, written into their record storage before the producer runs, - // each buffer at its case buffer's guest address. - for (key, command) in case.command_buffers() { - if command.commands.is_empty() { - continue; - } - let storage = embedded - .get(&key) - .ok_or_else(|| format!("command buffer {key:?} has no record storage"))?; - // SAFETY: the storage was created for this run and nothing has been submitted yet. - let mapped = unsafe { storage.buffer.map()? }; - command - .encode_host_records(mapped.bytes, |buffer| case_address(key, buffer)) - .map_err(ExecutorError::Failed)?; - } let ranges = BufferRanges::of(device.profile().limits()); let state = graphics::bind_state(case, &addresses, &embedded_addresses, ranges) .map_err(ExecutorError::Failed)?; @@ -515,7 +454,7 @@ fn execute( descriptor_bytes: &commands.descriptor_bytes, tessellation_factors: factors.as_ref().map(|factors| factors.buffer.buffer), attachments: &attachments, - status: Some(status.buffer.buffer), + status: status.buffer.buffer, }, observed, )?; @@ -525,7 +464,7 @@ fn execute( let (table, sink) = upload_root_table(context, table, addressed)?; roots.push((vk::ShaderStageFlags::from(*stages), table, sink)); } - let push = push_writes(&commands, &roots, &status, &|_| None)?; + let push = push_writes(&commands, &roots, &status)?; let layout = match LayoutObjects::create(&context.device, &pipeline.layout) { Ok(layout) => layout, @@ -598,7 +537,6 @@ fn execute( rasterizer_discard: pipeline.graphics.rasterizer_discard, graphics: &pipeline.graphics, draw: &commands, - replayed: None, }, )?; @@ -648,85 +586,6 @@ fn execute( let bytes = unsafe { allocation.buffer.map()? }.bytes[..len].to_vec(); finals.argument_buffer_buffers.insert(key, bytes); } - // Each command buffer's records as the host contract decodes them: an encoding fault fails the - // run. Then the commands the case executes run, over the run's allocations, and the buffers are - // read again. - validate_records(case.command_buffers(), &finals.argument_buffer_buffers) - .map_err(ExecutorError::Failed)?; - let (children, replayed) = if case - .command_buffers() - .any(|(_, command)| command.execute.is_some()) - { - // Each allocation at its guest address and the length the guest sees (not the padding). - let lengths = |stage: Stage, index: u32| { - case.function(stage).map_or(0, |function| { - function - .resources - .buffers - .get(&index) - .map_or(0, |bytes| bytes.len() as u64) - }) - }; - let live = buffers - .iter() - .filter(|(&(stage, index), _)| lengths(stage, index) != 0) - .map(|(&(stage, index), allocation)| { - ( - addresses[&(stage, index)], - lengths(stage, index), - allocation, - ) - }) - .chain(embedded.iter().map(|(key, allocation)| { - ( - embedded_addresses[key], - finals.argument_buffer_buffers[key].len() as u64, - allocation, - ) - })) - .map(|(address, length, allocation)| Live { - buffer: allocation.buffer.buffer, - address, - length, - }) - .collect::>(); - // A render command buffer on the device where the runtime's GPU form draws it, from what - // the host and this draw's functions may write into its records; every other one by the - // host replay. A render case registers no compute replay variant. - let replayed = replay_commands( - context, - device, - case.command_buffers(), - Replay { - live: &live, - records: &finals.argument_buffer_buffers, - addresses: &case_address, - compile, - }, - OnDevice { - registered: &[], - storage: &|key| embedded.get(&key).and_then(|allocation| allocation.address), - writes: pipeline.interface.command_writes, - }, - )?; - for (&(stage, index), allocation) in &buffers { - if let Some(bytes) = finals.buffers.get_mut(&(stage, index)) { - let len = bytes.len(); - // SAFETY: as for the status buffer; every replayed command completed too. - *bytes = unsafe { allocation.buffer.map()? }.bytes[..len].to_vec(); - } - } - for (key, allocation) in &embedded { - if let Some(bytes) = finals.argument_buffer_buffers.get_mut(key) { - let len = bytes.len(); - // SAFETY: as for the status buffer. - *bytes = unsafe { allocation.buffer.map()? }.bytes[..len].to_vec(); - } - } - replayed - } else { - (Vec::new(), Vec::new()) - }; match (observed, case.output) { (Some(key @ TextureKey::Slot(observed)), _) => { if let Some(texture) = textures.get(&observed) { @@ -778,267 +637,23 @@ fn execute( output, status: report, escaped, - children, - replayed, }) } -/// What [`execute`] read after the draw: the output, the status, the guard and padding bytes -/// that changed around each guarded out-of-bounds target, by target, the census of each module -/// a replayed command executed, and which replay ran each executed command buffer. +/// What [`execute`] read after the draw: the output, the status, and the guard and padding bytes +/// that changed around each guarded out-of-bounds target, by target. struct Drawn { output: Vec, status: StatusReport, escaped: BTreeMap, - children: Vec, - replayed: Vec, } -/// Draw one replayed render command: `pipeline`, compiled for `case` (a render template with the -/// command's draw, which the checker requires to be a rasterization-disabled vertex case and the -/// candidate a vertex function that binds buffers only, `engine::replay_templates`), planned -/// for `state` (the plan must name no other variant and no neutral), over the run's allocations -/// `guest` (by slot), with `primitive`'s topology, which must be within the class the template was -/// compiled for (`graphics::replayed_draw_in_class`; a draw of another class fails the run). Its -/// pass is the template's own: the oracle's 1x1 `R8Unorm` scaffolding, which rasterization-disabled -/// drawing never writes. Each draw is submitted and waited for, with a clean status required, -/// before the next command. -pub(super) fn submit_draw_child( - context: &VulkanContext, - device: &Device, - case: &RenderCase, - pipeline: &RenderPipeline, - state: &metal2vulkan::bind::BindState, - primitive: crate::case::Primitive, - guest: &BTreeMap, -) -> Result<(), ExecutorError> { - graphics::replayed_draw_in_class(&case.assembly, primitive).map_err(ExecutorError::Failed)?; - let addressed = context - .enabled - .features - .contains(&VkFeature::BufferDeviceAddress); - let shape = state.shape(); - let plan = pipeline - .plan(device, &shape) - .map_err(|e| bind_refusal(&e))?; - if let Some(diagnostic) = plan.diagnostics.first() { - return Err(incompatible_binding(diagnostic)); - } - if !plan.vertex_buffers.is_empty() { - return Err(not_implemented("a replayed draw's vertex inputs")); - } - let commands = plan - .instantiate_draw(state, &case.draw) - .map_err(|e| bind_refusal(&e))?; - if commands.indirect_needs_arguments { - return Err(not_implemented("an indirect draw read on the CPU")); - } - let status = allocate( - context, - "replayed draw status", - &ExecutionStatus::initial(), - addressed, - vk::BufferUsageFlags::empty(), - )?; - draw_child( - context, - device, - (case, primitive), - (pipeline, &plan, &commands), - (state, guest), - (&status, &|_| None), - None, - )?; - // SAFETY: the submission completed (the fence signaled), and nothing else maps it. - let status_bytes: [u8; ExecutionStatus::BYTES] = unsafe { status.buffer.map()? }.bytes - [..ExecutionStatus::BYTES] - .try_into() - .map_err(|_| "the status buffer is shorter than ExecutionStatus")?; - status_verdict(&status_bytes)?; - Ok(()) -} - -/// What a draw replay records around its variant's draw (`compute::draw_replay`): before the -/// render pass, each owned kernel's pass in order (the preprocess, then a merged replay's two -/// merge passes), the first after a barrier from every command earlier in submission order and -/// each after one from the pass before it; in the pass, in place of the draw's own, each of -/// `draws` in order. -pub(super) struct ReplayedDraws<'a> { - pub(super) passes: &'a [OwnedPass], - /// The scratch the draws read their arguments from. - pub(super) scratch: vk::Buffer, - pub(super) draws: &'a [ReplayedDraw], -} - -/// The address a draw replay gives a push hole of its variant's draw (a slot table's, its merged -/// draw's header), where it fills that hole. -pub(super) type Holes<'a> = &'a dyn Fn(&PushHole) -> Option; - -/// One owned kernel's dispatch: its pipeline and layout, push bytes (`COMPUTE`, offset 0), and -/// group count. -pub(super) struct OwnedPass { - pub(super) pipeline: vk::Pipeline, - pub(super) layout: vk::PipelineLayout, - pub(super) push: Vec, - pub(super) group_count: [u32; 3], -} - -/// One draw of a draw replay: `vkCmdDrawIndirect` of one draw at `arguments` in the scratch, after -/// the push writes that make it its command's (none for the first, whose writes the variant's -/// draw carries). -pub(super) struct ReplayedDraw { - pub(super) push: Vec<(vk::ShaderStageFlags, u32, Vec)>, - pub(super) arguments: u64, -} - -/// Draw a replayed execution's commands on the device: `pipeline`, the draw replay variant of -/// `case` (a render template, as [`submit_draw_child`] states it), planned as `plan` and -/// instantiated as `commands` (one indirect draw) for `state`, over the run's allocations `guest` -/// (by slot), with `primitive`'s topology, which must be within the template's class; its push -/// holes the replay fills (`holes`: a slot table's, the merged draw's header) with their -/// addresses, `status` its `ExecutionStatus`, and `replayed`'s passes and draws in place of the -/// draw's own. Submitted and waited for; the caller reads the status. -pub(super) fn submit_replayed_draws( - context: &VulkanContext, - device: &Device, - (case, primitive): (&RenderCase, crate::case::Primitive), - instantiated: (&RenderPipeline, &BindingPlan, &DrawCommands), - bound: (&BindState, &BTreeMap), - filled: (&Allocation, Holes<'_>), - replayed: &ReplayedDraws<'_>, -) -> Result<(), ExecutorError> { - graphics::replayed_draw_in_class(&case.assembly, primitive).map_err(ExecutorError::Failed)?; - draw_child( - context, - device, - (case, primitive), - instantiated, - bound, - filled, - Some(replayed), - ) -} - -/// Record and submit one replayed command's draw (or a draw replay's, `replayed`) of `pipeline`, -/// planned as `plan` and instantiated as `commands` for `state`, over the run's allocations -/// `guest`, in its template's pass (as [`submit_draw_child`] states it) with `primitive`'s -/// topology, its push holes filled by `holes` first, then from what the draw names (its root -/// tables, `status`); wait for it. The caller reads the status. -fn draw_child( - context: &VulkanContext, - device: &Device, - (case, primitive): (&RenderCase, crate::case::Primitive), - (pipeline, plan, commands): (&RenderPipeline, &BindingPlan, &DrawCommands), - (state, guest): (&BindState, &BTreeMap), - (status, holes): (&Allocation, Holes<'_>), - replayed: Option<&ReplayedDraws<'_>>, -) -> Result<(), ExecutorError> { - let addressed = context - .enabled - .features - .contains(&VkFeature::BufferDeviceAddress); - let mut constant_blobs: BTreeMap> = BTreeMap::new(); - for module in &pipeline.stages { - if let Some(blob) = &module.constant_blob { - let stage = stage_of(module, false)? - .ok_or("a replayed draw's synthesized stage carries a constant blob")?; - constant_blobs.insert(stage, blob.clone()); - } - } - let targets = Targets::create(context, &pipeline.graphics, case)?; - // A multisampled template's attachments leave the initializer's layout the same way. - let readers = multisampled::SampleReaders::create(context, &targets)?; - let mut resources = PlanResources::create( - context, - device, - &plan.descriptors, - &Guest { - buffers: guest, - textures: &BTreeMap::new(), - used_textures: &BTreeMap::new(), - samplers: &BTreeMap::new(), - argument_samplers: &state.argument_samplers, - constant_blobs: &constant_blobs, - descriptor_ranges: &commands.descriptor_ranges, - descriptor_bytes: &commands.descriptor_bytes, - tessellation_factors: None, - attachments: &BTreeMap::new(), - status: Some(status.buffer.buffer), - }, - None, - )?; - let mut roots = Vec::new(); - for (stages, table) in &commands.root_tables { - let (table, sink) = upload_root_table(context, table, addressed)?; - roots.push((vk::ShaderStageFlags::from(*stages), table, sink)); - } - let push = push_writes(commands, &roots, status, holes)?; - let layout = match LayoutObjects::create(&context.device, &pipeline.layout) { - Ok(layout) => layout, - Err(LayoutError::Shape(why) | LayoutError::Refused(why)) => { - return Err(ExecutorError::Failed(why)) - } - }; - let mut objects = Objects { - device: &context.device, - modules: Vec::new(), - render_pass: vk::RenderPass::null(), - framebuffer: vk::Framebuffer::null(), - pipeline: vk::Pipeline::null(), - command_pool: vk::CommandPool::null(), - fence: vk::Fence::null(), - layout, - }; - create_render_pass(context, &mut objects, &pipeline.graphics, &targets)?; - let (topology, primitive_restart) = graphics::input_assembly(primitive); - let topology: vk::PrimitiveTopology = topology.into(); - let encoder = EncoderState::of(case)?; - create_pipeline( - context, - &mut objects, - pipeline, - &plan.specialization, - (topology, primitive_restart), - encoder, - )?; - let sets = resources.write_sets(context, &objects.layout)?; - record_and_submit( - context, - &mut objects, - Recording { - resources: &resources, - targets: &targets, - readers: readers.as_ref(), - area: draw_area(targets.extent), - sets: &sets, - push: &push, - vertex_buffers: &[], - index_buffer: None, - dynamic: &pipeline.graphics.dynamic_states, - topology, - primitive_restart, - encoder, - rasterizer_discard: pipeline.graphics.rasterizer_discard, - graphics: &pipeline.graphics, - draw: commands, - replayed, - }, - )?; - drop(objects); - drop(readers); - drop(targets); - drop(resources); - Ok(()) -} - -/// Each stage's push-constant writes with the consumer's holes filled: the address `filled` gives -/// a hole (a draw replay's slot table, its merged draw's header), else its root table's and the +/// Each stage's push-constant writes with the consumer's holes filled: its root table's and the /// status buffer's device addresses. fn push_writes( commands: &DrawCommands, roots: &[(vk::ShaderStageFlags, Allocation, Allocation)], status: &Allocation, - filled: Holes<'_>, ) -> Result)>, ExecutorError> { let mut writes: Vec<(vk::ShaderStageFlags, u32, Vec)> = commands .push_constants @@ -1046,13 +661,8 @@ fn push_writes( .map(|w| (w.stages.into(), w.offset, w.bytes.clone())) .collect(); for hole in &commands.push_holes { - let (stages, offset, address) = match (*hole, filled(hole)) { - ( - PushHole::RootTableAddress { stages, offset } - | PushHole::MergedDrawAddress { stages, offset }, - Some(address), - ) => (stages.into(), offset, address), - (PushHole::RootTableAddress { stages, offset }, None) => { + let (stages, offset, address) = match *hole { + PushHole::RootTableAddress { stages, offset } => { let stages = vk::ShaderStageFlags::from(stages); let root = roots .iter() @@ -1061,14 +671,14 @@ fn push_writes( .ok_or("a root-table hole without its stage's root table")?; (stages, offset, root) } - (PushHole::ExecutionStatusAddress { stages, offset }, _) => ( + PushHole::ExecutionStatusAddress { stages, offset } => ( stages.into(), offset, status .address .ok_or("a status-address hole without device addresses")?, ), - (other, _) => return Err(not_implemented(format!("the push hole {other:?}"))), + other => return Err(not_implemented(format!("the push hole {other:?}"))), }; let write = writes .iter_mut() @@ -1929,9 +1539,6 @@ struct Recording<'r> { /// The pipeline's graphics state, whose render pass the draws record in. graphics: &'r GraphicsState, draw: &'r DrawCommands, - /// A draw replay's passes before the render pass and draws in place of `draw`'s own, which is - /// then one indirect draw. - replayed: Option<&'r ReplayedDraws<'r>>, } /// A vertex buffer's `(binding, buffer, offset)`. @@ -2158,50 +1765,17 @@ fn record_and_submit( offset: vk::Offset2D { x: 0, y: 0 }, extent, }; - let draw = match ( - recording.draw.draw, - recording.index_buffer, - recording.replayed, - ) { - (metal2vulkan::vk::DrawCommand::Draw { .. }, None, None) - | (metal2vulkan::vk::DrawCommand::DrawIndexed { .. }, Some(_), None) - | (metal2vulkan::vk::DrawCommand::DrawIndirect { .. }, None, Some(_)) => { - recording.draw.draw - } - (_, _, Some(_)) => return Err("a draw replay's draw is not one indirect draw".into()), - (metal2vulkan::vk::DrawCommand::DrawIndexed { .. }, None, _) => { + let draw = match (recording.draw.draw, recording.index_buffer) { + (metal2vulkan::vk::DrawCommand::Draw { .. }, None) + | (metal2vulkan::vk::DrawCommand::DrawIndexed { .. }, Some(_)) => recording.draw.draw, + (metal2vulkan::vk::DrawCommand::DrawIndexed { .. }, None) => { return Err("an indexed draw without an index buffer".into()) } - (metal2vulkan::vk::DrawCommand::Draw { .. }, Some(_), _) => { + (metal2vulkan::vk::DrawCommand::Draw { .. }, Some(_)) => { return Err("an index buffer for a draw that is not indexed".into()) } _ => return Err(not_implemented("an indirect draw")), }; - // A draw replay's barriers. Its preprocess reads the records and the buffers they name, which - // the producer's command buffer wrote: a pipeline barrier recorded outside a render pass - // instance has every command earlier in submission order in its first synchronization scope - // (the Vulkan specification's `vkCmdPipelineBarrier`), so one from every command makes those - // writes visible. Each pass's writes (the slot tables, the arguments, a merged replay's - // sections) before the next pass reads and writes them and the draws read them, as indirect - // arguments and in their functions; and the draws' writes, which the host reads after the - // wait, made visible to it. - let earlier = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::MEMORY_WRITE) - .dst_access_mask(vk::AccessFlags::SHADER_READ); - let passed = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask( - vk::AccessFlags::SHADER_READ - | vk::AccessFlags::SHADER_WRITE - | vk::AccessFlags::INDIRECT_COMMAND_READ, - ); - let drawn = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::SHADER_WRITE) - .dst_access_mask(vk::AccessFlags::HOST_READ); - let after_pass = vk::PipelineStageFlags::COMPUTE_SHADER - | vk::PipelineStageFlags::DRAW_INDIRECT - | vk::PipelineStageFlags::VERTEX_SHADER - | vk::PipelineStageFlags::FRAGMENT_SHADER; // SAFETY: every handle recorded is live until the fence signals; the buffer is recorded once. unsafe { device @@ -2259,38 +1833,6 @@ fn record_and_submit( if let Some(readers) = recording.readers { readers.record_initialized(command, attachment_stages); } - if let Some(replayed) = recording.replayed { - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::ALL_COMMANDS, - vk::PipelineStageFlags::COMPUTE_SHADER, - vk::DependencyFlags::empty(), - &[earlier], - &[], - &[], - ); - for pass in replayed.passes { - device.cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, pass.pipeline); - device.cmd_push_constants( - command, - pass.layout, - vk::ShaderStageFlags::COMPUTE, - 0, - &pass.push, - ); - let [x, y, z] = pass.group_count; - device.cmd_dispatch(command, x, y, z); - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::COMPUTE_SHADER, - after_pass, - vk::DependencyFlags::empty(), - &[passed], - &[], - &[], - ); - } - } let begin = vk::RenderPassBeginInfo::default() .render_pass(objects.render_pass) .framebuffer(objects.framebuffer) @@ -2427,46 +1969,10 @@ fn record_and_submit( first_vertex, first_instance, ), - // A draw replay's draws, each of one draw at its arguments. - (metal2vulkan::vk::DrawCommand::DrawIndirect { .. }, _) => { - if let Some(replayed) = recording.replayed { - for draw in replayed.draws { - for (stages, offset, bytes) in &draw.push { - device.cmd_push_constants( - command, - objects.layout.pipeline_layout, - *stages, - *offset, - bytes, - ); - } - device.cmd_draw_indirect( - command, - replayed.scratch, - draw.arguments, - 1, - DRAW_ARGUMENT_BYTES as u32, - ); - } - } - } // Refused before recording began. _ => {} } device.cmd_end_render_pass(command); - if recording.replayed.is_some() { - device.cmd_pipeline_barrier( - command, - vk::PipelineStageFlags::COMPUTE_SHADER - | vk::PipelineStageFlags::VERTEX_SHADER - | vk::PipelineStageFlags::FRAGMENT_SHADER, - vk::PipelineStageFlags::HOST, - vk::DependencyFlags::empty(), - &[drawn], - &[], - &[], - ); - } if !to_source.is_empty() { device.cmd_pipeline_barrier( command, diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs index f5738367b..fcdbd07bf 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs @@ -26,8 +26,6 @@ pub(crate) fn case(entry: &str, buffer: Vec, dispatch: Dispatch) -> ComputeC argument_buffer_buffers: BTreeMap::new(), argument_buffer_textures: BTreeMap::new(), argument_buffer_samplers: BTreeMap::new(), - objects: std::collections::BTreeMap::new(), - command_buffers: std::collections::BTreeMap::new(), textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), @@ -73,8 +71,6 @@ fn run_linked( shape, ) }, - |_, token, _, _| Err(format!("no template has pipeline token {token}").into()), - &[], ) .result } diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs index 03737a6c4..4904aa163 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs @@ -36,7 +36,6 @@ fn run(case: &RenderCase, libraries: RenderLibraries<'_>) -> Result>(); compile_render(compile_worker(), device, &request, &sources) }, - |_, token, _, _| Err(format!("no template has pipeline token {token}").into()), ) .result } diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs index 838498838..ad124799a 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_textures.rs @@ -71,8 +71,6 @@ fn kernel( argument_buffer_buffers: BTreeMap::new(), argument_buffer_textures: BTreeMap::new(), argument_buffer_samplers: BTreeMap::new(), - objects: std::collections::BTreeMap::new(), - command_buffers: std::collections::BTreeMap::new(), textures: textures .into_iter() .map(|texture| (texture.binding, texture)) diff --git a/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs b/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs index 8e7521e75..80d974eff 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/gpu_fuzz.rs @@ -109,23 +109,16 @@ pub(super) mod device { bitcode: &[u8], ) -> Result { super::device_wait(); - platform::execute_engine( - crate::gpu::TEST_DEVICE, - label, - case, - |device, shape| { - crate::candidate::engine::compile_case( - super::super::compile_worker(), - device, - &crate::acceptance::retained(bitcode), - &[], - case, - shape, - ) - }, - |_, token, _, _| Err(format!("no template has pipeline token {token}").into()), - &[], - ) + platform::execute_engine(crate::gpu::TEST_DEVICE, label, case, |device, shape| { + crate::candidate::engine::compile_case( + super::super::compile_worker(), + device, + &crate::acceptance::retained(bitcode), + &[], + case, + shape, + ) + }) .result } @@ -168,8 +161,6 @@ pub(super) mod device { argument_buffer_buffers, argument_buffer_textures: BTreeMap::new(), argument_buffer_samplers: BTreeMap::new(), - objects: BTreeMap::new(), - command_buffers: BTreeMap::new(), textures: BTreeMap::new(), samplers: BTreeMap::new(), threadgroup_lengths: BTreeMap::new(), diff --git a/crates/metal2vulkan-validation/src/candidate/tests/widest_pin.rs b/crates/metal2vulkan-validation/src/candidate/tests/widest_pin.rs index 8c82a1f0f..c10e3323f 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/widest_pin.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/widest_pin.rs @@ -95,8 +95,6 @@ fn run( shape, ) }, - |_, token, _, _| Err(format!("no template has pipeline token {token}").into()), - &[], ) .result } diff --git a/crates/metal2vulkan-validation/src/requirement.rs b/crates/metal2vulkan-validation/src/requirement.rs index 5360c118a..27453501f 100644 --- a/crates/metal2vulkan-validation/src/requirement.rs +++ b/crates/metal2vulkan-validation/src/requirement.rs @@ -162,13 +162,6 @@ pub enum ToolingRequirement { /// the authored compile census still compiles an object or mesh case's pipeline /// (`engine::prepare_compile`). MeshRenderPipeline, - /// A replayed pipeline template the engine's candidate does not replay - /// (`candidate::engine::replay_templates`): a compute template that binds more than buffers - /// and threadgroup memory, or a render template that is not a rasterization-disabled vertex - /// function binding buffers only (a template of a family the runtime does not build is refused - /// as that family first). A case's templates raise it, never a source's structure, so no census - /// row carries it. - ReplayedTemplateResources, /// A sequentially consistent fence its entry's pipeline compiles /// (`executor_contract::seq_cst_fence`): an `atomic_thread_fence` of `memory_order_seq_cst` /// that orders a memory beyond its thread, or a `seq_cst` barrier of the MSL 4.1 form whose @@ -313,7 +306,7 @@ const AUTHORING: &[Executor] = &Executor::ALL; const ENGINE: &[Executor] = &[Executor::EngineCandidate]; impl ToolingRequirement { - pub const ALL: [Self; 44] = [ + pub const ALL: [Self; 43] = [ Self::FunctionConstantLiteral, Self::VertexAttributeLiteral, Self::TessellationAttributeLiteral, @@ -338,7 +331,6 @@ impl ToolingRequirement { Self::MeshCompanion, Self::DepthOutsideUnitRange, Self::MeshRenderPipeline, - Self::ReplayedTemplateResources, Self::SeqCstFence, Self::RenderFunctionTable, Self::IndexBufferPastEnd, @@ -388,7 +380,6 @@ impl ToolingRequirement { Self::MeshCompanion => "mesh_companion", Self::DepthOutsideUnitRange => "depth_outside_unit_range", Self::MeshRenderPipeline => "mesh_render_pipeline", - Self::ReplayedTemplateResources => "replayed_template_resources", Self::SeqCstFence => "seq_cst_fence", Self::RenderFunctionTable => "render_function_table", Self::IndexBufferPastEnd => "index_buffer_past_end", @@ -425,9 +416,8 @@ impl ToolingRequirement { /// rasterization-rate map data a case can author only as bytes, which hold one /// implementation's private layout where the engine's module decodes this crate's, and a /// depth outside `[0, 1]` a case gives a depth image, which the runtime puts nowhere - /// ([`ToolingRequirement::DepthOutsideUnitRange`]), and a mesh render pipeline or a replayed - /// template it does not draw or replay ([`ToolingRequirement::MeshRenderPipeline`], - /// [`ToolingRequirement::ReplayedTemplateResources`]), and a texture buffer an argument + /// ([`ToolingRequirement::DepthOutsideUnitRange`]), and a mesh render pipeline it does not + /// draw ([`ToolingRequirement::MeshRenderPipeline`]), and a texture buffer an argument /// buffer or a texture-handle array holds ([`ToolingRequirement::TextureBufferMember`]), /// and a sequentially consistent fence, a render function's function table, an indexed draw /// past its index buffer, a 64-bit texture atomic and separate depth and stencil attachments, @@ -462,7 +452,6 @@ impl ToolingRequirement { | Self::DepthOutsideUnitRange | Self::MeshRenderPipeline | Self::TextureBufferMember - | Self::ReplayedTemplateResources | Self::SeqCstFence | Self::RenderFunctionTable | Self::IndexBufferPastEnd diff --git a/crates/metal2vulkan-validation/src/worker/compile.rs b/crates/metal2vulkan-validation/src/worker/compile.rs index 9c6113512..8d3d8791a 100644 --- a/crates/metal2vulkan-validation/src/worker/compile.rs +++ b/crates/metal2vulkan-validation/src/worker/compile.rs @@ -753,8 +753,6 @@ mod tests { argument_buffer_buffers: Default::default(), argument_buffer_textures: Default::default(), argument_buffer_samplers: Default::default(), - objects: Default::default(), - command_buffers: Default::default(), textures: [( 0, crate::literal::LiteralTexture { @@ -783,7 +781,6 @@ mod tests { function: RequestFunction::new(case.entry.as_str(), case.constants.clone()), shape: shape.clone(), dispatch: None, - replay: false, }; let (bytes, digest) = input(&device, &bitcode, request.clone()); let (output, artifact) = served(&bytes, Instant::now()).unwrap(); @@ -855,7 +852,6 @@ mod tests { ) .unwrap(), ), - form: crate::candidate::engine::variants::DrawForm::Bound, }; let (bytes, digest) = input(&device, &bitcode, request.clone()); let (output, artifact) = served(&bytes, Instant::now()).unwrap(); @@ -969,7 +965,6 @@ mod tests { }, shape: BindShape::default(), dispatch: None, - replay: false, }; let libraries = [caller.as_slice(), functions.as_slice(), caller.as_slice()]; let (bytes, digest) = libraries_input(&device, &libraries, request.clone()); diff --git a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs index 88d911156..e4aa9acfb 100644 --- a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs +++ b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs @@ -305,9 +305,7 @@ fn the_census_refuses_command_buffer_cases_by_their_requirements() { #[test] fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() { use metal2vulkan_validation::authored_compile::compile_case; - use metal2vulkan_validation::candidate::engine::{ - case_compiles, prepare_case, prepare_compile, CompileSubject, - }; + use metal2vulkan_validation::candidate::engine::{case_compile, prepare_case, prepare_compile}; use metal2vulkan_validation::check::admission::{ admit, ExecutionRequest, ExecutorError, NotSupported, }; @@ -348,17 +346,7 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() { ); let prepared = prepare_compile(device, admitted()) .unwrap_or_else(|error| panic!("{name}: preparation: {error}")); - let planned = case_compiles(&prepared, &lavapipe).unwrap(); - assert_eq!(planned.host_replayed, 0, "{name}"); - assert_eq!( - planned - .compiles - .iter() - .map(|compile| compile.subject) - .collect::>(), - [CompileSubject::Case], - "{name}" - ); + case_compile(&prepared, &lavapipe).unwrap(); let cells = compile_case(scratch.path(), &worker, &case, &[&lavapipe]); assert_eq!(cells.len(), 1, "{name}"); assert_eq!( diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 60224772d..fa35c8292 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -491,7 +491,8 @@ cargo run -p metal2vulkan-validation --release --bin corpus-vulkan -- \ inherit the encoder's buffers `indirect_command_inheritance`, a command the host encodes `host_encoded_indirect_commands`, and a pipeline state an argument buffer holds, which the runtime gives no `gpuResourceID`, `argument_buffer_pipeline_state`: each the runtime's limit, - run on Metal alone. A pixel format the runtime makes no image of on the device records `not_enabled`, as + run on Metal alone. A command buffer of the runtime's form is refused as not implemented + (`executor_not_implemented`): the executor does not route one yet. A pixel format the runtime makes no image of on the device records `not_enabled`, as the executor's own context records a format its query lacks. A vertex or fragment case of any sample count draws through the runtime the same way (`engine::runs_render_through_runtime`): its own stage's buffers, bound textures and samplers, argument buffers of buffers, textures and samplers @@ -515,9 +516,8 @@ cargo run -p metal2vulkan-validation --release --bin corpus-vulkan -- \ `not_supported{uncontained:unchecked vertex_input}`. A rasterization-disabled vertex case renders into the oracle's 1x1 `R8Unorm` attachment, and a fragment case of no attachment into the oracle's pass of none: `renderTargetWidth` and `renderTargetHeight` 1, `defaultRasterSampleCount` - the case's samples. Layered rendering, an indirect command buffer, a patch index buffer or an - out-of-bounds target other than an attribute buffer keeps the case on the executor's own - context. A vertex buffer's dynamic stride carries `dynamic_vertex_stride` and a fragment + the case's samples. Layered rendering, a patch index buffer or an out-of-bounds target other + than an attribute buffer keeps the case on the executor's own context. A vertex buffer's dynamic stride carries `dynamic_vertex_stride` and a fragment function's imageblock `fragment_imageblock`, each the runtime's limit. An indexed draw past its index buffer, which the runtime refuses as Metal's validation does (`Refusal::IndexBufferOffset`), carries `index_buffer_past_end`, and a depth/stencil attachment