SEMANTICS 2143 / RUNTIME 2517: a selection on an own-pixel read keeps its snapshot slot

A fragment function that reads its own pixel of a colour attachment and branches on the value
was refused its snapshot read (SnapshotRefusal::Branch), so each such draw split its render pass
and copied the texture. On the consumer's desktop walks that was 614 draws/s on the XTX and the
Radeon 780M (510 render-pass splits/s, 20.8 M texels/s of split copies) and 107 draws/s on the
Iris Xe. In a pipeline dump of the 780M walk, 30 of the 33 readers refused for Branch branch
through selections whose arms hold no derivative, implicit-level sample, group op, kill or loop;
their values leave the arms through Function variables, not phis.

The rule (spirv/requirements/snapshot.rs, new snapshot/arms.rs): a branch or switch on a fetched
value keeps the slot when it is a selection whose arms leave only through its merge (no break,
continue, return, OpKill, OpTerminateInvocation or unreachable end), hold no tangled instruction
(Inst::is_tangled: a derivative, an implicit-level sample or LOD query, a subgroup or quad op),
hold no loop and no non-constant integer divisor or dynamic index, and call no function that
holds any of these. The merge's phis and the Function, Private and Output variables the arms (or
their callees) store to take the condition's reach, so a merged value that reaches a derivative
still refuses the slot (Derivative). A helper invocation may then take either arm: its stores to
Function, Private and Output memory have no effect beyond it ("Helper Invocations"), and nothing
in the arms observes its neighbours. The loop form stays Branch. demote_guard goes: the rule
covers it (demote arms are clean arms).

The facts a module states change (snapshot_textures, snapshot_refusals): SEMANTICS bump. A new
owned fixture, engine/snapshot_select.metal (scripts/regen-air-fixtures). No new Degradation
kind, WorkCounts field or public signature. Docs: SnapshotRefusal::Branch, docs/API.md (Snapshot
reads).

Tests: snapshot::tests (kept: empty arm, demote arms, Private store, callee and pointer forms;
refused for Branch: an arm with a derivative, a call to one, a kill, a loop, a non-constant
divisor, the loop exit; refused for Derivative: an arm's store or a merge phi reaching a
derivative); compile::tests::a_selection_on_the_texel_keeps_the_slot_where_a_helper_may_take_
either_arm (ss_read_selecting states no refusal on the 780M and lavapipe profiles;
ss_read_selecting_dfdx and wlk_read_branch state Branch); runtime_lane::snapshot_reads 12/12 on
lavapipe with two new lanes.

Verified (snapbranch lane): clippy -D warnings on the three crates (m3-max-39324), touched tests
6/6, lavapipe snapshot_reads 12/12 (m3-max-39334). The fixture's inventory, air_input printout
and golden hashes re-bless on development; clippy under the GPU cfgs, rustdoc, the release
translation timings and the PHOENIX lane run follow there.
This commit is contained in:
Anees Iqbal committed 2026-11-16 22:47:15 -08:00
1 parent 68c456e5ba
commit 4114585b2a
14 files changed
+911 -93

No files matched your search

