Issue 244167
Summary [Mips] MSA lowerFP_TO_FP16 converts f64 -> f16 through f32 (fexdo.w then fexdo.h), rounding twice
Labels backend:MIPS, miscompilation, floating-point, generated by fuzzer
Assignees
Reporter YuanchengJiang
    The following code:

```cpp
// MIPS MSA: (__fp16)double is computed as fexdo.w (f64 -> f32) then fexdo.h (f32 -> f16): two roundings.
// clang --target=mipsel-linux-gnu -march=mips32r5 -mmsa -mfp64 -O2 repro.c   (also mips64r5/r6 with -mmsa)
// Without -mmsa the conversion is the __truncdfhf2 libcall and is correct.
int printf(const char *, ...);
__attribute__((noinline)) unsigned short d2h(double x) {
  __fp16 h = (__fp16)x;
  unsigned short u;
  __builtin_memcpy(&u, &h, 2);
  return u;
}
int main(void) {
  volatile double in = 1.0 + 0x1p-11 + 0x1p-40; /* just above the midpoint of 1.0 and 1.0 + 2^-10 */
  unsigned short r = d2h(in);
  printf("(__fp16)(1 + 2^-11 + 2^-40) = 0x%04x, expected 0x3c01\n", r);
  printf(r == 0x3c01 ? "OK\n" : "MISCOMPILE\n");
 return r != 0x3c01;
}
```

Resulted in this output (`clang --target=mipsel-linux-gnu -march=mips32r5 -mmsa -mfp64 -O2`, run under `qemu-mipsel -cpu P5600` through an equivalent freestanding program, `repro_freestanding.c`):
```
(__fp16)(1 + 2^-11 + 2^-40) = 0x3c00 expected 0x3c01
MISCOMPILE
```

| input | correctly rounded `(__fp16)x` | MSA build |
|---|---|---|
| 1 + 2^-11 + 2^-40 (just above the midpoint of 1.0 and 1.0+2^-10) | 0x3c01 | **0x3c00** |

Wrong code: `splati.d; fexdo.w $w0,$w0,$w0; fexdo.h $w0,$w0,$w0`. Without `-mmsa`, the `__truncdfhf2` libcall is used and the result is correct.

Trunk: https://godbolt.org/z/eqbfddrj3

Root cause: `MipsSETargetLowering::lowerFP_TO_FP16` (added with the MSA f16 soft-promotion, #204158) converts an f64 source by splatting it to v2f64, narrowing it to f32 with `fexdo.w`, and then narrowing to f16 with `fexdo.h`. The intermediate rounding to f32 drops the sticky bits, so a value just above a half-precision rounding midpoint lands exactly on the midpoint and then rounds to even, the wrong neighbour.

Suggested fix: for f64 sources, use the `__truncdfhf2` libcall, which is the default expansion. Alternatively, round to f32 with round-to-odd before `fexdo.h`. Validated locally by returning an empty value for f64 sources so the default expansion runs: the libcall is emitted, the AGT check no longer fires, and among 137 llc RUN lines of the MIPS f16 tests the only output change is `fadd_f64` in `msa/f16-llvm-ir.ll`, which truncates a double to half.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to