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
114 changes: 114 additions & 0 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7177,6 +7177,117 @@ impl<'a> Lower<'a> {
Ok((r, enable))
}

/// Ceil or floor a binary64 value in its two 32-bit register words.
fn round_directed_f64(&mut self, inst: &Inst, guard: Option<V>, ceil: bool) -> Result<(), Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
};
if v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() {
return Err("binary64 rounding modifiers");
Comment on lines +7185 to +7186

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Clamped rounding blocks shader translation

round_directed_f64 rejects valid VOP3 ceiling and floor instructions with clamping or output scaling. Instruction lowering marks both result words missing, so translation fails when a store or export needs them.

Learn more

RDNA 2 VOP3 encodes output clamping and scaling on floating-point results, and the VALU decoder passes those fields to the emitter. LLVM's gfx1030 backend can fold a clamp of a double-precision floor result directly into v_floor_f64_e64 ... clamp. The rejection leaves both result words unavailable through instruction lowering. A buffer store that consumes the result then fails translation.

Example: With clamp active, flooring 2.75 and storing the result must store 1.0. The translator rejects the shader instead.

Recommended fix: Support CLAMP and OMOD on the rounded word pair, following RDNA 2's output modifier order and mode rules. Keep unsupported encodings separate from valid output modifiers. Add VOP3 tests for each modifier that consume both result words.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}
let Some(Operand::Vector { reg, .. }) = v.dst else {
return Err("a binary64 destination pair");
};
let dst_hi = reg
.checked_add(1)
.ok_or("a missing destination high word")?;
let source = *v.src.first().ok_or("a missing binary64 source")?;
let pair = |l: &mut Self, high: Reg| -> Result<(V, V), Why> {
let high = inst.read(high).ok_or("an unread high word")?;
Ok((l.operand(inst, &source)?, l.i32_of(high)?))
};
let (lo, mut hi) = match source {
Operand::Vector { reg, .. } => pair(
self,
Reg::V(reg.checked_add(1).ok_or("a missing high word")?),
)?,
Operand::Scalar { code, .. } if code != NULL => pair(
self,
Reg::S(code.checked_add(1).ok_or("a missing high word")?),
)?,
Operand::Literal(high) => (self.s.m.i32(0), self.s.m.i32(high)),
Operand::Const(code @ 240..=248) => {
let bits = if code == 248 {
0x3fc4_5f30_6dc9_c882 // Binary64 1/(2π).
} else {
let value = crate::resource::inline(code).ok_or("an unknown inline float")?;
f64::from(f32::from_bits(value)).to_bits()
};
(self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32))
}
_ => {
let high = if matches!(source, Operand::Const(193..=208)) {
u32::MAX
} else {
0
};
(self.operand(inst, &source)?, self.s.m.i32(high))
}
};
let c = self.cur;
let m = &mut self.s.m;
let i32t = self.s.t.i32;
let zero = m.i32(0);
let ones = m.i32(u32::MAX);
let sign_mask = m.i32(0x8000_0000);
let mag_mask = m.i32(0x7fff_ffff);
if v.abs & 1 != 0 {
hi = m.bin(c, Bin::And, hi, mag_mask);
}
if v.neg & 1 != 0 {
hi = m.bin(c, Bin::Xor, hi, sign_mask);
}
let sign = m.bin(c, Bin::And, hi, sign_mask);
let away = m.cmp(c, if ceil { pred::EQ } else { pred::NE }, sign, zero);

let mag_hi = m.bin(c, Bin::And, hi, mag_mask);
let k20 = m.i32(20);
let exponent = m.bin(c, Bin::LShr, mag_hi, k20);
let integral_exponent = m.i32(1023 + 52);
let integral = m.cmp(c, pred::IUGE, exponent, integral_exponent);
let n = m.bin(c, Bin::Sub, integral_exponent, exponent);
let (k31, k32) = (m.i32(31), m.i32(32));
let clears_low = m.cmp(c, pred::IUGE, n, k32);
let clears_high_bits = m.cmp(c, pred::IUGT, n, k32);
let shift = m.bin(c, Bin::And, n, k31);
let keep = m.bin(c, Bin::Shl, ones, shift);
let discard = m.bin(c, Bin::Xor, keep, ones);

// Add ones in the discarded bits when rounding away from zero.
// Then clearing those bits advances to the next integer only if
// the fraction was nonzero.
let low_bias = m.select(c, clears_low, ones, discard);
let low_bias = m.select(c, away, low_bias, zero);
let sum_lo = m.bin(c, Bin::Add, lo, low_bias);
let carry = m.cmp(c, pred::IULT, sum_lo, lo);
let carry = m.cast(c, Cast::ZExt, carry, i32t);
let high_increments = m.bin(c, Bin::And, away, clears_high_bits);
let high_bias = m.select(c, high_increments, discard, zero);
let sum_hi = m.bin(c, Bin::Add, hi, high_bias);
let sum_hi = m.bin(c, Bin::Add, sum_hi, carry);
let round_lo = m.bin(c, Bin::And, sum_lo, keep);
let round_lo = m.select(c, clears_low, zero, round_lo);
let round_hi = m.bin(c, Bin::And, sum_hi, keep);
let round_hi = m.select(c, clears_high_bits, round_hi, sum_hi);