@@ -11728,7 +11728,7 @@ pub struct WorkCounts {
/// (`StageModule::snapshot_refusals`).
pub reading_draws_split_unreadable_own_pixel: u64,
/// Of `reading_draws_split_unreadable_own_pixel`, those of a slot whose read decides a branch
/// or a switch, beside a branch that only decides whether the invocation demotes itself
/// or a switch, beside a selection a helper invocation may take either arm of
/// (`SnapshotRefusal::Branch`). A draw is counted in each of the clauses below that leave out
/// any of its slots no snapshot serves.
pub reading_draws_split_unreadable_own_pixel_branch: u64,
@@ -344,6 +344,7 @@ fixture smp_shared_sampler: metal: Apple metal version 32023.921 (metalfe-32023.
fixture smw_unread: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture smw_writers: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture snapshot_discard: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118)
fixture snapshot_select: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118)
fixture spc_bool_index: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture spc_num_samples: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture sps2_residency_probes: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
@@ -0,0 +1,126 @@
; Generated by scripts/regen-air-fixtures from snapshot_select.metal (typed pointers; xcrun metal-as reassembles it). Do not edit.
; ModuleID = '-'
source_filename = "-"
target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
%struct._texture_2d_t = type opaque
%struct._sampler_t = type opaque
; Function Attrs: mustprogress nofree nounwind readonly willreturn
define <4 x float> @ss_read_selecting(<4 x float> %0, %struct._texture_2d_t addrspace(1)* nocapture readonly %1) local_unnamed_addr #0 {
%3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> <i32 0, i32 1>
%4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7
%5 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8
%6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %1, %struct._sampler_t addrspace(2)* %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9
%7 = extractvalue { <4 x float>, i8 } %6, 0
%8 = extractelement <4 x float> %7, i64 0
%9 = fcmp ogt float %8, 0x3FD99999A0000000
br i1 %9, label %10, label %18
10: ; preds = %2
%11 = extractelement <4 x float> %7, i64 1
%12 = tail call float @air.sin.f32(float %11) #7
%13 = extractelement <4 x float> %7, i64 2
%14 = tail call float @air.exp2.f32(float %13) #7
%15 = fmul float %12, %14
%16 = tail call float @llvm.fmuladd.f32(float %8, float 5.000000e-01, float %15)
%17 = insertelement <4 x float> %7, float %16, i64 0
br label %18
18: ; preds = %10, %2
%19 = phi <4 x float> [ %17, %10 ], [ %7, %2 ]
ret <4 x float> %19
}
; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn
declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) local_unnamed_addr #1
; Function Attrs: mustprogress nocallback nofree nosync nounwind readnone speculatable willreturn
declare float @llvm.fmuladd.f32(float, float, float) #2
; Function Attrs: convergent mustprogress nounwind willreturn
define <4 x float> @ss_read_selecting_dfdx(<4 x float> %0, %struct._texture_2d_t addrspace(1)* nocapture readonly %1) local_unnamed_addr #3 {
%3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> <i32 0, i32 1>
%4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7
%5 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8
%6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %1, %struct._sampler_t addrspace(2)* %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9
%7 = extractvalue { <4 x float>, i8 } %6, 0
%8 = extractelement <4 x float> %7, i64 0
%9 = fcmp ogt float %8, 0x3FD99999A0000000
br i1 %9, label %10, label %21
10: ; preds = %2
%11 = extractelement <4 x float> %7, i64 1
%12 = tail call float @air.sin.f32(float %11) #7
%13 = extractelement <4 x float> %7, i64 2
%14 = tail call float @air.exp2.f32(float %13) #7
%15 = fmul float %12, %14
%16 = tail call float @llvm.fmuladd.f32(float %8, float 5.000000e-01, float %15)
%17 = extractelement <4 x float> %0, i64 0
%18 = tail call float @air.dfdx.f32(float %17) #10
%19 = tail call float @llvm.fmuladd.f32(float %11, float %18, float %16)
%20 = insertelement <4 x float> %7, float %19, i64 0
br label %21
21: ; preds = %10, %2
%22 = phi <4 x float> [ %20, %10 ], [ %7, %2 ]
ret <4 x float> %22
}
; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn
declare float @air.sin.f32(float) local_unnamed_addr #1
; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn
declare float @air.exp2.f32(float) local_unnamed_addr #1
; Function Attrs: convergent mustprogress nounwind willreturn
declare float @air.dfdx.f32(float) local_unnamed_addr #4
; Function Attrs: inaccessiblememonly mustprogress nofree nounwind readonly willreturn
declare %struct._sampler_t addrspace(2)* @air.get_read_sampler() local_unnamed_addr #5
; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn
declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #6
attributes #0 = { mustprogress nofree nounwind readonly willreturn "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
attributes #1 = { mustprogress nofree nosync nounwind readnone willreturn }
attributes #2 = { mustprogress nocallback nofree nosync nounwind readnone speculatable willreturn }
attributes #3 = { convergent mustprogress nounwind willreturn "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
attributes #4 = { convergent mustprogress nounwind willreturn }
attributes #5 = { inaccessiblememonly mustprogress nofree nounwind readonly willreturn }
attributes #6 = { argmemonly mustprogress nofree nounwind readonly willreturn }
attributes #7 = { nounwind readnone willreturn }
attributes #8 = { inaccessiblememonly nounwind readonly willreturn }
attributes #9 = { argmemonly nounwind readonly willreturn }
attributes #10 = { convergent nounwind willreturn }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8}
!air.fragment = !{!9, !15}
!air.compile_options = !{!16, !17, !18}
!llvm.ident = !{!19}
!air.version = !{!20}
!air.language_version = !{!21}
!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]}
!1 = !{i32 1, !"wchar_size", i32 4}
!2 = !{i32 7, !"frame-pointer", i32 2}
!3 = !{i32 7, !"air.max_device_buffers", i32 31}
!4 = !{i32 7, !"air.max_constant_buffers", i32 31}
!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31}
!6 = !{i32 7, !"air.max_textures", i32 128}
!7 = !{i32 7, !"air.max_read_write_textures", i32 8}
!8 = !{i32 7, !"air.max_samplers", i32 16}
!9 = !{<4 x float> (<4 x float>, %struct._texture_2d_t addrspace(1)*)* @ss_read_selecting, !10, !12}
!10 = !{!11}
!11 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}
!12 = !{!13, !14}
!13 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!14 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d<float, read>", !"air.arg_name", !"t"}
!15 = !{<4 x float> (<4 x float>, %struct._texture_2d_t addrspace(1)*)* @ss_read_selecting_dfdx, !10, !12}
!16 = !{!"air.compile.denorms_disable"}
!17 = !{!"air.compile.fast_math_disable"}
!18 = !{!"air.compile.framebuffer_fetch_enable"}
!19 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"}
!20 = !{i32 2, i32 8, i32 0}
!21 = !{!"Metal", i32 4, i32 0, i32 0}
@@ -0,0 +1,123 @@
; Generated by scripts/regen-air-fixtures from snapshot_select.metal (llvm-dis of snapshot_select.air). Do not edit.
; ModuleID = '<stdin>'
source_filename = "-"
target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
; Function Attrs: mustprogress nofree nounwind willreturn memory(read)
define <4 x float> @ss_read_selecting(<4 x float> %0, ptr addrspace(1) readonly captures(none) %1) local_unnamed_addr #0 {
%3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> <i32 0, i32 1>
%4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7
%5 = tail call ptr addrspace(2) @air.get_read_sampler() #8
%6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %1, ptr addrspace(2) %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9
%7 = extractvalue { <4 x float>, i8 } %6, 0
%8 = extractelement <4 x float> %7, i64 0
%9 = fcmp ogt float %8, 0x3FD99999A0000000
br i1 %9, label %10, label %18
10: ; preds = %2
%11 = extractelement <4 x float> %7, i64 1
%12 = tail call float @air.sin.f32(float %11) #7
%13 = extractelement <4 x float> %7, i64 2
%14 = tail call float @air.exp2.f32(float %13) #7
%15 = fmul float %12, %14
%16 = tail call float @llvm.fmuladd.f32(float %8, float 5.000000e-01, float %15)
%17 = insertelement <4 x float> %7, float %16, i64 0
br label %18
18: ; preds = %10, %2
%19 = phi <4 x float> [ %17, %10 ], [ %7, %2 ]
ret <4 x float> %19
}
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) local_unnamed_addr #1
; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
declare float @llvm.fmuladd.f32(float, float, float) #2
; Function Attrs: convergent mustprogress nounwind willreturn
define <4 x float> @ss_read_selecting_dfdx(<4 x float> %0, ptr addrspace(1) readonly captures(none) %1) local_unnamed_addr #3 {
%3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> <i32 0, i32 1>
%4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7
%5 = tail call ptr addrspace(2) @air.get_read_sampler() #8
%6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %1, ptr addrspace(2) %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9
%7 = extractvalue { <4 x float>, i8 } %6, 0
%8 = extractelement <4 x float> %7, i64 0
%9 = fcmp ogt float %8, 0x3FD99999A0000000
br i1 %9, label %10, label %21
10: ; preds = %2
%11 = extractelement <4 x float> %7, i64 1
%12 = tail call float @air.sin.f32(float %11) #7
%13 = extractelement <4 x float> %7, i64 2
%14 = tail call float @air.exp2.f32(float %13) #7
%15 = fmul float %12, %14
%16 = tail call float @llvm.fmuladd.f32(float %8, float 5.000000e-01, float %15)
%17 = extractelement <4 x float> %0, i64 0
%18 = tail call float @air.dfdx.f32(float %17) #10
%19 = tail call float @llvm.fmuladd.f32(float %11, float %18, float %16)
%20 = insertelement <4 x float> %7, float %19, i64 0
br label %21
21: ; preds = %10, %2
%22 = phi <4 x float> [ %20, %10 ], [ %7, %2 ]
ret <4 x float> %22
}
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
declare float @air.sin.f32(float) local_unnamed_addr #1
; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none)
declare float @air.exp2.f32(float) local_unnamed_addr #1
; Function Attrs: convergent mustprogress nounwind willreturn
declare float @air.dfdx.f32(float) local_unnamed_addr #4
; Function Attrs: mustprogress nofree nounwind willreturn memory(inaccessiblemem: read)
declare ptr addrspace(2) @air.get_read_sampler() local_unnamed_addr #5
; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read)
declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #6
attributes #0 = { mustprogress nofree nounwind willreturn memory(read) "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
attributes #1 = { mustprogress nofree nosync nounwind willreturn memory(none) }
attributes #2 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }
attributes #3 = { convergent mustprogress nounwind willreturn "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
attributes #4 = { convergent mustprogress nounwind willreturn }
attributes #5 = { mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) }
attributes #6 = { mustprogress nofree nounwind willreturn memory(argmem: read) }
attributes #7 = { nounwind willreturn memory(none) }
attributes #8 = { nounwind willreturn memory(inaccessiblemem: read) }
attributes #9 = { nounwind willreturn memory(argmem: read) }
attributes #10 = { convergent nounwind willreturn }
!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8}
!air.fragment = !{!9, !15}
!air.compile_options = !{!16, !17, !18}
!llvm.ident = !{!19}
!air.version = !{!20}
!air.language_version = !{!21}
!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]}
!1 = !{i32 1, !"wchar_size", i32 4}
!2 = !{i32 7, !"frame-pointer", i32 2}
!3 = !{i32 7, !"air.max_device_buffers", i32 31}
!4 = !{i32 7, !"air.max_constant_buffers", i32 31}
!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31}
!6 = !{i32 7, !"air.max_textures", i32 128}
!7 = !{i32 7, !"air.max_read_write_textures", i32 8}
!8 = !{i32 7, !"air.max_samplers", i32 16}
!9 = !{ptr @ss_read_selecting, !10, !12}
!10 = !{!11}
!11 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}
!12 = !{!13, !14}
!13 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}
!14 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d<float, read>", !"air.arg_name", !"t"}
!15 = !{ptr @ss_read_selecting_dfdx, !10, !12}
!16 = !{!"air.compile.denorms_disable"}
!17 = !{!"air.compile.fast_math_disable"}
!18 = !{!"air.compile.framebuffer_fetch_enable"}
!19 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"}
!20 = !{i32 2, i32 8, i32 0}
!21 = !{!"Metal", i32 4, i32 0, i32 0}
@@ -0,0 +1,36 @@
// Owned fixture: fragment functions that read, at their own pixel, the texture their pass renders
// and select by the texel they read, as a compositor's blend does; the runtime's lane draws them
// with `tob_renders.metal`'s `tob_rect`. Written for this repository; no third-party source.
// Loop-free.
// metal-fast-math: off
#include <metal_stdlib>
using namespace metal;
struct SsVertex {
float4 position [[position]];
};
// The texel of t under the pixel, its red halved where it is above 0.4. The arm also adds the
// sine of the texel's green scaled by two to its blue, 0 for a texel of green 0, which keeps the
// arm a branch of its own.
fragment float4 ss_read_selecting(SsVertex in [[stage_in]],
texture2d<float, access::read> t [[texture(0)]]) {
float4 c = t.read(uint2(in.position.xy));
float4 o = c;
if (c.r > 0.4) {
o.r = c.r * 0.5 + sin(c.g) * exp2(c.b);
}
return o;
}
// The same selection, whose arm also adds the texel's green times the derivative of the
// fragment's x across its quad: 0 for a texel of green 0.
fragment float4 ss_read_selecting_dfdx(SsVertex in [[stage_in]],
texture2d<float, access::read> t [[texture(0)]]) {
float4 c = t.read(uint2(in.position.xy));
float4 o = c;
if (c.r > 0.4) {
o.r = c.r * 0.5 + sin(c.g) * exp2(c.b) + c.g * dfdx(in.position.x);
}
return o;
}
@@ -43,6 +43,18 @@
//! translator lets a snapshot serve its slot (`StageModule::snapshot_textures`): a snapshot for
//! each reader where the device takes the path, else a split for each, and never a split for an
//! own-pixel read no snapshot serves (`WorkCounts::reading_draws_split_unreadable_own_pixel`).
//! - [`a_reader_that_selects_by_its_texel_takes_the_snapshot`]: the first test's draws with a
//! reader that halves the red it read where it is above 0.4 (`ss_read_selecting` of
//! `snapshot_select.metal`): the first reader adds `FILL` twice (`3 * FILL`, 120, under the
//! bound), the second adds half of that (180). Its arms leave through their merge alone and hold
//! nothing a helper invocation's path through them passes on, so the translator lets a snapshot
//! serve its slot (`StageModule::snapshot_textures`): a snapshot for each reader where the device
//! takes the path, else a split for each, and never a split for an own-pixel read no snapshot
//! serves.
//! - [`a_reader_whose_arm_takes_a_derivative_takes_the_split_for_its_branch`]: the same draws with
//! `ss_read_selecting_dfdx`, whose arm also takes a derivative, whose quad a helper's path would
//! change: the same answers, through a split for each reader on every device, each an own-pixel
//! read no snapshot serves, counted under its branch alone.
//! - [`a_reader_that_ends_itself_by_its_texel_takes_the_split_for_its_branch`]: the same draws on
//! a device that withholds `shaderDemoteToHelperInvocation`, where the discard ends the
//! invocation: the same answers, through a split for each reader on every device, each an
@@ -156,6 +168,15 @@ const READ: Fragment = ("tob_read", "tob_renders.ll");
/// The reader that discards its fragment where the texel it read is redder than 0.4.
const READ_DISCARDING: Fragment = ("sd_read_discarding", "snapshot_discard.ll");
/// The reader that halves the red it read where it is above 0.4.
const READ_SELECTING: Fragment = ("ss_read_selecting", "snapshot_select.ll");
/// [`READ_SELECTING`]'s selection, whose arm also takes a derivative.
const READ_SELECTING_DFDX: Fragment = ("ss_read_selecting_dfdx", "snapshot_select.ll");
/// The red the readers that select leave at the block: `3 * FILL`, then half of that added.
const SELECTED: u8 = 3 * FILL + 3 * FILL / 2;
/// The features the snapshot path takes.
const FEATURES: [VkFeature; 4] = [
VkFeature::AttachmentFeedbackLoopLayout,
@@ -748,6 +769,81 @@ fn a_reader_that_ends_itself_by_its_texel_takes_the_split_for_its_branch() {
);
}
#[test]
fn a_reader_that_selects_by_its_texel_takes_the_snapshot() {
on_default_policy(
|_| {},
|device| {
let queue = device.new_command_queue().unwrap();
let format = PixelFormat::RGBA8Unorm;
let before = device.work_counts();
let (bytes, moved, _) =
readers_over(device, &queue, format, true, None, false, READ_SELECTING);
let after = device.work_counts();
let unreadable = after.reading_draws_split_unreadable_own_pixel
- before.reading_draws_split_unreadable_own_pixel;
let takes = snapshots(device);
eprintln!(
"snapshot reads, a selecting reader, features {takes}: {moved:?}, \
unreadable own-pixel splits {unreadable}, by clause {:?}",
unreadable_by(&before, &after)
);
holds("a selecting reader", &bytes, SELECTED);
assert_eq!(
unreadable, 0,
"splits for an own-pixel read no snapshot serves"
);
let (snapshotted, splits) = if takes { (2, 0) } else { (0, 2) };
assert_eq!(
(moved.snapshotted, moved.splits),
(snapshotted, splits),
"readers through snapshots, splits"
);
},
);
}
#[test]
fn a_reader_whose_arm_takes_a_derivative_takes_the_split_for_its_branch() {
on_default_policy(
|_| {},
|device| {
let queue = device.new_command_queue().unwrap();
let format = PixelFormat::RGBA8Unorm;
let before = device.work_counts();
let (bytes, moved, _) = readers_over(
device,
&queue,
format,
true,
None,
false,
READ_SELECTING_DFDX,
);
let after = device.work_counts();
let unreadable = after.reading_draws_split_unreadable_own_pixel
- before.reading_draws_split_unreadable_own_pixel;
let clauses = unreadable_by(&before, &after);
eprintln!(
"snapshot reads, a reader whose arm takes a derivative: {moved:?}, unreadable \
own-pixel splits {unreadable}, by clause {clauses:?}"
);
holds("a reader whose arm takes a derivative", &bytes, SELECTED);
assert_eq!(
(moved.snapshotted, moved.splits),
(0, 2),
"readers through snapshots, splits"
);
assert_eq!(
unreadable, 2,
"splits for an own-pixel read no snapshot serves"
);
let named: Vec<_> = clauses.into_iter().filter(|&(_, n)| n != 0).collect();
assert_eq!(named, [("branch", 2)], "the clauses that left the slot out");
},
);
}
#[test]
fn readers_take_the_snapshot_by_the_area_rule() {
on_default_policy(
+2 -2
View File
@@ -61,7 +61,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 2142;
pub const SEMANTICS_VERSION: u32 = 2143;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 525;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2516;
pub const RUNTIME_VERSION: u32 = 2517;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -67,9 +67,10 @@
//! executed" (Memory Model): the second draw executes no copy, and the first no read of `S`. A
//! helper invocation copies nothing and reads nothing; its codes of the slot are 0, which reaches
//! no fragment's result, since no value read from the slot reaches a derivative, a quad or
//! subgroup operation or a branch (but one that only decides whether the invocation demotes
//! itself, which a helper already is), nor an integer divisor or a dynamic component index, whose
//! behavior SPIR-V leaves undefined at some values (`spirv::requirements::snapshot_textures`):
//! subgroup operation or a branch (but a selection whose arms leave through its merge alone and
//! hold none of those, no loop and no undefined operand, which a helper may take either arm of),
//! nor an integer divisor or a dynamic component index, whose behavior SPIR-V leaves undefined
//! at some values (`spirv::requirements::snapshot_textures`):
//! "Stores and atomics performed by helper invocations must not have any effect on memory except
//! for the Function, Private and Output storage classes" (Helper Invocations).
//!
@@ -2668,6 +2668,44 @@ fn the_interface_states_why_a_slot_takes_no_snapshot() {
}
}
/// A selection on the texel a fragment read at its own pixel keeps the slot where a helper
/// invocation may take either arm (`spirv::requirements::snapshot`'s `arms`): owned fixture
/// `snapshot_select`'s `ss_read_selecting`, whose arm halves the red, states none on the Radeon
/// 780M's profile and on lavapipe's; `ss_read_selecting_dfdx`, whose arm also takes a derivative,
/// and `wlk_readers`'s `wlk_read_branch`, whose texel decides a loop's trip count, state their
/// branch.
#[test]
fn a_selection_on_the_texel_keeps_the_slot_where_a_helper_may_take_either_arm() {
use crate::pipeline::interface::SnapshotRefusal;
let (Some(selecting), Some(looping)) = (fixture("snapshot_select"), fixture("wlk_readers"))
else {
return;
};
for stem in ["amd-780m-radv", "lavapipe"] {
let p = crate::pipeline::testing::profile(stem, DevicePolicy::default()).expect("profile");
for (bc, entry, refusals) in [
(&selecting, "ss_read_selecting", Vec::new()),
(
&selecting,
"ss_read_selecting_dfdx",
vec![(0, SnapshotRefusal::Branch)],
),
(
&looping,
"wlk_read_branch",
vec![(0, SnapshotRefusal::Branch)],
),
] {
let a = crate::pipeline::testing::compile(bc, entry, &p)
.unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
assert_eq!(a.interface.own_pixel_textures, [0u32], "{stem} {entry}");
let slots: &[u32] = if refusals.is_empty() { &[0] } else { &[] };
assert_eq!(a.interface.snapshot_textures, slots, "{stem} {entry}");
assert_eq!(a.interface.snapshot_refusals, refusals, "{stem} {entry}");
}
}
}
/// The interface states the own-pixel slots a draw can read through a snapshot
/// (`spirv::requirements::snapshot`): `tob_read`'s, whose texel reaches only its output. Its
/// snapshot variant (`LoweringInputs::snapshot_textures`) links and validates on every profile with
@@ -467,8 +467,10 @@ pub struct SamplerArray {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SnapshotRefusal {
/// It decides a conditional branch or a switch, but for a branch that only decides whether
/// the invocation demotes itself.
/// It decides a conditional branch or a switch, but for a selection whose arms leave through
/// its merge alone and hold no derivative, implicit-level sample or level-of-detail query,
/// subgroup or quad operation, loop, or operand undefined at a value that is not a constant,
/// nor call a function that does (a helper may take either of those arms).
Branch,
/// It is an operand of a derivative.
Derivative,
@@ -31,15 +31,24 @@
//! - a derivative, a sample, gather or level-of-detail query of any image, a subgroup or quad
//! operation, an atomic, an image write or texel pointer, a ray query, a mesh output count, or a
//! store to any other storage class;
//! - a conditional branch, a switch, or the entry's returned value, but for a branch that only
//! decides whether the invocation demotes itself (`if (c) discard_fragment();` at MSL 2.3 or
//! later on a profile with demote): one arm holds `OpDemoteToHelperInvocation` alone and goes on
//! to the other, where both paths meet with the same values, so a helper, which is one already,
//! takes either path to the same state ("is not considered a flow control instruction",
//! `OpDemoteToHelperInvocation`);
//! - a conditional branch or a switch, but for a selection whose arms a helper may take in place
//! of a fragment's to no one's harm (below), or the entry's returned value;
//! - the divisor of an integer division or remainder, the dividend of a signed one whose divisor
//! is not a constant without a `-1` lane, or a dynamic vector component index.
//!
//! A selection on such a value keeps the slot where its arms leave through its merge block alone
//! (no break, continue, return, `OpKill`, `OpTerminateInvocation` or unreachable end) and hold no
//! derivative, implicit-level sample or level-of-detail query, subgroup or quad operation, loop,
//! or operand undefined at some value that is not a constant, nor do the functions they call
//! ([`arms`]). A helper whose constant takes it down another arm than the texel would then
//! changes nothing another invocation reads: no tangled instruction runs in its arms ("When performing derivative or quad
//! group operations in a fragment shader, additional invocations may be spawned in order to ensure
//! correct results", so only those read a helper's values), it reaches the merge as a fragment
//! does, and `OpDemoteToHelperInvocation` in an arm leaves it what it is ("is not considered a
//! flow control instruction"). What it leaves behind, the merge's phis and what its arms store in
//! `Function`, `Private` and `Output` variables, takes the condition's reach, and its uses are
//! judged as any other. A loop's exit is a branch out of it, which no such selection holds.
//!
//! A call is followed into its callee: "Argument N is the object to copy to parameter N of
//! Function" (`OpFunctionCall`), so each argument's reach is its parameter's, a pointer argument's
//! memory is its parameter's (what either side stores through it the other may load), and the
@@ -62,14 +71,16 @@ use crate::budget::Meter;
use crate::error::Error;
use crate::pipeline::interface::SnapshotRefusal;
use crate::pipeline::sym::ResourceKind;
use crate::spirv::ids::{BlockId, Value};
use crate::spirv::ids::Value;
use crate::spirv::ir::{
BinOp, ConstKind, Constant, ExecModel, GlobalKind, Inst, Phi, StorageClass, Terminator, Type,
BinOp, ConstKind, Constant, ExecModel, GlobalKind, Inst, StorageClass, Terminator, Type,
TypedModule, UnOp, ValueOrigin,
};
use super::own_pixel::{carried_on, holds_image, use_of, Use};
use arms::Arms;
/// The most passes over the module the reach is followed for; a module whose values take more to
/// settle (a chain of loop-carried copies longer than this) has no slot.
const MOST_PASSES: u32 = 16;
@@ -77,6 +88,8 @@ const MOST_PASSES: u32 = 16;
/// No slot's image.
const NONE: u32 = u32::MAX;
mod arms;
#[cfg(test)]
mod tests;
@@ -131,8 +144,10 @@ pub fn snapshot_textures(
// Each value's slot image (`NONE` for none), its reach (the slots whose fetched values it
// holds), the reach of the memory behind it where it is a variable's pointer, and the
// variable a pointer points into; each block's function, and the reach each function
// returns.
let tables = n * (4 + 16 + 16 + 4) + 4 * m.blocks().len() + 16 * m.functions().len();
// returns; and the walks over the selections' arms.
let (blocks, functions) = (m.blocks().len(), m.functions().len());
let tables =
n * (4 + 16 + 16 + 4) + 4 * blocks + 16 * functions + Arms::bytes(blocks, functions);
meter.charge(tables)?;
let result = reach(m, &walked, n, &mut refused);
meter.release(tables);
@@ -226,6 +241,7 @@ fn reach(m: &TypedModule, own: &[u32], n: usize, bad: &mut Refused) -> Result<()
}
}
let mut returned = vec![0u128; m.functions().len()];
let mut arms = Arms::new(m);
let wanted: u128 = own.iter().fold(0, |acc, &s| acc | (1u128 << s));
let get = |table: &[u128], v: Value| table.get(v.index()).copied().unwrap_or(0);
for _ in 0..MOST_PASSES {
@@ -283,8 +299,9 @@ fn reach(m: &TypedModule, own: &[u32], n: usize, bad: &mut Refused) -> Result<()
changed |= join(&mut mask, r, operands);
}
}
// What a kept branch's arms store takes its condition's reach too.
Inst::Store { ptr, value, .. } => {
let reach = get(&mask, *value) | get(&mask, *ptr);
let reach = get(&mask, *value) | get(&mask, *ptr) | arms.control(at);
if kept_class(m, *ptr)? {
let root = root(&base, *ptr);
changed |= join(&mut memory, root, reach);
@@ -325,7 +342,7 @@ fn reach(m: &TypedModule, own: &[u32], n: usize, bad: &mut Refused) -> Result<()
} => {
bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *b));
let unsigned = matches!(op, BinOp::UDiv | BinOp::UMod);
if !unsigned && !never_minus_one(m, *b)? {
if !unsigned && !lanes_all(m, *b, |bits, ones| bits != ones)? {
bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *a));
}
if let Some(r) = node.result {
@@ -366,11 +383,23 @@ fn reach(m: &TypedModule, own: &[u32], n: usize, bad: &mut Refused) -> Result<()
}
}
match &b.term {
// A branch whose only effect is whether the invocation demotes itself reaches
// nothing a helper's value can change.
Terminator::CondBranch { t, f, .. } if demote_guard(m, at, *t, *f) => {}
// A selection whose arms a helper may take in place of a fragment's hands its
// condition's reach to its merge's phis and its arms' stores alone.
Terminator::CondBranch { cond: v, .. } | Terminator::Switch { sel: v, .. } => {
bad.add(SnapshotRefusal::Branch, get(&mask, *v))
let reach = get(&mask, *v);
if reach != 0 {
match arms.keeps(m, at, reach)? {
Some((merge, grew)) => {
changed |= grew;
for phi in
m.blocks().get(merge.index()).map_or(&[][..], |b| &b.phis)
{
changed |= join(&mut mask, phi.result, reach);
}
}
None => bad.add(SnapshotRefusal::Branch, reach),
}
}
}
// A callee's returned value reaches its calls' results; the entry's, the stage.
Terminator::ReturnValue(v) => {
@@ -521,47 +550,6 @@ fn copies_alone(m: &TypedModule, slots: &[u32], n: usize) -> Result<bool, Error>
Ok(!elsewhere && fetches.iter().all(|&f| f == 1))
}
/// Whether a conditional branch of block `from` to `t` or `f` only decides whether the invocation
/// demotes itself (`if (c) discard_fragment();` at MSL 2.3 or later on a profile with demote,
/// `lower::fragment::discard`): each target is the block both paths meet at, or a block with no
/// phi that branches on to it holding nothing or `OpDemoteToHelperInvocation` alone, at least one
/// of them the demote, and every phi of the meeting block takes the same value from both paths.
/// Both paths then meet with the same values, and a helper invocation, which is one already, is
/// no different for the demote: "Demote this fragment shader invocation to a helper invocation",
/// which "is not considered a flow control instruction" (`OpDemoteToHelperInvocation`). Neither
/// arm holds a derivative, quad or subgroup operation, loop or undefined behavior a helper's path
/// could reach.
fn demote_guard(m: &TypedModule, from: usize, t: BlockId, f: BlockId) -> bool {
let blocks = m.blocks();
// Where a path through `arm` meets the other: the block it reaches, the block it reaches it
// from, and whether it demotes on the way.
let path = |arm: BlockId| -> Option<(usize, usize, bool)> {
let block = blocks.get(arm.index())?;
let demotes_alone =
(block.insts.iter()).all(|n| matches!(n.inst, Inst::DemoteToHelperInvocation));
let forwards = block.phis.is_empty() && block.merge.is_none() && demotes_alone;
match block.term {
Terminator::Branch(to) if forwards => {
Some((to.index(), arm.index(), !block.insts.is_empty()))
}
_ => Some((arm.index(), from, false)),
}
};
let (Some((to, a, demotes_a)), Some((other, b, demotes_b))) = (path(t), path(f)) else {
return false;
};
let edge = |phi: &Phi, p: usize| {
(phi.incoming.iter())
.find(|(_, at)| at.index() == p)
.map(|(v, _)| *v)
};
to == other
&& a != b
&& (demotes_a || demotes_b)
&& (blocks.get(to))
.is_some_and(|meet| (meet.phis.iter()).all(|phi| edge(phi, a) == edge(phi, b)))
}
/// Add `reach` to `table[v]`; whether it grew.
fn join(table: &mut [u128], v: Value, reach: u128) -> bool {
match table.get_mut(v.index()) {
@@ -594,8 +582,9 @@ fn root(base: &[u32], ptr: Value) -> Value {
Value::new(at)
}
/// Whether `v` is a plain integer constant none of whose lanes is `-1` (every bit of its width set).
fn never_minus_one(m: &TypedModule, v: Value) -> Result<bool, Error> {
/// Whether `v` is a plain integer constant each of whose lanes' bits, within the lane's width,
/// pass `keep(bits, ones)`, `ones` every bit of the width set.
fn lanes_all(m: &TypedModule, v: Value, keep: impl Fn(u64, u64) -> bool) -> Result<bool, Error> {
let ValueOrigin::Const(c) = m.value(v)?.origin else {
return Ok(false);
};
@@ -610,13 +599,13 @@ fn never_minus_one(m: &TypedModule, v: Value) -> Result<bool, Error> {
64.. => u64::MAX,
w => (1u64 << w) - 1,
};
let other = |bits: u64| bits & ones != ones;
let lane = |bits: u64| keep(bits & ones, ones);
Ok(match &m.consts().get(c)?.kind {
ConstKind::Plain(Constant::Scalar { bits, .. }) => other(bits.0),
ConstKind::Plain(Constant::Scalar { bits, .. }) => lane(bits.0),
ConstKind::Plain(Constant::Composite { parts, .. }) => parts
.iter()
.all(|part| m.consts().scalar_bits(*part).is_some_and(|b| other(b.0))),
ConstKind::Plain(Constant::Null { .. }) => true,
.all(|part| m.consts().scalar_bits(*part).is_some_and(|b| lane(b.0))),
ConstKind::Plain(Constant::Null { .. }) => lane(0),
_ => false,
})
}
@@ -0,0 +1,279 @@
//! Which branches on a snapshot slot's fetched value keep the slot: the selections whose arms hold
//! nothing a helper invocation's path through them could pass on (the module docs of
//! [`super`]).
//!
//! A selection's arms are the blocks a walk from its header's targets reaches before its merge
//! block, and the blocks of every function a call in them reaches. The branch keeps the slot only
//! where the walk leaves the arms through the merge alone: no arm block is the merge or continue
//! target of a construct the selection lies in (a loop's break or continue, a switch's break),
//! returns, ends the invocation (`OpKill`, `OpTerminateInvocation`) or is unreachable; and where
//! no arm block or callee holds a tangled instruction (`Inst::is_tangled`: an implicit-level
//! sample or level-of-detail query, a derivative, a subgroup or quad operation), a loop, or an
//! operand an instruction's behavior is undefined for at some value that is not a constant
//! (an integer divisor, a signed one that may be `-1`, a dynamic vector component index).
//!
//! The merge then post-dominates the header, so whatever follows it runs in a helper as in a
//! fragment, and what the arms leave behind is all a helper's other path can change: the merge's
//! phis and the `Function`, `Private` and `Output` variables an arm or its callees store to. Those
//! take the branch's reach ([`Arms::control`]), and the walk judges their uses as any other.
use crate::error::Error;
use crate::spirv::ids::BlockId;
use crate::spirv::ir::{BinOp, Block, Inst, Merge, Terminator, TypedModule, ValueOrigin};
use super::{lanes_all, NONE};
/// A block declared by more than one header.
const MANY: u32 = u32::MAX - 1;
/// A header's verdict, before it is judged.
const UNJUDGED: u8 = 0;
/// A header whose arms keep the slot.
const KEPT: u8 = 1;
/// A header whose arms leave it out.
const LEFT_OUT: u8 = 2;
/// The tables of the walks over a module's selections, one entry for each block or function.
pub(super) struct Arms {
/// The header that declares each block its merge or continue target, `NONE` for none, `MANY`
/// for more than one.
declared: Vec<u32>,
/// The walk that last reached each block, and each function.
walked: Vec<u32>,
walked_fn: Vec<u32>,
walks: u32,
/// Each header's verdict.
verdict: Vec<u8>,
/// The reach each kept header has handed its arms.
applied: Vec<u128>,
/// Each block's reach of the branches it is control dependent on: the slots whose fetched
/// values decide a kept branch whose arms hold it.
control: Vec<u128>,
/// The blocks a walk reached, and its open blocks and functions.
reached: Vec<u32>,
stack: Vec<BlockId>,
calls: Vec<u32>,
}
impl Arms {
/// The bytes the tables take for a module of `blocks` blocks and `functions` functions.
pub(super) fn bytes(blocks: usize, functions: usize) -> usize {
blocks * (4 + 4 + 1 + 16 + 16 + 4 + 4) + functions * (4 + 4)
}
/// The tables of module `m`.
pub(super) fn new(m: &TypedModule) -> Arms {
let blocks = m.blocks().len();
let mut declared = vec![NONE; blocks];
for (at, b) in m.blocks().iter().enumerate() {
let targets = match b.merge {
Some(Merge::Selection { merge }) => [Some(merge), None],
Some(Merge::Loop { merge, cont }) => [Some(merge), Some(cont)],
_ => [None, None],
};
for t in targets.into_iter().flatten() {
if let Some(d) = declared.get_mut(t.index()) {
*d = if *d == NONE { at as u32 } else { MANY };
}
}
}
Arms {
declared,
walked: vec![0; blocks],
walked_fn: vec![0; m.functions().len()],
walks: 0,
verdict: vec![UNJUDGED; blocks],
applied: vec![0; blocks],
control: vec![0; blocks],
reached: Vec::with_capacity(blocks),
stack: Vec::with_capacity(blocks),
calls: Vec::with_capacity(m.functions().len()),
}
}
/// The reach of the kept branches block `at` is control dependent on.
pub(super) fn control(&self, at: usize) -> u128 {
self.control.get(at).copied().unwrap_or(0)
}
/// Whether the branch ending block `header`, whose condition holds the fetched values of the
/// slots of `reach`, keeps them: its merge block where it does, which takes `reach` into its
/// phis, its arms taking it into [`Arms::control`] (and whether that grew); `None` where it
/// leaves them out.
pub(super) fn keeps(
&mut self,
m: &TypedModule,
header: usize,
reach: u128,
) -> Result<Option<(BlockId, bool)>, Error> {
let verdict = self.verdict.get(header).copied().unwrap_or(LEFT_OUT);
let applied = self.applied.get(header).copied().unwrap_or(0);
let merge = match verdict {
LEFT_OUT => return Ok(None),
KEPT if applied | reach == applied => {
return Ok(merge_of(m, header).map(|b| (b, false)))
}
_ => self.walk(m, header)?,
};
let Some(merge) = merge else {
if let Some(v) = self.verdict.get_mut(header) {
*v = LEFT_OUT;
}
return Ok(None);
};
if let Some(v) = self.verdict.get_mut(header) {
*v = KEPT;
}
if let Some(a) = self.applied.get_mut(header) {
*a |= reach;
}
let mut grew = false;
for &b in &self.reached {
if let Some(c) = self.control.get_mut(b as usize) {
grew |= *c | reach != *c;
*c |= reach;
}
}
Ok(Some((merge, grew)))
}
/// Walk the arms of the selection block `header` heads, recording the blocks reached in
/// `reached`: its merge block where the arms keep the slot, else `None`.
fn walk(&mut self, m: &TypedModule, header: usize) -> Result<Option<BlockId>, Error> {
let Some(merge) = merge_of(m, header) else {
return Ok(None);
};
let blocks = m.blocks();
self.walks += 1;
let w = self.walks;
self.reached.clear();
self.stack.clear();
self.calls.clear();
if let Some(s) = self.walked.get_mut(header) {
*s = w;
}
let Some(head) = blocks.get(header) else {
return Ok(None);
};
targets(&head.term, |t| self.stack.push(t));
while let Some(b) = self.stack.pop() {
let at = b.index();
if b == merge || (self.walked.get(at) == Some(&w) && at != header) {
continue;
}
// Back at the header, or at a merge or continue target of a construct the selection
// lies in: the arm leaves it.
let declared = self.declared.get(at).copied().unwrap_or(MANY);
let inner = declared == NONE || self.walked.get(declared as usize) == Some(&w);
if at == header || !inner {
return Ok(None);
}
if let Some(s) = self.walked.get_mut(at) {
*s = w;
}
let Some(block) = blocks.get(at) else {
return Ok(None);
};
if !self.clean(m, block, w)? {
return Ok(None);
}
match block.term {
Terminator::Branch(_)
| Terminator::CondBranch { .. }
| Terminator::Switch { .. } => {}
_ => return Ok(None),
}
self.reached.push(at as u32);
targets(&block.term, |t| self.stack.push(t));
}
// Every function a call in the arms reaches runs in them; its returns go back to them.
while let Some(f) = self.calls.pop() {
let Some(func) = m.functions().get(f as usize) else {
return Ok(None);
};
for &b in &func.blocks {
let Some(block) = blocks.get(b.index()) else {
return Ok(None);
};
if !self.clean(m, block, w)? {
return Ok(None);
}
match block.term {
Terminator::Branch(_)
| Terminator::CondBranch { .. }
| Terminator::Switch { .. }
| Terminator::Return
| Terminator::ReturnValue(_) => {}
_ => return Ok(None),
}
self.reached.push(b.index() as u32);
}
}
Ok(Some(merge))
}
/// Whether block `block` of walk `w` heads no loop and holds no tangled instruction and no
/// operand undefined at some value that is not a constant; each function it calls is queued.
fn clean(&mut self, m: &TypedModule, block: &Block, w: u32) -> Result<bool, Error> {
if matches!(block.merge, Some(Merge::Loop { .. })) {
return Ok(false);
}
for node in &block.insts {
let inst = &node.inst;
if inst.is_tangled() {
return Ok(false);
}
let defined = match inst {
Inst::Binary { op, b, .. } => match op {
BinOp::UDiv | BinOp::UMod => lanes_all(m, *b, |bits, _| bits != 0)?,
BinOp::SDiv | BinOp::SRem | BinOp::SMod => {
lanes_all(m, *b, |bits, ones| bits != 0 && bits != ones)?
}
_ => true,
},
Inst::VectorExtractDynamic { index, .. }
| Inst::VectorInsertDynamic { index, .. } => {
matches!(m.value(*index)?.origin, ValueOrigin::Const(_))
}
Inst::Call { func, .. } => {
if let Some(s) = self.walked_fn.get_mut(func.index()).filter(|s| **s != w) {
*s = w;
self.calls.push(func.index() as u32);
}
true
}
_ => true,
};
if !defined {
return Ok(false);
}
}
Ok(true)
}
}
/// The merge block of the selection block `header` heads, if it heads one.
fn merge_of(m: &TypedModule, header: usize) -> Option<BlockId> {
match m.blocks().get(header)?.merge {
Some(Merge::Selection { merge }) => Some(merge),
_ => None,
}
}
/// Call `f` on each block `term` may branch to.
fn targets(term: &Terminator, mut f: impl FnMut(BlockId)) {
match term {
Terminator::Branch(t) => f(*t),
Terminator::CondBranch { t, f: e, .. } => {
f(*t);
f(*e);
}
Terminator::Switch { default, cases, .. } => {
f(*default);
for &(_, t) in cases {
f(t);
}
}
_ => {}
}
}
@@ -1,16 +1,18 @@
//! [`snapshot_textures`] on hand-built fragment modules: a fetched value that reaches only
//! arithmetic and an output qualifies, directly, through a variable or through a call; one that
//! reaches a derivative, a branch, an implicit sample, a quad operation, an integer divisor or a
//! dynamic index, a store elsewhere, an atomic or an image write, directly, through a variable,
//! or into and out of a callee, does not; nor does a module with an interlock or a coherent
//! resource, of a function that writes memory, or a slot past 127. A branch around a demote alone
//! qualifies. Each slot left out is stated with the clauses that leave it out.
//! reaches a derivative, an implicit sample, a quad operation, an integer divisor or a dynamic
//! index, a store elsewhere, an atomic or an image write, directly, through a variable, or into
//! and out of a callee, does not; nor does a module with an interlock or a coherent resource, of a
//! function that writes memory, or a slot past 127. A selection on it qualifies where its arms
//! leave through its merge alone and hold nothing tangled, no loop and no undefined operand, and
//! what its arms leave behind reaches nothing that leaves the slot out. Each slot left out is
//! stated with the clauses that leave it out.
use super::snapshot_textures;
use crate::budget::{Budget, Meter};
use crate::pipeline::interface::SnapshotRefusal;
use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage};
use crate::spirv::builder::constructs::ArmEnd;
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, KillForm, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{
@@ -69,6 +71,26 @@ enum Sink {
DemoteMergingValues,
/// Swapped across the quad.
QuadSwap,
/// Compared, and an arm on the comparison stores the position to a `Private` variable.
ArmStores,
/// Compared, and an arm on the comparison takes a derivative of the position.
ArmDerivative,
/// Compared, and an arm on the comparison calls a callee that takes a derivative.
ArmCallsDerivative,
/// Compared, and an arm on the comparison ends the invocation.
ArmKills,
/// Compared, and an arm on the comparison runs a loop.
ArmLoop,
/// Compared, and an arm on the comparison divides by the position's bits.
ArmDivides,
/// Compared, and a loop left where the comparison holds.
LoopExit,
/// Compared, an arm on the comparison storing to a `Function` variable whose value after the
/// merge reaches a derivative.
ArmToDerivative,
/// Compared, the arms' different values of the position merged and the merge's derivative
/// taken.
MergeToDerivative,
/// Its bits stored to a storage buffer's word.
StorageStore,
/// Its bits added to a storage buffer's word by an atomic.
@@ -233,6 +255,13 @@ fn module(sink: Sink) -> TypedModule {
})
.expect("pointer");
let callee = match sink {
Sink::ArmCallsDerivative => {
let mut g = b.routine(vec4).expect("routine");
let x = g.param(vec4).expect("x");
let d = g.derivative(DerivOp::DPdx, x).expect("derivative");
g.ret(Some(d)).expect("ret");
Some(g.finish().expect("callee"))
}
Sink::ThroughCall | Sink::DerivativeOfCall | Sink::BranchInCall => {
let mut g = b.routine(vec4).expect("routine");
let x = g.param(vec4).expect("x");
@@ -269,7 +298,7 @@ fn module(sink: Sink) -> TypedModule {
let mut f = b.function(void).expect("main");
let tv = f.module().global_value(t).expect("t");
let uv = f.module().global_value(u).expect("u");
let _ = out;
let position = f.module().global_value(out).expect("position");
let cv = f.module().global_value(color).expect("color");
let img = f.load(tv, MemAccess::default()).expect("t image");
let zero = scalar(&mut f, u32_, 0);
@@ -440,6 +469,88 @@ fn module(sink: Sink) -> TypedModule {
let merged = f.if_(&mut (), c, kept, Some(demoted)).expect("if");
merged.0.first().copied().unwrap_or(texel)
}
Sink::ArmStores
| Sink::ArmDerivative
| Sink::ArmCallsDerivative
| Sink::ArmKills
| Sink::ArmLoop
| Sink::ArmDivides => {
let c = above_half(&mut f, texel, f32_);
let pos = f.load(position, MemAccess::default()).expect("position");
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
match sink {
Sink::ArmStores => f.store(cv, pos, MemAccess::default())?,
Sink::ArmDerivative => {
f.derivative(DerivOp::DPdx, pos)?;
}
Sink::ArmCallsDerivative => {
f.call(callee.expect("callee"), &[pos])?;
}
Sink::ArmKills => {
f.kill(KillForm::Kill)?;
return Ok(ArmEnd::Exits);
}
Sink::ArmLoop => {
f.loop_(
&mut (),
LoopSpec::default(),
Box::new(|f, _, exits| exits.break_(f)),
)?;
}
_ => {
let x = f.composite_extract(pos, &[0])?;
let bits = f.convert(ConvOp::Bitcast, x, u32_)?;
let three = scalar(f, u32_, 3);
f.binary(BinOp::UDiv, three, bits)?;
}
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, arm, None).expect("if");
texel
}
Sink::LoopExit => {
let c = above_half(&mut f, texel, f32_);
let body: crate::spirv::builder::constructs::LoopFn<'_, ()> =
Box::new(move |f, _, exits| {
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
exits.break_(f)?;
Ok(ArmEnd::Exits)
});
f.if_(&mut (), c, arm, None)?;
Ok(())
});
f.loop_(&mut (), LoopSpec::default(), body).expect("loop");
texel
}
Sink::ArmToDerivative | Sink::MergeToDerivative => {
let c = above_half(&mut f, texel, f32_);
let pos = f.load(position, MemAccess::default()).expect("position");
let twice = f.binary(BinOp::FAdd, pos, pos).expect("twice");
let left = match sink {
Sink::ArmToDerivative => {
let var = f.local_var(vec4, None).expect("var");
let p = f.var_ptr(var).expect("pointer");
f.store(p, pos, MemAccess::default()).expect("store");
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
f.store(p, twice, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, arm, None).expect("if");
f.load(p, MemAccess::default()).expect("load")
}
_ => {
let then: ArmFn<'_, ()> =
Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![pos])));
let other: ArmFn<'_, ()> =
Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![twice])));
let merged = f.if_(&mut (), c, then, Some(other)).expect("if");
merged.0.first().copied().expect("merged")
}
};
f.derivative(DerivOp::DPdx, left).expect("derivative");
texel
}
Sink::SampleCoordinate => {
let si = f.load(uv, MemAccess::default()).expect("u");
let xy = f.vector_shuffle(texel, texel, &[0, 1]).expect("xy");
@@ -462,14 +573,17 @@ fn module(sink: Sink) -> TypedModule {
/// A fetched value that reaches arithmetic and a color output alone, directly, through a
/// `Function` variable or through a call, qualifies, as does an unsigned dividend, a signed one
/// beside a constant divisor without `-1`, and a dynamically indexed vector; a derivative of it,
/// directly, through a variable or of a call's result, a branch on it, in the entry or in a callee
/// it reaches as an argument, through a pointer argument's memory or back out of it, an implicit
/// sample at it, a quad swap of it, a divisor, a signed dividend beside `-1`, a dynamic index, a
/// store of it to a storage buffer, an atomic of it, or an image write of it leaves the slot out,
/// as does an interlock or a coherent resource anywhere in the module. A branch on it that only
/// decides whether the invocation demotes itself, in either arm, qualifies; one whose arm also
/// writes, or whose arms' values merge apart, does not. Each slot left out is stated with the one
/// clause that leaves it out. The analysis releases every charge.
/// directly, through a variable or of a call's result, an implicit sample at it, a quad swap of
/// it, a divisor, a signed dividend beside `-1`, a dynamic index, a store of it to a storage
/// buffer, an atomic of it, or an image write of it leaves the slot out, as does an interlock or a
/// coherent resource anywhere in the module. A selection on it qualifies, in the entry or in a
/// callee it reaches as an argument, through a pointer argument's memory or back out of it: with
/// an arm that is empty, demotes (in either arm, also writing, or with the arms' values merging
/// apart) or stores to a `Private` variable. One whose arm takes a derivative or calls a function
/// that does, ends the invocation, runs a loop or divides by a value that is not a constant leaves
/// the slot out for its branch, as does a loop it leaves; one whose arm's store or whose merge's
/// phi reaches a derivative, for the derivative. Each slot left out is stated with the one clause
/// that leaves it out. The analysis releases every charge.
#[test]
fn only_values_no_helper_can_pass_on_qualify() {
use SnapshotRefusal as R;
@@ -478,14 +592,14 @@ fn only_values_no_helper_can_pass_on_qualify() {
(Sink::ThroughVariable, None),
(Sink::Derivative, Some(R::Derivative)),
(Sink::DerivativeThroughVariable, Some(R::Derivative)),
(Sink::Branch, Some(R::Branch)),
(Sink::Branch, None),
(Sink::SampleCoordinate, Some(R::Sample)),
(Sink::Interlocked, Some(R::Interlock)),
(Sink::ThroughCall, None),
(Sink::DerivativeOfCall, Some(R::Derivative)),
(Sink::BranchInCall, Some(R::Branch)),
(Sink::BranchInCallThroughPointer, Some(R::Branch)),
(Sink::StoredByCallee, Some(R::Branch)),
(Sink::BranchInCall, None),
(Sink::BranchInCallThroughPointer, None),
(Sink::StoredByCallee, None),
(Sink::Divisor, Some(R::UndefinedOperand)),
(Sink::UnsignedDividend, None),
(Sink::SignedDividend, None),
@@ -494,8 +608,17 @@ fn only_values_no_helper_can_pass_on_qualify() {
(Sink::DynamicVector, None),
(Sink::DemoteGuard, None),
(Sink::DemoteInElse, None),
(Sink::DemoteAndStore, Some(R::Branch)),
(Sink::DemoteMergingValues, Some(R::Branch)),
(Sink::DemoteAndStore, None),
(Sink::DemoteMergingValues, None),
(Sink::ArmStores, None),
(Sink::ArmDerivative, Some(R::Branch)),
(Sink::ArmCallsDerivative, Some(R::Branch)),
(Sink::ArmKills, Some(R::Branch)),
(Sink::ArmLoop, Some(R::Branch)),
(Sink::ArmDivides, Some(R::Branch)),
(Sink::LoopExit, Some(R::Branch)),
(Sink::ArmToDerivative, Some(R::Derivative)),
(Sink::MergeToDerivative, Some(R::Derivative)),
(Sink::QuadSwap, Some(R::GroupOperation)),
(Sink::StorageStore, Some(R::Store)),
(Sink::AtomicAdd, Some(R::Atomic)),
+5 -1
View File
@@ -1871,7 +1871,11 @@ through a snapshot instead of a copy taken before the render pass instance. The
the fragment slots that allow it (`StageInterface::snapshot_textures`, `StageModule::
snapshot_textures`): own-pixel slots whose texels reach no derivative, sample, quad or subgroup
operation, branch, integer divisor, dynamic vector index or store outside the invocation, directly
or through a call, in a function that writes no memory. It says why it leaves out each other
or through a call, in a function that writes no memory. A selection on a texel is allowed where
its arms leave through its merge alone and hold no derivative, implicit-level sample or
level-of-detail query, quad or subgroup operation, loop or undefined operand, nor call a function
that does; what its arms leave behind (its merge's phis, the variables they store to) is judged
as the texel is. It says why it leaves out each other
own-pixel slot (`snapshot_refusals`: each slot with every `SnapshotRefusal` that holds for it).
Name the slots in `BindState::snapshot_textures`; the plan keeps those its pipeline can read so
and states them in `variant.snapshot_textures`, each with the form its snapshot holds texels in