https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128851
Bug ID: 128851
Summary: Fail to hoist invariant table offset when using
variable index
Product: gcc
Version: 16.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: matmal01 at gcc dot gnu.org
Target Milestone: ---
In the below code, loop invariant motion fails to act on the invariant
table-offset part of the access in `p->S[1][x & 255]`. When the
table-offset is manually extracted then the hoist is performed.
It seems that the loop invariant motion pass has nothing to attempt to
identify this situation so it's currently at the mercy of what IR it gets
given. I don't know if this means that the way to catch these cases would
be by adding more cleverness to the LIM pass or performing more lowering at
an earlier pass.
With the source code of
struct tables
{
unsigned S[4][256];
};
unsigned
lookup (const struct tables *p, unsigned x, unsigned int n)
{
for (unsigned int j = 0; j < n; ++j)
{
#ifdef HOIST
const unsigned *s1 = p->S[1];
x = s1[x & 255];
#else
x = p->S[1][x & 255];
#endif
}
return x;
}
We see that without the source-level isolation of the invariant component &
array access the compiler fails to hoist that dereferencing out of the loop.
$ aarch64-none-linux-gnu-gcc -O2 -S -o - repro/repro.c
.arch armv8-a
.file "repro.c"
.text
.align 2
.p2align 5,,15
.global lookup
.type lookup, %function
lookup:
.LFB0:
.cfi_startproc
cbz w2, .L2
mov w3, 0
.p2align 5,,15
.L3:
and x1, x1, 255
add w3, w3, 1
add w1, w1, 256
ldr w1, [x0, x1, lsl 2]
cmp w2, w3
bne .L3
.L2:
mov w0, w1
ret
.cfi_endproc
.LFE0:
.size lookup, .-lookup
With the source-level isolation:
$ aarch64-none-linux-gnu-gcc -O2 -S -o - repro/repro.c -DHOIST
.arch armv8-a
.file "repro.c"
.text
.align 2
.p2align 5,,15
.global lookup
.type lookup, %function
lookup:
.LFB0:
.cfi_startproc
cbz w2, .L4
add x3, x0, 1024
mov w0, w1
mov w1, 0
.p2align 5,,15
.L3:
ubfiz x0, x0, 2, 8
add w1, w1, 1
ldr w0, [x3, x0]
cmp w2, w1
bne .L3
ret
.p2align 2,,3
.L4:
mov w0, w1
ret
.cfi_endproc
.LFE0:
.size lookup, .-lookup