// Below one, the result is signed zero or signed one.
let magnitude = m.bin(c, Bin::Or, mag_hi, lo);
let nonzero = m.cmp(c, pred::NE, magnitude, zero);
let to_one = m.bin(c, Bin::And, away, nonzero);
Comment on lines +7274 to +7276

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Flushed subnormals round to one

With double-precision input flushing enabled, round_directed_f64 still treats subnormal inputs as nonzero. Instruction lowering ignores s_denorm_mode, so positive ceiling and negative floor produce ±1 instead of signed zero.

Learn more

RDNA 2's double-precision denormal mode controls whether a subnormal input reaches an arithmetic instruction as its original value or as signed zero. The register analysis accepts s_denorm_mode, and instruction lowering treats it as a no-op. The rounding code always tests the original mantissa, so it rounds away from zero even when the guest mode has already flushed the input.

Example: After s_denorm_mode 0, ceiling the positive input with bits 0x0000000000000001 must return +0.0. The emitted shader returns +1.0.

Recommended fix: Use the effective guest double-precision input denormal mode at the rounding instruction. When it requests input flushing, treat an exponent-zero input as signed zero before testing for a nonzero fraction. Add coverage for both flush and preserve modes.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

let one_hi = m.i32(0x3ff0_0000);
let small_hi = m.select(c, to_one, one_hi, zero);
let small_hi = m.bin(c, Bin::Or, small_hi, sign);
let bias = m.i32(1023);
let below_one = m.cmp(c, pred::IULT, exponent, bias);
let round_hi = m.select(c, below_one, small_hi, round_hi);

let result_lo = m.select(c, integral, lo, round_lo);
let result_hi = m.select(c, integral, hi, round_hi);
Comment on lines +7284 to +7285

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Unverified signaling NaN behavior

round_directed_f64 returns signaling NaNs without quieting them. A native RDNA 2 comparison would establish whether ceiling and floor preserve those bits.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

self.write(inst, Reg::V(reg), result_lo, guard);
self.write(inst, Reg::V(dst_hi), result_hi, guard);
Ok(())
}

fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
Expand Down Expand Up @@ -7630,6 +7741,9 @@ impl<'a> Lower<'a> {
};
float(self, r)
}
"v_ceil_f64" | "v_floor_f64" => {
self.round_directed_f64(inst, guard, name == "v_ceil_f64")
}
"v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => {
let mut a = f(self, 0)?;
if name == "v_cvt_rpi_i32_f32" {
Expand Down
67 changes: 67 additions & 0 deletions crates/victory-shader/src/emit/valu_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,73 @@ fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() {
}
}

#[test]
fn directed_f64_ceil_and_floor_write_both_words() {
let values = [
0.0,
-0.0,
f64::from_bits(1),
f64::from_bits(0x8000_0000_0000_0001),
0.75,
-0.75,
1.0,
-1.0,
1.5,
-1.5,
// Fractional fields of 33, 32 and 31 bits.
524_288.0,
f64::from_bits(524_288.0f64.to_bits() + 1),
-524_288.75,
1_048_576.125,
-1_048_576.125,
2_097_152.625,
-2_097_152.625,
4_503_599_627_370_495.5,
-4_503_599_627_370_495.5,
4_503_599_627_370_496.0,
f64::MAX,
f64::INFINITY,
f64::NEG_INFINITY,
];
let inputs: Vec<_> = values
.iter()
.map(|value| {
let bits = value.to_bits();
[bits as u32, (bits >> 32) as u32, 0, 0]
})
.collect();
let operations = [(0x018, f64::ceil as fn(f64) -> f64), (0x01a, f64::floor)];
for (op, expected) in operations {
for source in [vgpr(1), sgpr(0)] {
for (word, shift) in [(6, 0), (7, 32)] {
let shader = build_valu_cs(&[vop1(op, 6, source), vop1(0x001, 0, vgpr(word))]);
Comment on lines +465 to +467

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Masked lanes lack rounding coverage

build_valu_cs uses one thread, and the test never masks that thread before rounding. It does not check that both destination words survive when EXEC disables a lane.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

run_cases(&shader, &inputs, |backend, case, _, got| {
let want = (expected(values[case]).to_bits() >> shift) as u32;
assert_eq!(
got, want,
"{backend}: op {op:#x}, source {source}, case {case}, v{word}"
);
});
}
}
}
}

#[test]
fn directed_f64_vop3_negated_literal_rounds_in_both_directions() {
for (opcode, expected) in [(0x19a, 0xc02c_0000), (0x198, 0xc02a_0000)] {
let [op, sources] = vop3(opcode, 6, 255, 0, 0);
let shader = build_valu_cs(&[op, sources | 1 << 29, 0x402b_0000, vop1(0x001, 0, vgpr(7))]);
let container = crate::Container::parse(&shader.dxil).unwrap();
let features = container.part(crate::FourCC::SFI0).unwrap();
let bits = u64::from_le_bytes(features.data.try_into().unwrap());
assert_eq!(bits & 0x8001, 0, "SFI0 doubles and int64 feature bits");
run_cases(&shader, &[[0; 4]], |backend, _, _, got| {
assert_eq!(got, expected, "{backend}: opcode {opcode:#x}, -13.5");
});
}
}

#[test]
fn v_med3_f32_matches_rdna2_with_nan() {
// v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157)
Expand Down
Loading