The fix for 121534 causes another glibc test to fail: $ math/test-nearbyint-except PASS: float FAIL: float sNaN PASS: double FAIL: double sNaN PASS: long double PASS: long double sNaN The test that fails is /* But it mustn't lose exceptions from sNaN arguments. */ \ if (SNAN_TESTS (FLOAT)) \ { \ static volatile FLOAT snan = __builtin_nans ## SUFFIX (""); \ volatile FLOAT c __attribute__ ((unused)); \ feclearexcept (FE_ALL_EXCEPT); \ c = nearbyint ## SUFFIX (snan); \ if (fetestexcept (FE_INVALID) == FE_INVALID) \ puts ("PASS: " #FLOAT " sNaN"); \ else \ { \ puts ("FAIL: " #FLOAT " sNaN"); \ result = 1; \ } \ } \ It appears that gcc's round built-in is used in the place of nearbyint in the test. The test expects nearbyint to raise an exception for signaling NaN but previous fix(r16-3220-gf5696e9b1113b0a8e464cabb8cc26c871b1d9289) unconditionally saves and restores the fflags thus losing the FE_INVALID exception for sNaN input. That being said, I am not sure what's the expectation of round built-in. If it should always save/restore fflags, then the built-in should not be applied here. If not, we need a special case for signaling NaN.
Per previous Glibc discussion about nearbyint on x86: if frndint raises an "invalid" exception for a sNaN operand, that *should* be added into the restored environment. Thus we indeed should keep the exception here.
The easiest way would be a feq.[sd] with the operand as both inputs, and r0 as the output: "FEQ.S performs a quiet comparison: it only sets the invalid operation exception flag if either input is a signaling NaN."
Can you provide the exact flags used to build the test. Also will be handy the fragment of preprocessed test specifically around SNAN_TESTS. Thx.
Also I'm thinking to model this based on existing libc implementation which has been around for a while and should hopefully be correct. What glibc does is early check for nan and return x + x if so. See [1] This implicitly - doesn't restore flags for nan case (this PR/121652) - restores flag otherwise (retains fix for PR/121534) https://github.com/bminor/glibc/blob/master/sysdeps/riscv/rv64/rvd/s_round.c This requires the gcc builtin to call equivalent of __builtin_isnan(). However looks like there's a different problem lurking under the hood so let me run it by this group who care about these subtleties. Consider following test: -O2 -march=rv64gc -mabi=lp64d ` int myisnan(double __x) { return __builtin_isnan(__x); } ` generates ` myisnan: feq.d a0,fa0,fa0 xori a0,a0,1 ret ` FEQ.D is a quite comparison meaning it *can* set the invalid operation exception flag if either input is a signaling NaN. For the purpose of this PR I can implement isnan using fclass insn, but the general question stands (I'll open a seperate PR for that, since its an independent issue of its own).
My recollection is that Annex F leaves signaling NaN behavior implementation-defined, and so setting the invalid flag on signaling NaN is permitted but not required. For __builtin_isnan, I see that the ARMv8 and x86 backends use instructions that set the invalid flag on signaling NaNs, so it's probably best that we do the same. Furthermore, it's more efficient to use feq than fclass, because when the result controls an if-statement, the xori can be omitted (whereas fclass still needs an andi or a constant load).
(In reply to Andrew Waterman from comment #5) > My recollection is that Annex F leaves signaling NaN behavior > implementation-defined, and so setting the invalid flag on signaling NaN is > permitted but not required. It is required by Glibc manual: -- Macro: int FE_SNANS_ALWAYS_SIGNAL This macro, defined by TS 18661-1:2014, is defined to ‘1’ in ‘fenv.h’ to indicate that functions and operations with signaling NaN inputs and floating-point results always raise the invalid exception and return a quiet NaN, even in cases (such as ‘fmax’, ‘hypot’ and ‘pow’) where a quiet NaN input can produce a non-NaN result. Because some compiler optimizations may not handle signaling NaNs correctly, this macro is only defined if compiler support for signaling NaNs is enabled. That support can be enabled with the GCC option ‘-fsignaling-nans’. Thus the RISC-V implementation needs to raise it unless you announce -fsignaling-nans completely unsupported on RISC-V.
Ah, thanks. Regardless, it seems the `feq` scheme is the preferable one.
Created attachment 62200 [details] Preprocessed source code of test-nearbyint-except
(In reply to Vineet Gupta from comment #3) > Can you provide the exact flags used to build the test. Also will be handy > the fragment of preprocessed test specifically around SNAN_TESTS. Thx. The exact commands used are: (extracted from build logs) gcc test-nearbyint-except.c -c -std=gnu11 -fgnu89-inline -march=rv64gc -mabi=lp64d -O2 -pipe -Wformat -Wformat-security -fstack-clash-protection -g -ffile-prefix-map=/build/glibc/src=/usr/src/debug/glibc -Wall -Wwrite-strings -Wundef -Wimplicit-fallthrough -fmerge-all-constants -frounding-math -fstack-protector-strong -fno-common -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 -Wstrict-prototypes -Wold-style-definition -Wfree-labels -Wmissing-parameter-name -fmath-errno -fno-omit-frame-pointer -fPIE -I../include -I/build/glibc/src/glibc-build/math -I/build/glibc/src/glibc-build -I../sysdeps/unix/sysv/linux/riscv/rv64 -I../sysdeps/unix/sysv/linux/riscv/include -I../sysdeps/unix/sysv/linux/riscv -I../sysdeps/riscv/nptl -I../sysdeps/unix/sysv/linux/wordsize-64 -I../sysdeps/unix/sysv/linux/riscv/multiarch -I../sysdeps/unix/sysv/linux/include -I../sysdeps/unix/sysv/linux -I../sysdeps/nptl -I../sysdeps/pthread -I../sysdeps/gnu -I../sysdeps/unix/inet -I../sysdeps/unix/sysv -I../sysdeps/unix -I../sysdeps/posix -I../sysdeps/riscv/rv64/rvd -I../sysdeps/riscv/rv64/rvf -I../sysdeps/riscv/rvf -I../sysdeps/riscv/rvd -I../sysdeps/riscv/rv64 -I../sysdeps/riscv/multiarch -I../sysdeps/riscv -I../sysdeps/ieee754/ldbl-128 -I../sysdeps/ieee754/dbl-64 -I../sysdeps/ieee754/flt-32 -I../sysdeps/wordsize-64 -I../sysdeps/ieee754 -I../sysdeps/generic -I.. -I../libio -I. -nostdinc -isystem /usr/lib/gcc/riscv64-unknown-linux-gnu/15.1.1/include -isystem /usr/lib/gcc/riscv64-unknown-linux-gnu/15.1.1/include-fixed -isystem /usr/include -D_LIBC_REENTRANT -include /build/glibc/src/glibc-build/libc-modules.h -DMODULE_NAME=testsuite -include ../include/libc-symbols.h -DPIC -DTOP_NAMESPACE=glibc -o /build/glibc/src/glibc-build/math/test-nearbyint-except.o -MD -MP -MF /build/glibc/src/glibc-build/math/test-nearbyint-except.o.dt -MT /build/glibc/src/glibc-build/math/test-nearbyint-except.o gcc -o /build/glibc/src/glibc-build/math/test-nearbyint-except -pie -Wl,-O1 -nostdlib -nostartfiles -Wl,-O1 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,-z,relro /build/glibc/src/glibc-build/csu/Scrt1.o /build/glibc /src/glibc-build/csu/crti.o `gcc --print-file-name=crtbeginS.o` /build/glibc/src/glibc-build/math/test-nearbyint-except.o /build/glibc/src/glibc-build/support/libsupport_nonshared.a /build/glibc/src/glibc-build/math/libm.so.6 -Wl,-dynamic-linker=/usr/lib/ld-linux-riscv64-lp64d.so.1 -Wl,-rpath-link=/build/glibc/src/glibc-build:/build/glibc/src/glibc-build/math:/build/glibc/src/glibc-build/elf:/build/glibc/src/glibc-build/dlfcn:/build/glibc/src/glibc-build/nss:/build/ glibc/src/glibc-build/nis:/build/glibc/src/glibc-build/rt:/build/glibc/src/glibc-build/resolv:/build/glibc/src/glibc-build/mathvec:/build/glibc/src/glibc-build/support:/build/glibc/src/glibc-build/misc:/build/glibc/src/glibc-build/debug :/build/glibc/src/glibc-build/nptl:/lib/ -lgcc -Wl,--as-needed -lgcc_s -Wl,--no-as-needed /build/glibc/src/glibc-build/libc.so.6 /build/glibc/src/glibc-build/libc_nonshared.a -Wl,--as-needed /build/glibc/src/glibc-build/elf/ld.so -Wl,- -no-as-needed -lgcc -Wl,--as-needed -lgcc_s -Wl,--no-as-needed `gcc --print-file-name=crtendS.o` /build/glibc/src/glibc-build/csu/crtn.o Here are the flags for building preprocessed source gcc test-nearbyint-except.i -c -std=gnu11 -fgnu89-inline -march=rv64gc -mabi=lp64d -O2 -pipe -Wformat -Wformat-security -fstack-clash-protection -g -ffile-prefix-map=/build/glibc/src=/usr/src/debug/glibc -Wall -Wwrite-strings -Wundef -Wimplicit-fallthrough -fmerge-all-constants -frounding-math -fstack-protector-strong -fno-common -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 -Wstrict-prototypes -Wold-style-definition -Wfree-labels -Wmissing-parameter-name -fmath-errno -fno-omit-frame-pointer -fPIE
FE_SNANS_ALWAYS_SIGNAL is, as quoted, about operations *with floating-point results*. The classification macros are bound to IEEE operations that must not raise "invalid" for any inputs. isnan wrongly raising exceptions is bug 66462. (Comparison macros, however, unlike classification ones, should raise "invalid" for signaling NaNs.)
(In reply to Vineet Gupta from comment #4) > Also I'm thinking to model this based on existing libc implementation which > has been around for a while and should hopefully be correct. > > What glibc does is early check for nan and return x + x if so. See [1] > > This implicitly > - doesn't restore flags for nan case (this PR/121652) > - restores flag otherwise (retains fix for PR/121534) In addition the x+x addition converts a possible snan into a nan. > https://github.com/bminor/glibc/blob/master/sysdeps/riscv/rv64/rvd/s_round.c > > This requires the gcc builtin to call equivalent of __builtin_isnan(). > > However looks like there's a different problem lurking under the hood so let > me run it by this group who care about these subtleties. > > Consider following test: -O2 -march=rv64gc -mabi=lp64d > > ` > int myisnan(double __x) > { > return __builtin_isnan(__x); > } > ` > > generates > > ` > myisnan: > feq.d a0,fa0,fa0 > xori a0,a0,1 > ret > ` > > FEQ.D is a quite comparison meaning it *can* set the invalid operation > exception flag if either input is a signaling NaN. I think it is what we want no? In addition this is what is currently used by the GLIBC code. At the end it seems the GLIBC round code is correct and widely tested, so we just want to mimic it in the builtin.
(In reply to Aurelien Jarno from comment #11) > At the end it seems the GLIBC round code is correct and widely tested, so we > just want to mimic it in the builtin. The same way the comments in the GCC code mention saving and restoring flags due to the invalid flag. The reason why they are saved and restored in GLIBC is actually the inexact flag.
I am starting to wonder if it is really worth inlining so much code compared to a call to round(), and if it is not better to not try to handle NaN and fflags, requiring both !flag_trapping_math and flag_trapping_math. I even wonder if that wasn't the intent in the original code, just the condition was wrong and should have been: - && (TARGET_ZFA || flag_fp_int_builtin_inexact || !flag_trapping_math) + && (TARGET_ZFA || (flag_fp_int_builtin_inexact && !flag_trapping_math))
(In reply to Aurelien Jarno from comment #13) > I am starting to wonder if it is really worth inlining so much code compared > to a call to round(), and if it is not better to not try to handle NaN and > fflags, requiring both !flag_trapping_math and flag_trapping_math. I even > wonder if that wasn't the intent in the original code, just the condition > was wrong and should have been: > - && (TARGET_ZFA || flag_fp_int_builtin_inexact || !flag_trapping_math) > + && (TARGET_ZFA || (flag_fp_int_builtin_inexact && !flag_trapping_math)) It's not wrong: the GCC documentation clearly says: The default is -ffp-int-builtin-inexact, allowing the exception to be raised, unless C23 or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect. So if -fno-trapping-math, we should completely ignore flag_fp_int_builtin_exact. (Also the word above seems a little outdated as now GCC defaults to -std=gnu23.) If you'd make the expand only work for -fno-trapping-math you should just write TARGET_CFA || !flag_trapping_math instead.
(In reply to Xi Ruoyao from comment #14) > (In reply to Aurelien Jarno from comment #13) > > I am starting to wonder if it is really worth inlining so much code compared > > to a call to round(), and if it is not better to not try to handle NaN and > > fflags, requiring both !flag_trapping_math and flag_trapping_math. I even > > wonder if that wasn't the intent in the original code, just the condition > > was wrong and should have been: > > - && (TARGET_ZFA || flag_fp_int_builtin_inexact || !flag_trapping_math) > > + && (TARGET_ZFA || (flag_fp_int_builtin_inexact && !flag_trapping_math)) > > It's not wrong: the GCC documentation clearly says: > > The default is -ffp-int-builtin-inexact, allowing the exception to > be raised, unless C23 or a later C standard is selected. This > option does nothing unless -ftrapping-math is in effect. > > So if -fno-trapping-math, we should completely ignore > flag_fp_int_builtin_exact. > > (Also the word above seems a little outdated as now GCC defaults to > -std=gnu23.) > > If you'd make the expand only work for -fno-trapping-math you should just > write TARGET_CFA || !flag_trapping_math instead. Indeed you are correct that there is no need to check for the two. That said my comment still stands, I believe the original code was not intended to handle all cases and that the way to fix that is just to fix the condition as you proposed. Otherwise I find strange that flag_fp_int_builtin_inexact is mentioned in the condition while not having the corresponding code to handle that.
WRT c#13, yes, it's worth it, the performance gains were huge. Of course if we look out Zfa should become ubiquitious and that other path won't matter. But we're not at that point yet IMHO.
(In reply to Jeffrey A. Law from comment #16) > WRT c#13, yes, it's worth it, the performance gains were huge. Of course if > we look out Zfa should become ubiquitious and that other path won't matter. > But we're not at that point yet IMHO. Yep, but they were huge for the -ffast-math case used by SPEC2017. The code works fine for that case, and changing the condition of the pattern as suggested does not change the code generated with -ffast-math and thus the SPEC2017 performance. My point is do we want to inline the case that handles both inexact and NaN? I guess we are talking about going from 7 to 13 instructions.
Created attachment 62345 [details] Patch / Proof of concept In case we want to keep the condition unchanged, here is a patch to correctly handle the sNaN case. It checks for NaN using feq, and jump to a code adding the two arguments in case flag_trapping_math is active to convert the sNaN into a qNan. This is similar to what is done on the GLIVC side. This means there is no need to save and restore the fflags anymore, as this is allowed by -ffp-int-builtin-inexact. Note that it is my first changes in that area of GCC, and I am not fully sure I have done things correctly with the jumps, and especially with the emit_barrier() call. That's why it's maybe only a proof of concept. That said I have however checked and tested the generated code for various combinaison of -f(no-)fp-int-builtin-inexact and -f(no-)signaling-nans. I also checked that the GLIBC testsuite fully passes with this change.
(In reply to Aurelien Jarno from comment #18) > > > > However looks like there's a different problem lurking under the hood so let > > me run it by this group who care about these subtleties. > > > > Consider following test: -O2 -march=rv64gc -mabi=lp64d > > > > ` > > int myisnan(double __x) > > { > > return __builtin_isnan(__x); > > } > > ` > > > > generates > > > > ` > > myisnan: > > feq.d a0,fa0,fa0 > > xori a0,a0,1 > > ret > > ` > > > > FEQ.D is a quite comparison meaning it *can* set the invalid operation > > exception flag if either input is a signaling NaN. > > I think it is what we want no? In addition this is what is currently used by > the GLIBC code. Yeah I was just pointing a different/orthogonal potential existing issue. That current __builtin_isnan() can potentially raising an FP exception (Invalid op). This could be fine for its intended usage in round builtin, but not sure if that is fine as a general API / implementation agreement etc. > At the end it seems the GLIBC round code is correct and widely tested, so we > just want to mimic it in the builtin. Yes totally agree on that.
(In reply to Aurelien Jarno from comment #18) > Created attachment 62345 [details] > Patch / Proof of concept > > In case we want to keep the condition unchanged, here is a patch to > correctly handle the sNaN case. You mean the expander gate ? I don't see a strong argument to not change it if we can agree it is wrong. I still don't fully comprehend all the discussions above regarding this, but I won't mind changing that too (in addition to other changes u proposed). With review and enough testing I think that change should be fine too. > It checks for NaN using feq, and jump to a > code adding the two arguments in case flag_trapping_math is active to > convert the sNaN into a qNan. This is similar to what is done on the GLIVC > side. This means there is no need to save and restore the fflags anymore, as > this is allowed by -ffp-int-builtin-inexact. Cool. > Note that it is my first changes in that area of GCC, and I am not fully > sure I have done things correctly with the jumps, and especially with the > emit_barrier() call. That's why it's maybe only a proof of concept. I think its worthwhile to pos tit as RFC to the list. That way we get more eyes to stare at the patch especially with the expertise of Joseph and others proficient in the area. > That said I have however checked and tested the generated code for various > combinaison of -f(no-)fp-int-builtin-inexact and -f(no-)signaling-nans. I > also checked that the GLIBC testsuite fully passes with this change. Nice. You change for early Nan detection and removal of save/restore look sane to me.
(In reply to Vineet Gupta from comment #19) > Yeah I was just pointing a different/orthogonal potential existing issue. > That current __builtin_isnan() can potentially raising an FP exception > (Invalid op). This could be fine for its intended usage in round builtin, > but not sure if that is fine as a general API / implementation agreement etc. That is PR 66462.
I have posted a patch to the gcc-patches mailing-list: https://gcc.gnu.org/pipermail/gcc-patches/2025-September/696217.html
The master branch has been updated by Jeff Law <law@gcc.gnu.org>: https://gcc.gnu.org/g:60c6f92fb192352d784ab3153a9e11c19a3216a0 commit r16-4191-g60c6f92fb192352d784ab3153a9e11c19a3216a0 Author: Aurelien Jarno <aurelien@aurel32.net> Date: Thu Oct 2 09:05:34 2025 -0600 [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.
Update regression marker targets. Expecting to backport in a week or so before closing.
The releases/gcc-15 branch has been updated by Jeff Law <law@gcc.gnu.org>: https://gcc.gnu.org/g:ddf34234be385a4f2750e7da790ff9218067d881 commit r15-10399-gddf34234be385a4f2750e7da790ff9218067d881 Author: Aurelien Jarno <aurelien@aurel32.net> Date: Thu Oct 2 09:05:34 2025 -0600 [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. (cherry picked from commit 60c6f92fb192352d784ab3153a9e11c19a3216a0)
Cherry-picked to the gcc-15 branch. Closing as fixed.
(In reply to Jeffrey A. Law from comment #26) > Cherry-picked to the gcc-15 branch. Closing as fixed. Thanks Jeff!