Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub struct KernelOptions {
/// Version of the direct translator's output, part of the on-disk translation cache's
/// identity (`recomp::pso`): bump it on any change that alters the emitted containers
/// (the `gpu/dxil` sources are not in build.rs's translator source hash).
pub const TRANSLATOR_VERSION: u32 = 7;
pub const TRANSLATOR_VERSION: u32 = 8;

/// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this
/// translator, with the HLSL path as the fallback for what it cannot translate yet.
Expand Down Expand Up @@ -423,6 +423,7 @@ impl Lw {
sampler_base: o.sampler_base,
dyn_rm: false,
f32_rm: false,
track_frexp_denorm: crate::gpu::recomp::emit::tracks_frexp_f32_denorm(insts),
has_f64_round_op: false,
exec_cache: HashMap::new(),
xs: None,
Expand Down
7 changes: 4 additions & 3 deletions crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ pub struct Lw {
/// the program writes a non-default MODE[1:0]: rounding f32 instructions round by
/// `lower_round::VAR_F32_MODE` (`lower_round`)
pub f32_rm: bool,
pub track_frexp_denorm: bool,
pub has_f64_round_op: bool,
/// static samplers bound so far: (S#, comparison, handle) at `s<i>, space1`
pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>,
Expand Down Expand Up @@ -909,7 +910,7 @@ impl Lw {
if self.geom.is_some() && self.geom_inst(d, &name).is_some() {
return Ok(());
}
if name == "s_denorm_mode" && self.f32_rm {
if name == "s_denorm_mode" && (self.f32_rm || self.track_frexp_denorm) {
return self.denorm_mode(Self::fv(d, "SIMM16") as u32);
}
if NOOPS.contains(&name.as_str()) {
Expand Down Expand Up @@ -1000,11 +1001,11 @@ impl Lw {
fn setreg(&mut self, d: &Decoded, name: &str) -> LResult<()> {
let simm = Self::fv(d, "SIMM16") as u16;
let (sp_mask, dp_mask, off) = hwreg_mode_round_masks(simm);
if self.f32_rm {
if self.f32_rm || self.track_frexp_denorm {
// the mirrored MODE bits (single-precision round / denormal modes)
let (id, offset, width) = decode_hwreg(simm);
if id == 1 {
let wmask = if width >= 32 { u32::MAX } else { ((1u32 << width) - 1) << offset };
let wmask = (if width == 32 { u32::MAX } else { (1u32 << width) - 1 }) << offset;
let src = if name == "s_setreg_imm32_b32" {
let imm = d.literal.ok_or_else(|| format!("{}: literal", rdna2::format(d)))?;
self.c(imm)
Expand Down
11 changes: 9 additions & 2 deletions crates/xcl/src/gpu/dxil/lower_round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@
use super::lower::{LResult, Lw};
use super::module::{BinOp, CastOp, Pred, Value};

/// MODE[1:0] | MODE[5:4] << 4 (single-precision round and denormal modes), `f32_rm` programs.
/// MODE[1:0] and MODE[5:4] (single-precision round and denormal modes).
pub const VAR_F32_MODE: u32 = super::lower::VAR_BUDGET + 5;
/// The MODE bits `VAR_F32_MODE` mirrors.
pub const MODE_BITS: u32 = 0x33;
/// Initial MODE (nearest even, f32 denormals kept: what the translator assumes elsewhere).
pub const MODE_INIT: u32 = 0x30;
/// Translator-only flag: an instruction on this path has explicitly written MODE[4].
pub(super) const F32_DENORM_INPUT_WRITTEN: u32 = 1 << 31;

const MASK52: u64 = (1 << 52) - 1;

Expand All @@ -43,13 +45,18 @@ impl Lw {
/// MODE ← (MODE & !mask) | (v & mask), on the mirrored bits.
pub fn mode_write(&mut self, v: Value, mask: u32) {
let mask = mask & MODE_BITS;
if mask == 0 || !self.f32_rm {
if mask == 0 || !(self.f32_rm || self.track_frexp_denorm) {
return;
}
let cur = self.rd(VAR_F32_MODE);
let keep = self.andc(cur, !mask);
let nv = self.andc(v, mask);
let r = self.or(keep, nv);
let r = if self.track_frexp_denorm && mask & 0x10 != 0 {
self.orc(r, F32_DENORM_INPUT_WRITTEN)
} else {
r
};
self.wr(VAR_F32_MODE, r);
}

Expand Down
5 changes: 1 addition & 4 deletions crates/xcl/src/gpu/dxil/lower_valu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,10 +582,7 @@ impl Lw {
let x = fs!(0);
fr!(self.frexp_mant(x))
}
"v_frexp_exp_i32_f32" => {
let x = fs!(0);
self.frexp_exp(x)
}
"v_frexp_exp_i32_f32" => self.frexp_exp_f32(a, |lw| lw.fsrc(&m, 0, a)),
"v_ldexp_f32" => {
let x = fs!(0);
fr!(self.ldexp_f(x, b))
Expand Down
38 changes: 38 additions & 0 deletions crates/xcl/src/gpu/dxil/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,44 @@ impl Lw {
let ei = self.ftosi(e);
self.selc(s, 0, ei)
}
pub fn frexp_exp_f32(&mut self, bits: Value, legacy_src: impl FnOnce(&mut Self) -> Value) -> Value {
use super::lower_round::{F32_DENORM_INPUT_WRITTEN, VAR_F32_MODE};
let mode = if self.track_frexp_denorm { self.rd(VAR_F32_MODE) } else { self.c(0) };
let written = self.andc(mode, F32_DENORM_INPUT_WRITTEN);
let known = self.nz(written);
let legacy = |lw: &mut Self| {
let x = legacy_src(lw);
lw.frexp_exp(x)
};
match self.s.m.const_u64(known) {
Some(0) => legacy(self),
Some(1) => self.frexp_exp_f32_bits(bits, mode),
_ => {
let result = self.frexp_exp_f32_bits(bits, mode);
let old = legacy(self);
self.sel(known, result, old)
}
}
}

fn frexp_exp_f32_bits(&mut self, bits: Value, mode: Value) -> Value {
let e8 = self.lshrc(bits, 23);
let exp = self.andc(e8, 0xFF);
let fraction = self.andc(bits, 0x7F_FFFF);
let normal = self.addc(exp, (-126i32) as u32);
// firstbithigh(0) returns -1; a zero fraction always produces 0 below.
let top = self.firstbithigh(fraction);
let subnormal = self.addc(top, (-148i32) as u32);
let empty = self.cmpc(Pred::Eq, fraction, 0);
let keep = self.andc(mode, 0x10);
let flush = self.cmpc(Pred::Eq, keep, 0);
let zero = self.lor(empty, flush);
let low = self.selc(zero, 0, subnormal);
let no_exp = self.cmpc(Pred::Eq, exp, 0);
let finite = self.sel(no_exp, low, normal);
let special = self.cmpc(Pred::Eq, exp, 0xFF);
self.selc(special, 0, finite)
}
/// `ldexp_f`: exact x · 2^n on the bits.
pub fn ldexp_f(&mut self, x: Value, n: Value) -> Value {
let u = self.bits(x);
Expand Down
28 changes: 28 additions & 0 deletions crates/xcl/src/gpu/dxil/round_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,34 @@ fn gpu_direct_f32_round_modes_dynamic_and_denormals() {
}
}

#[test]
fn gpu_frexp_exp_f32_denorm_with_directed_rounding() {
if !gpu_ready() {
return;
}
let mut code = encode("S_DENORM_MODE", "ENC_SOPP", &[("SIMM16", 3)], None).unwrap();
for (name, enc, fields) in [
("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 1)][..]),
("V_FREXP_EXP_I32_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V)]),
("S_DENORM_MODE", "ENC_SOPP", &[("SIMM16", 2)]),
("V_FREXP_EXP_I32_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V)]),
("V_ADD_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 1), ("VSRC1", 2)]),
("S_ENDPGM", "ENC_SOPP", &[]),
] {
code.extend(encode(name, enc, fields, None).unwrap());
}
let mut st = KernelState::default();
for v in &mut st.vgpr {
v[..3].copy_from_slice(&[1, 0x3F80_0000, 0x3380_0000]);
}
let r = run(&code, &st);
for (lane, v) in r.vgpr.iter().enumerate() {
assert_eq!(v[4] as i32, -148, "lane {lane}: preserve after S_ROUND_MODE");
assert_eq!(v[5], 0, "lane {lane}: flush after S_DENORM_MODE");
assert_eq!(v[6], 0x3F80_0001, "lane {lane}: round toward +inf after S_DENORM_MODE");
}
}

/// Unimplemented directed ops are translation errors, not silent nearest-even results.
#[test]
fn direct_f32_round_mode_unsupported_op_rejected() {
Expand Down
67 changes: 63 additions & 4 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub(super) struct Em {
has_f64_round_op: bool,
/// program writes a non-default `MODE[3:2]` and uses f16 ops (emits `xcl_fp16_rm`)
dynamic_f16_rm: bool,
track_frexp_denorm: bool,
/// multi-warp Compute/Mesh shader containing `s_barrier`: use early-exit-safe, bounded
/// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits,
/// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`.
Expand Down Expand Up @@ -366,6 +367,28 @@ fn decode_hwreg(simm16: u16) -> (u32, u32, u32) {
(id, offset, width)
}

/// Source bit that a `s_setreg*` field writes to MODE[4] (FP32 denormal input preserve).
fn frexp_f32_denorm_shift(simm16: u16) -> Option<u32> {
let (id, offset, width) = decode_hwreg(simm16);
(id == 1 && (offset..offset + width).contains(&4)).then(|| 4 - offset)
}

pub(crate) fn writes_frexp_f32_denorm(d: &Decoded) -> bool {
match d.inst.name {
"S_DENORM_MODE" => true,
"S_SETREG_IMM32_B32" | "S_SETREG_B32" => {
let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) as u16;
frexp_f32_denorm_shift(simm).is_some()
}
_ => false,
}
}

pub(crate) fn tracks_frexp_f32_denorm(insts: &[Decoded]) -> bool {
insts.iter().any(|d| d.inst.name == "V_FREXP_EXP_I32_F32")
&& insts.iter().any(writes_frexp_f32_denorm)
}

/// Bits of `MODE[1:0]` (sp) and `MODE[3:2]` (dp/f16) touched by a `s_setreg*` `SIMM16`.
/// Returns `(sp_mask, dp_mask)` (each 2 bits) and `offset`. Non-`MODE` registers return `(0, 0, 0)`.
fn hwreg_mode_round_masks(simm16: u16) -> (u32, u32, u32) {
Expand Down Expand Up @@ -489,6 +512,7 @@ impl Em {
has_f16_round_op: false,
has_f64_round_op: false,
dynamic_f16_rm: false,
track_frexp_denorm: false,
safe_barrier: false,
}
}
Expand All @@ -507,6 +531,7 @@ impl Em {
/// Pre-scan the program for f16/f64 rounding-sensitive ops, non-default `MODE[3:2]` writes,
/// and multi-warp `s_barrier` usage (for early-exit-safe, bounded `xcl_s_barrier`).
pub fn configure_round_modes(&mut self, insts: &[Decoded], stop_at_endpgm: bool) {
self.track_frexp_denorm = tracks_frexp_f32_denorm(insts);
let mut writes_nonzero_dp = false;
let mut has_s_barrier = false;
for d in insts {
Expand Down Expand Up @@ -872,7 +897,8 @@ impl Em {
}
// s_sendmsg is a no-op except GS_ALLOC_REQ (mesh) and GS emit/cut (geometry)
let mesh_msg = name == "s_sendmsg" && matches!(self.opt.mode, Mode::Mesh(_) | Mode::Geometry(_));
if NOOPS.contains(&name.as_str()) && !mesh_msg {
let frexp_denorm_write = name == "s_denorm_mode" && self.track_frexp_denorm;
if NOOPS.contains(&name.as_str()) && !mesh_msg && !frexp_denorm_write {
*self.ignored.entry(name).or_default() += 1;
return Flow::Next;
}
Expand Down Expand Up @@ -945,6 +971,11 @@ impl Em {
}
Flow::Next
}
"s_denorm_mode" => {
let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0);
self.line(&format!("xcl_frexp_f32_denorm = {}u;", 1 + (simm & 1)));
Flow::Next
}
"s_round_mode" => {
// MODE[3:0] = SIMM16[3:0]: [1:0] = f32 (SP), [3:2] = f64/f16 (DP).
// 0 = RNE (HLSL default), 1 = +inf, 2 = -inf, 3 = RTZ.
Expand Down Expand Up @@ -991,9 +1022,21 @@ impl Em {

fn setreg(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> {
let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) as u16;
let denorm_shift = if self.track_frexp_denorm { frexp_f32_denorm_shift(simm) } else { None };
if let Some(shift) = denorm_shift {
if name == "s_setreg_imm32_b32" {
let imm = d.literal.ok_or("literal")?;
self.line(&format!("xcl_frexp_f32_denorm = {}u;", 1 + ((imm >> shift) & 1)));
} else {
let src = self.code32(Self::field(d, "SDST"), None, false).ok_or("register")?;
self.line(&format!("xcl_frexp_f32_denorm = 1u + (({src} >> {shift}u) & 1u);"));
}
}
let (sp_mask, dp_mask, off) = hwreg_mode_round_masks(simm);
if sp_mask == 0 && dp_mask == 0 {
*self.ignored.entry(name.to_string()).or_default() += 1;
if denorm_shift.is_none() {
*self.ignored.entry(name.to_string()).or_default() += 1;
}
return Ok(());
}
if name == "s_setreg_imm32_b32" {
Expand All @@ -1013,7 +1056,7 @@ impl Em {
let keep = (!dp_mask) & 3;
self.line(&format!("xcl_fp16_rm = (xcl_fp16_rm & {keep}u) | {dp}u;"));
}
} else {
} else if denorm_shift.is_none() {
*self.ignored.entry(name.to_string()).or_default() += 1;
}
return Ok(());
Expand Down Expand Up @@ -1041,7 +1084,7 @@ impl Em {
_ => format!("xcl_fp16_rm = (xcl_fp16_rm & 1u) | (({src} & 1u) << 1);"),
};
self.line(&stmt);
} else {
} else if denorm_shift.is_none() {
*self.ignored.entry(name.to_string()).or_default() += 1;
}
Ok(())
Expand Down Expand Up @@ -3352,6 +3395,9 @@ impl Em {
"v_ceil_f32" => fr(format!("ceil({})", fs(0))),
"v_rndne_f32" => fr(format!("round({})", fs(0))),
"v_frexp_mant_f32" => fr(format!("frexp_mant({})", fs(0))),
"v_frexp_exp_i32_f32" if self.track_frexp_denorm => {
format!("(uint)frexp_exp_f32({a}, {}, xcl_frexp_f32_denorm)", fs(0))
}
"v_frexp_exp_i32_f32" => format!("(uint)frexp_exp({})", fs(0)),
"v_ldexp_f32" => fr(format!("ldexp_f({}, (int){b})", fs(0))),
"v_add_f32" => fr(format!("{} + {}", fs(0), fs(1))),
Expand Down Expand Up @@ -4279,6 +4325,9 @@ impl Em {
if self.dynamic_f16_rm {
h.push_str("static uint xcl_fp16_rm = 0u;\n");
}
if self.track_frexp_denorm {
h.push_str("static uint xcl_frexp_f32_denorm = 0u;\n");
}
let mut sg: BTreeSet<u64> = self.sgprs.clone();
sg.extend([106, 107, 124, 126, 127]);
let load_sgprs = |h: &mut String| {
Expand Down Expand Up @@ -5735,6 +5784,16 @@ uint cvt_norm_i16_f32(float f) {
}
float frexp_mant(float x) { float e; return (isinf(x) || isnan(x)) ? x : frexp(x, e); }
int frexp_exp(float x) { float e; frexp(x, e); return (isinf(x) || isnan(x)) ? 0 : (int)e; }
int frexp_exp_f32(uint bits, float legacy_src, uint denorm) {
// 0: initial MODE unknown, 1: flush input, 2: preserve input.
if (denorm == 0u) return frexp_exp(legacy_src);
uint exp = (bits >> 23u) & 0xFFu;
if (exp == 0xFFu) return 0;
if (exp != 0u) return (int)exp - 126;
uint fraction = bits & 0x7FFFFFu;
if (fraction == 0u || denorm == 1u) return 0;
return (int)firstbithigh(fraction) - 148;
}
// Exact f32 x * 2^n on the IEEE-754 bits: handles |n| >= 127, ±0, ±inf, NaN, and subnormals
// without exp2() overflow/underflow or FTZ flushing.
float ldexp_f(float x, int n) {
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/recomp/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ struct Lower<'a, I: Ir> {
/// per IR block: not every lane that reached one of the program's lane branches gets here
/// before they meet again (a loop that lanes leave one by one, an arm some lanes skip)
partial: Vec<bool>,
track_frexp_denorm: bool,
/// stale-value ownership for blocks split by a coalesced run: backbone blocks of console
/// block b (`blk(b)` and its continuations) share `blk(b)` for both defs and uses, while a
/// run's inner block keeps its own `def_owner` (any def there is partial to outside reads)
Expand Down Expand Up @@ -1228,6 +1229,7 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
bit_uses: Vec::new(),
lane: None,
partial,
track_frexp_denorm: super::emit::tracks_frexp_f32_denorm(insts),
def_owner,
use_owner,
unguarded: false,
Expand Down Expand Up @@ -1587,6 +1589,9 @@ impl<I: Ir> Lower<'_, I> {
if name == "S_BARRIER" && self.partial[b] {
return Err("a barrier where some lanes are elsewhere".into());
}
if self.track_frexp_denorm && self.partial[b] && super::emit::writes_frexp_f32_denorm(d) {
return Err("a FREXP denormal mode write where some lanes are elsewhere".into());
}
// instructions whose #1426 semantics are known to differ from the HLSL path and the
// console (each reported on #1426): left to the fallback until fixed there
const DIFFERS_ON_1426: &[&str] = &[
Expand Down
30 changes: 30 additions & 0 deletions crates/xcl/src/gpu/recomp/lower_dxil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,36 @@ mod tests {
}
}

#[test]
fn gpu_frexp_exp_f32_denorm_per_lane() {
const PRESERVE: I = ("S_DENORM_MODE", "ENC_SOPP", &[("SIMM16", 13)]);
const FREXP: I = ("V_FREXP_EXP_I32_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V)]);
let partial = decode(&[
("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]),
("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]),
("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]),
PRESERVE,
("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]),
FREXP,
ENDPGM,
]);
let err = super::kernel(&partial, false).unwrap_err();
assert!(err.contains("FREXP denormal mode write where some lanes are elsewhere"), "{err}");

if !gpu() {
return;
}
let (dxil, _) = super::kernel(&decode(&[PRESERVE, FREXP, ENDPGM]), false).unwrap();
let mut state = runner::KernelState::default();
for v in &mut state.vgpr {
v[0] = 1;
}
let result = runner::run(&dxil, &state, &[]).unwrap();
for (lane, v) in result.vgpr.iter().take(32).enumerate() {
assert_eq!(v[4] as i32, -148, "lane {lane}");
}
}

/// An instruction lowered by #1426 that writes to `Lw`'s entry block after the program's
/// blocks are written (scratch) gives a container, and runs.
#[test]
Expand Down
Loading
Loading