Shaders: v_cvt_u16_f16 and v_cvt_i16_f16 saturate at 16 bits

They went through a 32-bit conversion, so an f16 past the i16 range
(32768 up to 65504) wrapped, and infinities and NaN were undefined. The
value is now clamped in f32 to the 16-bit range first (every f16 is exact
there) and NaN gives 0, as the hardware's conversions do.
This commit is contained in:
Luiz Neves committed 2026-11-23 23:49:01 -03:00
1 parent d2a4bae1f4
commit 2af66ff1d8
2 files changed
+53 -6

No files matched your search

+13 -6
View File
@@ -4357,15 +4357,22 @@ impl<'a> Lower<'a> {
}
let r = match name {
"v_cvt_u16_f16" | "v_cvt_i16_f16" => {
// shortcut: converted through 32 bits, so out-of-range values
// wrap instead of saturating at 16 bits.
// Toward zero, saturating at the 16-bit range (infinities
// included); NaN gives 0. Clamped in f32 first, where every
// f16 is exact, so the conversion never leaves i32's range.
let a = self.half_fsrc(inst, 0)?;
let op = if name == "v_cvt_u16_f16" {
Cast::FpToUi
let (lo, hi) = if name == "v_cvt_u16_f16" {
(0.0f32, 65535.0f32)
} else {
Cast::FpToSi
(-32768.0, 32767.0)
};
self.s.m.cast(c, op, a, i32t)
let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits()));
let t = self.binary(35, a, lo);
let t = self.binary(36, t, hi);
let r = self.s.m.cast(c, Cast::FpToSi, t, i32t);
let nan = self.s.m.cmp(c, pred::UNO, a, a);
let z = self.s.m.i32(0);
self.s.m.select(c, nan, z, r)
}
_ => {
let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?);
@@ -520,6 +520,46 @@ fn v_sin_and_v_cos_f32_reduce_large_turns() {
});
}
#[test]
fn v_cvt_u16_and_i16_f16_saturate() {
// v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053).
let cases: &[(u16, u16, u16)] = &[
// (f16 input, u16 result, i16 result)
(0x0000, 0, 0), // 0
(0x8000, 0, 0), // -0
(0x3E00, 1, 1), // 1.5 -> 1 (toward zero)
(0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1
(0x57D0, 125, 125), // 125.0
(0x7800, 32768, 32767), // 32768 saturates i16
(0x77FF, 32752, 32752), // 32752, the largest f16 below 32768
(0xF800, 0, 0x8000), // -32768 fits i16
(0xF801, 0, 0x8000), // -32800 saturates i16
(0x7BFF, 65504, 32767), // max finite f16
(0xFBFF, 0, 0x8000), // -65504
(0x7C00, 0xFFFF, 32767), // +inf
(0xFC00, 0, 0x8000), // -inf
(0x7E00, 0, 0), // NaN
(0xFE00, 0, 0), // -NaN
(0x0001, 0, 0), // smallest subnormal
];
for (op, what, pick) in [
(0x052u16, "v_cvt_u16_f16", 0usize),
(0x053, "v_cvt_i16_f16", 1),
] {
let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]);
let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect();
run_cases(&shader, &inputs, |backend, i, _, got| {
let want = if pick == 0 { cases[i].1 } else { cases[i].2 };
assert_eq!(
got,
u32::from(want),
"{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}",
cases[i].0,
);
});
}
}
#[test]
fn v_sin_and_v_cos_f16_reduce_large_turns() {
let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]);