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

            Bug ID: 129189
           Summary: [17 Regression] wrong code at -O1 and above on x86-64:
                    -copysign (x, -1.0) computed as x & sign-mask (returns
                    +-0 instead of |x|) since r17-6672
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: target
          Assignee: unassigned at gcc dot gnu.org
          Reporter: haoxintu at gmail dot com
  Target Milestone: ---

Hi,

$cat repro.c

[[gnu::noipa]] float f (float x)
{
  return -__builtin_copysignf (x, -1.0f);
}
int main (void)
{
  if (f (3.5f) != 3.5f)
    __builtin_abort ();
  return 0;
}

$ gcc-trunk -O0 repro.c && ./a.out ; echo $?     # 0
$ gcc-trunk -O1 repro.c && ./a.out ; echo $?     # Aborted, 134 (also -O2, -O3,
-Os)
```

Expected: `copysign (3.5f, -1.0f)` is -3.5f, so `f` returns 3.5f (it is `|x|`).
Actual: `f` returns +0.0. Trunk emits

```
f:
        andps   .LC0(%rip), %xmm0
        ret
.LC0:
        .long   -2147483648          # 0x80000000: the sign mask, not ~sign
mask
```

i.e. `x & 0x80000000` instead of `x & 0x7fffffff`. The double version
(`-copysign (x, -2.0)` from `<math.h>`) fails the same way (`andpd` with the
double sign mask). The original finding has `-copysignf (t, -0.0f)`: any
negative constant sign triggers it.


**Bisected to r17-6672** (79cc525f7f6, "i386: Change the sign of a float in
memory in place", 2026-11-25):
https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=79cc525f7f64ca2e1de25c6a9d225c4c6950fef8

| commit (C-only build, repro.c at -O2) | result |
|---|---|
| d1c239ad86e (parent of r17-6672) | ok |
| **79cc525f7f6 (r17-6672)** | **aborts** |

Its ChangeLog says "ix86_expand_copysign (...): Emit a negative constant sign
as NEG of ABS with a USE of the mask". Before that, copysign with a negative
constant was expanded as a plain IOR, which combine cannot merge like this.
-fdisable-rtl-combine alone does not help, because late_combine2 does the same
merge.

- gcc trunk c10b819941b (2026-11-30): -O1, -O2, -O3 and -Os abort; -O0 ok.
- gcc 16, gcc 15, gcc 13: ok at every level, so it's a regression in 17.
- clang trunk, clang 21: ok at every level.
- UB: none; gcc -O0, clang trunk/21 -O0, ASan+UBSan (gcc trunk and clang 21)
and MSan (clang 21) all exit 0.

Godbolt (gcc trunk, -O2 vs -O0, executed): https://godbolt.org/z/dGb5eEqb9

Thanks.

Reply via email to