diff --git a/crates/metal2vulkan-conformance/src/degradation.rs b/crates/metal2vulkan-conformance/src/degradation.rs index 17f296d2d..e2a72de10 100644 --- a/crates/metal2vulkan-conformance/src/degradation.rs +++ b/crates/metal2vulkan-conformance/src/degradation.rs @@ -115,10 +115,6 @@ pub enum Degradation { HalfOutputPrecision, /// `metal2vulkan-degrade-extended-range-blend-source`. ExtendedRangeBlendSource, - /// `metal2vulkan-degrade-discard-drops-simdgroup-stores`. - DiscardDropsSimdgroupStores, - /// `metal2vulkan-degrade-helper-branch-drops-simdgroup-stores`. - HelperBranchDropsSimdgroupStores, /// `metal2vulkan-degrade-extended-range-float-blend-source`. ExtendedRangeFloatBlendSource, /// `metal2vulkan-degrade-anisotropic-filter`. @@ -242,8 +238,6 @@ impl Degradation { Degradation::ArgumentPixelSamplerScaling, Degradation::HalfOutputPrecision, Degradation::ExtendedRangeBlendSource, - Degradation::DiscardDropsSimdgroupStores, - Degradation::HelperBranchDropsSimdgroupStores, Degradation::ExtendedRangeFloatBlendSource, Degradation::AnisotropicFilter, Degradation::DeviceAnisotropicFilter, @@ -360,12 +354,6 @@ impl Degradation { Degradation::ExtendedRangeBlendSource => { "metal2vulkan-degrade-extended-range-blend-source" } - Degradation::DiscardDropsSimdgroupStores => { - "metal2vulkan-degrade-discard-drops-simdgroup-stores" - } - Degradation::HelperBranchDropsSimdgroupStores => { - "metal2vulkan-degrade-helper-branch-drops-simdgroup-stores" - } Degradation::ExtendedRangeFloatBlendSource => { "metal2vulkan-degrade-extended-range-float-blend-source" } @@ -469,10 +457,6 @@ impl Degradation { PrecisionNote::ArgumentPixelSamplerScaling => Degradation::ArgumentPixelSamplerScaling, PrecisionNote::HalfOutputPrecision => Degradation::HalfOutputPrecision, PrecisionNote::ExtendedRangeBlendSource => Degradation::ExtendedRangeBlendSource, - PrecisionNote::DiscardDropsSimdgroupStores => Degradation::DiscardDropsSimdgroupStores, - PrecisionNote::HelperBranchDropsSimdgroupStores => { - Degradation::HelperBranchDropsSimdgroupStores - } PrecisionNote::ExtendedRangeFloatBlendSource => { Degradation::ExtendedRangeFloatBlendSource } diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/README.md b/crates/metal2vulkan-validation/fixtures/public/engine/README.md index 1ba9fe67b..45fb3c537 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/README.md +++ b/crates/metal2vulkan-validation/fixtures/public/engine/README.md @@ -211,11 +211,11 @@ threadgroup's threads); an authored case that executes a loop declares it | `rt6_render_state` | `rt6_full`, `rt6_flip`, `rt6_small`, `rt6_point`, `rt6_white`, `rt6_half` | the functions of a Metal probe on an M4 (macOS 27.0.1): Metal's fullscreen triangle at a depth `z + slope * x` from a buffer, the same triangle in the other winding, a small triangle (with a fourth vertex, a strip over a quad), one point of 4 pixels, and a white and a half-gray fragment | the texels Metal stored in that probe (no authored case) | | `rt6_resolves` | `rt6_resolve_full`, `rt6_resolve_half`, `rt6_resolve_white`, `rt6_resolve_samples`, `rt6_resolve_sample_values`, `rt6_resolve_masked` | the functions of a Metal probe on an M4 (macOS 27.0.1): Metal's fullscreen triangle at a depth `z` from a buffer, half the target (its diagonal pixels half covered), white, two fragments whose values follow `[[sample_id]]`, and white on the samples of a mask from a buffer | the texels Metal resolved in that probe (no authored case) | | `rdw_tile_kept` | `rdw_tile_kept_fill`, `rdw_tile_kept_dump`, `rdw_tile_kept_fill_dump` | tile functions over an explicit imageblock of one `uint4` a cell standing alone (after an `R32Uint` attachment, at byte 16): a fill of word `k` as `seed + k`, a dump of every word, and a fill a word at a dynamic index read back at once, run in passes of fewer imageblock bytes than the state's 32 | the words Metal's probes kept (below the pass's bytes rounded up to 8) and read as zero (no authored case) | -| `rch_guarded_effects` | `rch_guarded_vertex`, `rch_guarded_store`, `rch_guarded_atomic`, `rch_guarded_loop`, `rch_guarded_write`, `rch_guarded_copy`, `rch_guarded_simd` | fragment functions that sample an 8x8 texture repeated over the target, discard where the sampled alpha is below 0.5, and then make side effects: a store, an atomic whose old value picks the slot of a later store, a store in a loop, a texture write, a copy of a pair of vectors, and a store of a simdgroup sum; a vertex function drawing a triangle from three corners | where the discard is predicated (a device without demote; MoltenVK on an Apple GPU, whose store-dropping defect defers it), each side effect runs under `if !discarded` and the atomic's result is zero for a discarded invocation; the simdgroup sum keeps the demote on MoltenVK (`PrecisionNote::DiscardDropsSimdgroupStores`) and is refused needing demote where no whole-quad exit can be placed (`tests::engine_fragment`); every side effect lands at the kept pixels alone | -| `rch_helper_branch` | `rch_helper_branch`, `rch_helper_branch_late`, `rch_helper_branch_gradient`, `rch_helper_branch_unsampled`, `rch_helper_branch_loop` | fragment functions that read a coverage texture, round `half` values in a branch where the coverage is not 1 (where every covered pixel's coverage is 1, only the quad helpers past a primitive's edges take it) and write a buffer after it; they sample at LOD 0 before the branch, also at an implicit LOD after it at the pixel, at a coordinate the branch computes, not at all, or round in a loop as long as the coverage | on MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`) the branch's helper invocations take its empty arm where nothing they compute differently reaches a derivative (census `fragment.helper-guard`), and the gradient and loop functions record `PrecisionNote::HelperBranchDropsSimdgroupStores` (`tests::engine_fragment`); no other device changes them. Apple's compiler loses the live threads' texture writes of a simdgroup whose helpers alone call an `optnone` function there (measured on an M4) | -| `rch_helper_tangle` | `rch_tangle_vertex`, `rch_tangle_sample_after`, `rch_tangle_dfdx_after`, `rch_tangle_quad_after`, `rch_tangle_lod_after`, `rch_tangle_quad_before`, `rch_tangle_sample_before`, `rch_tangle_unread`, `rch_tangle_merge_after`, `rch_tangle_loop_after` | fragment functions that read a coverage texture, sample at LOD 0, round to `half` where only the quad helpers past a primitive's edges run (a branch where the coverage is not 1, or a loop only they repeat) beside a tangled instruction, and write a texture after it: the tangled instruction reads the rounded value after the rounding (in the arm an implicit-LOD sample at it, `dfdx`, `quad_sum`, the LOD query; a sample after the branch's merge; a sample after the loop), comes first reading none of it (`quad_sum`, an implicit-LOD sample), or comes after reading none of it; a vertex function drawing a triangle from three corners | On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`) nothing is guarded; the `after` functions record no `PrecisionNote::HelperBranchDropsSimdgroupStores` and the others record it (`tests::engine_fragment`); no covered pixel's write is lost where no note is recorded | -| `rch_helper_select` | `rch_select_vertex`, `rch_select_arm`, `rch_select_and`, `rch_select_sampled`, `rch_select_uniform` | fragment functions without fast math (every float operation `NoContraction`, which SPIRV-Cross writes through its `optnone` `spvFAdd`) that read a coverage texture, sample at LOD 0 and pick a sum where the coverage is not 1 (only the quad helpers past a primitive's edges do), with no branch: the compiler writes a select, which SPIRV-Cross writes as a `?:` whose arm holds the call; the sum as a component, its comparison on the right of a `&&`, a coordinate an implicit-LOD sample reads after it, or on a constant block's flag; each writes a texture after it; a vertex function drawing a triangle from three corners | On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`) nothing is guarded; `rch_select_arm` and `rch_select_and` are fenced (census `fragment.helper-fence`), or record `PrecisionNote::HelperBranchDropsSimdgroupStores` without a fragment shuffle, and the others are left as they are (`tests::engine_fragment`); no covered pixel's write is lost where no note is recorded | -| `rch_uniform_branch` | `rch_uniform_branch` | a fragment function that, where a constant block's flag says (a branch every invocation of a draw takes alike), divides a coordinate by a texture's size and takes the high word of a product (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes through its `optnone` `spvMulExtended`), then samples the `half` texture through a runtime sampler at the coordinate and writes the sample and the product's lowest bit to a buffer. | On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`): the module holds the product, and no `fragment.helper-guard` census and no `PrecisionNote::HelperBranchDropsSimdgroupStores`; L3 | +| `rch_guarded_effects` | `rch_guarded_vertex`, `rch_guarded_store`, `rch_guarded_atomic`, `rch_guarded_loop`, `rch_guarded_write`, `rch_guarded_copy`, `rch_guarded_simd` | fragment functions that sample an 8x8 texture repeated over the target, discard where the sampled alpha is below 0.5, and then make side effects: a store, an atomic whose old value picks the slot of a later store, a store in a loop, a texture write, a copy of a pair of vectors, and a store of a simdgroup sum; a vertex function drawing a triangle from three corners | where the discard is predicated (a device without demote), each side effect runs under `if !discarded` and the atomic's result is zero for a discarded invocation; the simdgroup sum is refused needing demote where no whole-quad exit can be placed (`tests::engine_fragment`); every side effect lands at the kept pixels alone | +| `rch_helper_branch` | `rch_helper_branch`, `rch_helper_branch_late`, `rch_helper_branch_gradient`, `rch_helper_branch_unsampled`, `rch_helper_branch_loop` | fragment functions that read a coverage texture, round `half` values in a branch where the coverage is not 1 (where every covered pixel's coverage is 1, only the quad helpers past a primitive's edges take it) and write a buffer after it; they sample at LOD 0 before the branch, also at an implicit LOD after it at the pixel, at a coordinate the branch computes, not at all, or round in a loop as long as the coverage | compiled as written on every device. Apple's compiler loses the live threads' texture writes of a simdgroup whose helpers alone call an `optnone` function there (measured on an M4, through SPIRV-Cross's MSL) | +| `rch_helper_tangle` | `rch_tangle_vertex`, `rch_tangle_sample_after`, `rch_tangle_dfdx_after`, `rch_tangle_quad_after`, `rch_tangle_lod_after`, `rch_tangle_quad_before`, `rch_tangle_sample_before`, `rch_tangle_unread`, `rch_tangle_merge_after`, `rch_tangle_loop_after` | fragment functions that read a coverage texture, sample at LOD 0, round to `half` where only the quad helpers past a primitive's edges run (a branch where the coverage is not 1, or a loop only they repeat) beside a tangled instruction, and write a texture after it: the tangled instruction reads the rounded value after the rounding (in the arm an implicit-LOD sample at it, `dfdx`, `quad_sum`, the LOD query; a sample after the branch's merge; a sample after the loop), comes first reading none of it (`quad_sum`, an implicit-LOD sample), or comes after reading none of it; a vertex function drawing a triangle from three corners | compiled as written on every device | +| `rch_helper_select` | `rch_select_vertex`, `rch_select_arm`, `rch_select_and`, `rch_select_sampled`, `rch_select_uniform` | fragment functions without fast math (every float operation `NoContraction`, which SPIRV-Cross writes through its `optnone` `spvFAdd`) that read a coverage texture, sample at LOD 0 and pick a sum where the coverage is not 1 (only the quad helpers past a primitive's edges do), with no branch: the compiler writes a select, which SPIRV-Cross writes as a `?:` whose arm holds the call; the sum as a component, its comparison on the right of a `&&`, a coordinate an implicit-LOD sample reads after it, or on a constant block's flag; each writes a texture after it; a vertex function drawing a triangle from three corners | compiled as written on every device | +| `rch_uniform_branch` | `rch_uniform_branch` | a fragment function that, where a constant block's flag says (a branch every invocation of a draw takes alike), divides a coordinate by a texture's size and takes the high word of a product (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes through its `optnone` `spvMulExtended`), then samples the `half` texture through a runtime sampler at the coordinate and writes the sample and the product's lowest bit to a buffer. | the module holds the product; L3 | | `sps2_residency_probes` | `sps2_residency_probes` | the residency word (`sparse_color::resident()`) and value of a texture's fetch, storage read, nearest and linear sample, and gather at authored coordinates (a probe buffer), on ordinary or sparse textures | `out[2i]` = probe `i`'s value bits, `out[2i + 1]` = `(resident, kind, i, 0x5A5)` | | `spse_level_probes` | `spse_level_probes` | the residency word and value of a 2D texture's fetch at a level, nearest and linear sample at a level, and gather, at authored coordinates (a probe buffer) | `out[2i]` = probe `i`'s value bits, `out[2i + 1]` = `(resident, kind, i, 0x5A5)` | | `spse_array_probes` | `spse_array_probes` | the same of a 2D array texture at a layer and level | `out[2i]` = probe `i`'s value bits, `out[2i + 1]` = `(resident, kind, i, 0x5A5)` | diff --git a/crates/metal2vulkan-validation/src/coverage.rs b/crates/metal2vulkan-validation/src/coverage.rs index 0ccbe15d9..2fee45f52 100644 --- a/crates/metal2vulkan-validation/src/coverage.rs +++ b/crates/metal2vulkan-validation/src/coverage.rs @@ -443,8 +443,7 @@ impl HostClass { /// fetches, past their buffer read or wrote the next buffer's bytes; texel buffer accesses /// were contained. By user decision the product keeps the robust encoding there (no in-shader /// check), as native Metal bounds none of these either. SwiftShader's robustness leaves a - /// storage buffer's atomics uncontained too, but the product checks them in the shader there - /// (`DriverWorkaround::BufferAtomicsUncontained`). Under `robustBufferAccess` its storage + /// storage buffer's atomics uncontained too, below the floor. Under `robustBufferAccess` its storage /// buffer loads and stores and its storage texel buffer atomic add and store were measured /// contained, and OB1's cases (storage, uniform, and texel buffers, and buffer atomics with the /// check) matched. Its vertex-input fetches and index-buffer reads were not measured; like diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs index 49ee878b7..5a8bdd8fa 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs @@ -447,13 +447,6 @@ pub fn containment( ) -> Result { let ModuleFacts { stage, slots, .. } = *module; let robust = robust_check(profile)?; - // A descriptor view's atomic is checked in the shader where the driver's robustness leaves - // buffer atomics uncontained (`DeviceProfile::checks_atomics_in_shader`). - let atomic_check = if profile.checks_atomics_in_shader() { - Check::Shader - } else { - robust - }; let slot = |class, index| { slots .get(&SlotRef { @@ -502,7 +495,7 @@ pub fn containment( BufferForm::Descriptor(view) => { let (form, check) = match view { DescriptorView::Storage if atomic => { - (ContainmentForm::BufferAtomic, atomic_check) + (ContainmentForm::BufferAtomic, robust) } DescriptorView::Storage => (ContainmentForm::StorageBuffer, robust), DescriptorView::UniformWords | DescriptorView::UniformVec4 => { @@ -678,8 +671,8 @@ pub fn containment( } /// The check `profile`'s leg gives every access its compiled modules leave to the device's buffer -/// robustness (the two encodings): a descriptor view's loads and stores (and atomics, unless -/// `DeviceProfile::checks_atomics_in_shader`) and fixed-function vertex input. +/// robustness (the two encodings): a descriptor view's loads, stores and atomics and +/// fixed-function vertex input. /// [`Check::Robust2`] under `robustBufferAccess2`, [`Check::Robust`] under `robustBufferAccess` /// alone, and [`Check::Shader`] without buffer robustness; `Err` for a containment validation /// never compiles (`Containment::UnsafeOff`) or does not know. The only source of diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 46dda57a8..5c610d0f8 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -333,8 +333,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::NativeDot | N::NativeMix | N::DevicePackConversion - | N::DiscardDropsSimdgroupStores - | N::HelperBranchDropsSimdgroupStores | N::UnorderedFetchWithinDraw | N::NativeLogicOperation | N::NativeFloat8 diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 0f00e83fa..164eef5a9 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -2384,17 +2384,12 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result BindError::Unsupported(u), - other => internal(format!("an object function's threadgroup memory: {other}")), - })?; + crate::lower::mesh::stage_workgroup_limit(Stage::Object, profile, payload.map(u64::from)) + .check(u64::from(static_bytes).saturating_add(regions)) + .map_err(|e| match e { + crate::error::Error::Unsupported(u) => BindError::Unsupported(u), + other => internal(format!("an object function's threadgroup memory: {other}")), + })?; } record_specialized(&push, shape, &mut resources)?; record_noted(&p.stages, shape, &mut resources, &heap_reach)?; diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 6a92c8f61..cf49bc774 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1216,7 +1216,7 @@ codec_enum! { } IoInterpolation { Flat, Smooth { sampling, perspective } } IoSampling { Center, Centroid, Sample, Interpolant { center, centroid, sample } } - CoverageLoop { NotNeeded, Looped, Unlooped, Refused(f0), DriverRunsPerSample } + CoverageLoop { NotNeeded, Looped, Unlooped, Refused(f0) } ChannelWrite { Unorm { bits }, Snorm { bits, blended }, Srgb, FloatTowardZero { mantissa, signed }, Device, FloatNearestEven { mantissa, signed }, BlendedNearestEven { mantissa, signed }, @@ -1497,8 +1497,6 @@ codec_enum! { ArgumentPixelSamplerScaling, HalfOutputPrecision, ExtendedRangeBlendSource, - DiscardDropsSimdgroupStores, - HelperBranchDropsSimdgroupStores, ExtendedRangeFloatBlendSource, AnisotropicFilter, DeviceAnisotropicFilter, diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 1dac38ab7..470691fd9 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -194,13 +194,6 @@ impl DeviceProfile { crate::memory::contain::encoding(self) == Check::InShader } - /// Whether a module compiled for this profile checks a buffer atomic in the shader: as - /// [`DeviceProfile::checks_buffers_in_shader`], and also where the driver's robustness leaves a - /// storage buffer's atomics uncontained ([`DriverWorkaround::BufferAtomicsUncontained`]). - pub fn checks_atomics_in_shader(&self) -> bool { - crate::memory::contain::atomic_encoding(self) == Check::InShader - } - /// Whether this profile leaves an out-of-bounds read of an image (`texel_buffer`: of a texel /// buffer) to the device, whose robustness answers Metal's out-of-bounds texel; elsewhere the /// shader checks the read. diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index 248ee9849..f83ad00c7 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -74,8 +74,8 @@ //! access, Mesa's RADV and ANV never showed a relaxed one a store that arrived after its first //! read. //! -//! **Containment** is the plain access's (`contain::atomic_encoding`): robust descriptors emit no -//! check, except on a driver whose robustness leaves buffer atomics uncontained; an in-shader check +//! **Containment** is the plain access's (`contain::encoding`): robust descriptors emit no +//! check; an in-shader check //! guards a view's atomic with `if_(inb)` (its result is 0 out of bounds, where Metal's is //! unmeasured); a device-address atomic out of bounds (a static slot's or a wide pointer's, checked //! against the root entry's size) operates on the write-only sink and yields 0; an arena atomic @@ -697,7 +697,7 @@ pub fn select( } } else { let (mut targets, null) = static_roots(cx, r.ptr, m)?; - let check = contain::atomic_encoding(cx.profile); + let check = contain::encoding(cx.profile); let fixed = super::fixed_offset(cx, r.ptr); for t in &mut targets { t.check = check; diff --git a/crates/metal2vulkan/src/lower/fragment/coverage.rs b/crates/metal2vulkan/src/lower/fragment/coverage.rs index f3292cbee..d7e15e3ab 100644 --- a/crates/metal2vulkan/src/lower/fragment/coverage.rs +++ b/crates/metal2vulkan/src/lower/fragment/coverage.rs @@ -57,15 +57,6 @@ //! pipeline that reads `[[sample_mask]]`, looped or not, or that reads a centroid varying and runs //! once per pixel, records `PrecisionNote::ClippedCoverageSplit` on a device whose rasterizer is //! not Apple's (`DriverWorkaround::ClippedCoverageNotMetals`). -//! -//! MoltenVK on Apple's GPU runs a shader that writes memory once per covered sample, as Metal -//! does, sample shading or not (`DriverWorkaround::MemoryWritingFragmentsRunPerSample`), so the -//! loop of a function that writes memory would repeat each pass there. Such a function is compiled -//! as written there instead (`CoverageLoop::DriverRunsPerSample`), each of the driver's runs -//! reading the pixel's coverage, its sample index and its sample-qualified varyings, with the -//! pipeline's sample shading off; except where MoltenVK's SPIRV-Cross masks the coverage with the -//! run's sample bit (a module with `SampleRateShading` that reads `FragCoord`), where it is refused -//! as the driver's defect. use crate::air::abi::{ Builtin, Interpolation as AirInterp, ParamRole, Sampling as AirSampling, Stage as AirStage, @@ -73,7 +64,7 @@ use crate::air::abi::{ use crate::air::ir::{ArgIdx, Body, Value}; use crate::device::requirements::VkFeature; use crate::device::DriverWorkaround; -use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported}; +use crate::error::{Error, InternalError, InternalKind}; use crate::lower::arith::legal::form_on; use crate::lower::emit::FamilyDecls; use crate::lower::select::{Plan, SelectCx}; @@ -97,13 +88,6 @@ pub struct CoveragePlan { /// Why the function cannot loop, as far as its interface shows before its body is selected: /// its early tests, its attachments, or the device's interpolation functions. pub refusal: Option, - /// The function writes memory, which a driver with - /// `DriverWorkaround::MemoryWritingFragmentsRunPerSample` repeats per covered sample. - pub writes: bool, - /// Such a driver runs the function once per covered sample itself, each run reading the - /// pixel's coverage, so it is compiled as written, without the loop - /// (`CoverageLoop::DriverRunsPerSample`). - pub driver_runs: bool, /// Where the looping function reads a sample-qualified varying: the most samples a pipeline of /// the device may have, at each of which the entry reads every such varying before the loop. pub samples_before_loop: Option, @@ -213,15 +197,6 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { && !p .enabled .portability_withholds(VkFeature::ShaderSampleRateInterpolationFunctions); - // A driver that runs a memory writer once per covered sample hands each run the pixel's - // coverage, unless its shader compiler masks the coverage with the run's sample bit: MoltenVK - // 1.4.1's SPIRV-Cross (`adec7acb`) does where the module declares `SampleRateShading` (it - // reads the sample index or a sample-qualified varying) and reads `FragCoord`. - let position = used(&|r| matches!(r, ParamRole::Builtin(Builtin::Position(_)))); - let driver_runs = writes - && p.workarounds - .contains(&DriverWorkaround::MemoryWritingFragmentsRunPerSample) - && !((sample_id || sample_varying) && position); let attachments = super::rog::declared(cx) || used(&|r| matches!(r, ParamRole::ColorInput { .. } | ParamRole::Imageblock(_))); let refusal = if matches!( @@ -233,12 +208,12 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { Some(CoverageLoopRefusal::EarlyFragmentTests) } else if attachments { Some(CoverageLoopRefusal::Attachments) - } else if sample_varying && !interpolation && !driver_runs { + } else if sample_varying && !interpolation { Some(CoverageLoopRefusal::InterpolationFunctions) } else { None }; - let looped = cx.inputs.multisampled && refusal.is_none() && !driver_runs; + let looped = cx.inputs.multisampled && refusal.is_none(); // Each pass's outputs land on every sample the passes keep, the last pass's (the module docs). if looped && !e.ep.outputs.is_empty() { cx.precision.insert(PrecisionNote::LoopedSampleOutputs); @@ -251,8 +226,6 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.fragment.coverage = Some(CoveragePlan { looped, refusal, - writes, - driver_runs, samples_before_loop, }); Ok(()) @@ -279,10 +252,7 @@ fn most_samples(limits: &crate::device::Limits) -> u32 { /// Complete the plan once every instruction is selected (`fragment::finish`): a discard, or a /// derivative, implicit-LOD sample, quad or simdgroup operation, or barrier, refuses the loop. A /// looping function is refused here; any other records in its interface how link treats it -/// (`StageIo::coverage_loop`). On a driver that runs such a shader once per covered sample -/// (`MemoryWritingFragmentsRunPerSample`) a function that writes memory runs as written, or, where -/// that driver would mask its coverage, is refused as its defect: the loop would repeat each pass -/// per covered sample there. +/// (`StageIo::coverage_loop`). pub(super) fn finish(cx: &mut SelectCx<'_>) -> Result { let Some(plan) = cx.families.fragment.coverage else { return Ok(false); @@ -299,20 +269,11 @@ pub(super) fn finish(cx: &mut SelectCx<'_>) -> Result { } else { None }; - if plan.looped { - if let Some(r) = late { - return Err(r.error()); - } - let per_sample = DriverWorkaround::MemoryWritingFragmentsRunPerSample; - if plan.writes && cx.profile.fields().workarounds.contains(&per_sample) { - return Err( - Unsupported::driver_defect(Feature::PixelCoverageAtSampleRate, per_sample).into(), - ); - } + if let (true, Some(r)) = (plan.looped, late) { + return Err(r.error()); } cx.families.stage_io.interface.coverage_loop = match (plan.looped, plan.refusal.or(late)) { (true, _) => CoverageLoop::Looped, - (false, None) if plan.driver_runs => CoverageLoop::DriverRunsPerSample, (false, None) => CoverageLoop::Unlooped, (false, Some(r)) => CoverageLoop::Refused(r), }; diff --git a/crates/metal2vulkan/src/lower/fragment/discard.rs b/crates/metal2vulkan/src/lower/fragment/discard.rs index 8c16308cc..a7650368d 100644 --- a/crates/metal2vulkan/src/lower/fragment/discard.rs +++ b/crates/metal2vulkan/src/lower/fragment/discard.rs @@ -43,37 +43,6 @@ //! operations. Demote needs no guard: Vulkan helper invocations have no memory side effects and //! their outputs are discarded. //! -//! **A discard before the storage writes, on Apple's compiler**. Where a fragment function discards -//! (`discard_fragment()`, which SPIRV-Cross writes for both a demote and a terminate), then writes -//! a texture, samples a texture through an argument buffer, and calls a `[[clang::optnone]]` -//! function (SPIRV-Cross's `spvFAdd` for an `OpFAdd` decorated `NoContraction`) in a branch only -//! discarded threads enter, Apple's compiler drops the texture writes of every live thread of a -//! simdgroup (8 by 4 pixels) holding a discarded thread: measured in plain Metal on an M4 with -//! macOS 27.0.1 (probes: MoltenVK's MSL of a storage-form fragment of our own lost its writes in -//! whole 8-by-4 blocks; without the sample, with the `optnone` call plain, in straight-line code or -//! in a branch live threads enter too, with direct binding, or with the discard recorded and taken -//! after the write, every write landed, and color outputs landed in every form). MoltenVK binds -//! through argument buffers, and on an Apple GPU it carries -//! `DriverWorkaround::DiscardDropsSimdgroupStores`. There a function meets the -//! defect ([`late_discards`]) where it samples (`sample` at any LOD, or `gather`), and after a site -//! that would discard at once (a demote; a terminate outside an interlock, since inside one it -//! records the discard and returns to the entry) it computes or returns a floating-point value (the -//! lowering may decorate such arithmetic `NoContraction`: `x + -0.0` rounds every narrowed value -//! and color write) and writes storage: a store, atomic or image write (buffer stores and atomics -//! are not measured, and are counted), or the storage images its entry writes at its returns (a -//! storage-form color, an imageblock, a shader-side stencil's shadow, an in-shader depth test's -//! stand-in). A function that writes colors alone keeps its forms. In such a function those sites -//! are predicated where predication holds (no store, atomic, image write or non-quad subgroup -//! operation after such a site): the discarded invocation runs on, as Metal's discarded thread -//! does, a lane of its quad, its outputs dropped and its storage writes at the returns skipped, and -//! it is killed once past them, after the critical section. Its census names its discards -//! `fragment.discard.deferred`. Where some such site cannot be predicated (the side-effect guard, -//! is not threaded through the access and texture emitters yet), the function keeps its forms and -//! records `PrecisionNote::DiscardDropsSimdgroupStores`: its storage writes may be lost as the -//! defect loses them. The defect needs no discard: the quad helpers past a primitive's edges meet -//! it alone, and the emitted module keeps every helper invocation, a demoted one included, out of -//! the branches that hold such a call where that is exact (`spirv::helper_branches`). -//! //! **A quad of helpers alone**. Metal drops a quad whose every thread is discarded from the //! simdgroup. Vulkan leaves that to the implementation: one whose four invocations are all helpers //! "may" be terminated, and under `RequireFullQuadsKHR` lavapipe keeps such a quad a lane of a @@ -96,7 +65,6 @@ use crate::air::ir::{ use crate::budget::Meter; use crate::device::requirements::VkFeature; use crate::device::subgroup::OpBits; -use crate::device::DriverWorkaround; use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported}; use crate::lower::select::SelectCx; use crate::lower::simd::uniform::Uniformity; @@ -127,9 +95,6 @@ impl Reach { const TANGLED: u8 = 1; const NON_QUAD: u8 = 2; const SIDE_EFFECT: u8 = 4; - /// A floating-point value computed or returned: where the lowering may emit arithmetic - /// decorated `NoContraction` (`late_discards`). - const FLOAT: u8 = 8; fn has(self, bit: u8) -> bool { self.0 & bit != 0 @@ -159,30 +124,12 @@ fn is_thread_ptr(cx: &SelectCx<'_>, v: Value) -> bool { }) } -/// Whether type `ty` holds a floating-point value (a scalar, or one in a vector, array or -/// struct). -fn floating(cx: &SelectCx<'_>, ty: TypeId) -> bool { - match cx.entry.module.types().get(ty) { - Some(Type::Half | Type::BFloat | Type::Float | Type::Double) => true, - Some(Type::Vector { elem, .. } | Type::Array { elem, .. }) => floating(cx, *elem), - Some(Type::Struct { fields, .. }) => fields.iter().any(|&f| floating(cx, f)), - _ => false, - } -} - /// What instruction `id` itself contributes. fn contribution(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> Reach { let mut r = 0u8; if cx.values.inst(id).is_some_and(|v| cx.tangled.contains(&v)) { r |= Reach::TANGLED; } - let returned = match inst.kind { - InstKind::Ret(Some(v)) => cx.value_ty(v).is_some_and(|t| floating(cx, t)), - _ => false, - }; - if returned || floating(cx, inst.ty) { - r |= Reach::FLOAT; - } r |= match &inst.kind { InstKind::Store { ptr, .. } if !is_thread_ptr(cx, *ptr) => Reach::SIDE_EFFECT, InstKind::AtomicRmw { .. } | InstKind::CmpXchg { .. } => Reach::SIDE_EFFECT, @@ -380,12 +327,6 @@ pub(super) struct DiscardPlan { pub forms: BTreeMap, pub quad_exits: BTreeSet, pub counted_before: bool, - /// The sites that would discard at once were predicated against the store-dropping defect - /// ([`late_discards`]). - pub deferred: bool, - /// The function meets the store-dropping defect and some such site could not be predicated: - /// it keeps its forms (`PrecisionNote::DiscardDropsSimdgroupStores`). - pub exposed: bool, /// The side effects a predicated site reaches, each run only where the invocation was not /// discarded ([`guarded`]). pub guarded: BTreeSet, @@ -529,53 +470,6 @@ fn quad_exits_hold( Ok(held) } -/// Whether the function meets the store-dropping defect (the module docs): its driver has -/// `DriverWorkaround::DiscardDropsSimdgroupStores`; it samples; a floating-point value is -/// computed or returned after some site of `exposed` (each with what is reachable after it), -/// where the lowering may emit the `NoContraction` arithmetic the defect needs; and a storage -/// write follows such a site: a store, atomic or image write, or one the entry makes at its -/// returns ([`stores_at_return`]). -fn late_discards(cx: &SelectCx<'_>, body: &Body, exposed: &[(InstId, Reach)]) -> bool { - cx.profile - .fields() - .workarounds - .contains(&DriverWorkaround::DiscardDropsSimdgroupStores) - && exposed.iter().any(|(_, r)| r.has(Reach::FLOAT)) - && (stores_at_return(cx) || exposed.iter().any(|(_, r)| r.has(Reach::SIDE_EFFECT))) - && samples(body) -} - -/// Whether the function writes storage images at its returns, past every discard site: a color -/// attachment it writes in the storage form, its imageblock, a shader-side stencil's shadow, or an -/// in-shader depth test's stand-in. -fn stores_at_return(cx: &SelectCx<'_>) -> bool { - let fp = &cx.families.fragment; - fp.fetch - .values() - .any(|c| c.writes && !c.view.stores_nothing()) - || fp.imageblock.is_some() - || fp.stencil.is_some() - || fp.depth_test.is_some() -} - -/// Whether the function samples a texture through a sampler (`sample`, at any LOD or with -/// gradients, or `gather`), which the store-dropping defect needs ([`late_discards`]). -fn samples(body: &Body) -> bool { - body.insts.values().any(|inst| match &inst.kind { - InstKind::Call(call) => matches!( - &call.callee, - Callee::Air { - op: AirIntrinsic::Texture(t), - .. - } if matches!( - t.op, - TexOp::Sample { .. } | TexOp::SampleGrad { .. } | TexOp::Gather { .. } - ) - ), - _ => false, - }) -} - /// Decide the form of every discard site in `sites`, and where whole quads exit. `interlocked`: the /// function runs inside an interlock. pub(super) fn plan( @@ -664,34 +558,6 @@ pub(super) fn plan( } planned.forms.insert(site, form); } - // On a driver whose compiler drops a simdgroup's live threads' storage writes where one of - // them discards, a function that meets the defect discards no thread before those writes - // (the module docs): each site that would discard at once (a demote, or a terminate outside - // an interlock; inside one a terminate records the discard and returns to the entry) is - // predicated where that holds, and else the function keeps its forms, recorded. - let exposed: Vec<(InstId, Reach)> = placed - .iter() - .zip(&after) - .filter(|((site, _), _)| match planned.forms.get(site) { - Some(DiscardForm::Demote) => true, - Some(DiscardForm::Terminate) => !interlocked, - _ => false, - }) - .map(|(&(site, _), &r)| (site, r)) - .collect(); - if late_discards(cx, body, &exposed) { - // A side effect after a site is guarded; a non-quad subgroup operation stops the - // predicate (the module docs). - let held = exposed.iter().all(|(_, r)| !r.has(Reach::NON_QUAD)); - if held { - for (site, _) in exposed { - planned.forms.insert(site, DiscardForm::Predicate); - } - planned.deferred = true; - } else { - planned.exposed = true; - } - } // Every side effect a predicated site reaches runs only where the invocation was not // discarded. No such site reaches a non-quad subgroup operation here, so no asynchronous // copy either. diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index 8cdeb4f29..a650d83cd 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -127,14 +127,7 @@ //! (`StorageAttachmentUse::view`). Either needs `sampleRateShading`. The pixel interlock orders //! every invocation covering the pixel, and so each sample's. A returned sample mask keeps an //! invocation's write exactly when it sets the invocation's sample's bit (measured), so each write -//! is gated on that bit ([`sample_bit`]); at one sample on bit 0 (measured). A driver that drops -//! the image writes of an early-tests fragment shader in a multisampled pass -//! (`DriverWorkaround::EarlyTestsDropMultisampledImageWrites`: MoltenVK on Apple's GPU) refuses the -//! per-sample form's writes where the module declares early tests (`Needs::DriverDefect`). Where -//! only a depth or stencil attachment would have the module declare them, it declares none there: -//! it stores before the tests and states `TestedStorageWrites` without the early-tests variant, so -//! only a draw whose tests drop no fragment runs it; a function whose Metal source declares early -//! tests keeps the refusal. +//! is gated on that bit ([`sample_bit`]); at one sample on bit 0 (measured). //! //! **A write mask** short of the format's channels: Metal keeps the channels the mask leaves out. //! The write reads the texel at the pixel first and writes those channels back as it read them @@ -316,7 +309,6 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::air::abi::{AbiInt, OutputRole, ParamRole}; use crate::air::intrinsics::{AirIntrinsic, Fragment, PackDir, PackFormat}; use crate::air::ir::{Callee, InstKind, Type as AirType, TypeId as AirTypeId, Value}; -use crate::device::profile::DriverWorkaround; use crate::device::requirements::{FormatUsage, VkFeature}; use crate::device::DeviceProfile; use crate::error::{ @@ -1198,16 +1190,6 @@ pub(crate) fn storage_form( } let kept = crate::metal::state::color_write_mask(kept)?; let f = p.fields(); - // The per-sample form's writes are storage image writes of the fragment shader; where it - // declares early tests, a driver that drops such writes in a pass of more than one sample - // would lose every one. - let defect = DriverWorkaround::EarlyTestsDropMultisampledImageWrites; - if multisampled && writes && use_.early_tests && f.workarounds.contains(&defect) { - return Ok(Err(Unsupported::driver_defect( - Feature::FramebufferFetch, - defect, - ))); - } // What the form needs whatever view it takes, and what the view's own route lacks. let mut common = Vec::new(); let mut route = Vec::new(); @@ -1397,25 +1379,23 @@ struct StoredBeforeTests { /// Only its discard keeps the function from early tests: its stores are Metal's where a /// draw's tests drop no fragment, and under early tests where they write and count nothing. tested: bool, - /// It writes other memory, or returns depth, stencil, or a sample mask, or early tests would - /// lose its writes (`dropped`): its stores are Metal's only where a draw's tests drop no - /// fragment. + /// It writes other memory, or returns depth, stencil, or a sample mask: its stores are Metal's + /// only where a draw's tests drop no fragment. untested: bool, } /// [`StoredBeforeTests`] of a function whose body holds `body`, that Metal runs under early tests /// where `declared_early` and returns depth, stencil, or a sample mask where `exports`, in a -/// pipeline with a depth or stencil attachment where `depth_or_stencil`, where early tests would -/// drop its storage writes where `dropped`. +/// pipeline with a depth or stencil attachment where `depth_or_stencil`. fn stored_before_tests( body: &BodyFacts, (declared_early, exports): (bool, bool), - (depth_or_stencil, dropped): (bool, bool), + depth_or_stencil: bool, ) -> StoredBeforeTests { let testable = depth_or_stencil && !(exports || body.side_effects); StoredBeforeTests { tested: !declared_early && testable && body.discards, - untested: !declared_early && depth_or_stencil && (exports || body.side_effects || dropped), + untested: !declared_early && depth_or_stencil && (exports || body.side_effects), } } @@ -1601,48 +1581,18 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { // declaration would change nothing, and it is left out: Apple's GPU drops the image writes // of an early-tests fragment shader in a pass of more than one sample. let testable = inputs.depth_or_stencil && !(exports || body.side_effects); - // A driver that drops the image writes of an early-tests fragment shader in a pass of more - // than one sample would lose every storage write of a function that writes a fetched color - // beside a depth or stencil attachment under early tests: such a function declares none (unless - // Metal's does), and stores before the tests, Metal's where its draws' tests drop no fragment; - // it has no early-tests variant. (its form checks the driver's defect itself, and the device - // blends it where that blocks it) - let writes_read = read.iter().any(|&color| { - outputs.iter().any(|o| { - matches!( - o.role, - OutputRole::RenderTarget { - attachment: AbiInt::Const(a), - index: 0, - .. - } if a == color - ) - }) - }); - let dropped = cx.inputs.multisampled - && inputs.depth_or_stencil - && writes_read - && cx - .profile - .fields() - .workarounds - .contains(&DriverWorkaround::EarlyTestsDropMultisampledImageWrites); // A function that only its discard keeps from early tests, on a device that requires ordered // fetch (`tested`): its storage writes are Metal's where its draws' tests drop no fragment, // before the tests, and where they write neither attachment and count no visibility result, // under early tests (`LoweringInputs::read_only_tests`), which then drop no fragment Metal's // later tests keep and leave the attachments as Metal's do; the plan of each draw checks // which (`RuntimeFact::TestedStorageWrites`). One that writes other memory, or returns depth, - // stencil, or a sample mask, beside a depth or stencil attachment, or whose driver would drop - // its writes under early tests (`untested`): Metal runs its memory writes for every fragment, + // stencil, or a sample mask, beside a depth or stencil attachment (`untested`): Metal runs its memory writes for every fragment, // those its tests then drop included, and tests what it returns (measured on Apple's M4), which // early tests would not, so its storage writes before the tests are Metal's where its draws' // tests drop no fragment, which the plan of each draw checks; it has no early-tests variant. - let StoredBeforeTests { tested, untested } = stored_before_tests( - &body, - (declared_early, exports), - (inputs.depth_or_stencil, dropped), - ); + let StoredBeforeTests { tested, untested } = + stored_before_tests(&body, (declared_early, exports), inputs.depth_or_stencil); let early_tests = declared_early || (testable && !body.discards && !untested) || (tested && cx.inputs.read_only_tests && !untested); diff --git a/crates/metal2vulkan/src/lower/fragment/imageblock.rs b/crates/metal2vulkan/src/lower/fragment/imageblock.rs index 493752747..da464c3bd 100644 --- a/crates/metal2vulkan/src/lower/fragment/imageblock.rs +++ b/crates/metal2vulkan/src/lower/fragment/imageblock.rs @@ -64,7 +64,6 @@ use crate::air::abi::{ImageblockArg, ImageblockKind, Member, OutputRole, StructI use crate::air::container::Hash256; use crate::air::ir::{ArgIdx, Type, TypeId as AirTypeId, Value}; use crate::device::requirements::VkFeature; -use crate::device::DriverWorkaround; use crate::error::{Capability, Error, Feature, Unsupported}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; @@ -150,10 +149,6 @@ pub struct ImageblockPlan { /// The module declares early fragment tests, which the function does not, so that a depth or /// stencil test the fragment fails drops its write as Metal's does ([`plan_tests`]). pub early_tests: bool, - /// The module declares no early fragment tests, which the function does: its draws test - /// before its write as each one's plan chooses, on a driver that would drop its writes under - /// early tests ([`plan_tests`]). - pub late_tests: bool, } /// An upper estimate of the words one view's members add (each leaf read or written, and a @@ -522,16 +517,8 @@ fn declared_early(cx: &SelectCx<'_>) -> bool { /// early tests (where only a discard kept them away, `early_variant`), and one whose depth test /// acts the variant that runs the draw's depth test itself, before the write /// (`depth_test`), and its stencil test too where that acts (`bind::graphics`). -/// -/// A driver that drops every image write of an early-tests fragment shader in a pass of more than -/// one sample (`DriverWorkaround::EarlyTestsDropMultisampledImageWrites`, MoltenVK on Apple's -/// GPU) takes no early tests at more than one sample: the function's draws test in the shader -/// there, and one that declares early tests itself is refused as that defect. fn plan_tests(cx: &mut SelectCx<'_>) -> Result { - let defect = DriverWorkaround::EarlyTestsDropMultisampledImageWrites; - let drops = cx.inputs.multisampled && cx.profile.fields().workarounds.contains(&defect); - let declared = declared_early(cx); - if declared && !drops { + if declared_early(cx) { return Ok(false); } let outputs = &cx.entry.ep.outputs; @@ -545,20 +532,6 @@ fn plan_tests(cx: &mut SelectCx<'_>) -> Result { let exported = exports.depth.is_some() || exports.stencil.is_some() || exports.mask.is_some(); let body = super::fetch::body_facts(cx); let only_outputs = !exported && !body.side_effects; - if declared { - // Metal tests such a function early. One whose only effects are its outputs and its - // write, which does not discard, leaves the attachments under late tests as under early - // ones, so where the driver's defect would drop its writes the module declares none and - // its draws test before the write as below. Another (a discard, an export, or other - // memory writes after its early tests) has no form here. - if !only_outputs || body.discards { - return Err(Unsupported::driver_defect(Feature::Imageblocks, defect).into()); - } - if let Some(plan) = cx.families.fragment.imageblock.as_mut() { - plan.late_tests = true; - } - } - let only_outputs = only_outputs && !drops; let fp = &cx.families.fragment; // A framebuffer fetch's storage form that declares early tests holds the function to them, // which keeps the write Metal's: it declares them only where the function would here. @@ -572,21 +545,13 @@ fn plan_tests(cx: &mut SelectCx<'_>) -> Result { RuntimeFact::TestedStorageWrites { early_variant, .. } => Some(early_variant), _ => None, }); - match stated { - // The storage form's early-tests variant (whose function writes no other memory and - // exports nothing) would lose this write to the driver's defect. - Some(true) if drops => { - return Err(Unsupported::driver_defect(Feature::Imageblocks, defect).into()); - } - Some(_) => {} - None => { - cx.facts.insert(RuntimeFact::TestedStorageWrites { - early_tests: only_outputs && cx.inputs.read_only_tests, - early_variant: only_outputs, - }); - if cx.inputs.shader_tests && cx.families.fragment.depth_test.is_none() { - super::depth_test::plan(cx, exports)?; - } + if stated.is_none() { + cx.facts.insert(RuntimeFact::TestedStorageWrites { + early_tests: only_outputs && cx.inputs.read_only_tests, + early_variant: only_outputs, + }); + if cx.inputs.shader_tests && cx.families.fragment.depth_test.is_none() { + super::depth_test::plan(cx, exports)?; } } Ok(stated.is_none() && only_outputs && cx.inputs.read_only_tests) diff --git a/crates/metal2vulkan/src/lower/fragment/input_shadow.rs b/crates/metal2vulkan/src/lower/fragment/input_shadow.rs index 8dbfda92a..ad7f33b16 100644 --- a/crates/metal2vulkan/src/lower/fragment/input_shadow.rs +++ b/crates/metal2vulkan/src/lower/fragment/input_shadow.rs @@ -36,7 +36,6 @@ use std::collections::BTreeMap; use crate::air::abi::{AbiInt, OutputRole, Stage as AbiStage}; -use crate::device::profile::DriverWorkaround; use crate::device::requirements::{FormatUsage, VkFeature}; use crate::device::DeviceProfile; use crate::error::{Attachment, Capability, Error, Feature, RuntimeInput, Unsupported}; @@ -209,13 +208,7 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { // tests (see the module docs). let stores = planned.values().any(InputShadow::stores); if inputs.depth_or_stencil && stores && !declared_early { - let dropped = multisampled - && cx - .profile - .fields() - .workarounds - .contains(&DriverWorkaround::EarlyTestsDropMultisampledImageWrites); - if exports || body.discards || body.side_effects || dropped { + if exports || body.discards || body.side_effects { let color = planned.keys().next().copied().unwrap_or_default(); return Err(refused(color)); } diff --git a/crates/metal2vulkan/src/lower/fragment/mod.rs b/crates/metal2vulkan/src/lower/fragment/mod.rs index 23b1173ec..f2a576ea7 100644 --- a/crates/metal2vulkan/src/lower/fragment/mod.rs +++ b/crates/metal2vulkan/src/lower/fragment/mod.rs @@ -156,9 +156,6 @@ pub enum FragmentStrategy { impl FamilyStrategy for FragmentStrategy { fn name(&self, plans: &FamilyPlans) -> Cow<'static, str> { Cow::Borrowed(match self { - FragmentStrategy::Discard if plans.fragment.deferred_discards => { - "fragment.discard.deferred" - } FragmentStrategy::Discard => "fragment.discard", FragmentStrategy::NumSamples(_) => "fragment.num_samples", FragmentStrategy::IsHelperThread => "fragment.is_helper_thread", @@ -191,10 +188,6 @@ pub struct FragmentPlan { /// or a helper exits, as Metal drops such a quad from the simdgroup: every site is then /// predicated, or, where a side effect follows one, every site demotes. Filled by [`finish`]. pub quad_exits: BTreeSet, - /// The sites that would discard at once are predicated against the driver's store-dropping - /// defect (`DriverWorkaround::DiscardDropsSimdgroupStores`), so the census names the - /// function's discards `fragment.discard.deferred`. Filled by [`finish`]. - pub deferred_discards: bool, /// The stores, atomics, image writes and copies a predicated site reaches: each runs only /// where the invocation was not discarded ([`not_discarded`]). Filled by [`finish`]. pub guarded: BTreeSet, @@ -387,18 +380,12 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { forms, quad_exits, counted_before, - deferred, - exposed, guarded, } = discard::plan(cx, &sites, interlock.is_some(), m)?; if counted_before { cx.precision .insert(PrecisionNote::QuadsCountedBeforeDiscard); } - if exposed { - cx.precision - .insert(PrecisionNote::DiscardDropsSimdgroupStores); - } if !quad_exits.is_empty() { // The exits' quad swaps are quad operations of the simd family's class. let simd = &mut cx.families.simd; @@ -457,7 +444,6 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { let fp = &mut cx.families.fragment; fp.discards = forms; fp.quad_exits = quad_exits; - fp.deferred_discards = deferred; fp.guarded = guarded; fp.terminate_invocation = terminate; fp.interlock = interlock; @@ -515,10 +501,6 @@ pub fn declare( if fp.fetch_early_tests || imageblock_early { modes.push(ExecMode::EarlyFragmentTests); } - // The function's own early tests, where the imageblock's write tests late instead. - if fp.imageblock.as_ref().is_some_and(|p| p.late_tests) { - modes.retain(|m| *m != ExecMode::EarlyFragmentTests); - } if fp.records_discards() { let bool_ = mb.ty(SType::Bool)?; let no = mb.constant(Constant::Scalar { diff --git a/crates/metal2vulkan/src/lower/mesh/mod.rs b/crates/metal2vulkan/src/lower/mesh/mod.rs index 8b5de11a2..f5d5debbb 100644 --- a/crates/metal2vulkan/src/lower/mesh/mod.rs +++ b/crates/metal2vulkan/src/lower/mesh/mod.rs @@ -53,14 +53,8 @@ //! A point mesh whose vertex type has no `point_size` culls every primitive (Metal draws none); //! it still writes `PointSize = 1.0` for each vertex, which a point topology needs. //! -//! **Staged indices.** On a driver that misplaces a store into one component of an index vector -//! (`DriverWorkaround::MeshIndexComponentStoresMisplaced`: lavapipe before Mesa 26.2), a line or -//! triangle mesh keeps its indices in workgroup words, one per index ([`Declared::staged`]): the -//! wrapper zeroes them where it would zero the indices, `set_index` and `set_indices` store into -//! them, and after the body each invocation writes its slots' indices whole, one vector per -//! primitive. They count among the wrapper's workgroup words ([`workgroup_limit`]). The wrapper's -//! words (the grid, the count, the staged indices) take the function's coherence of shared -//! memory (`NonPrivatePointer` under the Vulkan model), so its barriers order them. +//! The wrapper's words (the grid, the count) take the function's coherence of shared memory +//! (`NonPrivatePointer` under the Vulkan model), so its barriers order them. //! //! Each `set_*` writes straight to its output array: `set_position`, `set_point_size`, //! `set_clip_distance` and `set_vertex_data` at their vertex, `set_primitive_culled`, @@ -120,7 +114,6 @@ use crate::air::intrinsics::{AirIntrinsic, Elem, MemFlags, Mesh as MeshOp, NumTy use crate::air::ir::{Callee, Const, Inst, InstId, InstKind, Value}; use crate::air::Entry; use crate::bind::mesh_arguments::{METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL}; -use crate::device::profile::DriverWorkaround; use crate::device::requirements::{VkExtension, VkFeature, VkLimit}; use crate::device::DeviceProfile; use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported}; @@ -251,10 +244,6 @@ pub struct MeshPlan { pub outputs: Vec, /// A point mesh whose vertex type has no `point_size`: it draws nothing (the module docs). pub unsized_points: bool, - /// A line or triangle mesh on a driver that misplaces a store into one component of an - /// index vector (`DriverWorkaround::MeshIndexComponentStoresMisplaced`): its indices are - /// workgroup words ([`Declared::staged`]) that the wrapper writes to the indices whole. - pub staged_indices: bool, /// An object or mesh function on a device without `VK_EXT_mesh_shader`: a `GLCompute` /// entry, an object function writing its grid and payload to its slot of the draw's work /// buffer and a mesh function its outputs as records ([`records`], the module docs). @@ -441,21 +430,14 @@ pub fn payload_extent(cx: &SelectCx<'_>) -> Option { Some(own.max(object)) } -/// The workgroup memory limit of the entry ([`stage_workgroup_limit`] of its stage, payload and -/// staged indices). +/// The workgroup memory limit of the entry ([`stage_workgroup_limit`] of its stage and payload). pub fn workgroup_limit(cx: &SelectCx<'_>) -> WorkgroupLimit { - stage_workgroup_limit( - cx.stage, - cx.profile, - payload_extent(cx), - staged_index_bytes(cx), - ) + stage_workgroup_limit(cx.stage, cx.profile, payload_extent(cx)) } /// The workgroup memory limit of a `stage` entry on `profile` ([`arena::workgroup_limit`]), with /// its payload arena's bytes where it has a payload of `payload` bytes (`arena::payload_bytes`): -/// an object or mesh entry's workgroup memory and payload share a limit. `staged` is a mesh -/// entry's staged index words' bytes ([`staged_index_bytes`]). An emulated object or mesh +/// an object or mesh entry's workgroup memory and payload share a limit. An emulated object or mesh /// function's is the compute stage's, with its grid or count words and its payload. The binder /// checks an object function's arena with the encoder's lengths against it /// (`RuntimeFact::ObjectThreadgroupArena`). @@ -463,7 +445,6 @@ pub fn stage_workgroup_limit( stage: Stage, profile: &DeviceProfile, payload: Option, - staged: u64, ) -> WorkgroupLimit { let limits = &profile.fields().limits; // An emulated entry's: the compute stage's, with its wrapper's words (an object function's @@ -478,38 +459,12 @@ pub fn stage_workgroup_limit( }; } let w = arena::workgroup_limit(stage, limits); - let w = WorkgroupLimit { - wrapper: w.wrapper.saturating_add(staged), - ..w - }; match payload { Some(size) => w.with_payload(arena::payload_bytes(size)), None => w, } } -/// The bytes of the workgroup words a mesh entry keeps its indices in on a driver that misplaces -/// a store into one component of an index vector -/// (`DriverWorkaround::MeshIndexComponentStoresMisplaced`, [`MeshPlan::staged_indices`]): a word -/// per index of a line or triangle mesh there, and none elsewhere. -fn staged_index_bytes(cx: &SelectCx<'_>) -> u64 { - let defect = DriverWorkaround::MeshIndexComponentStoresMisplaced; - if cx.stage != Stage::Mesh || !cx.profile.fields().workarounds.contains(&defect) { - return 0; - } - let Some(out) = mesh_outputs(cx) else { - return 0; - }; - let k: u64 = match out.topology { - MeshTopology::Point => return 0, - MeshTopology::Line => 2, - MeshTopology::Triangle => 3, - }; - u64::from(out.max_primitives) - .saturating_mul(k) - .saturating_mul(4) -} - /// The check of a payload of `size` bytes: its arena within `maxTaskPayloadSize`, and, with the /// wrapper's workgroup words, within the stage's limit on its workgroup memory and payload together /// (the function's own workgroup memory joins that check where it is planned). @@ -648,15 +603,8 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { if point_size && shape.topology == MeshTopology::Point { crate::lower::stage_io::note_device_point_size(cx); } - // Staged indices are the wrapper's workgroup words, held to the stage's limit whether or not - // the function has threadgroup memory of its own. - let staged = !emulated && staged_index_bytes(cx) > 0; - if staged { - workgroup_limit(cx).check(0)?; - } let plan = &mut cx.families.mesh; plan.mesh = Some(shape); - plan.staged_indices = staged; plan.emulated = emulated; plan.payload_words = if emulated { payload_words } else { 0 }; plan.unsized_points = shape.topology == MeshTopology::Point && !point_size; @@ -1058,9 +1006,6 @@ pub struct Declared { pub count: Option, /// The object function's mesh grid, a workgroup `uvec3`. pub grid: Option, - /// A mesh function's staged indices ([`MeshPlan::staged_indices`]): a workgroup `uint` per - /// index. - pub staged: Option, /// An emulated mesh function's records buffer (`SyntheticBinding::MeshRecords`). pub records: Option, /// An emulated mesh function's first word of its threadgroup's records: a private `uint` @@ -1312,11 +1257,6 @@ pub fn declare( let ty = array(mb, index, shape.primitives)?; d.indices = Some(mb.builtin(b, IoDir::Output, ty)?); d.count = Some(mb.plain_global(StorageClass::Workgroup, u32_, None)?); - if mp.staged_indices { - let n = shape.primitives.saturating_mul(shape.per_primitive()); - let words = array(mb, u32_, n)?; - d.staged = Some(mb.plain_global(StorageClass::Workgroup, words, None)?); - } Ok(d) } @@ -1366,7 +1306,7 @@ fn k32(fb: &mut FunctionBuilder<'_>, n: u32) -> BResult { } /// The memory operands of a load or (`store`) a store of one of the wrapper's workgroup words -/// (the grid, the count, the staged indices), which other invocations read after a barrier: the +/// (the grid, the count), which other invocations read after a barrier: the /// function's coherence of shared memory (`NonPrivatePointer` under the Vulkan model). fn word_access( coherence: Coherence, @@ -1691,18 +1631,6 @@ fn store_index( if k == 1 { return store_element(cx, fb, g, len, at, None, value); } - if let Some(w) = cx.decl.families.mesh.staged { - // The index's own workgroup word, which the wrapper writes to the indices whole. - let coherence = coherence(cx.plan); - let n = k32(fb, len)?; - let inside = fb.binary(BinOp::ULessThan, at, n)?; - return when(fb, cx, inside, move |fb, _| { - let base = fb.module().global_value(w)?; - let ptr = fb.access_chain(base, &[at])?; - let access = word_access(coherence, fb, true)?; - fb.store(ptr, value, access) - }); - } let n = k32(fb, len)?; let inside = fb.binary(BinOp::ULessThan, at, n)?; let kk = k32(fb, k)?; @@ -2019,29 +1947,13 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) -> }; let none = fb.module().constant(Constant::Null { ty: index_ty })?; let none = fb.module().const_value(none)?; - // Staged indices are zeroed in their words and written to the indices after the body; the - // others are zeroed in place. - let staged = d.staged; - let k = shape.per_primitive(); - let kk = k32(&mut fb, k)?; + // The indices are zeroed in place. strided(cx, &mut fb, (lin, n), shape.primitives, move |fb, _, p| { - let unstaged = staged.is_none().then_some((indices, none)); - for (g, v) in unstaged.into_iter().chain([(culled, no), (ids, p)]) { + for (g, v) in [(indices, none), (culled, no), (ids, p)] { let base = fb.module().global_value(g)?; let ptr = fb.access_chain(base, &[p])?; fb.store(ptr, v, MemAccess::default())?; } - if let Some(w) = staged { - let at = fb.binary(BinOp::IMul, p, kk)?; - for j in 0..k { - let off = k32(fb, j)?; - let at = fb.binary(BinOp::IAdd, at, off)?; - let base = fb.module().global_value(w)?; - let ptr = fb.access_chain(base, &[at])?; - let access = word_access(coherence, fb, true)?; - fb.store(ptr, zero, access)?; - } - } Ok(()) })?; if let Some(g) = sizes { @@ -2070,23 +1982,6 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) -> fb.load(p, access)? }; strided(cx, &mut fb, (lin, n), shape.primitives, move |fb, cx, p| { - if let Some(w) = staged { - // The primitive's staged indices, written whole. - let at = fb.binary(BinOp::IMul, p, kk)?; - let mut words = Vec::new(); - for j in 0..k { - let off = k32(fb, j)?; - let at = fb.binary(BinOp::IAdd, at, off)?; - let base = fb.module().global_value(w)?; - let ptr = fb.access_chain(base, &[at])?; - let access = word_access(coherence, fb, false)?; - words.push(fb.load(ptr, access)?); - } - let whole = fb.composite_construct(index_ty, &words)?; - let base = fb.module().global_value(indices)?; - let ptr = fb.access_chain(base, &[p])?; - fb.store(ptr, whole, MemAccess::default())?; - } let past = fb.binary(BinOp::UGreaterThanEqual, p, drawn)?; when(fb, cx, past, move |fb, _| { let base = fb.module().global_value(culled)?; diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 07ab82970..ce261497d 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2194,16 +2194,6 @@ fn input_builtin( if !frag.barycentric { return Err(cx.invariant("a barycentric builtin without the feature")); } - // A driver that rejects a shader reading both forms refuses the second. - let defect = DriverWorkaround::BothBarycentricFormsRejected; - let other = StageBuiltin::BaryCoord { - perspective: !perspective, - }; - if cx.families.stage_io.interface.builtins.contains(&other) - && cx.profile.fields().workarounds.contains(&defect) - { - return Err(Unsupported::driver_defect(Feature::Barycentrics, defect).into()); - } let b = if perspective { B::BaryCoordKHR } else { diff --git a/crates/metal2vulkan/src/memory/contain.rs b/crates/metal2vulkan/src/memory/contain.rs index 2b3cf36ea..f09d2374a 100644 --- a/crates/metal2vulkan/src/memory/contain.rs +++ b/crates/metal2vulkan/src/memory/contain.rs @@ -9,9 +9,6 @@ //! - **In shader**: loads read at `select(inb, off, 0)` and yield `select(inb, v, 0)`; stores and //! atomics sit in a builder-closed `if_(inb)`. //! -//! An atomic takes [`atomic_encoding`]: the in-shader check also where a driver workaround says -//! its robustness leaves buffer atomics uncontained. -//! //! An image or texel buffer is contained by the texture family: its reads by //! [`device_reads_texels`], its writes by [`device_drops_texel_writes`], each in the shader where //! the device's robustness does not give Metal's answer. Validation labels its runs by the same two @@ -22,7 +19,7 @@ //! relative to the containment domain's base, so a wrapped GEP result is a huge offset and fails //! the check. -use crate::device::profile::{Containment, DriverWorkaround, Robustness}; +use crate::device::profile::{Containment, Robustness}; use crate::device::DeviceProfile; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; @@ -49,23 +46,6 @@ pub fn encoding(p: &DeviceProfile) -> Check { } } -/// The descriptor-view encoding of an atomic on `p`: [`encoding`], except that where it relies on -/// buffer robustness and the driver's robustness leaves a storage buffer's atomics uncontained -/// (`DriverWorkaround::BufferAtomicsUncontained`), the atomic is checked in the shader. -pub fn atomic_encoding(p: &DeviceProfile) -> Check { - let fields = p.fields(); - match (encoding(p), fields.containment) { - (Check::None, Containment::On { .. }) - if fields - .workarounds - .contains(&DriverWorkaround::BufferAtomicsUncontained) => - { - Check::InShader - } - (check, _) => check, - } -} - /// Whether the device's robustness on `p` returns Metal's out-of-bounds texel for a read of an /// image (`buffer`: a texel buffer), so the read is left to it: `robustImageAccess2` /// (`robustBufferAccess2` for a texel buffer), under containment. Elsewhere the shader checks the diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index d2c35633d..930254a90 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1427,47 +1427,6 @@ pub enum PrecisionNote { /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review. ExtendedRangeBlendSource, - /// A fragment function meets the store-dropping defect of - /// [`DriverWorkaround::DiscardDropsSimdgroupStores`] (MoltenVK on an Apple GPU: Apple's - /// compiler drops the texture writes of every live thread of a simdgroup holding a discarded - /// thread, where the function discards, then writes storage, samples, and calls - /// SPIRV-Cross's `optnone` arithmetic helpers), and a discard site that would discard at - /// once cannot wait until after the writes: a store, atomic, image write or non-quad - /// subgroup operation follows it, which a predicated discard does not yet guard - /// (`lower::fragment::discard`). The module keeps its forms, so the live fragments of a - /// simdgroup (8 by 4 pixels) that holds a discarded one may lose their texture writes (and, - /// not measured, their buffer stores and atomics); color outputs are not affected. - /// - /// Validation derives no tolerance and no explanation from it: a difference stays a - /// mismatch for review, deferred in C3 until an exact path exists. - /// - /// [`DriverWorkaround::DiscardDropsSimdgroupStores`]: crate::device::DriverWorkaround::DiscardDropsSimdgroupStores - DiscardDropsSimdgroupStores, - /// A fragment function meets the store-dropping defect of - /// [`DriverWorkaround::DiscardDropsSimdgroupStores`] without a discard: SPIRV-Cross writes an - /// operation of the module as an `optnone` call (a sum, difference or product decorated - /// `NoContraction`, among others) where only helper invocations (the quad helpers past a - /// primitive's edges, or demoted invocations) may run it before a storage write (not in a - /// selection on a value every invocation of a draw computes alike), and keeping them out would - /// not be exact (`spirv::helper_branches`): a derivative or subgroup operation reads what they - /// compute there or after, an arm leaves its selection otherwise than at its merge, the call is - /// in a loop whose helper invocations may iterate alone, or it is in no branch at all but - /// SPIRV-Cross writes it in one (a `?:` arm, the right side of a `&&` or `||`, or a - /// selection's arm, where its value is read once). Only where a path from the call - /// ends without a tangled instruction (an implicit-LOD sample, an LOD query, a derivative, a - /// subgroup operation) that reads what it computes: one after it keeps the writes. And only - /// where no identity shuffle of the call's result can follow it, which the module places - /// elsewhere to keep the writes: the device has no fragment-stage subgroup shuffle, or the - /// result is a 64-bit or `bool` lane, or an 8- or 16-bit one without - /// `shaderSubgroupExtendedTypes`. The live fragments of a simdgroup (8 by 4 pixels) whose - /// helpers make the call alone may lose their texture writes (and, not measured, their buffer - /// stores and atomics); color outputs are not affected. - /// - /// Validation derives no tolerance and no explanation from it: a difference stays a - /// mismatch for review, deferred in C3 until an exact path exists. - /// - /// [`DriverWorkaround::DiscardDropsSimdgroupStores`]: crate::device::DriverWorkaround::DiscardDropsSimdgroupStores - HelperBranchDropsSimdgroupStores, /// [`PrecisionNote::ExtendedRangeBlendSource`] for a `float` color output (a scalar or vector /// of AIR's `float`): blended into an extended-range or padded 10-bit attachment in the shader /// in the device's arithmetic, which the device's compiler may contract and regroup, where diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 6c0fcf679..3ff3fc6da 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3285,10 +3285,6 @@ fn lower_bounded( }, crate::lower::emit::Emitted { mut module, merged }, ) = stage_bound::emit(r, p, (word_cap, bounds), m)?; - // On a driver whose compiler loses a simdgroup's storage writes after an `optnone` call only - // its helper invocations make, those invocations take another arm where that is exact, and - // each such call left is fenced once every analysis below has read the module. - let (helper_guard, fences) = crate::spirv::helper_branches::guard_for(&mut module, p, m)?; let function_tables = spec.function_tables.clone(); let reaches_command_buffers = spec.may_encode_indirect_commands(); let command_writes = spec.command_writes(); @@ -3429,10 +3425,6 @@ fn lower_bounded( precision.sort_unstable(); } } - if helper_guard.exposed { - precision.push(PrecisionNote::HelperBranchDropsSimdgroupStores); - precision.sort_unstable(); - } if numbering_differs { precision.push(PrecisionNote::LinkedSamplerNumbering); precision.sort_unstable(); @@ -3449,8 +3441,6 @@ fn lower_bounded( precision.push(PrecisionNote::DeviceSampling); precision.sort_unstable(); } - // The fences are identities, which the analyses above would read as moves between lanes. - fences.apply(&mut module)?; let stats = crate::spirv::verify::verify(&module, p, m)?; let kept = keep(&module); let mut symbols = @@ -3653,7 +3643,7 @@ fn lower_bounded( subgroup: plan.subgroup, reconvergence, precision, - strategies: emitted_census(&plan, helper_guard), + strategies: census(&plan), stats, // The module's own blob (the identity domains) is in its words: the artifact carries a // bound blob's bytes alone. @@ -3735,37 +3725,6 @@ fn census(plan: &Plan) -> StrategyCensus { c } -/// [`census`] of the emitted module: the plan's, the selections whose helper invocations take -/// another arm (`spirv::helper_branches`), each with its helper query and one or two logical -/// operations (about 12 words), and the `optnone` calls an identity shuffle follows, each with -/// its lane's load and its shuffle (about 10 words; a structure's two members and their -/// construction about 30). -fn emitted_census( - plan: &Plan, - helper_guard: crate::spirv::helper_branches::Guarded, -) -> StrategyCensus { - let mut c = census(plan); - if helper_guard.selections > 0 { - c.entries.insert( - crate::spirv::helper_branches::STRATEGY.to_owned(), - StrategyUse { - uses: helper_guard.selections, - words: u64::from(helper_guard.selections) * 12, - }, - ); - } - if helper_guard.fences > 0 { - c.entries.insert( - crate::spirv::helper_branches::FENCE_STRATEGY.to_owned(), - StrategyUse { - uses: helper_guard.fences, - words: u64::from(helper_guard.fences) * 30, - }, - ); - } - c -} - /// The stage interface the artifact carries: the slots, the push placement, the module's link /// contract (every descriptor binding and specialization constant it declares), and whether it /// writes memory. A buffer slot's access is the function's, with what the accesses through loaded diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index a6925a26f..67ddedc53 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -100,10 +100,7 @@ //! sample from a loop over the coverage (`StageIo::coverage_loop`), its outputs the last pass's //! (`PrecisionNote::LoopedSampleOutputs`); compiled without `multisampled` it is //! `NeedsInput(Multisampled)`, and one the loop does not fit is refused for the reason its -//! interface records (`CoverageLoopRefusal`). On a driver that runs a -//! memory-writing function once per covered sample itself (`CoverageLoop::DriverRunsPerSample`, -//! MoltenVK on Apple's GPU) the function runs as written, without sample shading, and its other -//! reads are checked as below. A per-sample function reads the pixel values Vulkan has no pixel +//! interface records (`CoverageLoopRefusal`). A per-sample function reads the pixel values Vulkan has no pixel //! form for where Vulkan evaluates them, as a pixel-rate function does: `[[position]]`'s z and w //! (the interpolated depth and `1/w`, at a position Vulkan does not state), `[[point_coord]]` //! ("the fragment center, or the location of a sample"), `[[barycentric_coord]]`, and a centroid @@ -973,11 +970,7 @@ fn sample_invocations( // pixel's sample invocations: a quad holds one sample index, and no subgroup is promised to // hold the rest. The function runs once per pixel instead, compiled for the pipeline, and its // body once per covered sample, without sample shading; one the loop does not fit is refused - // for the reason its interface records. A driver that runs a - // memory-writing function once per covered sample whatever the pipeline's sample shading hands - // each run the pixel's coverage itself, as Metal does: the function's other reads are checked - // as any per-sample function's, and the pipeline enables no sample shading, under which that - // driver would mask the coverage. + // for the reason its interface records. if io.builtins.contains(&StageBuiltin::SampleMaskIn) { match io.coverage_loop { CoverageLoop::Looped => return Ok(false), @@ -988,10 +981,8 @@ fn sample_invocations( Unsupported::not_representable(Feature::PixelCoverageAtSampleRate).into(), ) } - CoverageLoop::DriverRunsPerSample => {} } } - let sample_shading = sample_shading && io.coverage_loop != CoverageLoop::DriverRunsPerSample; if sample_shading && !rate { return Err(refused()); } diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index ce3be41ab..e0ce64c5c 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -455,13 +455,6 @@ pub enum CoverageLoop { /// The function cannot loop over its covered samples: link refuses it in a pipeline of more /// than one sample for this reason. Refused(CoverageLoopRefusal), - /// The driver runs the function, which writes memory, once per covered sample whatever the - /// pipeline's sample shading, each run reading the pixel's coverage, as Metal does - /// (`DriverWorkaround::MemoryWritingFragmentsRunPerSample`): it is compiled as written, without - /// the loop, its `[[sample_id]]` and sample-qualified varyings read per sample, and link - /// enables no sample shading, under which the driver would hand each run only its own sample's - /// bit of the coverage. - DriverRunsPerSample, } /// Why a fragment function that reads `[[sample_mask]]` and runs once per sample on Metal has no diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index e95ace514..3122454ac 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -407,8 +407,6 @@ fn typed_module_of( crate::lower::emit::emit_module(&spec, &plan, m)?; crate::spirv::roll::roll_entry(&mut module, m)?; crate::spirv::hoist::hoist_uniform_loads(&mut module, p.containment(), m)?; - let (_, fences) = crate::spirv::helper_branches::guard_for(&mut module, p, m)?; - fences.apply(&mut module)?; crate::spirv::verify::verify(&module, p, m)?; if walked(&plan) { let words = crate::spirv::serialize::serialize(module.clone())?.words; diff --git a/crates/metal2vulkan/src/spirv/helper_branches.rs b/crates/metal2vulkan/src/spirv/helper_branches.rs deleted file mode 100644 index 17d94969a..000000000 --- a/crates/metal2vulkan/src/spirv/helper_branches.rs +++ /dev/null @@ -1,1842 +0,0 @@ -//! Helper invocations kept out of the branches whose code SPIRV-Cross writes as `optnone` calls, -//! on a driver whose compiler loses a simdgroup's storage writes there. -//! -//! Apple's compiler loses every texture write a simdgroup (8 by 4 pixels) makes after a -//! `[[clang::optnone]]` function is called in a branch that only its non-live threads enter, in a -//! fragment function that samples a texture through an argument buffer: the quad helpers past a -//! primitive's right and bottom edges (the probe: 1,040 to 1,063 of 2,584 texels lost a -//! run, in 98 or 99 blocks, with no discard at all), and the threads a discard demotes. With the -//! call plain, in straight-line code, with no sample, or with the resources bound directly, every -//! write landed, and color outputs landed in every form. SPIRV-Cross (MoltenVK 1.4.1's, as -//! Homebrew's) writes these SPIR-V instructions as `optnone` calls ([`optnone`]): an `OpFAdd`, -//! `OpFSub` or `OpFMul` decorated `NoContraction` (`spvFAdd`, `spvFSub`, `spvFMul`, which the -//! lowering uses wherever an operation must be rounded on its own), `OpQuantizeToF16`, -//! `OpUMulExtended` and `OpSMulExtended` (`spvMulExtended`, which `mulhi` and `madhi` take), and -//! `GLSL.std.450` `Reflect`. MoltenVK binds every resource through argument buffers, and on an -//! Apple GPU carries `DriverWorkaround::DiscardDropsSimdgroupStores`. -//! -//! There, in a fragment entry whose code samples (`OpImageSample*` or a gather) and writes storage -//! (an image write, or a store or atomic through a `StorageBuffer`, `PhysicalStorageBuffer`, -//! `Uniform` or `Image` pointer), [`guard`] sends the helper invocations of each selection that -//! has such a call in an arm, with a storage write after it, to an arm that has none: the -//! selection's condition is and'ed with "not a helper" (`OpIsHelperInvocationEXT`, which -//! SPIRV-Cross reads from the `gl_HelperInvocation` it sets at entry from -//! `simd_is_helper_thread()` and at each discard) where the false arm is the safe one, or'ed with -//! "a helper" where the true arm is, and a switch's selector is the safe case's literal for a -//! helper (measured both conditions' forms in plain Metal on an M4). Selections -//! are guarded innermost first; an arm whose calls an inner guard keeps helpers out of has none -//! left. -//! -//! A selection whose condition or selector every invocation of the draw computes alike (built only -//! from constants, specialization constants among them, and loads through push constant, uniform -//! block and resource handle pointers, by arithmetic, composites, selects and access chains) sends -//! a quad's helper invocations with its live ones, never alone: no call in its arms is where only -//! helpers may run it, so it is neither guarded nor counted as exposed. -//! -//! A guard is exact, so it is placed only where nothing a helper invocation can show changes: -//! -//! - every arm stays inside the selection and leaves it only for its merge (no return, kill, -//! break or continue), so a helper reaches the merge on either route and no loop it is in runs -//! longer or shorter; -//! - no arm holds a tangled instruction (implicit-LOD sampling, `OpImageQueryLod`, derivatives, -//! subgroup operations), directly or in a function it calls, since the helpers in it change; -//! - nothing a helper computes differently on the new route reaches one: the merge's phis, and -//! the `Function` and `Private` variables the arms store to, are followed through every -//! instruction, phi, variable, parameter and return value of the entry's functions, and a -//! tangled instruction reading one, or a branch or switch on one in a module with any tangled -//! instruction, leaves the selection as it is. -//! -//! A helper invocation's own writes and outputs have no effect, so its new route changes nothing -//! else. A call can stay where only helper invocations may run it before a storage write: an arm -//! of a selection that cannot be guarded exactly and that no enclosing guard covers, or a loop, -//! whose helpers may iterate alone. -//! -//! There the call is harmless where a tangled instruction follows it: the defect loses nothing where the helpers make -//! an implicit-LOD sample, a derivative, an LOD query or a simdgroup operation after the call. In -//! plain Metal on an M4, 0 of 2,584 texels were lost with any of them after the call in its arm (a -//! sample at a coordinate the call computes or of its own, `dfdx`, `fwidth`, either LOD query, -//! `simd_sum`, `simd_broadcast`, a ballot, a ballot and shuffles, `quad_shuffle`, `quad_sum`), with -//! a sample reading the call's value after the branch's merge, and with one in a branch inside the -//! arm; 1,046 to 1,063 were lost with the same instruction before the call, with a helper test -//! after it, or with nothing after it, the written texture read-write or write-only alike. So a -//! call counts only where a path from it ends (a return, kill or termination) without passing a -//! tangled instruction that reads what the call computes, through the instructions after it. -//! Reading it is what keeps the instruction after the call in the Metal code: SPIRV-Cross moves a -//! single-use expression to its use, so a tangled instruction merely later in the module may come -//! before the call there (the probe's `hoist` forms). It is followed through `Function` and -//! `Private` variables too, but not back from a later block's phi or store. A call outside every -//! selection and loop of a callee counts at its call sites. An arm a guard sends helpers past holds -//! no tangled instruction, so the guards are as before. -//! -//! **Calls a condition picks outside a branch.** SPIRV-Cross moves an expression read once into -//! what reads it, so a call outside every selection and loop still runs only where a condition -//! picks it when the chain of its value's single readers reaches an arm of a `?:` (a value operand -//! of an `OpSelect` on a scalar condition), the right side of a `&&` or `||` (the second operand of -//! a scalar `OpLogicalAnd` or `OpLogicalOr`), or an instruction inside a selection's arm, where -//! that condition is not draw-uniform ([`Facts::conditional`]): SPIRV-Cross writes the call there. -//! Such a call counts as one in an arm does, where only helper invocations may make it: a test of -//! a coverage, `coverage < t ? spvFAdd(a, b) : c`, is one only the helpers past a primitive's edges -//! pass. A loop that reads the value keeps it where it is defined, so the chain ends there. -//! -//! **Fences.** Each call that counts is fenced ([`Fences`]): an identity shuffle follows it, its -//! result read in every invocation from the invocation's own lane (`OpGroupNonUniformShuffle` at -//! `SubgroupLocalInvocationId`; a `MulExtended`'s structure member by member, put together again), -//! and every use of the result reads the shuffled value. Every invocation, a helper too, reads its -//! own value, so no answer changes and no lane reads another's (a guard's exactness holds); the -//! shuffle is the simdgroup operation after the call that reads what it computes, which keeps the -//! simdgroup's writes. The caller places the fences once every analysis of the module has run -//! ([`Fences::apply`]): they would read the shuffle as a move between lanes. A call stays bare where -//! the profile has no fragment shuffle (`subgroupSupportedStages` without the fragment stage, or -//! `subgroupSupportedOperations` without `SHUFFLE`) or its result is a lane no shuffle moves (a -//! 64-bit or `bool` one, or an 8- or 16-bit one without `shaderSubgroupExtendedTypes`); then -//! [`Guarded::exposed`] says so, and the caller records -//! `PrecisionNote::HelperBranchDropsSimdgroupStores`: the writes may be lost as the defect loses -//! them. - -use std::collections::{BTreeMap, BTreeSet}; - -use crate::budget::Meter; -use crate::device::{DeviceProfile, DriverWorkaround}; -use crate::error::{Error, InternalError, InternalKind}; -use crate::spirv::ids::{BlockId, ConstId, FuncId, GlobalId, TypeId, Value, VarId}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, Contraction, Decl, ExecModel, GlobalKind, GlobalVar, GlslOp, - GroupInst, Inst, InstNode, IoDir, MemAccess, Merge, Scope, ScopeId, ShuffleOp, StorageClass, - Terminator, Type, TypedModule, UnOp, ValueDef, ValueOrigin, -}; - -/// The census name of the selections [`guard`] guards ([`Guarded::selections`]), which the -/// runtime's pipeline creation log prints as `helper-guard `. -pub const STRATEGY: &str = "fragment.helper-guard"; - -/// "None" in the dense position tables. -const NONE: u32 = u32::MAX; - -/// The most whole-module passes a taint analysis takes before it calls its guard inexact. -const MAX_PASSES: u32 = 64; - -/// The census name of the `optnone` calls [`guard`] fences ([`Guarded::fences`]), which the -/// runtime's pipeline creation log prints as `helper-fence `. -pub const FENCE_STRATEGY: &str = "fragment.helper-fence"; - -/// What [`guard`] did to a module. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Guarded { - /// The selections whose helper invocations now take an arm without an `optnone` call. - pub selections: u32, - /// The `optnone` calls an identity shuffle of what they compute follows ([`Fences`]). - pub fences: u32, - /// An `optnone` call stays where only helper invocations may run it before a storage write. - pub exposed: bool, -} - -/// The `optnone` calls a guard left where only helper invocations may make them before a storage -/// write, with no tangled instruction reading what they compute after them, each to be followed -/// by an identity shuffle of its result ([`Fences::apply`]). [`guard`] decides them; the caller -/// applies them once every analysis of the module has run, since a shuffle is an identity that -/// those analyses would read as a move between lanes. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Fences { - /// Each call's block and result. - sites: Vec<(BlockId, Value)>, -} - -/// The fences a profile can place: a fragment entry's `OpGroupNonUniformShuffle` -/// (`subgroupSupportedStages` with the fragment stage, `subgroupSupportedOperations` with -/// `SHUFFLE`), and of 8- and 16-bit values (`shaderSubgroupExtendedTypes`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct FenceForms { - shuffle: bool, - extended: bool, -} - -/// [`guard`] where `p`'s driver has the defect (`DriverWorkaround::DiscardDropsSimdgroupStores`); -/// nothing elsewhere. A helper query needs `shaderDemoteToHelperInvocation`: without it nothing -/// is guarded. A call that stays where only helpers may run it is fenced where the profile can -/// place the fence ([`Fences`]), else reported. -pub fn guard_for( - m: &mut TypedModule, - p: &DeviceProfile, - meter: &mut Meter, -) -> Result<(Guarded, Fences), Error> { - let fields = p.fields(); - if !fields - .workarounds - .contains(&DriverWorkaround::DiscardDropsSimdgroupStores) - { - return Ok((Guarded::default(), Fences::default())); - } - let fragment = &fields.subgroup.fragment; - let forms = FenceForms { - shuffle: fragment.supported - && fragment - .ops - .contains(crate::device::subgroup::OpBits::SHUFFLE), - extended: fields - .enabled - .features - .contains(&crate::device::requirements::VkFeature::ShaderSubgroupExtendedTypes), - }; - guard(m, fields.fragment.demote_to_helper, forms, meter) -} - -/// Keep `m`'s helper invocations out of the arms that hold an `optnone` call before a storage -/// write (the module docs), where `m` is a fragment entry that samples and writes storage, and -/// fence each call that stays where only they may make it (`forms`, [`Fences`]). -/// `query`: the module may ask whether its invocation is a helper (`OpIsHelperInvocationEXT`). -fn guard( - m: &mut TypedModule, - query: bool, - forms: FenceForms, - meter: &mut Meter, -) -> Result<(Guarded, Fences), Error> { - if m.entry.model != ExecModel::Fragment { - return Ok((Guarded::default(), Fences::default())); - } - let (guards, fences, exposed) = { - let facts = Facts::new(m, meter)?; - if !facts.samples - || !facts - .writes - .get(m.entry.func.index()) - .copied() - .unwrap_or(false) - { - return Ok((Guarded::default(), Fences::default())); - } - let Plan { - guards, - bare, - problem, - } = facts.plan(query, meter)?; - // Every bare call is fenced where its result can be shuffled; the note stays where one - // cannot. - let mut fences = Fences::default(); - let mut exposed = false; - if problem { - for (b, v) in bare { - match forms.shuffle && facts.fenceable(v, forms.extended)? { - true => fences.sites.push((b, v)), - false => exposed = true, - } - } - } - (guards, fences, exposed) - }; - let selections = u32::try_from(guards.len()).map_err(|_| invariant("guard count"))?; - if !guards.is_empty() { - for g in &guards { - apply(m, g)?; - } - m.rederive()?; - } - let count = u32::try_from(fences.sites.len()).map_err(|_| invariant("fence count"))?; - Ok(( - Guarded { - selections, - fences: count, - exposed, - }, - fences, - )) -} - -fn invariant(detail: &str) -> Error { - Error::Internal(InternalError::new(InternalKind::Invariant, detail)) -} - -/// Whether SPIRV-Cross writes `inst` as a call of an `[[clang::optnone]]` function. -fn optnone(inst: &Inst) -> bool { - matches!( - inst, - Inst::Binary { - op: BinOp::FAdd | BinOp::FSub | BinOp::FMul, - contract: Contraction::Forbidden, - .. - } | Inst::Binary { - op: BinOp::UMulExtended | BinOp::SMulExtended, - .. - } | Inst::Unary { - op: UnOp::QuantizeToF16, - .. - } | Inst::Glsl { - op: GlslOp::Reflect, - .. - } - ) -} - -/// Whether `inst` samples a texture through a sampler. -fn samples(inst: &Inst) -> bool { - matches!( - inst, - Inst::ImageSample { .. } | Inst::ImageGather { .. } | Inst::ImageDrefGather { .. } - ) -} - -/// Whether a terminator leaves its function or ends its invocation. -fn exits(t: &Terminator) -> bool { - !matches!( - t, - Terminator::Branch(_) | Terminator::CondBranch { .. } | Terminator::Switch { .. } - ) -} - -/// The branch targets of a terminator. -fn targets(t: &Terminator) -> Vec { - match t { - Terminator::Branch(x) => vec![*x], - Terminator::CondBranch { t, f, .. } => vec![*t, *f], - Terminator::Switch { default, cases, .. } => std::iter::once(*default) - .chain(cases.iter().map(|c| c.1)) - .collect(), - _ => Vec::new(), - } -} - -/// Where a pointer points: into a `Function` variable, a `Private` variable, or anything else -/// (storage, an output, an image), whose writes a helper invocation cannot read back. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -enum Root { - Local(VarId), - Private(GlobalId), - Other, -} - -/// How a guarded selection's header sends a helper invocation. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Route { - /// To the false target: the condition and'ed with "not a helper". - False, - /// To the true target: the condition or'ed with "a helper". - True, - /// To the target of this selector value. - Case(u64), -} - -/// One selection to guard: its header and the route. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Guard { - header: BlockId, - route: Route, -} - -/// What [`Facts::plan`] decides. -struct Plan { - /// The selections to guard. - guards: Vec, - /// Every bare `optnone` call (its block and result: one a path from which ends without - /// passing a tangled instruction that reads what it computes) where only helper invocations - /// may make it, or in a callee, outside its selections and loops, that its callers may call - /// so. - bare: Vec<(BlockId, Value)>, - /// A bare call where only helper invocations may make it. - problem: bool, -} - -/// A structured construct of one function: the layout interval `[start, end)` from its header to -/// its merge. -#[derive(Clone, Copy, Debug)] -struct Construct { - header: BlockId, - merge: BlockId, - start: u32, - end: u32, - selection: bool, -} - -impl Construct { - /// Whether the block at layout position `p` is inside the construct: past a selection's - /// header, at a loop's header or past it, and before the merge. - fn holds(&self, p: u32) -> bool { - if self.selection { - self.start < p && p < self.end - } else { - self.start <= p && p < self.end - } - } -} - -/// What reads a value of the entry's functions: nothing, one operand of one instruction (its -/// block and index), or anything else (more than one operand, a phi, a terminator). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Reader { - Nothing, - One(BlockId, u32), - Other, -} - -/// What [`Facts::uniform`] has decided: the instruction of each result of the entry's functions -/// (built at the first question), and each value decided. -#[derive(Default)] -struct Uniformity<'a> { - defs: Option>, - decided: BTreeMap, -} - -/// Whether the storage class holds what every invocation of a draw reads alike: push constants, -/// uniform blocks (which no shader writes), and resource handles. -fn uniform_class(class: StorageClass) -> bool { - matches!( - class, - StorageClass::PushConstant | StorageClass::Uniform | StorageClass::UniformConstant - ) -} - -/// Whether `inst` computes the same result in every invocation that gives it the same operands, -/// reading no invocation's own state: arithmetic, logic, conversions, composites, and an access -/// chain or load (of a class [`uniform_class`] admits). -fn same_from_same(inst: &Inst) -> bool { - matches!( - inst, - Inst::Unary { .. } - | Inst::Binary { .. } - | Inst::Select { .. } - | Inst::BitFieldInsert { .. } - | Inst::Fma { .. } - | Inst::BitFieldExtract { .. } - | Inst::Convert { .. } - | Inst::CompositeConstruct { .. } - | Inst::CompositeExtract { .. } - | Inst::CompositeInsert { .. } - | Inst::VectorExtractDynamic { .. } - | Inst::VectorInsertDynamic { .. } - | Inst::VectorShuffle { .. } - | Inst::Glsl { .. } - | Inst::AccessChain { .. } - | Inst::Load { .. } - ) -} - -/// What the analysis knows of the module's functions. -struct Facts<'a> { - m: &'a TypedModule, - /// The functions the entry reaches, callers before callees. - order: Vec, - /// By block: its position in its function's layout. - pos: Vec, - /// By function: it, or a function it calls, writes storage. - writes: Vec, - /// By function: it, or a function it calls, holds a tangled instruction. - tangled: Vec, - /// By function: it, or a function it calls, holds an `optnone` call. - calls_optnone: Vec, - /// By function: a storage write may follow one of its returns, in a caller. - after_return: Vec, - /// By block: a storage write may follow the block's start. - reach_write: Vec, - /// The entry's code samples a texture. - samples: bool, - /// The pointer each access chain or copy result points into. - roots: BTreeMap, -} - -impl<'a> Facts<'a> { - fn new(m: &'a TypedModule, meter: &mut Meter) -> Result, Error> { - let nf = m.functions.len(); - let callees = |f: FuncId| -> Vec { - let mut out = Vec::new(); - for b in m - .functions - .get(f.index()) - .map_or(&[][..], |f| &f.blocks[..]) - { - for node in m.blocks.get(b.index()).map_or(&[][..], |b| &b.insts[..]) { - if let Inst::Call { func, .. } = node.inst { - out.push(func); - } - } - } - out - }; - // Postorder of the call graph from the entry (SPIR-V has no recursion). - let mut post = Vec::new(); - let mut seen = vec![false; nf]; - let mut stack = vec![(m.entry.func, callees(m.entry.func), 0usize)]; - if let Some(s) = seen.get_mut(m.entry.func.index()) { - *s = true; - } - while let Some(top) = stack.last_mut() { - let (f, next) = (top.0, top.1.get(top.2).copied()); - top.2 += 1; - match next { - Some(c) => { - if let Some(s) = seen.get_mut(c.index()).filter(|s| !**s) { - *s = true; - stack.push((c, callees(c), 0)); - } - } - None => { - post.push(f); - stack.pop(); - } - } - } - let order: Vec = post.iter().rev().copied().collect(); - let mut pos = vec![NONE; m.blocks.len()]; - for f in &order { - let func = m - .functions - .get(f.index()) - .ok_or_else(|| invariant("a called function"))?; - for (p, b) in func.blocks.iter().enumerate() { - if let Some(x) = pos.get_mut(b.index()) { - *x = u32::try_from(p).map_err(|_| invariant("block positions"))?; - } - } - } - let mut facts = Facts { - m, - order, - pos, - writes: vec![false; nf], - tangled: vec![false; nf], - calls_optnone: vec![false; nf], - after_return: vec![false; nf], - reach_write: vec![false; m.blocks.len()], - samples: false, - roots: BTreeMap::new(), - }; - // Callees first: what each function or its callees hold. - for f in &post { - let (mut w, mut t, mut o) = (false, false, false); - for b in facts.blocks_of(*f) { - let blk = facts.block(b)?; - meter.tick(u32::try_from(blk.insts.len()).unwrap_or(u32::MAX))?; - for node in &blk.insts { - let inst = &node.inst; - w |= facts.writes_inst(inst); - t |= inst.is_tangled() || facts.calls(inst, &facts.tangled); - o |= optnone(inst) || facts.calls(inst, &facts.calls_optnone); - facts.samples |= samples(inst); - let root = match inst { - Inst::AccessChain { base, .. } => Some(facts.root(*base)), - Inst::Unary { - op: UnOp::CopyObject, - a, - } if facts.is_pointer(*a) => Some(facts.root(*a)), - _ => None, - }; - if let (Some(r), Some(v)) = (root, node.result) { - facts.roots.insert(v, r); - } - } - } - for (table, v) in [ - (&mut facts.writes, w), - (&mut facts.tangled, t), - (&mut facts.calls_optnone, o), - ] { - if let Some(x) = table.get_mut(f.index()) { - *x = v; - } - } - } - // Callers first: whether a write may follow a return, then each block's reach. - let mut sites: Vec> = vec![Vec::new(); nf]; - for g in &facts.order { - for b in facts.blocks_of(*g) { - for (i, node) in facts.block(b)?.insts.iter().enumerate() { - if let Inst::Call { func, .. } = node.inst { - if let Some(s) = sites.get_mut(func.index()) { - s.push((*g, b, i)); - } - } - } - } - } - for f in facts.order.clone() { - let mut after = false; - for &(g, b, i) in sites.get(f.index()).map_or(&[][..], |s| &s[..]) { - after |= facts.write_after(g, b, i + 1)?; - } - if let Some(x) = facts.after_return.get_mut(f.index()) { - *x = after; - } - facts.reach_writes(f, meter)?; - } - Ok(facts) - } - - /// Whether every invocation of a draw takes the same arm of the selection headed by - /// `header`: its condition or selector is [`Facts::uniform`]. - fn uniform_branch( - &self, - header: BlockId, - u: &mut Uniformity<'a>, - meter: &mut Meter, - ) -> Result { - match self.block(header)?.term { - Terminator::CondBranch { cond: v, .. } | Terminator::Switch { sel: v, .. } => { - self.uniform(v, u, meter) - } - _ => Ok(false), - } - } - - /// Whether every invocation of a draw computes `v` alike: a constant (a specialization - /// constant among them), a push constant's, uniform block's or resource's pointer, or what - /// [`same_from_same`] computes from such values alone (a load reading one of those - /// classes). A phi, a parameter, a `Function` variable, and anything else are not. - fn uniform(&self, v: Value, u: &mut Uniformity<'a>, meter: &mut Meter) -> Result { - let m = self.m; - if u.defs.is_none() { - let mut defs = BTreeMap::new(); - for f in &self.order { - for b in self.blocks_of(*f) { - let blk = self.block(b)?; - meter.tick(u32::try_from(blk.insts.len()).unwrap_or(u32::MAX))?; - for node in &blk.insts { - if let Some(r) = node.result { - defs.insert(r, &node.inst); - } - } - } - } - u.defs = Some(defs); - } - let Uniformity { defs, decided } = u; - let defs = defs.as_ref().ok_or_else(|| invariant("the definitions"))?; - // Operands first: a value is decided once all of its operands are (SSA without phis has - // no cycle). - let mut stack = vec![(v, false)]; - while let Some((x, expanded)) = stack.pop() { - if decided.contains_key(&x) { - continue; - } - meter.tick(1)?; - let inst = match m.values.get(x.index()).map(|d| d.origin) { - Some(ValueOrigin::Const(_)) => { - decided.insert(x, true); - continue; - } - Some(ValueOrigin::Global(g)) => { - let class = m.globals.get(g.index()).map(|gv| gv.class); - decided.insert(x, class.is_some_and(uniform_class)); - continue; - } - Some(ValueOrigin::Inst(_)) => defs.get(&x).copied(), - _ => None, - }; - let Some(inst) = inst.filter(|i| same_from_same(i)) else { - decided.insert(x, false); - continue; - }; - if let Inst::Load { ptr, .. } = inst { - if !self.class(*ptr).is_some_and(uniform_class) { - decided.insert(x, false); - continue; - } - } - let mut operands = Vec::new(); - inst.for_each_value(|o| operands.push(o)); - if expanded { - let all = operands - .iter() - .all(|o| decided.get(o).copied().unwrap_or(false)); - decided.insert(x, all); - } else { - stack.push((x, true)); - stack.extend( - operands - .into_iter() - .filter(|o| !decided.contains_key(o)) - .map(|o| (o, false)), - ); - } - } - Ok(decided.get(&v).copied().unwrap_or(false)) - } - - /// Whether the result `v` of an `optnone` call can be shuffled between lanes - /// ([`Fences::apply`]): a scalar or vector of 32-bit integers or floats, or of 8- or 16-bit - /// ones where `extended` (`shaderSubgroupExtendedTypes`), or a structure of such members (a - /// `MulExtended`'s). A 64-bit or `bool` lane is not: Metal's simdgroup shuffles move no - /// 64-bit value. - fn fenceable(&self, v: Value, extended: bool) -> Result { - let ty = self - .m - .values - .get(v.index()) - .map(|d| d.ty) - .ok_or_else(|| invariant("an optnone call's result"))?; - match self.m.types.get(ty)? { - Type::Struct { members, .. } => { - for member in members.iter() { - if !lane_type(self.m, *member, extended)? { - return Ok(false); - } - } - Ok(true) - } - _ => lane_type(self.m, ty, extended), - } - } - - fn blocks_of(&self, f: FuncId) -> Vec { - self.m - .functions - .get(f.index()) - .map_or_else(Vec::new, |f| f.blocks.clone()) - } - - fn block(&self, b: BlockId) -> Result<&'a crate::spirv::ir::Block, Error> { - self.m - .blocks - .get(b.index()) - .ok_or_else(|| invariant("a block of a reached function")) - } - - fn pos(&self, b: BlockId) -> u32 { - self.pos.get(b.index()).copied().unwrap_or(NONE) - } - - /// Whether `inst` calls a function `table` marks. - fn calls(&self, inst: &Inst, table: &[bool]) -> bool { - matches!(inst, Inst::Call { func, .. } if table.get(func.index()).copied().unwrap_or(false)) - } - - fn is_pointer(&self, v: Value) -> bool { - self.m - .values - .get(v.index()) - .and_then(|d| self.m.types.get(d.ty).ok()) - .is_some_and(|t| matches!(t, Type::Pointer { .. })) - } - - /// The storage class of pointer `v`. - fn class(&self, v: Value) -> Option { - let d = self.m.values.get(v.index())?; - match self.m.types.get(d.ty).ok()? { - Type::Pointer { class, .. } => Some(*class), - _ => None, - } - } - - /// Where pointer `v` points; `None` for a parameter (the caller's). - fn root(&self, v: Value) -> Root { - match self.m.values.get(v.index()).map(|d| d.origin) { - Some(ValueOrigin::Var(var)) => Root::Local(var), - Some(ValueOrigin::Global(g)) => match self.m.globals.get(g.index()) { - Some(gv) if gv.class == StorageClass::Private => Root::Private(g), - _ => Root::Other, - }, - _ => self.roots.get(&v).copied().unwrap_or(Root::Other), - } - } - - /// Whether `inst` writes storage, itself or in a function it calls. - fn writes_inst(&self, inst: &Inst) -> bool { - let ptr = match inst { - Inst::ImageWrite { .. } => return true, - Inst::Call { .. } => return self.calls(inst, &self.writes), - Inst::Store { ptr, .. } => *ptr, - _ => match inst.atomic_pointer() { - Some(p) => p, - None => return false, - }, - }; - matches!( - self.class(ptr), - Some( - StorageClass::StorageBuffer - | StorageClass::PhysicalStorageBuffer - | StorageClass::Uniform - | StorageClass::Image - ) - ) - } - - /// Whether a storage write may follow instruction `from` of block `b` of `f`: one later in - /// the block, at a successor's reach, or after `f` returns. - fn write_after(&self, f: FuncId, b: BlockId, from: usize) -> Result { - let blk = self.block(b)?; - if blk - .insts - .get(from..) - .unwrap_or(&[]) - .iter() - .any(|n| self.writes_inst(&n.inst)) - { - return Ok(true); - } - if exits(&blk.term) { - return Ok( - matches!(blk.term, Terminator::Return | Terminator::ReturnValue(_)) - && self.after_return.get(f.index()).copied().unwrap_or(false), - ); - } - Ok(targets(&blk.term) - .iter() - .any(|t| self.reach_write.get(t.index()).copied().unwrap_or(false))) - } - - /// Fill `reach_write` for `f`'s blocks, to a fixpoint over its loops. - fn reach_writes(&mut self, f: FuncId, meter: &mut Meter) -> Result<(), Error> { - let blocks = self.blocks_of(f); - loop { - let mut changed = false; - meter.tick(u32::try_from(blocks.len()).unwrap_or(u32::MAX))?; - for b in blocks.iter().rev() { - if self.reach_write.get(b.index()).copied().unwrap_or(true) { - continue; - } - if self.write_after(f, *b, 0)? { - if let Some(x) = self.reach_write.get_mut(b.index()) { - *x = true; - } - changed = true; - } - } - if !changed { - return Ok(()); - } - } - } - - /// The structured constructs of `f`. - fn constructs(&self, f: FuncId) -> Result, Error> { - let mut out = Vec::new(); - for b in self.blocks_of(f) { - let blk = self.block(b)?; - let (merge, selection) = match blk.merge { - Some(Merge::Selection { merge }) => (merge, true), - Some(Merge::Loop { merge, .. }) => (merge, false), - None => continue, - }; - out.push(Construct { - header: b, - merge, - start: self.pos(b), - end: self.pos(merge), - selection, - }); - } - Ok(out) - } - - /// The blocks of `f` an arm entered at `t` runs before selection `c`'s merge, by position, or - /// `None` where the arm leaves the selection otherwise (a return, kill, break or continue). - fn arm(&self, f: &[BlockId], c: &Construct, t: BlockId) -> Result>, Error> { - let mut seen = BTreeSet::new(); - let mut work = vec![t]; - while let Some(b) = work.pop() { - if b == c.merge { - continue; - } - let p = self.pos(b); - if p <= c.start || p >= c.end || f.get(p as usize) != Some(&b) { - return Ok(None); - } - if !seen.insert(p) { - continue; - } - let blk = self.block(b)?; - if exits(&blk.term) { - return Ok(None); - } - work.extend(targets(&blk.term)); - } - Ok(Some(seen.into_iter().collect())) - } - - /// Decide the guards, callees first, and whether a call stays exposed. - fn plan(&self, query: bool, meter: &mut Meter) -> Result { - let m = self.m; - let nf = m.functions.len(); - // By function: an `optnone` call no guard covers, before a write. - let mut exposed_fn = vec![false; nf]; - // By function: a call it leaves open that a path returns past with no tangled - // instruction reading what the call computes. - let mut bare_fn = vec![false; nf]; - let mut problem = false; - let mut guards = Vec::new(); - let mut bare = Vec::new(); - // Every guard exact at once, where the union of all candidates' taint reaches nothing. - let mut all_exact: Option = None; - let mut uniformity = Uniformity::default(); - // Each value's reader, taken at the first call outside every construct. - let mut readers: Option> = None; - for f in self.order.iter().rev() { - let blocks = self.blocks_of(*f); - let n = blocks.len(); - let mut exposed = vec![false; n]; - for (p, b) in blocks.iter().enumerate() { - let blk = self.block(*b)?; - meter.tick(u32::try_from(blk.insts.len()).unwrap_or(u32::MAX))?; - for (i, node) in blk.insts.iter().enumerate() { - // A callee's own calls are exposed where a write follows them, inside it or - // after it returns. - let hit = if optnone(&node.inst) { - self.write_after(*f, *b, i + 1)? - } else { - self.calls(&node.inst, &exposed_fn) - }; - if hit { - if let Some(x) = exposed.get_mut(p) { - *x = true; - } - break; - } - } - } - if !exposed.contains(&true) { - continue; - } - // A selection whose condition every invocation of the draw computes alike sends a - // quad's helpers along with its live invocations, never alone: no call in its arms is - // where only helpers may run it, so it is no construct here. - let mut cons = Vec::new(); - for c in self.constructs(*f)? { - if c.selection && self.uniform_branch(c.header, &mut uniformity, meter)? { - continue; - } - cons.push(c); - } - cons.sort_by_key(|c| std::cmp::Reverse(c.start)); - let mut shielded = vec![false; n]; - for c in cons.iter().filter(|c| c.selection) { - if m.switches_at_use.contains(&c.header) { - continue; - } - let live = |p: &u32| { - exposed.get(*p as usize).copied().unwrap_or(false) - && !shielded.get(*p as usize).copied().unwrap_or(false) - }; - let inside = (c.start + 1)..c.end; - if !inside.clone().any(|p| live(&p)) { - continue; - } - let Some(route) = self.route(&blocks, c, &exposed, &shielded)? else { - continue; - }; - if !query { - continue; - } - if self.arms_tangled(&blocks, c)? { - continue; - } - if all_exact.is_none() { - let every = self.candidates()?; - all_exact = Some(self.exact(&every, meter)?); - } - let exact = all_exact == Some(true) || self.exact(&[(*f, *c)], meter)?; - if !exact { - continue; - } - guards.push(Guard { - header: c.header, - route: route.0, - }); - for p in route.1 { - if let Some(x) = shielded.get_mut(p as usize) { - *x = true; - } - } - } - // What stays exposed: in a function, any call; where only helpers may run it, a - // call inside a selection's arm or a loop. - let open: Vec = (0..n) - .filter(|p| { - exposed.get(*p).copied().unwrap_or(false) - && !shielded.get(*p).copied().unwrap_or(false) - }) - .collect(); - if let Some(x) = exposed_fn.get_mut(f.index()) { - *x = !open.is_empty(); - } - // What the note counts: an open call a path from which ends (a return, kill or - // termination) without passing a tangled instruction that reads what the call - // computes. A call inside a selection or loop whose condition is not draw-uniform - // records the note, and so does one outside them that SPIRV-Cross writes where a - // condition picks it ([`Facts::conditional`]); another outside every such construct - // of a callee is its callers' to count, through the call. Guards are as before: an arm - // they guard holds no tangled instruction at all. Every function's bare calls are - // listed, whatever the note. - let mut inner = Vec::new(); - let mut outer = Vec::new(); - for &p in &open { - let at = u32::try_from(p).unwrap_or(NONE); - let inside = cons.iter().any(|c| c.holds(at)); - let Some(b) = blocks.get(p) else { - continue; - }; - let blk = self.block(*b)?; - // A write follows instruction `i` where the block's last write is past it, or - // one may follow the block. - let last = blk.insts.iter().rposition(|n| self.writes_inst(&n.inst)); - let tail = self.write_after(*f, *b, blk.insts.len())?; - for (i, node) in blk.insts.iter().enumerate() { - let hit = if optnone(&node.inst) { - tail || last.is_some_and(|l| l > i) - } else { - self.calls(&node.inst, &bare_fn) - }; - if !hit { - continue; - } - let picked = match node.result { - Some(v) if !inside => { - let readers = match &mut readers { - Some(r) => r, - None => readers.insert(self.readers(meter)?), - }; - self.conditional(v, &cons, readers, &mut uniformity, meter)? - } - _ => false, - }; - if inside || picked { - inner.push((p, i)); - } else if *f != m.entry.func { - outer.push((p, i)); - } - } - } - let inner = self.bare(&blocks, &inner, meter)?; - let outer = self.bare(&blocks, &outer, meter)?; - if !inner.is_empty() { - problem = true; - } else if !outer.is_empty() { - if let Some(x) = bare_fn.get_mut(f.index()) { - *x = true; - } - } - for (p, i) in inner.into_iter().chain(outer) { - let Some(b) = blocks.get(p) else { - continue; - }; - // A call of a function is cured inside the function. - if let Some(node) = self.block(*b)?.insts.get(i).filter(|n| optnone(&n.inst)) { - let v = node - .result - .ok_or_else(|| invariant("an optnone call's result"))?; - bare.push((*b, v)); - } - } - } - Ok(Plan { - guards, - bare, - problem, - }) - } - - /// Each value's [`Reader`] among the entry's functions, by value. - fn readers(&self, meter: &mut Meter) -> Result, Error> { - let mut out = vec![Reader::Nothing; self.m.values.len()]; - let mut read = |v: Value, by: Reader| { - if let Some(x) = out.get_mut(v.index()) { - *x = match *x { - Reader::Nothing => by, - _ => Reader::Other, - }; - } - }; - for f in &self.order { - for b in self.blocks_of(*f) { - let blk = self.block(b)?; - meter.tick(u32::try_from(blk.insts.len() + blk.phis.len()).unwrap_or(u32::MAX))?; - for phi in &blk.phis { - for (v, _) in &phi.incoming { - read(*v, Reader::Other); - } - } - for (i, node) in blk.insts.iter().enumerate() { - let i = u32::try_from(i).map_err(|_| invariant("an instruction index"))?; - node.inst.for_each_value(|v| read(v, Reader::One(b, i))); - } - blk.term.for_each_value(|v| read(v, Reader::Other)); - } - } - Ok(out) - } - - /// Whether SPIRV-Cross writes the call whose result is `v` (an `optnone` call, or a call of a - /// function that holds one), outside every construct of `cons` (its function's, less the - /// selections every invocation of a draw takes alike), where an invocation makes it only on a - /// condition. SPIRV-Cross moves an expression read once into what reads it, so the call is - /// written where the chain of its value's single readers ends: at a value read more than once, - /// at one without a reader, at a statement (a store, a phi's or terminator's operand, an - /// instruction without a result), or where a loop reads it (a value a loop it is outside reads - /// stays where it is defined: measured with Homebrew's SPIRV-Cross). On the way, a value - /// operand of an `OpSelect` on a scalar condition is an arm of a `?:`, and the second operand - /// of a scalar `OpLogicalAnd` or `OpLogicalOr` the right side of a `&&` or `||` (not a - /// vector's, which SPIRV-Cross writes component by component, the operands held first): the - /// call is conditional where such a condition or first operand is not draw-uniform - /// ([`Facts::uniform`]), or where a reader is inside a selection of `cons`, the arm SPIRV-Cross - /// writes the call in. - fn conditional( - &self, - v: Value, - cons: &[Construct], - readers: &[Reader], - u: &mut Uniformity<'a>, - meter: &mut Meter, - ) -> Result { - let mut x = v; - loop { - meter.tick(1)?; - let Some(&Reader::One(b, i)) = readers.get(x.index()) else { - return Ok(false); - }; - let at = self.pos(b); - if cons.iter().any(|c| !c.selection && c.holds(at)) { - return Ok(false); - } - if cons.iter().any(|c| c.selection && c.holds(at)) { - return Ok(true); - } - let node = self - .block(b)? - .insts - .get(i as usize) - .ok_or_else(|| invariant("a value's reader"))?; - let cond = match node.inst { - Inst::Select { cond, t, f } if t == x || f == x => Some(cond), - Inst::Binary { - op: BinOp::LogicalAnd | BinOp::LogicalOr, - a, - b, - .. - } if b == x => Some(a), - _ => None, - }; - if let Some(c) = cond { - if self.scalar_bool(c) && !self.uniform(c, u, meter)? { - return Ok(true); - } - } - match node.result { - Some(r) => x = r, - None => return Ok(false), - } - } - } - - /// Whether `v` is a scalar `bool`. - fn scalar_bool(&self, v: Value) -> bool { - self.m - .values - .get(v.index()) - .and_then(|d| self.m.types.get(d.ty).ok()) - .is_some_and(|t| matches!(t, Type::Bool)) - } - - /// The calls of `calls` (block position and instruction index in `blocks`, one function's - /// layout) a path from which ends without passing a tangled instruction that reads what the - /// call computes. The calls are taken 64 at a time: one pass over the function's layout from - /// the first of them marks, by block, the calls each tangled instruction there reads (a bit a - /// call, through every operand, phi, and `Function` or `Private` variable stored to, from the - /// call on, in layout order, where a block's dominators come first; what a block reaches only - /// through a later block's phi or store is not followed), then each call's paths are walked to - /// their end or to such a block. - fn bare( - &self, - blocks: &[BlockId], - calls: &[(usize, usize)], - meter: &mut Meter, - ) -> Result, Error> { - let mut out = Vec::new(); - for batch in calls.chunks(64) { - let bit: BTreeMap<(usize, usize), u64> = batch - .iter() - .zip(0..64) - .map(|(c, k)| (*c, 1u64 << k)) - .collect(); - let first = batch.iter().map(|c| c.0).min().unwrap_or(blocks.len()); - let mut reads: BTreeMap = BTreeMap::new(); - let mut held: BTreeMap = BTreeMap::new(); - let mut meets = vec![0u64; blocks.len()]; - for (q, b) in blocks.iter().enumerate().skip(first) { - let blk = self.block(*b)?; - meter.tick(u32::try_from(blk.insts.len() + blk.phis.len()).unwrap_or(u32::MAX))?; - for phi in &blk.phis { - let mask = phi - .incoming - .iter() - .fold(0, |a, (v, _)| a | reads.get(v).copied().unwrap_or(0)); - if mask != 0 { - reads.insert(phi.result, mask); - } - } - for (i, node) in blk.insts.iter().enumerate() { - let mut mask = bit.get(&(q, i)).copied().unwrap_or(0); - let mut read = 0; - node.inst - .for_each_value(|v| read |= reads.get(&v).copied().unwrap_or(0)); - match node.inst { - Inst::Load { ptr, .. } => { - read |= held.get(&self.root(ptr)).copied().unwrap_or(0); - } - Inst::Store { ptr, value, .. } => { - let root = self.root(ptr); - let stored = reads.get(&value).copied().unwrap_or(0); - if root != Root::Other && stored != 0 { - *held.entry(root).or_insert(0) |= stored; - } - } - _ => {} - } - if node.inst.is_tangled() { - if let Some(x) = meets.get_mut(q) { - *x |= read; - } - } - mask |= read; - if let (Some(r), true) = (node.result, mask != 0) { - reads.insert(r, mask); - } - } - } - for (k, &(p, i)) in batch.iter().enumerate() { - if self.bare_path(blocks, &meets, p, 1u64 << k)? { - out.push((p, i)); - } - } - } - Ok(out) - } - - /// Whether a path from the block at position `p` of `blocks` ends (a return, kill or - /// termination) without entering a block whose `meets` holds `bit`, or leaves the layout. - fn bare_path( - &self, - blocks: &[BlockId], - meets: &[u64], - p: usize, - bit: u64, - ) -> Result { - let met = |q: usize| meets.get(q).is_some_and(|x| x & bit != 0); - if met(p) { - return Ok(false); - } - let Some(&b) = blocks.get(p) else { - return Err(invariant("a block of the function")); - }; - let mut seen = BTreeSet::from([p]); - let mut work = vec![b]; - while let Some(x) = work.pop() { - let blk = self.block(x)?; - match blk.term { - Terminator::Unreachable => continue, - ref t if exits(t) => return Ok(true), - _ => {} - } - for t in targets(&blk.term) { - let q = self.pos(t) as usize; - if blocks.get(q) != Some(&t) { - return Ok(true); - } - if !met(q) && seen.insert(q) { - work.push(t); - } - } - } - Ok(false) - } - - /// Where selection `c` can send its helper invocations: its route, with the positions of the - /// arms they no longer enter. `None` where an arm leaves the selection otherwise than at its - /// merge, or every arm runs an exposed call. - fn route( - &self, - blocks: &[BlockId], - c: &Construct, - exposed: &[bool], - shielded: &[bool], - ) -> Result)>, Error> { - let blk = self.block(c.header)?; - let tgs = targets(&blk.term); - let mut arms: Vec<(BlockId, Vec, bool)> = Vec::new(); - for t in tgs.iter().copied().collect::>() { - let Some(region) = self.arm(blocks, c, t)? else { - return Ok(None); - }; - let hot = region.iter().any(|p| { - exposed.get(*p as usize).copied().unwrap_or(false) - && !shielded.get(*p as usize).copied().unwrap_or(false) - }); - arms.push((t, region, hot)); - } - // The merge itself when an arm is empty, else the first arm without a call. - let safe = if tgs.contains(&c.merge) { - c.merge - } else { - match arms.iter().find(|a| !a.2) { - Some(a) => a.0, - None => return Ok(None), - } - }; - let route = match &blk.term { - Terminator::CondBranch { t, .. } if *t == safe => Route::True, - Terminator::CondBranch { f, .. } if *f == safe => Route::False, - Terminator::Switch { default, cases, .. } => match cases.iter().find(|x| x.1 == safe) { - Some(x) => Route::Case(x.0), - None if *default == safe => { - let used: BTreeSet = cases.iter().map(|x| x.0).collect(); - let free = (0u64..).find(|v| !used.contains(v)).unwrap_or(0); - Route::Case(free) - } - None => return Ok(None), - }, - _ => return Ok(None), - }; - let away = arms - .into_iter() - .filter(|a| a.0 != safe) - .flat_map(|a| a.1) - .collect(); - Ok(Some((route, away))) - } - - /// Whether a block inside selection `c` holds a tangled instruction or calls a function that - /// does. - fn arms_tangled(&self, blocks: &[BlockId], c: &Construct) -> Result { - for p in (c.start + 1)..c.end { - let Some(b) = blocks.get(p as usize) else { - continue; - }; - if self - .block(*b)? - .insts - .iter() - .any(|n| n.inst.is_tangled() || self.calls(&n.inst, &self.tangled)) - { - return Ok(true); - } - } - Ok(false) - } - - /// Every selection with an `optnone` call (or a call of a function holding one) in its arms. - fn candidates(&self) -> Result, Error> { - let mut out = Vec::new(); - for f in &self.order { - let blocks = self.blocks_of(*f); - for c in self.constructs(*f)?.into_iter().filter(|c| c.selection) { - let mut hot = false; - for p in (c.start + 1)..c.end { - if let Some(b) = blocks.get(p as usize) { - hot |= - self.block(*b)?.insts.iter().any(|n| { - optnone(&n.inst) || self.calls(&n.inst, &self.calls_optnone) - }); - } - } - if hot { - out.push((*f, c)); - } - } - } - Ok(out) - } - - /// Whether rerouting the helper invocations of `selections` changes nothing a tangled - /// instruction reads (the module docs): what a helper computes differently from there (each - /// merge's phis, and the variables the arms store to) is followed to a fixpoint through the - /// entry's functions. - fn exact(&self, selections: &[(FuncId, Construct)], meter: &mut Meter) -> Result { - let m = self.m; - let tangled_anywhere = self - .tangled - .get(m.entry.func.index()) - .copied() - .unwrap_or(false); - let mut taint = vec![false; m.values.len()]; - meter.charge(taint.len())?; - let r = self.taint(selections, &mut taint, tangled_anywhere, meter); - meter.release(taint.len()); - r - } - - fn taint( - &self, - selections: &[(FuncId, Construct)], - taint: &mut [bool], - tangled_anywhere: bool, - meter: &mut Meter, - ) -> Result { - let m = self.m; - let mut vars: BTreeSet = BTreeSet::new(); - let mut returns = vec![false; m.functions.len()]; - let set = |taint: &mut [bool], v: Value| -> bool { - match taint.get_mut(v.index()) { - Some(x) if !*x => { - *x = true; - true - } - _ => false, - } - }; - let is = |taint: &[bool], v: Value| taint.get(v.index()).copied().unwrap_or(false); - for (f, c) in selections { - let blocks = self.blocks_of(*f); - for phi in &self.block(c.merge)?.phis { - set(taint, phi.result); - } - for p in (c.start + 1)..c.end { - let Some(b) = blocks.get(p as usize) else { - continue; - }; - for node in &self.block(*b)?.insts { - let ptrs: Vec = match &node.inst { - Inst::Store { ptr, .. } => vec![*ptr], - Inst::Call { args, .. } => args - .iter() - .copied() - .filter(|a| self.is_pointer(*a)) - .collect(), - other => other.atomic_pointer().into_iter().collect(), - }; - for ptr in ptrs { - match self.root(ptr) { - Root::Other if self.class(ptr) == Some(StorageClass::Function) => { - // A parameter's pointer: the caller's variable. - return Ok(false); - } - Root::Other => {} - r => { - vars.insert(r); - } - } - } - } - } - } - let mut passes = 0; - loop { - passes += 1; - if passes > MAX_PASSES { - return Ok(false); - } - let mut changed = false; - for f in &self.order { - let func = m - .functions - .get(f.index()) - .ok_or_else(|| invariant("a reached function"))?; - for b in &func.blocks { - let blk = self.block(*b)?; - meter.tick( - u32::try_from(blk.insts.len() + blk.phis.len()).unwrap_or(u32::MAX), - )?; - for phi in &blk.phis { - if phi.incoming.iter().any(|(v, _)| is(taint, *v)) { - changed |= set(taint, phi.result); - } - } - for node in &blk.insts { - let inst = &node.inst; - let mut hit = false; - inst.for_each_value(|v| hit |= is(taint, v)); - if let Inst::Load { ptr, .. } = inst { - hit |= vars.contains(&self.root(*ptr)); - } - if let Inst::Call { func: callee, args } = inst { - // A tainted argument taints its parameter, for every call (the - // callee's own instructions are followed in the same passes), and a - // tainted return value every call's result. - let callee_fn = m - .functions - .get(callee.index()) - .ok_or_else(|| invariant("a called function"))?; - for (param, arg) in callee_fn.params.iter().zip(args.iter()) { - if is(taint, *arg) { - changed |= set(taint, *param); - } - } - hit |= returns.get(callee.index()).copied().unwrap_or(false); - } - if !hit { - continue; - } - if inst.is_tangled() { - return Ok(false); - } - let ptr = match inst { - Inst::Store { ptr, .. } => Some(*ptr), - other => other.atomic_pointer(), - }; - if let Some(ptr) = ptr { - match self.root(ptr) { - Root::Other if self.class(ptr) == Some(StorageClass::Function) => { - return Ok(false); - } - Root::Other => {} - r => changed |= vars.insert(r), - } - } - if let Some(r) = node.result { - changed |= set(taint, r); - } - } - match blk.term { - Terminator::CondBranch { cond: v, .. } - | Terminator::Switch { sel: v, .. } - if tangled_anywhere && is(taint, v) => - { - return Ok(false); - } - Terminator::ReturnValue(v) if is(taint, v) => { - if let Some(x) = returns.get_mut(f.index()) { - if !*x { - *x = true; - changed = true; - } - } - } - _ => {} - } - } - } - if !changed { - return Ok(true); - } - } - } -} - -/// Whether a value of type `ty` is a lane a simdgroup shuffle moves ([`Facts::fenceable`]). -fn lane_type(m: &TypedModule, ty: TypeId, extended: bool) -> Result { - let scalar = match m.types.get(ty)? { - Type::Vector { elem, .. } => *elem, - _ => ty, - }; - Ok(match m.types.get(scalar)? { - Type::Int { width, .. } => *width == 32 || (extended && matches!(*width, 8 | 16)), - Type::Float { width } => *width == 32 || (extended && *width == 16), - _ => false, - }) -} - -impl Fences { - /// Follow each fenced call with an identity shuffle of what it computes: its result read in - /// every invocation from the invocation's own lane (`OpGroupNonUniformShuffle` at - /// `SubgroupLocalInvocationId`, a structure's members each), which every later use reads in - /// its place. Every invocation, a helper too, reads its own value, so no answer changes; the - /// shuffle is the tangled instruction after the call that keeps the simdgroup's writes on - /// Apple's compiler (the module docs). The entry reads the lane through the module's - /// `SubgroupLocalInvocationId` input, declared where the module has none. - pub fn apply(&self, m: &mut TypedModule) -> Result<(), Error> { - if self.sites.is_empty() { - return Ok(()); - } - let u32_ty = ty( - m, - Type::Int { - width: 32, - signed: false, - }, - )?; - let lane = lane_input(m, u32_ty)?; - let scope = ScopeId { - scope: Scope::Subgroup, - id: constant_id( - m, - Constant::Scalar { - ty: u32_ty, - bits: ConstBits(Scope::Subgroup.to_spirv() as u64), - }, - )?, - }; - for &(b, v) in &self.sites { - fence(m, (b, v), lane, u32_ty, scope)?; - } - m.rederive()?; - Ok(()) - } -} - -/// The pointer of the module's `SubgroupLocalInvocationId` input, declared where it has none. -fn lane_input(m: &mut TypedModule, u32_ty: TypeId) -> Result { - let builtin = crate::spv::BuiltIn::SubgroupLocalInvocationId; - let found = m.globals.iter().find(|g| { - g.kind - == GlobalKind::BuiltIn { - builtin, - dir: IoDir::Input, - } - && g.pointee == u32_ty - }); - if let Some(g) = found { - return Ok(g.value); - } - let class = StorageClass::Input; - let ptr_ty = ty( - m, - Type::Pointer { - class, - pointee: u32_ty, - }, - )?; - let id = GlobalId::new(u32::try_from(m.globals.len()).map_err(|_| invariant("global ids"))?); - let value = new_value(m, ptr_ty, ValueOrigin::Global(id))?; - m.globals.push(GlobalVar { - class, - pointee: u32_ty, - ptr_ty, - value, - init: None, - kind: GlobalKind::BuiltIn { - builtin, - dir: IoDir::Input, - }, - }); - m.decls.push(Decl::Global(id)); - Ok(value) -} - -/// Follow the call of block `b` whose result is `v` with an identity shuffle of `v` (a -/// structure's members each, put together again), renaming every use of `v` in its function to -/// the shuffled value. -fn fence( - m: &mut TypedModule, - (b, v): (BlockId, Value), - lane: Value, - u32_ty: TypeId, - scope: ScopeId, -) -> Result<(), Error> { - let blk = m - .blocks - .get(b.index()) - .ok_or_else(|| invariant("a fenced call's block"))?; - let func = blk.func; - let at = blk - .insts - .iter() - .position(|n| n.result == Some(v)) - .ok_or_else(|| invariant("a fenced call"))?; - let ty_of = |m: &TypedModule, x: Value| { - m.values - .get(x.index()) - .map(|d| d.ty) - .ok_or_else(|| invariant("a fenced value")) - }; - let result_ty = ty_of(m, v)?; - let fenced = new_value(m, result_ty, ValueOrigin::Inst(b))?; - // Every use reads the shuffled value; the shuffle, placed after this, reads the call's. - let rename = |x: &mut Value| { - if *x == v { - *x = fenced; - } - }; - for blk in m.blocks.iter_mut().filter(|blk| blk.func == func) { - for phi in &mut blk.phis { - for (x, _) in &mut phi.incoming { - rename(x); - } - } - for node in &mut blk.insts { - node.inst.for_each_value_mut(rename); - } - blk.term.for_each_value_mut(rename); - } - if m.stored_texels.contains(&v) { - m.stored_texels.insert(fenced); - } - let mut nodes = Vec::new(); - let id = new_value(m, u32_ty, ValueOrigin::Inst(b))?; - nodes.push(InstNode { - result: Some(id), - inst: Inst::Load { - ptr: lane, - access: MemAccess::default(), - }, - }); - let shuffle = |value| Inst::Group { - scope, - op: GroupInst::Shuffle { - op: ShuffleOp::Shuffle, - value, - x: id, - }, - }; - let members = match m.types.get(result_ty)? { - Type::Struct { members, .. } => Some(members.to_vec()), - _ => None, - }; - match members { - Some(members) => { - let mut parts = Vec::with_capacity(members.len()); - for (k, member) in members.into_iter().enumerate() { - let index = u32::try_from(k).map_err(|_| invariant("a member index"))?; - let part = new_value(m, member, ValueOrigin::Inst(b))?; - nodes.push(InstNode { - result: Some(part), - inst: Inst::CompositeExtract { - composite: v, - indices: Box::new([index]), - }, - }); - let moved = new_value(m, member, ValueOrigin::Inst(b))?; - nodes.push(InstNode { - result: Some(moved), - inst: shuffle(part), - }); - parts.push(moved); - } - nodes.push(InstNode { - result: Some(fenced), - inst: Inst::CompositeConstruct { - parts: parts.into_boxed_slice(), - }, - }); - } - None => nodes.push(InstNode { - result: Some(fenced), - inst: shuffle(v), - }), - } - let blk = m - .blocks - .get_mut(b.index()) - .ok_or_else(|| invariant("a fenced call's block"))?; - let tail = blk.insts.split_off(at + 1); - blk.insts.extend(nodes); - blk.insts.extend(tail); - Ok(()) -} - -/// Make the header of `g` send its helper invocations by its route. -fn apply(m: &mut TypedModule, g: &Guard) -> Result<(), Error> { - let bool_ty = ty(m, Type::Bool)?; - let h = value(m, g.header, bool_ty, Inst::IsHelperInvocation)?; - let blk = m - .blocks - .get(g.header.index()) - .ok_or_else(|| invariant("a guarded header"))?; - let new = match (&blk.term, g.route) { - (Terminator::CondBranch { cond, .. }, Route::False) => { - let cond = *cond; - let not = value( - m, - g.header, - bool_ty, - Inst::Unary { - op: UnOp::LogicalNot, - a: h, - }, - )?; - value( - m, - g.header, - bool_ty, - Inst::Binary { - op: BinOp::LogicalAnd, - a: cond, - b: not, - contract: Contraction::Allowed, - }, - )? - } - (Terminator::CondBranch { cond, .. }, Route::True) => { - let cond = *cond; - value( - m, - g.header, - bool_ty, - Inst::Binary { - op: BinOp::LogicalOr, - a: cond, - b: h, - contract: Contraction::Allowed, - }, - )? - } - (Terminator::Switch { sel, .. }, Route::Case(lit)) => { - let sel = *sel; - let sel_ty = m - .values - .get(sel.index()) - .map(|d| d.ty) - .ok_or_else(|| invariant("a switch selector"))?; - let lit = constant( - m, - Constant::Scalar { - ty: sel_ty, - bits: ConstBits(lit), - }, - )?; - value( - m, - g.header, - sel_ty, - Inst::Select { - cond: h, - t: lit, - f: sel, - }, - )? - } - _ => return Err(invariant("a guard's route does not fit its header")), - }; - let blk = m - .blocks - .get_mut(g.header.index()) - .ok_or_else(|| invariant("a guarded header"))?; - match &mut blk.term { - Terminator::CondBranch { cond, .. } => *cond = new, - Terminator::Switch { sel, .. } => *sel = new, - _ => return Err(invariant("a guarded header without a branch")), - } - Ok(()) -} - -/// Intern type `t`, declaring it when new. -fn ty(m: &mut TypedModule, t: Type) -> Result { - let (id, fresh) = m.types.intern(t, &m.consts)?; - if fresh { - m.decls.push(Decl::Type(id)); - } - Ok(id) -} - -fn new_value( - m: &mut TypedModule, - ty: crate::spirv::ids::TypeId, - origin: ValueOrigin, -) -> Result { - let v = Value::new(u32::try_from(m.values.len()).map_err(|_| invariant("value ids"))?); - m.values.push(ValueDef { ty, origin }); - Ok(v) -} - -/// Append `inst` of result type `ty` to block `b`'s instructions; its result. -fn value( - m: &mut TypedModule, - b: BlockId, - ty: crate::spirv::ids::TypeId, - inst: Inst, -) -> Result { - let v = new_value(m, ty, ValueOrigin::Inst(b))?; - m.blocks - .get_mut(b.index()) - .ok_or_else(|| invariant("a guarded header"))? - .insts - .push(InstNode { - result: Some(v), - inst, - }); - Ok(v) -} - -/// The value of plain constant `c`, declaring it when new. -fn constant(m: &mut TypedModule, c: Constant) -> Result { - let id = constant_id(m, c)?; - Ok(m.const_value(id)?) -} - -/// Plain constant `c`, declared when new. -fn constant_id(m: &mut TypedModule, c: Constant) -> Result { - let ty = c.ty(); - let (id, fresh) = m.consts.intern(c, &m.types)?; - if fresh { - if id.index() != m.const_values.len() { - return Err(invariant("constant ids")); - } - let v = new_value(m, ty, ValueOrigin::Const(id))?; - m.const_values.push(v); - m.decls.push(Decl::Const(id)); - } - Ok(id) -} diff --git a/crates/metal2vulkan/src/spirv/mod.rs b/crates/metal2vulkan/src/spirv/mod.rs index 34afd8e62..2ce2592cc 100644 --- a/crates/metal2vulkan/src/spirv/mod.rs +++ b/crates/metal2vulkan/src/spirv/mod.rs @@ -8,7 +8,6 @@ pub mod builder; pub mod dead; pub mod error; pub mod half_hold; -pub mod helper_branches; pub mod hoist; pub mod ids; // The CPU interpreter: test support for the crate's own tests. diff --git a/crates/metal2vulkan/src/tests/engine_coverage_loop.rs b/crates/metal2vulkan/src/tests/engine_coverage_loop.rs index ed1701964..1b651b8eb 100644 --- a/crates/metal2vulkan/src/tests/engine_coverage_loop.rs +++ b/crates/metal2vulkan/src/tests/engine_coverage_loop.rs @@ -32,7 +32,7 @@ use std::path::Path; use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy, DriverWorkaround}; +use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::error::{Error, Feature, Needs, RuntimeInput, Unsupported}; use crate::library::Library; use crate::metal::PixelFormat; @@ -111,17 +111,6 @@ fn device(stem: &str) -> Device { Device::from_queries(description(stem), DevicePolicy::default()).expect("device") } -/// The refusal of a memory writer on a driver that runs it once per covered sample where that -/// driver would mask its coverage, where `dev`'s profile carries that workaround. -fn per_sample_defect(dev: &Device) -> Option { - let defect = DriverWorkaround::MemoryWritingFragmentsRunPerSample; - dev.profile() - .fields() - .workarounds - .contains(&defect) - .then(|| Unsupported::driver_defect(Feature::PixelCoverageAtSampleRate, defect).into()) -} - /// Every committed profile's stem, sorted. fn stems() -> Vec { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); @@ -256,10 +245,9 @@ fn a_coverage_reading_memory_writer_loops_over_its_covered_samples() { for samples in [2, 4] { let what = format!("{stem} at {samples}"); let d = render(&lib, function(&lib, COVERAGE), samples, false); - let driver_runs = per_sample_defect(&dev).is_some(); match dev.compile_render_pipeline(&d, &Budget::standard()) { Ok(p) => { - looped += usize::from(!driver_runs); + looped += 1; assert!(!p.graphics.sample_shading, "{what}"); assert_eq!( Shape { @@ -268,8 +256,8 @@ fn a_coverage_reading_memory_writer_loops_over_its_covered_samples() { }, Shape { sample_mask: true, - loops: !driver_runs, - find_lsb: !driver_runs, + loops: true, + find_lsb: true, ..Shape::default() }, "{what}" @@ -513,9 +501,8 @@ fn l3(dev: &Device, p: &RenderPipeline, what: &str) { /// made), and the sample-qualified varying loops, read at each /// pass's sample through `InterpolateAtSample` with no `Sample` decoration, or is refused as /// needing the interpolation functions on a device that withholds them. A device that does not -/// make the memory writers refuses them for what it lacks, never for the loop, except a driver -/// that runs a memory writer once per covered sample (MoltenVK on Apple's GPU), which refuses them, -/// and the varying, as its defect, and every other function by its reason. +/// make the memory writers refuses them for what it lacks, never for the loop, and every other +/// function by its reason. #[test] fn the_loop_refuses_each_function_it_does_not_fit_by_its_reason() { let Some(lib) = library("coverage_loop") else { @@ -531,12 +518,7 @@ fn the_loop_refuses_each_function_it_does_not_fit_by_its_reason() { for stem in stems() { let dev = device(&stem); let fits = COV_FITS.map(|f| coverage_loop_pipeline(&dev, &lib, COV_COVER, f)); - let defect = per_sample_defect(&dev); - if let Some(defect) = &defect { - for (f, made) in COV_FITS.iter().zip(&fits) { - assert_eq!(made.as_ref().map(|_| ()), Err(defect), "{f} on {stem}"); - } - } else if fits.iter().any(Result::is_err) { + if fits.iter().any(Result::is_err) { for (f, made) in COV_FITS.iter().zip(&fits) { match made { Ok(_) => {} diff --git a/crates/metal2vulkan/src/tests/engine_fragment.rs b/crates/metal2vulkan/src/tests/engine_fragment.rs index f7bc86630..317cae28e 100644 --- a/crates/metal2vulkan/src/tests/engine_fragment.rs +++ b/crates/metal2vulkan/src/tests/engine_fragment.rs @@ -207,7 +207,7 @@ fn simd_after_discard(bc: &[u8], entry: &str, stem: &str, p: &DeviceProfile) { /// The `if !discarded` selections of `m`: conditional branches on the negation of a load of a /// `Private` variable, as the guard of a side effect a predicated site reaches is written. fn discard_guards(m: &TypedModule) -> usize { - use crate::spirv::ir::{BinOp, StorageClass, UnOp, ValueOrigin}; + use crate::spirv::ir::{StorageClass, UnOp, ValueOrigin}; let defs: std::collections::HashMap<_, _> = m .blocks() .iter() @@ -224,16 +224,9 @@ fn discard_guards(m: &TypedModule) -> usize { let loaded = |v| matches!(defs.get(&v), Some(Inst::Load { ptr, .. }) if private(*ptr)); let not_discarded = |v| matches!(defs.get(&v), Some(Inst::Unary { op: UnOp::LogicalNot, a }) if loaded(*a)); - // Or the predicate and'ed with "not a helper" (`spirv::helper_branches`), which a guard takes - // on MoltenVK where its arm calls a routine SPIRV-Cross writes `optnone` code in. m.blocks() .iter() - .filter(|b| { - matches!(&b.term, Terminator::CondBranch { cond, .. } - if not_discarded(*cond) - || matches!(defs.get(cond), Some(Inst::Binary { op: BinOp::LogicalAnd, a, .. }) - if not_discarded(*a))) - }) + .filter(|b| matches!(&b.term, Terminator::CondBranch { cond, .. } if not_discarded(*cond))) .count() } @@ -278,17 +271,14 @@ fn predication_guards_the_side_effects_after_a_site() { /// demote, as no whole-quad exit can be placed on a profile without fragment quad operations. A /// device that demotes (`moltenvk-m3`, `intel-arl-anv`) demotes each and guards nothing; the /// simdgroup sum, which counts the helpers Metal runs, is refused needing `shaderQuadControl` -/// where the device lacks it (`moltenvk-m3`), as only full quads give those helpers. No module -/// defers a discard (`fragment.discard.deferred`) or records -/// `PrecisionNote::DiscardDropsSimdgroupStores`. Every module passes L3. +/// where the device lacks it (`moltenvk-m3`), as only full quads give those helpers. Every module +/// passes L3. #[test] fn a_predicated_discard_guards_each_later_store_atomic_and_image_write() { use crate::spirv::ir::ValueOrigin; let Some(bc) = fixture("rch_guarded_effects") else { return; }; - let noted = PrecisionNote::DiscardDropsSimdgroupStores; - let deferred = "fragment.discard.deferred"; // (entry, its side effects after the discard) let cases = [ ("rch_guarded_store", 1), @@ -363,12 +353,6 @@ fn a_predicated_discard_guards_each_later_store_atomic_and_image_write() { assert!(zero_merged, "{what}: no merge of the atomic's result"); } let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - assert!( - !a.strategies.entries.contains_key(deferred), - "{what}: {:?}", - a.strategies.entries.keys().collect::>() - ); - assert!(!a.precision.contains(¬ed), "{what}: the note"); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); } } @@ -5341,93 +5325,6 @@ fn a_blended_extended_range_output_records_its_blend_note() { assert!(checked > 0, "no interlock profile made the storage form"); } -/// The selection headers of `m` whose condition or selector asks whether the invocation is a -/// helper, as `spirv::helper_branches` writes it: the condition or'ed with -/// `OpIsHelperInvocationEXT`, and'ed with its negation, or a selector chosen by it. -fn helper_guards(m: &TypedModule) -> usize { - use crate::spirv::ir::{BinOp, UnOp}; - let defs: std::collections::HashMap<_, _> = m - .blocks() - .iter() - .flat_map(|b| &b.insts) - .filter_map(|n| n.result.map(|r| (r, &n.inst))) - .collect(); - let helper = |v| matches!(defs.get(&v), Some(Inst::IsHelperInvocation)); - let not_helper = - |v| matches!(defs.get(&v), Some(Inst::Unary { op: UnOp::LogicalNot, a }) if helper(*a)); - m.blocks() - .iter() - .filter(|b| match &b.term { - Terminator::CondBranch { cond, .. } => match defs.get(cond) { - Some(Inst::Binary { - op: BinOp::LogicalOr, - b: x, - .. - }) => helper(*x), - Some(Inst::Binary { - op: BinOp::LogicalAnd, - b: x, - .. - }) => not_helper(*x), - _ => false, - }, - Terminator::Switch { sel, .. } => { - matches!(defs.get(sel), Some(Inst::Select { cond, .. }) if helper(*cond)) - } - _ => false, - }) - .count() -} - -/// A selection whose condition every invocation of a draw computes alike (a constant block's flag) -/// holds no branch only helper invocations take, so an `optnone` call in its arm is neither guarded -/// nor noted. The owned fixture `rch_uniform_branch` divides a coordinate by a texture's size and -/// takes the high word of a product (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes -/// through its `optnone` `spvMulExtended`) in a branch on a constant block's flag, then samples -/// the texture at the coordinate and writes the sample and the product to a buffer. On -/// `moltenvk-m3` the module holds the product, and no helper census entry, no guard, no -/// `HelperBranchDropsSimdgroupStores`, and L3. -#[test] -fn a_branch_every_invocation_takes_alike_leaves_no_helper_alone() { - use crate::spirv::ir::BinOp; - let Some(bc) = fixture("rch_uniform_branch") else { - return; - }; - let p = profile("moltenvk-m3", DevicePolicy::default()).expect("profile"); - let noted = PrecisionNote::HelperBranchDropsSimdgroupStores; - let what = "rch_uniform_branch on moltenvk-m3"; - let inputs = LoweringInputs::new(); - let (_, m) = typed_module_with(&bc, "rch_uniform_branch", &p, &inputs) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_with(&bc, "rch_uniform_branch", &p, &inputs) - .unwrap_or_else(|e| panic!("{what}: {e}")); - let helper: Vec<_> = a - .strategies - .entries - .keys() - .filter(|k| k.starts_with("fragment.helper")) - .collect(); - let products = m - .blocks() - .iter() - .flat_map(|b| &b.insts) - .filter(|n| { - matches!( - n.inst, - Inst::Binary { - op: BinOp::UMulExtended, - .. - } - ) - }) - .count(); - assert_eq!(products, 1, "{what}: the products"); - assert!(helper.is_empty(), "{what}: {helper:?}"); - assert_eq!(helper_guards(&m), 0, "{what}"); - assert!(!a.precision.contains(¬ed), "{what}: the note"); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); -} - /// The opcodes of every instruction in `words`, and the capabilities it declares. fn opcodes_and_capabilities(words: &[u32]) -> (Vec, Vec) { let (mut ops, mut caps) = (Vec::new(), Vec::new()); diff --git a/docs/API.md b/docs/API.md index e3df5c328..4df919336 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2405,12 +2405,6 @@ bound. steepest, in the conformance suite's extended-range and padded blend cases; and where the device's compiler regroups a padded format's blend, an infinite second source stores the end code its sign picks where Metal's sum is NaN, stored as code 0. -- `metal2vulkan-degrade-discard-drops-simdgroup-stores` (precision). - `PrecisionNote::DiscardDropsSimdgroupStores`: Recorded by no device: its condition, - `DriverWorkaround::DiscardDropsSimdgroupStores`, is one no profile takes. -- `metal2vulkan-degrade-helper-branch-drops-simdgroup-stores` (precision). - `PrecisionNote::HelperBranchDropsSimdgroupStores`: Recorded by no device: its condition, - `DriverWorkaround::DiscardDropsSimdgroupStores`, is one no profile takes. - `metal2vulkan-degrade-extended-range-float-blend-source` (precision). `PrecisionNote::ExtendedRangeFloatBlendSource`: `PrecisionNote::ExtendedRangeBlendSource` for a `float` color output (a scalar or vector of AIR's `float`): blended into an extended-range or