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

            Bug ID: 129027
           Summary: [14/15/16/17 Regression] wrong code at -O1 and above:
                    SLSR builds a MEM_REF whose base points before the
                    object
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: alias, wrong-code
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: hhhuang at smu dot edu.sg
  Target Milestone: ---

Compiler Explorer: https://godbolt.org/z/q5hKq53TP

Note:
- works: 4.8.5, 4.9.3
- fails: 5.1 and later, including 16.2 and trunk
- -fno-tree-slsr makes it disappear
- x86_64 and aarch64
- not the SLSR integer-overflow bugs fixed by r16-7000 / r16-7003 (PR 106883,
PR 121347); this is the CAND_REF path

$ gcc-17 -v
Using built-in specs.
COLLECT_GCC=gcc-17
Target: x86_64-pc-linux-gnu
Configured with: ../gcc-17-20261122/configure --prefix=/w/out/gcc-trunk
--program-suffix=-17 --enable-languages=c --disable-bootstrap
--disable-multilib --disable-nls --disable-libsanitizer --enable-multiarch
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 17.0.0 20261122 (experimental) (GCC)
$ gcc-17 -O1 t.c && ./a.out
Aborted (core dumped)
$ gcc-17 -O1 -fno-tree-slsr t.c && ./a.out
$ gcc-17 -O0 t.c && ./a.out
$ cat t.c
struct S { unsigned short a[8]; } g;

__attribute__((noipa)) int
f (struct S *q, long i)
{
  g.a[0] = 1;
  q->a[i + 1] += q->a[i + 2];
  return g.a[0];
}

int
main (void)
{
  g.a[1] = 1;
  if (f (&g, -1) != 2)
    __builtin_abort ();
  return 0;
}

With q == &g and i == -1 the subscripts are 0 and 1, so f only accesses g.a[0]
and g.a[1] and must return 2; it returns 1. -Wall -Wextra gives no warnings,
-fno-strict-aliasing -fwrapv -fno-aggressive-loop-optimizations does not change
the result, and -fsanitize=address,undefined is clean (gcc 16.2).

SLSR rewrites q->a[i + 1] as MEM <short unsigned int> [(struct S *)_15 + 2B]
with _15 = q + i * 2, which points before g. indirect_ref_may_alias_decl_p
assumes a MEM_REF base never points before the object (only TARGET_MEM_REF is
exempt, PR 48702), so the store is taken not to alias g.a[0] and the final load
is folded to 1 (by DOM at -O1, by FRE at -O2).

Reply via email to