Bug 294692 - lib/msun: Replaced manual checks with isnan()
Summary: lib/msun: Replaced manual checks with isnan()
Status: Closed FIXED
Alias: None
Product: Base System
Classification: Unclassified
Component: standards (show other bugs)
Version: CURRENT
Hardware: Any Any
: --- Affects Only Me
Assignee: Robert Clausecker
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2026-04-21 18:19 UTC by Jesús Cipriano Blázquez Martínez
Modified: 2026-04-22 22:41 UTC (History)
3 users (show)

See Also:


Attachments
Differential for the commit (68.80 KB, patch)
2026-04-21 18:19 UTC, Jesús Cipriano Blázquez Martínez
no flags Details | Diff
New differential (69.23 KB, patch)
2026-04-22 17:57 UTC, Jesús Cipriano Blázquez Martínez
no flags Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description Jesús Cipriano Blázquez Martínez 2026-04-21 18:19:00 UTC
Created attachment 269983 [details]
Differential for the commit

This patch replaces the bitwise logic in the fmax, fmaximum, nextafter and nexttoward to look for NaNs with the generic isnan() macro.
Comment 1 Steve Kargl freebsd_committer freebsd_triage 2026-04-21 23:41:58 UTC
Jesus, this looks okay to me.  But, I do wonder about one issue
and have one suggestion.

Issue: All of the bitwise expressions that have been replaced
worked even if a user compiled libm with -ffast-math.  I
suspect the new changes will be optimized out.  I don't know
if we need to be paranoid about this or not; worse yet, I do 
not know how to warn users to be careful with compiler options.

Suggestion:  In the changed routines, we either assign parameters
to internal variables or directly access the bits before the
isnan() tests.  For example,

 double
 nextafter(double x, double y)
 {
 	volatile double t;
 	int32_t hx,hy,ix,iy;
 	u_int32_t lx,ly;
 
 	EXTRACT_WORDS(hx,lx,x);
 	EXTRACT_WORDS(hy,ly,y);
 	ix = hx&0x7fffffff;		/* |x| */
 	iy = hy&0x7fffffff;		/* |y| */
 
-	if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) ||   /* x is nan */
-	   ((iy>=0x7ff00000)&&((iy-0x7ff00000)|ly)!=0))     /* y is nan */
+	if(isnan(x) || isnan(y))     /* x or y is nan */
 	   return x+y;
 	if(x==y) return y;		/* x=y, return y */
 	if((ix|lx)==0) {			/* x == 0 */
 	    INSERT_WORDS(x,hy&0x80000000,1);	/* return +-minsubnormal */

You can move the isnan() test to before EXTRACT_WORDS() in the above
as well as the 'x == y' test.  That is, extract the bits when we need
them.
Comment 2 Mark Linimon freebsd_committer freebsd_triage 2026-04-22 01:46:59 UTC
^Triage: since Bugzilla has grown the ability to label attachments as Patch,
the [patch] convention is no longer necessary.
Comment 3 Robert Clausecker freebsd_committer freebsd_triage 2026-04-22 17:11:15 UTC
The change in nexttoward() looks dubious.

-	if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) ||
-	    (uy.bits.exp == 0x7fff &&
-	     ((uy.bits.manh&~LDBL_NBIT)|uy.bits.manl) != 0))
+	if(isnan(x) || isnan(y))

The former is not a NaN check on x and y.  It seems more complex than that.  Same for the float and long double versions.
Comment 4 Jesús Cipriano Blázquez Martínez 2026-04-22 17:23:43 UTC
(In reply to Robert Clausecker from comment #3)

I believe it is only NaN check, but since they have to extract the absolute value for the function anyway, they are using it to save a bit of performance at the cost of legibility. 

(ix>=0x7ff00000) is equal to ux.exp== 0x7ff and ((ix-0x7ff00000)|lx)!=0) is checking the mantissa isn't 0.

