]> git.ipfire.org Git - thirdparty/gcc.git/commit
[PATCH v2] RISC-V: fix __builtin_round NaN handling [PR target/121652]
authorAurelien Jarno <aurelien@aurel32.net>
Thu, 2 Oct 2025 15:05:34 +0000 (09:05 -0600)
committerJeff Law <jlaw@ventanamicro.com>
Thu, 2 Oct 2025 15:14:21 +0000 (09:14 -0600)
commit60c6f92fb192352d784ab3153a9e11c19a3216a0
treee30818cdb6d4783505154d174d81aee062106007
parentdf7525d352379b4179a5872b7779d2a55c51891b
[PATCH v2] RISC-V: fix __builtin_round NaN handling [PR target/121652]

__builtin_round() fails to correctly generate invalid exceptions for NaN
inputs when -ftrapping-math is used (which is the default). According to
the specification, an invalid exception should be raised for sNaN, but
not for qNaN.

Commit f12a27216952 ("RISC-V: fix __builtin_round clobbering FP...")
attempted to avoid raising an invalid exception for qNaN by saving and
restoring the FP exception flags. However this inadvertently suppressed
the invalid exception for sNaN as well.

Instead of saving/restoring fflags, this patch uses the same approach
than the well tested GLIBC round implementation. When flag_trapping_math
is enabled, it first checks whether the input is a NaN using feq.s/d. In
that case it adds the input value with itself to possibly convert sNaN
into qNaN. With this change, the glibc testsuite passes again.

The generated code with -ftrapping-math now looks like:

convert_float_to_float_round
  feq.s       a5,fa0,fa0
  beqz        a5,.L6
  auipc       a5,0x0
  flw         fa4,42(a5)
  fabs.s      fa5,fa0
  flt.s       a5,fa5,fa4
  beqz        a5,.L5
  fcvt.w.s    a5,fa0,rmm
  fcvt.s.w    fa5,a5
  fsgnj.s     fa0,fa5,fa0
  ret
.L6:
  fadd.s      fa0,fa0,fa0
.L5:
  ret

With -fno-trapping-math, the additional checks are omitted so the
resulting code is unchanged.

In addition this fixes the following failures:
FAIL: gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c -O3 -ftree-vectorize -mrvv-vector-bits=scalable  scan-assembler-times frflags\\s+[atx][0-9]+ 32
FAIL: gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c -O3 -ftree-vectorize -mrvv-vector-bits=scalable  scan-assembler-times fsflags\\s+[atx][0-9]+ 32

Fixes: f652a35877e3 ("This is almost exclusively Jivan's work....")
Fixes: f12a27216952 ("RISC-V: fix __builtin_round clobbering FP...")
PR target/121652

gcc/ChangeLog:

* config/riscv/riscv.md (round_pattern): special case NaN input
instead of saving/restoring fflags.

gcc/testsuite/ChangeLog:

* gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c: Adjust
scan pattern for fewer instances of frflags/fsrflags.
gcc/config/riscv/riscv.md
gcc/testsuite/gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c