https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128903
Bug ID: 128903
Summary: wrong code at -O2: -~a rewritten to a + 1 in a
narrower type than the source computes it (tail
merging), introducing signed overflow
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: haoxintu at gmail dot com
Target Milestone: ---
Hi,
This appears to be a latent issue that has been present since GCC 11.
$cat repro.c
[[gnu::noipa]] __int128 f (int a, __int128 b)
{
return (b ? -(a ? ~a : 0) : -(unsigned __int128) ~(__int128) a) >> 65;
}
int main (void)
{
/* b == 0, so only the second arm is evaluated: ~(__int128) 0x7fffffff =
-2^31, as unsigned __int128 2^128 - 2^31,
negated 2^31; 2^31 >> 65 == 0. (The first arm, which would overflow for
this a, is not evaluated.) */
if (f (0x7fffffff, 0) != 0)
__builtin_abort ();
return 0;
}
$ gcc -O2 repro.c && ./a.out # also -O3, -Os; -O0 / -O1 fine
Aborted
With b == 0 only the second arm is evaluated: -(unsigned __int128) ~(__int128)
a == (unsigned __int128) a + 1, computed in 128 bits, i.e. 2^31 for a =
INT_MAX, and 2^31 >> 65 == 0. The first arm, -(a ? ~a : 0), is computed in int
and would overflow for this a, but it is not evaluated, so the program has no
undefined behaviour.
Optimized GIMPLE (-O2): both arms are merged into one block that computes the
addition in int:
```
<bb 4>:
_1 = a_9(D) + 1;
_2 = (__int128 unsigned) _1;
_3 = _2 >> 65;
```
For a = INT_MAX, a + 1 overflows (wraps to INT_MIN), the sign extension gives
2^128 - 2^31 and the result is
0x3fff... instead of 0. -O2 -fno-tree-tail-merge is correct. Presumably, value
numbering considers (unsigned __int128) (a + 1) equal to (unsigned __int128) a
+ 1 — valid only where the signed a + 1 is executed — and tail merging then
uses that equivalence for the arm where it is not.
## Checked Versions
- Wrong at -O2/-O3/-Os with gcc 11, 12, 13, 15.2, 16 and trunk;
- -O0/O1 with GCC and clang are correct.
Reproduced in Godbolt: https://godbolt.org/z/x4vWTad4q
Thanks.