I do agree that maybe it is better to leave the checks in those functions as they were, or to do as Kargl said and move them before the EXTRACT_WORDS. I don't know what would be better.
Comment 5 Robert Clausecker freebsd_committer freebsd_triage 2026-04-22 17:25:47 UTC
(In reply to Jesús Cipriano Blázquez Martínez from comment #4)

Yes correct, for ix it's a NaN check.  But is it also for iy?  Does not look like it.
Comment 6 Steve Kargl freebsd_committer freebsd_triage 2026-04-22 17:29:23 UTC
(In reply to Robert Clausecker from comment #5)
I believe the check for NaN of a long double looks more
complicated because the bit twiddling needs to deal with
the 'hidden bit' for LD80, which is explicitly set in
the significand.
Comment 7 Jesús Cipriano Blázquez Martínez 2026-04-22 17:31:58 UTC
(In reply to Steve Kargl from comment #1)
Is it because isnan(x) can be expanded to x != x and it can be optimized away? If that's the case, shouldn't we reconsider how we define isnan(x)?
Comment 8 Steve Kargl freebsd_committer freebsd_triage 2026-04-22 17:36:38 UTC
Compare aarch64/_fpmath.h and amd64/_fpmath.h.  In the former you
have

#define LDBL_NBIT       0
#define LDBL_IMPLICIT_NBIT
#define mask_nbit_l(u)  ((void)0)

while the latter has

#define LDBL_NBIT       0x80000000
#define mask_nbit_l(u)  ((u).bits.manh &= ~LDBL_NBIT)

The complication is do to masking the hidden bit.
Comment 9 Robert Clausecker freebsd_committer freebsd_triage 2026-04-22 17:46:33 UTC
(In reply to Steve Kargl from comment #6)

I think the whole spiel about “what if somebody builds libm with -ffast-math?!” is not productive.  Do you suggest we should continue to generate really bad code in the default case, just to support building libm with -ffast-math, which isn't supported in any case right now?  I don't quite get how it is relevant what happens when these files are built with -ffast-math.  We don't build with -ffast-math, and that option is known to generate wrong code, so why should we care?

> I believe the check for NaN of a long double looks more
> complicated because the bit twiddling needs to deal with
> the 'hidden bit' for LD80, which is explicitly set in
> the significand.

Ok that makes sense, I didn't clue in on the two numbers having different types.

So overall LGTM from my side.

> Is it because isnan(x) can be expanded to x != x and it can be optimized away? If that's the case, shouldn't we reconsider how we define isnan(x)?

That definition is actually wrong these days I think as x != x triggers FE_INVALID on sNaN, which isnan(x) should not.  There is a compiler built-in we use for isnan(x), which does the right thing.  I think we should remove the inline definitions from math.h, as they do more harm than good.
Comment 10 Jesús Cipriano Blázquez Martínez 2026-04-22 17:57:47 UTC
Created attachment 270001 [details]
New differential

Now with the NaN checks before extracting parameters. I imagine it doesn't matter but also before type punning.
Comment 11 Steve Kargl freebsd_committer freebsd_triage 2026-04-22 18:03:45 UTC
(In reply to Robert Clausecker from comment #9)

In the face of -ffast-math, libm and its bit twiddling
gives the correct and expected result.  Changing to 
use compiler builtins may generate wrong results.
I suppose we can't control users shooting themselves
in the foot.  If the proposal to add a README.md 
to directories moves forward, then we can add the
warning their.
Comment 12 Robert Clausecker freebsd_committer freebsd_triage 2026-04-22 18:12:12 UTC
(In reply to Steve Kargl from comment #11)

-ffast-math is documented as (by gcc13):

     -ffast-math
         Sets the options -fno-math-errno, -funsafe-math-optimizations,
         -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans,
         -fcx-limited-range and -fexcess-precision=fast.

         This option causes the preprocessor macro "__FAST_MATH__" to be
         defined.

         This option is not turned on by any -O option besides -Ofast since it
         can result in incorrect output for programs that depend on an exact
         implementation of IEEE or ISO rules/specifications for math
         functions. It may, however, yield faster code for programs that do
         not require the guarantees of these specifications.

In particular, -ffinite-math-only is documented as:

     -ffinite-math-only
         Allow optimizations for floating-point arithmetic that assume that
         arguments and results are not NaNs or +-Infs.

         This option is not turned on by any -O option since it can result in
         incorrect output for programs that depend on an exact implementation
         of IEEE or ISO rules/specifications for math functions. It may,
         however, yield faster code for programs that do not require the
         guarantees of these specifications.

         The default is -fno-finite-math-only.

So anybody who expects correct outcomes with respect to NaN values in the face of -ffast-math is a fool.  I don't think we need to add documentation to point out explicitly that you'll shoot yourself in the foot if you compile with foot-shooting turned on and aim the compiler at your foot.
Comment 13 Steve Kargl freebsd_committer freebsd_triage 2026-04-22 20:28:28 UTC
Jesus, the new patch looks fine. Robert, does he need a final approval from you prior to committing?
Comment 14 Robert Clausecker freebsd_committer freebsd_triage 2026-04-22 22:32:07 UTC
(In reply to Steve Kargl from comment #13)

> Jesus, the new patch looks fine.

I agree, I'll go check the test suite and then try to land it.

> Robert, does he need a final approval from you prior to committing?

Jesús is not a committer.  I'll land it on his behalf.  Thank you for your review and assistance.
Comment 15 commit-hook freebsd_committer freebsd_triage 2026-04-22 22:40:44 UTC
A commit in branch main references this bug:

URL: https://cgit.FreeBSD.org/src/commit/?id=f6e1f27e9f005447e88a9b37df8a75751b1e0c3a

commit f6e1f27e9f005447e88a9b37df8a75751b1e0c3a
Author:     Jesús Blázquez <jesuscblazquez@gmail.com>
AuthorDate: 2026-04-21 15:23:20 +0000
Commit:     Robert Clausecker <fuz@FreeBSD.org>
CommitDate: 2026-04-22 22:39:51 +0000

    lib/msun: Replace manual checks with isnan() calls

    The maximum and minimum functions, as well as nextafter and nexttoward,
    were using manual NaN checks instead of the isnan() macro.

    PR:             294692
    Reviewed by:    fuz, kargl
    MFC after:      1 month

 lib/msun/src/s_fmax.c          |  4 ++--
 lib/msun/src/s_fmaxf.c         |  4 ++--
 lib/msun/src/s_fmaximum.c      |  3 +--
 lib/msun/src/s_fmaximum_mag.c  |  3 +--
 lib/msun/src/s_fmaximum_magf.c |  3 +--
 lib/msun/src/s_fmaximum_magl.c |  3 +--
 lib/msun/src/s_fmaximum_num.c  |  4 ++--
 lib/msun/src/s_fmaximum_numf.c |  4 ++--
 lib/msun/src/s_fmaximum_numl.c |  4 ++--
 lib/msun/src/s_fmaximumf.c     |  3 +--
 lib/msun/src/s_fmaximuml.c     |  3 +--
 lib/msun/src/s_fmaxl.c         |  4 ++--
 lib/msun/src/s_fmin.c          |  4 ++--
 lib/msun/src/s_fminf.c         |  4 ++--
 lib/msun/src/s_fminimum.c      |  3 +--
 lib/msun/src/s_fminimum_mag.c  |  3 +--
 lib/msun/src/s_fminimum_magf.c |  3 +--
 lib/msun/src/s_fminimum_magl.c |  3 +--
 lib/msun/src/s_fminimum_num.c  |  4 ++--
 lib/msun/src/s_fminimum_numf.c |  4 ++--
 lib/msun/src/s_fminimum_numl.c |  4 ++--
 lib/msun/src/s_fminimumf.c     |  3 +--
 lib/msun/src/s_fminimuml.c     |  3 +--
 lib/msun/src/s_fminl.c         |  4 ++--
 lib/msun/src/s_nextafter.c     |  8 ++++----
 lib/msun/src/s_nextafterf.c    |  8 ++++----
 lib/msun/src/s_nextafterl.c    | 10 ++++------
 lib/msun/src/s_nexttoward.c    |  9 ++++-----
 lib/msun/src/s_nexttowardf.c   |  9 ++++-----
 29 files changed, 56 insertions(+), 72 deletions(-)