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

            Bug ID: 129136
           Summary: [14/15/16/17 Regression] wrong code at -O2: store
                    through a flexible array member in a callee is lost
                    (modref/DSE), since r12-5236
           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: jeffchen006 at gmail dot com
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

int printf(const char *, ...);
void *malloc(unsigned long);
struct S { int n; int d[]; };
int x, k = 16;
void h(int *p) {
  int y = x;
  for (int i = 0; i < y; i++)
    y = y * i % 3 + y / 5;
  for (int i = 0; i < y; i++)
    y = y * i % 3 + y / 5;
  p[3] = 9 + y;
}
int main(void) {
  char *b = malloc(64);
  h(((struct S *)b)->d);
  printf("%d\n", ((struct S *)(b + k))->n);
  return 0;
}

$ gcc -O1 t.c && ./a.out
9
$ gcc -O2 t.c && ./a.out
0

-O3 too, and the same with g++ (extern "C" declarations). The two loops never
run (x is 0); they only keep h from being inlined.

h stores the int 9 at b + 4 + 12 = b + 16, and main reads that int back as the
member n of a struct S at b + 16, so the read must see 9. At -O2 the store is
gone and the read sees whatever malloc returned. -O3 -Wall even warns that the
value is used uninitialized.

-fno-tree-dse, -fno-ipa-modref, -fno-tree-pta or -fno-strict-aliasing all give
9. Bisected to r12-5236-g5aa91072e24 ("Implement DSE of dead functions calls
storing memory"); its parent prints 9 at -O2.

The modref summary of h is right (store at param offset 12, 4 bytes). But the
ref built for the call from the argument &MEM[(struct S *)b].d keeps the typed
base MEM[(struct S *)b], with offset 128 bits, outside the d member. The load
is MEM[(struct S *)_4].n with _4 = b + k, offset 0. indirect_refs_may_alias_p
then sees the same type on both sides and compares the base-relative ranges
[128,160) and [0,32), says no alias, and DSE removes the call. The real ranges
are the same 4 bytes.

The same wrong answer shows up in FRE with two _Complex int stores (fails since
13.1); that form can be attached if useful.

gcc version 17.0.0 20261128 (experimental), r17-6781-gd10e6c3818a,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release

Reply via email to