https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51446

liu zhenyu <lzy20000419 at outlook dot com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |lzy20000419 at outlook dot com

--- Comment #23 from liu zhenyu <lzy20000419 at outlook dot com> ---
Another case, without -ffast-math or -fno-trapping-math. At -Os a literal
__builtin_nan ("") comes out as -NaN, because a register that holds a computed
-NaN is reused for it:

    #include <stdio.h>
    #include <string.h>
    __attribute__((noipa)) void pd (double d)
    { unsigned long long u; memcpy (&u, &d, 8); printf (" %016llx", u); }
    double g;
    int main ()
    {
      for (int i = 0; i < 1; i++)
        pd (g ? -1.0 : g);
      double t;
      for (int i = 0; i < 1; i++)
        t = __builtin_nan ("");
      double b = -t;
      double v = b > 0.0 ? 1.0 : b;
      pd (-1.0 - v);
      pd (0);
      pd (__builtin_nan (""));   /* expect 7ff8000000000000 */
      printf ("\n");
      return 0;
    }

    $ gcc -Os t.c && ./a.out
     0000000000000000 fff8000000000000 0000000000000000 fff8000000000000
    $ gcc -O0 t.c && ./a.out
     0000000000000000 fff8000000000000 0000000000000000 7ff8000000000000

x86_64 at -Os: 7.5, 13.4, 14.4, 15.3, 16.2 and trunk (17.0.0 20261126) print
fff8000000000000 as the last value; 8.5, 9.5, 10.5, 11.5 and 12.5 print
7ff8000000000000 (probably just not triggered). On trunk -O0, -O1, -O2, -Os
-fdisable-rtl-cse1 and -Os -fno-trapping-math all print 7ff8000000000000.

In the cse1 dump, the subtraction -1.0 - v (v is -NaN at run time) gets a
REG_EQUAL note of +QNaN. do_add in real.cc gives the NaN result the sign
a->sign ^ subtract_p, which is + here, while subsd returns the NaN operand,
-NaN:

    (insn 27 26 28 5 (set (reg:DF 106 [ _2 ])
            (minus:DF (reg:DF 107)
                (reg/v:DF 101 [ v ]))) {*fop_df_1}
         (expr_list:REG_EQUAL (const_double:DF +QNaN [+QNaN])

At -Os the subsd stays (it is cheaper than a constant pool load), but CSE
records reg 106 as equivalent to +QNaN, and the later load of the literal NaN
becomes a copy of reg 106:

    (insn 33 32 34 5 (set (reg:DF 109)
            (reg:DF 106 [ _2 ]))
         (expr_list:REG_EQUAL (const_double:DF +QNaN [+QNaN])

So the one evaluation of the subtraction is treated as +NaN for one use and as
-NaN for another. That is the "wobbly value" case from comment 22, which is not
allowed even though the sign of the NaN result itself is unspecified. Perhaps
CSE should not record a folded NaN constant as equivalent to a register that is
computed at run time when NaNs are honored.

Godbolt (trunk -Os and -O0, with execution): https://godbolt.org/z/szeeqW57b

Disclaimer: This test case was found with LLM-assisted targeted testing, and
the comment was written with LLM assistance.

Reply via email to