Leave a settled two-leaf sum undecorated where no device can combine it with a neighbour

Content: the tree of `development` at d5ea6075d8, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:04 +02:00
1 parent 83ecf464ec
commit eaaa1741fb
6 files changed
+1136 -6

No files matched your search

@@ -689,6 +689,8 @@ mod separate_samples;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod seq_cst_fences;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod settled_sums;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod shader_stencil;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod shared_exponent_storage;
@@ -0,0 +1,395 @@
//! The sums the translation leaves undecorated, on the device the cfg selects, under the validation
//! layer: a two-leaf `fast` sum that gives a device nothing to fuse or regroup it with is left as
//! written, without `NoContraction` (`lower::arith::reassoc`, its module docs' **Alone**).
//!
//! Each kernel below has a settled twin whose one more use of a sum, a comparison or a product,
//! keeps that sum `NoContraction` (the translator's `tests::engine_settled_sums` checks which is
//! which in the SPIR-V). On the device each form and its twin must give the same words over 4096
//! inputs: `stored`'s sums (of a buffer's two lanes, stored to device memory), `converted`'s
//! integers (a difference converted to `int`), and `sampled`'s texels, sampled at sums of a
//! buffer's lanes and a constant buffer's, whole, lane by lane and with a negated lane
//! (`(d.x, -d.y) + uv`), and summed in turn. `stored`'s
//! sums must be the correctly rounded ones and `converted`'s integers the truncated differences
//! too.
use super::{buffer_with, read_buffer, validated_device, Messages, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::metal::{PixelFormat, SamplerAddressMode, SamplerMinMagFilter};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::llvm_assemble_text;
use metal2vulkan_runtime::{
CommandBufferStatus, Device, PipelineOptions, Region, SamplerState, Size, Texture,
TextureDescriptor,
};
const MODULE: &str = r#"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"
define void @stored(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fadd fast float %a, %b
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %s, ptr addrspace(1) %po, align 4
ret void
}
define void @stored_compared(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fadd fast float %a, %b
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %s, ptr addrspace(1) %po, align 4
%lt = fcmp fast olt float %s, 0.000000e+00
%z = zext i1 %lt to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %z, ptr addrspace(1) %pz, align 4
ret void
}
define void @converted(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fsub fast float %a, %b
%i = fptosi float %s to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %i, ptr addrspace(1) %pz, align 4
ret void
}
define void @converted_multiplied(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fsub fast float %a, %b
%i = fptosi float %s to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %i, ptr addrspace(1) %pz, align 4
%p = fmul fast float %s, %a
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %p, ptr addrspace(1) %po, align 4
ret void
}
define void @sampled(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, ptr addrspace(2) %k, ptr addrspace(1) %tex, ptr addrspace(2) %smp, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%uv = load <2 x float>, ptr addrspace(1) %pi, align 8
%d = load <2 x float>, ptr addrspace(2) %k, align 8
%c = fadd fast <2 x float> %uv, %d
%a = extractelement <2 x float> %uv, i64 0
%b = extractelement <2 x float> %d, i64 1
%x = fadd fast float %a, %b
%y = fsub fast float %a, %b
%c0 = insertelement <2 x float> poison, float %x, i64 0
%c1 = insertelement <2 x float> %c0, float %y, i64 1
%r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v0 = extractvalue { <4 x float>, i8 } %r0, 0
%r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c1, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v1 = extractvalue { <4 x float>, i8 } %r1, 0
%dx = extractelement <2 x float> %d, i64 0
%dy = extractelement <2 x float> %d, i64 1
%ny = fneg fast float %dy
%n0 = insertelement <2 x float> poison, float %dx, i64 0
%dn = insertelement <2 x float> %n0, float %ny, i64 1
%c2 = fadd fast <2 x float> %dn, %uv
%r2 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c2, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v2 = extractvalue { <4 x float>, i8 } %r2, 0
%w = fadd fast <4 x float> %v0, %v1
%w2 = fadd fast <4 x float> %v2, %v1
%g2 = shl i32 %g, 1
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g2
store <4 x float> %w, ptr addrspace(1) %po, align 16
%g21 = or i32 %g2, 1
%po2 = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g21
store <4 x float> %w2, ptr addrspace(1) %po2, align 16
ret void
}
define void @sampled_compared(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, ptr addrspace(2) %k, ptr addrspace(1) %tex, ptr addrspace(2) %smp, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%uv = load <2 x float>, ptr addrspace(1) %pi, align 8
%d = load <2 x float>, ptr addrspace(2) %k, align 8
%c = fadd fast <2 x float> %uv, %d
%a = extractelement <2 x float> %uv, i64 0
%b = extractelement <2 x float> %d, i64 1
%x = fadd fast float %a, %b
%y = fsub fast float %a, %b
%c0 = insertelement <2 x float> poison, float %x, i64 0
%c1 = insertelement <2 x float> %c0, float %y, i64 1
%r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v0 = extractvalue { <4 x float>, i8 } %r0, 0
%r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c1, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v1 = extractvalue { <4 x float>, i8 } %r1, 0
%dx = extractelement <2 x float> %d, i64 0
%dy = extractelement <2 x float> %d, i64 1
%ny = fneg fast float %dy
%n0 = insertelement <2 x float> poison, float %dx, i64 0
%dn = insertelement <2 x float> %n0, float %ny, i64 1
%c2 = fadd fast <2 x float> %dn, %uv
%r2 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c2, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v2 = extractvalue { <4 x float>, i8 } %r2, 0
%w = fadd fast <4 x float> %v0, %v1
%w2 = fadd fast <4 x float> %v2, %v1
%g2 = shl i32 %g, 1
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g2
store <4 x float> %w, ptr addrspace(1) %po, align 16
%g21 = or i32 %g2, 1
%po2 = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g21
store <4 x float> %w2, ptr addrspace(1) %po2, align 16
%cx = extractelement <2 x float> %c, i64 0
%lt = fcmp fast olt float %cx, 5.000000e-01
%z = zext i1 %lt to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %z, ptr addrspace(1) %pz, align 4
ret void
}
declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)
!air.kernel = !{!20, !21, !22, !23, !24, !25}
!air.version = !{!1}
!air.language_version = !{!2}
!1 = !{i32 2, i32 8, i32 0}
!2 = !{!"Metal", i32 4, i32 0, i32 0}
!3 = !{}
!4 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"in"}
!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"out"}
!6 = !{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"aux"}
!7 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"}
!9 = !{!4, !5, !6, !7}
!11 = !{i32 3, !"air.buffer", !"air.location_index", i32 3, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"k"}
!12 = !{i32 4, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"tex"}
!13 = !{i32 5, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"smp"}
!14 = !{i32 6, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"}
!15 = !{!4, !16, !6, !11, !12, !13, !14}
!16 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}
!20 = !{ptr @stored, !3, !9}
!21 = !{ptr @stored_compared, !3, !9}
!22 = !{ptr @converted, !3, !9}
!23 = !{ptr @converted_multiplied, !3, !9}
!24 = !{ptr @sampled, !3, !15}
!25 = !{ptr @sampled_compared, !3, !15}
"#;
/// The threads, one input each, in threadgroups of 64.
const THREADS: usize = 4096;
/// The texture's side.
const SIDE: u64 = 16;
/// A fixed xorshift generator.
struct Words(u32);
impl Words {
fn next(&mut self) -> u32 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 17;
self.0 ^= self.0 << 5;
self.0
}
}
/// The pairs `stored` and `converted` read: ties, signed zeros and differences near an integer,
/// then normal operands of magnitude below 2^24 with random fractions.
fn pairs() -> Vec<[f32; 2]> {
let ulp = 2f32.powi(-23);
let mut out = vec![
[1.0, ulp / 2.0],
[1.0 + ulp, ulp / 2.0],
[1.0, 3.0 * ulp / 2.0],
[-1.0, -ulp / 2.0],
[-0.0, -0.0],
[0.0, -0.0],
[1.5, -1.5],
[16_777_216.0, -0.5],
[4_194_304.5, 0.25],
[-1_048_576.0 - 0.25, 0.125],
[1.0e30, 1.0e30],
[1.0e-37, 1.0e-37],
];
let mut w = Words(0x9E37_79B9);
while out.len() < THREADS {
let mut normal = || {
let x = w.next();
let exponent = 127 - 20 + (x >> 24) % 44;
f32::from_bits((x & 0x8000_0000) | (exponent << 23) | (w.next() & 0x7F_FFFF))
};
out.push([normal(), normal()]);
}
out
}
/// The coordinates `sampled` reads: 24 random bits in `[0, 1)` each.
fn coordinates() -> Vec<[f32; 2]> {
let mut w = Words(0x2545_F491);
let mut unit = || (w.next() >> 8) as f32 / 16_777_216.0;
(0..THREADS).map(|_| [unit(), unit()]).collect()
}
/// An `RGBA8Unorm` texture of random bytes.
fn texture(device: &Device) -> Texture {
let descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false);
let texture = device.new_texture(&descriptor).unwrap();
let mut w = Words(0x0BAD_5EED);
let bytes: Vec<u8> = (0..4 * SIDE * SIDE)
.map(|_| (w.next() >> 24) as u8)
.collect();
texture
.replace_region(
Region::new_2d(0, 0, SIDE, SIDE),
0,
0,
&bytes,
4 * SIDE,
4 * SIDE * SIDE,
)
.unwrap();
texture
}
/// A linear sampler clamping to the edge.
fn sampler(device: &Device) -> SamplerState {
let mut descriptor = SamplerDescriptor::new();
descriptor.min_filter = SamplerMinMagFilter::Linear;
descriptor.mag_filter = SamplerMinMagFilter::Linear;
descriptor.s_address_mode = SamplerAddressMode::ClampToEdge;
descriptor.t_address_mode = SamplerAddressMode::ClampToEdge;
device.new_sampler_state(&descriptor).unwrap()
}
/// The words of `kernel`'s `out` (`out_words` a thread) and `aux` buffers on `device`, over
/// `input`.
fn run(
device: &Device,
library: &metal2vulkan_runtime::Library,
kernel: &str,
input: &[[f32; 2]],
out_words: usize,
) -> (Vec<u32>, Vec<u32>) {
let function = library.new_function_with_name(kernel).unwrap();
let pipeline = device
.new_compute_pipeline_state(
&ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())),
&PipelineOptions::default(),
)
.unwrap();
let bytes: Vec<u8> = input
.iter()
.flat_map(|[a, b]| a.to_le_bytes().into_iter().chain(b.to_le_bytes()))
.collect();
let input = buffer_with(device, &bytes).unwrap();
let out = buffer_with(device, &vec![0xEE; 4 * out_words * THREADS]).unwrap();
let aux = buffer_with(device, &vec![0xEE; 4 * THREADS]).unwrap();
// `d`: 0.1 and 0.0123 as `float`s, which round the sums.
let k: Vec<u8> = [0.1f32, 0.0123]
.iter()
.flat_map(|f| f.to_le_bytes())
.collect();
let k = buffer_with(device, &k).unwrap();
let (texture, sampler) = (texture(device), sampler(device));
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&pipeline).unwrap();
for (index, buffer) in [&input, &out, &aux, &k].into_iter().enumerate() {
let index = u32::try_from(index).unwrap();
encoder.set_buffer(Some(buffer), 0, index).unwrap();
}
encoder.set_texture(Some(&texture), 0).unwrap();
encoder.set_sampler_state(Some(&sampler), 0).unwrap();
encoder
.dispatch_threadgroups(Size::new(THREADS as u64 / 64, 1, 1), Size::new(64, 1, 1))
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let words = |b, n: usize| -> Vec<u32> {
read_buffer(b, 0, 4 * (n * THREADS) as u64)
.unwrap()
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect()
};
(words(&out, out_words), words(&aux, 1))
}
/// The inputs whose word differs between `a` and `b`, with the two words, at most 24.
fn differing(a: &[u32], b: &[u32]) -> Vec<(usize, u32, u32)> {
(a.iter().zip(b).enumerate())
.filter(|(_, (x, y))| x != y)
.map(|(g, (x, y))| (g, *x, *y))
.take(24)
.collect()
}
/// Each form gives its settled twin's words on the device, and `stored`'s sums and `converted`'s
/// integers are the correctly rounded sums and the truncated differences (module docs).
#[test]
fn a_sum_left_as_written_gives_its_settled_twin_s_words() {
let messages = Messages::default();
let cache = ScratchCache::new().unwrap();
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let name = device.name().to_owned();
let bitcode = llvm_assemble_text(MODULE).unwrap();
let library = device.new_library_with_air(&bitcode).unwrap();
let (pairs, coordinates) = (pairs(), coordinates());
let mut failures = Vec::new();
let (sums, _) = run(&device, &library, "stored", &pairs, 1);
let (twin_sums, _) = run(&device, &library, "stored_compared", &pairs, 1);
let (_, ints) = run(&device, &library, "converted", &pairs, 1);
let (_, twin_ints) = run(&device, &library, "converted_multiplied", &pairs, 1);
let (texels, _) = run(&device, &library, "sampled", &coordinates, 8);
let (twin_texels, _) = run(&device, &library, "sampled_compared", &coordinates, 8);
for (what, a, b) in [
("stored", &sums, &twin_sums),
("converted", &ints, &twin_ints),
("sampled", &texels, &twin_texels),
] {
let differ = differing(a, b);
eprintln!(
"settled sums {what} on {name}: {} words differ from the settled twin's",
differ.len()
);
if !differ.is_empty() {
failures.push(format!("{what} on {name}: (word, form, twin) {differ:x?}"));
}
}
let rounded: Vec<u32> = pairs.iter().map(|[a, b]| (a + b).to_bits()).collect();
let truncated: Vec<u32> = pairs.iter().map(|[a, b]| (a - b) as i32 as u32).collect();
for (what, got, want) in [
("stored against the rounded sums", &sums, &rounded),
(
"converted against the truncated differences",
&ints,
&truncated,
),
] {
let differ = differing(got, want);
if !differ.is_empty() {
failures.push(format!(
"{what} on {name}: (input, device, host) {differ:x?}"
));
}
}
assert!(failures.is_empty(), "{failures:#?}");
}
let reported = messages.take();
assert!(
reported.is_empty(),
"the validation layer reported: {reported:#?}"
);
}
+1 -1
View File
@@ -60,7 +60,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 = 1805;
pub const SEMANTICS_VERSION: u32 = 1806;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
+165 -5
View File
@@ -37,6 +37,23 @@
//! `PrecisionNote::FastMathRewrites` for them. A sum of two leaves that joins no other sum, lane
//! by lane, is Metal's grouping as written ([`Sums::pair`]) and is settled alike.
//!
//! **Alone** ([`Sums::alone`]): such a sum that gives a device nothing to fuse or regroup it with
//! is left as written instead, every flag kept, so the lowering leaves it undecorated. Each
//! operand, through lane selections, insertions, extractions and negations, is a parameter, a load
//! from memory a thread does not own (device, constant or threadgroup), or a texture operation's
//! result; and each use, through lane selections, insertions and extractions, takes the sum where
//! no compiler combines it with anything: a texture operation's coordinate, a conversion to an
//! integer, or the value of a store to device or threadgroup memory. A negation is exact, and a
//! compiler that folds it into the sum makes the subtraction of the same value, which rounds
//! alike; where one lies on the way the two operands read no value in common, since a value added
//! to its own negation may fold to a zero. Any other operation on either side keeps the settled
//! form: a float operation, a comparison (Mesa's inexact rules rewrite `a + b < c`), a constant
//! lane, a select or phi, a negation of the sum, and a load from or store to thread memory
//! (forwarded into the arithmetic that reads it). Such a sum rounds once on every device whether
//! or not it is decorated, and the decoration is not free: MoltenVK's SPIRV-Cross writes a
//! `NoContraction` addition as a call to an `optnone` helper, which the Metal compiler does not
//! inline.
//!
//! **Not rewritten** (kept as written, with the note): a sum that is not pinned; a vector sum of
//! three leaves or more; one whose operations do not carry every fast-math flag (the probes
//! measured `fast`); one that reaches another block; one with a constant, repeated, negated or
@@ -45,9 +62,11 @@
//! place (a division, a call outside the AIR and LLVM intrinsics); a leaf negated in a sum that is
//! not modeled or in an earlier sum not rewritten.
use crate::air::intrinsics::{AirIntrinsic, NumKind, TexRole};
use crate::air::ir::{
BinOp as AirBin, Block, BlockId, Body, Call, Callee, Const, FastMath, FuncId, Idx, Inst,
InstId, InstKind, IntFlags, MemoryEffects, ModRef, Module, Type, TypeId, Value,
AddrSpace, BinOp as AirBin, Block, BlockId, Body, Call, Callee, CastOp, Const, FastMath,
FuncId, Idx, Inst, InstId, InstKind, IntFlags, MemoryEffects, ModRef, Module, Type, TypeId,
Value,
};
use crate::air::Entry;
use crate::budget::Meter;
@@ -74,6 +93,10 @@ const MOST_LEAVES: usize = 64;
/// The deepest operand chain a rank follows; a leaf whose rank reads deeper is not modeled.
const DEPTH: u32 = 2048;
/// The most lane selections, insertions and extractions [`Sums::alone`] follows from a sum, on
/// either side; a sum reached through more keeps the settled form.
const LANE_STEPS: u32 = 4;
fn invariant(what: &'static str) -> Error {
Error::Internal(InternalError::new(InternalKind::Invariant, what))
}
@@ -444,6 +467,7 @@ enum Expr {
/// The facts of the function a sum is read in.
struct Sums<'a> {
module: &'a Module,
func: FuncId,
body: &'a Body,
/// Each instruction's users, once per operand.
users: Users,
@@ -472,7 +496,7 @@ struct Sum {
}
impl<'a> Sums<'a> {
fn new(module: &'a Module, body: &'a Body, m: &mut Meter) -> Result<Self, Error> {
fn new(module: &'a Module, func: FuncId, body: &'a Body, m: &mut Meter) -> Result<Self, Error> {
let mut block = vec![None; body.insts.len()];
for (b, blk) in body.blocks.iter() {
for id in blk.inst_ids() {
@@ -486,6 +510,7 @@ impl<'a> Sums<'a> {
let users = Users::of(body);
Ok(Sums {
module,
func,
body,
users,
block,
@@ -638,6 +663,138 @@ impl<'a> Sums<'a> {
})
}
/// Whether the settled pair `root` (`a + b` or `a - b`) gives a device nothing to fuse or
/// regroup it with (module docs): every operand and every use takes it where no compiler
/// combines it with another operation.
fn alone(&self, root: InstId) -> bool {
let Some(InstKind::BinOp { a, b, .. }) = self.body.insts.get(root).map(|i| &i.kind) else {
return false;
};
let (mut x, mut y) = (BTreeSet::new(), BTreeSet::new());
let (Some(nx), Some(ny)) = (
self.opaque_sources(*a, LANE_STEPS, &mut x),
self.opaque_sources(*b, LANE_STEPS, &mut y),
) else {
return false;
};
// A value added to its own negation may fold to a zero.
if (nx || ny) && !x.is_disjoint(&y) {
return false;
}
self.opaque_uses(root, LANE_STEPS)
}
/// The values `v` reads, added to `out`, where each is one no compiler combines an addition
/// with, through at most `depth` lane selections, insertions, extractions and negations: a
/// parameter, a load from memory a thread does not own, or a texture operation's result; with
/// whether a negation lies on the way. `None` for any other. An `undef` or `poison` lane
/// source selects nothing.
fn opaque_sources(&self, v: Value, depth: u32, out: &mut BTreeSet<Value>) -> Option<bool> {
let id = match v {
Value::Arg(_) => {
out.insert(v);
return Some(false);
}
Value::Const(c) => {
return matches!(
self.module.consts().get(c).map(|c| &c.value),
Some(Const::Undef | Const::Poison)
)
.then_some(false)
}
Value::Inst(id) => id,
};
let mut through = |sources: &[Value], negates: bool| -> Option<bool> {
let depth = depth.checked_sub(1)?;
let mut negated = negates;
for s in sources {
negated |= self.opaque_sources(*s, depth, out)?;
}
Some(negated)
};
match self.body.insts.get(id).map(|i| &i.kind)? {
InstKind::Load { ptr, .. }
if self.space(*ptr).is_some_and(|s| s != AddrSpace::Thread) =>
{
out.insert(v);
Some(false)
}
InstKind::ExtractValue { agg, .. } if self.texture_call(*agg) => {
out.insert(v);
Some(false)
}
InstKind::FNeg { v: x, .. } => through(&[*x], true),
InstKind::ExtractElement { vec, .. } => through(&[*vec], false),
InstKind::InsertElement { vec, elt, .. } => through(&[*vec, *elt], false),
InstKind::ShuffleVector { a, b, .. } => through(&[*a, *b], false),
_ => None,
}
}
/// Whether every use of `id` takes it where no compiler combines it with another operation,
/// through at most `depth` lane selections, insertions and extractions: a texture operation's
/// coordinate, a conversion to an integer, or the value of a store to device or threadgroup
/// memory.
fn opaque_uses(&self, id: InstId, depth: u32) -> bool {
let v = Value::Inst(id);
self.users
.get(id)
.iter()
.all(|&u| match self.body.insts.get(u).map(|i| &i.kind) {
Some(
InstKind::ExtractElement { .. }
| InstKind::InsertElement { .. }
| InstKind::ShuffleVector { .. },
) => depth > 0 && self.opaque_uses(u, depth - 1),
Some(InstKind::Cast {
op: CastOp::FPToSI | CastOp::FPToUI,
..
}) => true,
Some(InstKind::Store { val, ptr, .. }) => {
*val == v
&& *ptr != v
&& self.space(*ptr).is_some_and(|s| {
matches!(s, AddrSpace::Device | AddrSpace::Threadgroup)
})
}
Some(InstKind::Call(call)) => match &call.callee {
Callee::Air {
op: AirIntrinsic::Convert(c),
..
} => c.dst_kind != NumKind::Float,
Callee::Air {
op: AirIntrinsic::Texture(t),
..
} => {
let coord = t.layout().index(TexRole::Coord);
(call.args.iter().enumerate()).all(|(i, a)| *a != v || Some(i) == coord)
}
_ => false,
},
_ => false,
})
}
/// The address space of pointer `ptr`.
fn space(&self, ptr: Value) -> Option<AddrSpace> {
let ty = self.module.value_ty(self.func, ptr)?;
self.module.types().ptr_space(ty)
}
/// Whether `v` is a call of a texture operation.
fn texture_call(&self, v: Value) -> bool {
matches!(
self.kind(v),
Some(InstKind::Call(call)) if matches!(
call.callee,
Callee::Air {
op: AirIntrinsic::Texture(_),
..
}
)
)
}
/// `(op, fmf, a, b)` of an addition or subtraction `v` of a `half` or `float` scalar.
fn add(&self, v: Value) -> Option<(AirBin, FastMath, Value, Value)> {
let Value::Inst(id) = v else {
@@ -979,7 +1136,7 @@ type Visited = (Option<(Sum, Vec<Leaf>)>, BTreeSet<Value>);
/// order.
fn plan(module: &Module, func: FuncId, body: &Body, m: &mut Meter) -> Result<Planned, Error> {
let mut ranks = Ranks::new(module, func, body, m)?;
let sums = Sums::new(module, body, m)?;
let sums = Sums::new(module, func, body, m)?;
let mut seen: Vec<Visited> = Vec::new();
let mut pairs: Planned = BTreeMap::new();
for block in reverse_post_order(body, m)? {
@@ -989,7 +1146,10 @@ fn plan(module: &Module, func: FuncId, body: &Body, m: &mut Meter) -> Result<Pla
for id in b.inst_ids() {
m.tick(1)?;
if let Some(e) = sums.pair(id) {
pairs.insert(id, (e, BTreeSet::from([id])));
// A pair alone keeps its flags: no device can combine it with a neighbour.
if !sums.alone(id) {
pairs.insert(id, (e, BTreeSet::from([id])));
}
continue;
}
match sums.sum(id, &mut ranks, m)? {
@@ -0,0 +1,572 @@
//! A settled sum no device can combine with a neighbour is left as written (`lower::arith::reassoc`,
//! its module docs' **Alone**), so the lowering leaves it undecorated; every other settled sum keeps
//! `NoContraction`.
//!
//! One module holds the forms, each a kernel (or a fragment) of two-leaf `fast` sums:
//!
//! - left as written: a sum of a buffer's lanes stored to device memory (`stored`) or to
//! threadgroup memory (`shared`), a difference converted to an integer (`converted`), and sums
//! of a buffer's lanes and a constant buffer's that are texture coordinates, whole, lane by lane
//! through insertions, and with a negated lane (`(d.x, -d.y) + uv`), with sums of the samples
//! stored (`sampled`); a fragment's coordinates `uv + d` and `(d.x, -d.y) + uv` (`bg`);
//! - settled: each twin of the first, its sum given one more use that a device may combine with it,
//! a comparison (`stored_compared`, and a lane of `sampled_compared`'s vector coordinate) or a
//! product (`converted_multiplied`); a sum stored to thread memory and read back
//! (`stored_private`), one whose operand is read back from thread memory (`from_private`), a sum
//! of `(v.x, -v.x)` and `v`, whose operands read one value and a negation of it
//! (`negated_beside_its_source`), and the fragment's sum of its two samples, which it returns
//! (`bg`).
//!
//! `llvm-as` assembles the module; without it the tests skip visibly.
use std::collections::BTreeMap;
use crate::air::ir::{BinOp as AirBin, FastMath, InstKind, Type};
use crate::device::profile::DeviceProfile;
use crate::error::Error;
use crate::library::FunctionConstantValues;
use crate::lower::select::Plan;
use crate::pipeline::sym::{Axis, ResourceKind, ResourceSlot, SpecKey, Stage};
use crate::pipeline::testing::{
compile, link_and_validate, llvm_assemble, meter, specialized_entry, typed_module,
AssembleError,
};
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::committed_profiles;
const MODULE: &str = r#"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"
@tg = internal addrspace(3) global [64 x float] undef, align 4
define void @stored(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fadd fast float %a, %b
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %s, ptr addrspace(1) %po, align 4
ret void
}
define void @stored_compared(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fadd fast float %a, %b
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %s, ptr addrspace(1) %po, align 4
%lt = fcmp fast olt float %s, 0.000000e+00
%z = zext i1 %lt to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %z, ptr addrspace(1) %pz, align 4
ret void
}
define void @converted(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fsub fast float %a, %b
%i = fptosi float %s to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %i, ptr addrspace(1) %pz, align 4
ret void
}
define void @converted_multiplied(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fsub fast float %a, %b
%i = fptosi float %s to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %i, ptr addrspace(1) %pz, align 4
%p = fmul fast float %s, %a
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %p, ptr addrspace(1) %po, align 4
ret void
}
define void @stored_private(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%m = alloca [2 x float], align 4
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fadd fast float %a, %b
%j = and i32 %g, 1
%pm = getelementptr inbounds [2 x float], ptr %m, i32 0, i32 %j
store float %s, ptr %pm, align 4
%r = load float, ptr %pm, align 4
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %r, ptr addrspace(1) %po, align 4
ret void
}
define void @from_private(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%m = alloca [2 x float], align 4
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%j = and i32 %g, 1
%pm = getelementptr inbounds [2 x float], ptr %m, i32 0, i32 %j
store float %a, ptr %pm, align 4
%r = load float, ptr %pm, align 4
%s = fadd fast float %r, %b
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %s, ptr addrspace(1) %po, align 4
ret void
}
define void @shared(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g, i32 %t) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%b = extractelement <2 x float> %v, i64 1
%s = fadd fast float %a, %b
%pt = getelementptr inbounds [64 x float], ptr addrspace(3) @tg, i32 0, i32 %t
store float %s, ptr addrspace(3) %pt, align 4
tail call void @air.wg.barrier(i32 2, i32 1)
%u = sub i32 63, %t
%pu = getelementptr inbounds [64 x float], ptr addrspace(3) @tg, i32 0, i32 %u
%r = load float, ptr addrspace(3) %pu, align 4
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g
store float %r, ptr addrspace(1) %po, align 4
ret void
}
define void @sampled(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, ptr addrspace(2) %k, ptr addrspace(1) %tex, ptr addrspace(2) %smp, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%uv = load <2 x float>, ptr addrspace(1) %pi, align 8
%d = load <2 x float>, ptr addrspace(2) %k, align 8
%c = fadd fast <2 x float> %uv, %d
%a = extractelement <2 x float> %uv, i64 0
%b = extractelement <2 x float> %d, i64 1
%x = fadd fast float %a, %b
%y = fsub fast float %a, %b
%c0 = insertelement <2 x float> poison, float %x, i64 0
%c1 = insertelement <2 x float> %c0, float %y, i64 1
%r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v0 = extractvalue { <4 x float>, i8 } %r0, 0
%r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c1, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v1 = extractvalue { <4 x float>, i8 } %r1, 0
%dx = extractelement <2 x float> %d, i64 0
%dy = extractelement <2 x float> %d, i64 1
%ny = fneg fast float %dy
%n0 = insertelement <2 x float> poison, float %dx, i64 0
%dn = insertelement <2 x float> %n0, float %ny, i64 1
%c2 = fadd fast <2 x float> %dn, %uv
%r2 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c2, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v2 = extractvalue { <4 x float>, i8 } %r2, 0
%w = fadd fast <4 x float> %v0, %v1
%w2 = fadd fast <4 x float> %v2, %v1
%g2 = shl i32 %g, 1
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g2
store <4 x float> %w, ptr addrspace(1) %po, align 16
%g21 = or i32 %g2, 1
%po2 = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g21
store <4 x float> %w2, ptr addrspace(1) %po2, align 16
ret void
}
define void @sampled_compared(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, ptr addrspace(2) %k, ptr addrspace(1) %tex, ptr addrspace(2) %smp, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%uv = load <2 x float>, ptr addrspace(1) %pi, align 8
%d = load <2 x float>, ptr addrspace(2) %k, align 8
%c = fadd fast <2 x float> %uv, %d
%a = extractelement <2 x float> %uv, i64 0
%b = extractelement <2 x float> %d, i64 1
%x = fadd fast float %a, %b
%y = fsub fast float %a, %b
%c0 = insertelement <2 x float> poison, float %x, i64 0
%c1 = insertelement <2 x float> %c0, float %y, i64 1
%r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v0 = extractvalue { <4 x float>, i8 } %r0, 0
%r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c1, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v1 = extractvalue { <4 x float>, i8 } %r1, 0
%dx = extractelement <2 x float> %d, i64 0
%dy = extractelement <2 x float> %d, i64 1
%ny = fneg fast float %dy
%n0 = insertelement <2 x float> poison, float %dx, i64 0
%dn = insertelement <2 x float> %n0, float %ny, i64 1
%c2 = fadd fast <2 x float> %dn, %uv
%r2 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c2, i1 true, <2 x i32> zeroinitializer, i1 true, float 0.000000e+00, float 0.000000e+00, i32 0)
%v2 = extractvalue { <4 x float>, i8 } %r2, 0
%w = fadd fast <4 x float> %v0, %v1
%w2 = fadd fast <4 x float> %v2, %v1
%g2 = shl i32 %g, 1
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g2
store <4 x float> %w, ptr addrspace(1) %po, align 16
%g21 = or i32 %g2, 1
%po2 = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i32 %g21
store <4 x float> %w2, ptr addrspace(1) %po2, align 16
%cx = extractelement <2 x float> %c, i64 0
%lt = fcmp fast olt float %cx, 5.000000e-01
%z = zext i1 %lt to i32
%pz = getelementptr inbounds i32, ptr addrspace(1) %aux, i32 %g
store i32 %z, ptr addrspace(1) %pz, align 4
ret void
}
define <4 x float> @bg(<2 x float> %uv, ptr addrspace(2) %k, ptr addrspace(1) %tex, ptr addrspace(2) %smp) {
%d = load <2 x float>, ptr addrspace(2) %k, align 8
%c0 = fadd fast <2 x float> %uv, %d
%dx = extractelement <2 x float> %d, i64 0
%dy = extractelement <2 x float> %d, i64 1
%ny = fneg fast float %dy
%n0 = insertelement <2 x float> poison, float %dx, i64 0
%dn = insertelement <2 x float> %n0, float %ny, i64 1
%c1 = fadd fast <2 x float> %dn, %uv
%r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c0, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)
%v0 = extractvalue { <4 x float>, i8 } %r0, 0
%r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %smp, <2 x float> %c1, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)
%v1 = extractvalue { <4 x float>, i8 } %r1, 0
%w = fadd fast <4 x float> %v0, %v1
ret <4 x float> %w
}
define void @negated_beside_its_source(ptr addrspace(1) %in, ptr addrspace(1) %out, ptr addrspace(1) %aux, i32 %g) {
%pi = getelementptr inbounds <2 x float>, ptr addrspace(1) %in, i32 %g
%v = load <2 x float>, ptr addrspace(1) %pi, align 8
%a = extractelement <2 x float> %v, i64 0
%na = fneg fast float %a
%m = insertelement <2 x float> %v, float %na, i64 1
%s = fadd fast <2 x float> %m, %v
%g2 = shl i32 %g, 1
%po = getelementptr inbounds float, ptr addrspace(1) %out, i32 %g2
store <2 x float> %s, ptr addrspace(1) %po, align 4
ret void
}
declare void @air.wg.barrier(i32, i32)
declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)
!air.kernel = !{!20, !21, !22, !23, !24, !25, !26, !27, !28, !29}
!air.fragment = !{!40}
!air.version = !{!1}
!air.language_version = !{!2}
!1 = !{i32 2, i32 8, i32 0}
!2 = !{!"Metal", i32 4, i32 0, i32 0}
!3 = !{}
!4 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"in"}
!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"out"}
!6 = !{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"aux"}
!7 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"}
!8 = !{i32 4, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}
!9 = !{!4, !5, !6, !7}
!10 = !{!4, !5, !6, !7, !8}
!11 = !{i32 3, !"air.buffer", !"air.location_index", i32 3, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"k"}
!12 = !{i32 4, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"tex"}
!13 = !{i32 5, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"smp"}
!14 = !{i32 6, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"g"}
!15 = !{!4, !16, !6, !11, !12, !13, !14}
!16 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"}
!20 = !{ptr @stored, !3, !9}
!21 = !{ptr @stored_compared, !3, !9}
!22 = !{ptr @converted, !3, !9}
!23 = !{ptr @converted_multiplied, !3, !9}
!24 = !{ptr @stored_private, !3, !9}
!25 = !{ptr @from_private, !3, !9}
!26 = !{ptr @shared, !3, !10}
!27 = !{ptr @sampled, !3, !15}
!28 = !{ptr @sampled_compared, !3, !15}
!29 = !{ptr @negated_beside_its_source, !3, !9}
!40 = !{ptr @bg, !41, !43}
!41 = !{!42}
!42 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}
!43 = !{!44, !45, !46, !47}
!44 = !{i32 0, !"air.fragment_input", !"generated(2uvDv2_f)", !"air.center", !"air.perspective", !"air.arg_type_name", !"float2", !"air.arg_name", !"uv"}
!45 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"k"}
!46 = !{i32 2, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"tex"}
!47 = !{i32 3, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"smp"}
"#;
/// Each form: its entry, and its two-leaf `float` sums left as written and settled.
const FORMS: [(&str, usize, usize); 11] = [
("stored", 1, 0),
("stored_compared", 0, 1),
("converted", 1, 0),
("converted_multiplied", 0, 1),
("stored_private", 0, 1),
("from_private", 0, 1),
("shared", 1, 0),
("sampled", 6, 0),
("sampled_compared", 5, 1),
("bg", 2, 1),
("negated_beside_its_source", 0, 1),
];
/// Each form left as written and its settled twin, whose one more use of a sum is one a device may
/// combine it with.
const TWINS: [(&str, &str); 3] = [
("stored", "stored_compared"),
("converted", "converted_multiplied"),
("sampled", "sampled_compared"),
];
fn assemble() -> Option<Vec<u8>> {
let dir = std::env::temp_dir().join(format!("m2v-settled-sums-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch");
let ll = dir.join("k.ll");
std::fs::write(&ll, MODULE).expect("write");
let r = llvm_assemble(&ll);
let _ = std::fs::remove_dir_all(&dir);
match r {
Ok(b) => Some(b),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected the module: {why}"),
}
}
/// The `float` additions and subtractions of `entry` after the rewrite on `p`: those that keep
/// `reassoc` (left as written) and those without it (settled).
fn sums(bc: &[u8], entry: &str, p: &DeviceProfile) -> (usize, usize) {
let e = specialized_entry(
bc,
entry,
p,
&FunctionConstantValues::defaults(),
&[],
&mut meter(),
)
.unwrap_or_else(|err| panic!("{entry}: {err}"));
let body = e
.module
.func(e.func)
.and_then(|f| f.body.as_ref())
.expect("a body");
let types = e.module.types();
let (mut alone, mut settled) = (0, 0);
for (_, inst) in body.insts.iter() {
let InstKind::BinOp {
op: AirBin::FAdd | AirBin::FSub,
fmf,
..
} = &inst.kind
else {
continue;
};
let elem = match types.get(inst.ty) {
Some(Type::Vector { elem, .. }) => types.get(*elem),
t => t,
};
assert!(matches!(elem, Some(Type::Float)), "{entry}: a float sum");
if fmf.contains(FastMath::REASSOC) {
alone += 1;
} else {
settled += 1;
}
}
(alone, settled)
}
/// After the rewrite each form's sums are left as written or settled as the module docs say, on
/// every committed profile.
#[test]
fn a_sum_no_device_can_combine_is_left_as_written() {
let Some(bc) = assemble() else {
return;
};
for (stem, p) in committed_profiles().expect("profiles") {
for (entry, alone, settled) in FORMS {
assert_eq!(
sums(&bc, entry, &p),
(alone, settled),
"{stem} {entry}: (left as written, settled)"
);
}
}
}
/// The ids of every `OpFAdd` and `OpFSub` result of `words` decorated `NoContraction`.
fn decorated_sums(words: &[u32]) -> usize {
let (mut sums, mut decorated) = (Vec::new(), Vec::new());
let mut i = 5;
while i < words.len() {
let (len, opcode) = ((words[i] >> 16) as usize, words[i] & 0xFFFF);
assert!(len > 0 && i + len <= words.len(), "malformed module");
if opcode == crate::spv::Op::Decorate as u32
&& words[i + 2] == crate::spv::Decoration::NoContraction as u32
{
decorated.push(words[i + 1]);
}
if opcode == crate::spv::Op::FAdd as u32 || opcode == crate::spv::Op::FSub as u32 {
sums.push(words[i + 2]);
}
i += len;
}
sums.iter().filter(|s| decorated.contains(s)).count()
}
/// In SPIR-V, on every committed profile, each settled twin decorates exactly one addition or
/// subtraction more than its form left as written, and the forms whose only sum is left as
/// written (`stored`, `converted`, `shared`) decorate none; every module validates.
#[test]
fn only_a_settled_sum_is_no_contraction() {
let Some(bc) = assemble() else {
return;
};
for (stem, p) in committed_profiles().expect("profiles") {
let decorated = |entry: &str| -> Option<usize> {
let a = match compile(&bc, entry, &p) {
Ok(a) => a,
Err(Error::Unsupported(u)) => {
eprintln!("{stem} {entry}: refused: {u}");
return None;
}
Err(e) => panic!("{stem} {entry}: {e}"),
};
let (_, words) =
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}"));
Some(decorated_sums(&words))
};
for entry in ["stored", "converted", "shared"] {
if let Some(n) = decorated(entry) {
assert_eq!(n, 0, "{stem} {entry}: decorated sums");
}
}
for (alone, twin) in TWINS {
if let (Some(a), Some(t)) = (decorated(alone), decorated(twin)) {
assert_eq!(t, a + 1, "{stem} {alone} {twin}: decorated sums");
}
}
}
}
/// The pairs the kernels read: the special pairs below, then pairs from a fixed generator, each
/// operand normal and the result in range for `converted`'s integer.
fn pairs() -> Vec<[f32; 2]> {
let ulp = 2f32.powi(-23);
let mut out = vec![
// Ties: each rounds to even.
[1.0, ulp / 2.0],
[1.0 + ulp, ulp / 2.0],
[1.0, 3.0 * ulp / 2.0],
[-1.0, -ulp / 2.0],
// Zeros: `-0 + -0` is `-0`, `x + -x` is `+0`.
[-0.0, -0.0],
[0.0, -0.0],
[1.5, -1.5],
// Near an integer, where the difference's rounding moves its truncation.
[16_777_216.0, -0.5],
[4_194_304.5, 0.25],
[-1_048_576.0 - 0.25, 0.125],
[1.0e30, 1.0e30],
[1.0e-37, 1.0e-37],
];
let mut x: u32 = 0x9E37_79B9;
while out.len() < 4096 {
let mut next = || {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
x
};
// Normal operands of magnitude below 2^24, with 23 random fraction bits.
let mut normal = || {
let w = next();
let exponent = 127 - 20 + (w >> 24) % 44;
f32::from_bits((w & 0x8000_0000) | (exponent << 23) | (next() & 0x7F_FFFF))
};
out.push([normal(), normal()]);
}
out
}
/// The words of `entry`'s `out` and `aux` buffers on the interpreter, for `p`, over [`pairs`].
fn interpret(
plan_module: &(Plan, crate::spirv::ir::TypedModule),
n: usize,
) -> (Vec<u32>, Vec<u32>) {
let (plan, module) = plan_module;
let slot = |index: u32| ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index,
};
let buffer = |index: u32, bytes: Vec<u8>| Buffer {
slot: Some(slot(index)),
address: None,
bytes,
};
let input: Vec<u8> = pairs()
.iter()
.flat_map(|[a, b]| a.to_le_bytes().into_iter().chain(b.to_le_bytes()))
.collect();
let mut spec = BTreeMap::new();
spec.insert(SpecKey::LocalSize(Axis::X), 64);
spec.insert(SpecKey::LocalSize(Axis::Y), 1);
spec.insert(SpecKey::LocalSize(Axis::Z), 1);
spec.insert(SpecKey::FlatLocalSize, 64);
let push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
let resources = Resources {
buffers: vec![
buffer(0, input),
buffer(1, vec![0xEE; 4 * n]),
buffer(2, vec![0xEE; 4 * n]),
],
push,
spec,
};
let cfg = Config {
workgroups: [u32::try_from(n / 64).expect("groups"), 1, 1],
order: Order::Forward,
step_limit: 1 << 28,
..Config::default()
};
let o = run(module, &cfg, resources).expect("run");
let words = |b: &[u8]| -> Vec<u32> {
b.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect()
};
(words(&o.buffers[1]), words(&o.buffers[2]))
}
/// On the interpreter the forms and their settled twins give the same words, on every committed
/// profile: `stored`'s sums and `converted`'s integers, over 4096 pairs. The interpreter rounds
/// each operation on its own whether or not it is decorated, so this holds the module's own
/// semantics, not a device's (the runtime lane `settled_sums` runs the forms on the device): and
/// each sum is the correctly rounded one, each integer the truncated difference.
#[test]
fn a_sum_left_as_written_gives_the_settled_twin_s_words() {
let Some(bc) = assemble() else {
return;
};
let pairs = pairs();
let n = pairs.len();
for (stem, p) in committed_profiles().expect("profiles") {
let run_of = |entry: &str| {
let m = typed_module(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
interpret(&m, n)
};
let (sums, _) = run_of("stored");
let (twin_sums, _) = run_of("stored_compared");
assert_eq!(sums, twin_sums, "{stem}: stored");
let (_, ints) = run_of("converted");
let (_, twin_ints) = run_of("converted_multiplied");
assert_eq!(ints, twin_ints, "{stem}: converted");
for (g, [a, b]) in pairs.iter().enumerate() {
let s = a + b;
if s.is_normal() || s == 0.0 {
assert_eq!(sums[g], s.to_bits(), "{stem}: {a:e} + {b:e}");
}
let d = a - b;
if d.is_finite() && d.abs() < 2f32.powi(31) {
assert_eq!(ints[g] as i32, d as i32, "{stem}: {a:e} - {b:e}");
}
}
}
}
+1
View File
@@ -120,6 +120,7 @@ mod engine_sampler_unk;
mod engine_selected_indices;
mod engine_separate_samplers;
mod engine_seq_cst;
mod engine_settled_sums;
mod engine_shared_switch;
mod engine_simd;
mod engine_simd_emulated;