https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129300
Bug ID: 129300
Summary: wrong code at -O1 -ftrapv: SCEV/ivopts materialize the
IV step 2*g as a signed MULT in the preheader, which
traps although the program never computes it
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: 0599jiangyc at gmail dot com
Target Milestone: ---
The following code:
```c
#include <stdio.h>
long gs;
__attribute__((noipa)) void
f (long a, long g)
{
long h = 1;
for (;;)
{
long s = (h + a) - ~h; /* 2*h + a + 1, never overflows here */
gs = s;
if (h <= s)
break;
h += g;
}
}
int
main ()
{
/* iteration 1: h = 1, s = a + 3 < 1, h += g -> 2^62 + 1
iteration 2: s = 2^63 - 2^31 + 24, h <= s -> exit.
The step of s is 2*g = 2^63, which overflows but is never computed by the
program. */
f (-2147483627L, 0x4000000000000000L);
printf ("%lx\n", (unsigned long) gs);
return gs != 0x7fffffff80000018L;
}
```
Resulted in this output:
```
$ gcc -O0 -ftrapv repro.c && ./a.out
7fffffff80000018
$ gcc -O1 -ftrapv repro.c && ./a.out
Aborted (core dumped)
(also -O2/-O3 -ftrapv; -O0 -ftrapv, -O1 -ftrapv -fno-ivopts and -O2 without
-ftrapv exit 0)
```
Trunk: https://godbolt.org/z/dzh5xx9c1
- Trunk, GCC 15.1, 14.2, 13.2, 12.2 and 11.4 abort; not a regression.