Issue 244168
Summary [LoongArch] With F but not D, fptosi/fptoui float -> i64 is lowered with the 32-bit ftintrz.w.s, so results saturate at INT32_MIN/INT32_MAX
Labels miscompilation, backend:loongarch, floating-point, generated by fuzzer
Assignees
Reporter YuanchengJiang
    The following code:

```cpp
// LoongArch64 with single-float only (+f,-d / -mfpu=32): fptosi float -> i64 is done with ftintrz.w.s (32-bit)
// clang --target=loongarch64-linux-gnu -mabi=lp64f -mfpu=32 -O2 (Godbolt: loongarch64 clang trunk, asm only)
int printf(const char *, ...);
__attribute__((noinline)) long long f2ll(float x) { return (long long)x; }
__attribute__((noinline)) unsigned long long f2ull(float x) { return (unsigned long long)x; }
int main(void) {
 volatile float a = 3.0e9f, b = -1.0e10f, c = 1.0e19f;
  long long r1 = f2ll(a), r2 = f2ll(b); unsigned long long r3 = f2ull(c);
  printf("%lld %lld %llu\n", r1, r2, r3);
  int bad = r1 != 3000000000LL || r2 != -10000000000LL || r3 != 9999999980506447872ULL;
  printf(bad ? "MISCOMPILE\n" : "OK\n");
  return bad;
}
```

Resulted in this output (`clang --target=loongarch64-linux-gnu -mabi=lp64f -mfpu=32 -O2`, run under qemu-loongarch64 through a freestanding variant of this program, `repro_freestanding.c`, that prints the same values in hex; -O0 is the same):
```
f2ll(3e9)   = 000000007fffffff expected 00000000b2d05e00
f2ll(-1e10) = ffffffff80000000 expected fffffffdabf41c00
f2ull(1e19) = 800000007fffffff expected 8ac7230000000000
MISCOMPILE
```

| input | expected | `-mfpu=32` (+f,-d) |
|---|---|---|
| `(long long)3e9f` | 3000000000 | **2147483647** |
| `(long long)-1e10f` | -10000000000 | **-2147483648** |
| `(unsigned long long)1e19f` | 9999999980506447872 | **0x800000007fffffff** |

With `-mabi=lp64d` (D available) the output is correct.

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

Root cause: `LoongArchTargetLowering::lowerFP_TO_SINT` handles a result wider than 32 bits when F is available but D is not. It emits `LoongArchISD::FTINT` with an f32 result, which is selected as `ftintrz.w.s`, a 32-bit saturating conversion, and then sign-extends it with `MOVFR2GR_S_LA64`. Every float outside [-2^31, 2^31) therefore converts to INT32_MIN/INT32_MAX instead of its i64 value. The fptoui expansion, built from fptosi, inherits the error.

Suggested fix: without D there is no 64-bit FP register for `ftintrz.l.s`, so for i64 results use the libcall (`__fixsfdi`/`__fixunssfdi`) or a GPR sequence. Validated locally with `makeLibCall(RTLIB::getFPTOSINT/getFPTOUINT(...))` in that branch: both functions now call `__fixsfdi`, the AGT check no longer fires, and among 210 llc RUN lines of the LoongArch float tests the only output change is the `+f,-d` line of `ir-instruction/float-convert.ll`, whose CHECK lines encode the 32-bit conversion.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to