https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129138
Bug ID: 129138
Summary: wrong code at -O3: loop interchange moves load of a[i]
past the reduction store a[i] = s (equal DR_REF pair
skipped in tree_loop_interchange_compute_ddrs)
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 *, ...);
int b[100][16], a[6];
int main(void)
{
for (int j = 0; j < 100; j++)
for (int i = 0; i < 6; i++)
b[j][i] = 1;
for (int i = 0; i < 6; i++) {
int s = 0, t = a[i];
for (int j = 0; j < 100; j++) {
int x = b[j][i];
s += ((x + t) & 7) * (x | 2) * (x | 4) * (x | 8);
}
a[i] = s;
}
printf("%d\n", a[0]);
return 0;
}
$ gcc -O2 t.c && ./a.out
13500
$ gcc -O3 t.c && ./a.out
135
Same with -O1 -floop-interchange and with g++; -O3 -fno-loop-interchange gives
13500. Bisected to r8-5164-gfbdec14e80e, the commit that added the pass (its
parent is fine).
tree_loop_interchange_compute_ddrs skips a pair of outer loop refs with equal
DR_REF without any dependence test. Here that pair is the load t = a[i] and the
store a[i] = s. After the interchange t = a[i] is in the inner loop, and
undo_simple_reduction stores a[i] = s in every iteration, so t reads the
partial sum: after j = 0, t is 135, (1 + 135) & 7 is 0, and all later terms are
0. The skip is only ok for the reduction's own load/store pair. The long
product is only there to get past the cost model.
A 3-deep nest goes wrong in a related way (same commit), maybe the same fix:
int printf(const char *, ...);
int b[100][16], a[6];
int main(void)
{
for (int j = 0; j < 100; j++)
for (int i = 0; i < 6; i++)
b[j][i] = 1;
for (int l = 0; l < 2; l++)
for (int i = 0; i < 6; i++) {
int s = 0;
for (int j = 0; j < 100; j++) {
int x = b[j][i];
s += x * (x | 2) * (x | 4);
}
a[i] = s;
}
printf("%d\n", a[0]);
return 0;
}
$ gcc -O2 t2.c && ./a.out
1500
$ gcc -O3 t2.c && ./a.out
2985
Here (i, j) is interchanged first, which turns a[i] into a memory reduction,
and then (l, j). The DDRs are computed once before the first pair, with the
same equal-ref skip, and update_data_info only permutes them, so the second
interchange never sees the a[i] dependence carried by l.
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