| Issue |
241285
|
| Summary |
[MachineSink] Load from a dynamic alloca is sunk past stackrestore (miscompile at -O3)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
jeffchen006
|
In a loop with a VLA, MachineSink moves a load from the VLA of iteration 1 past the `$rsp = COPY` (stackrestore) and past the allocation and fill of the next VLA at the same address. The load then reads the new data.
**Reproducer** (`repro.c`)
```c
/* Two loop iterations, n = 65520 and n = 65528. Each makes a new VLA v filled with n
and adds v[n] to sum. Correct output: 131048 (= 65520 + 65528) */
int printf(const char *, ...);
int zero;
long b;
char c;
int main(void) {
long sum = 0;
unsigned short end = zero, n = zero - 16;
for (; n != end; n += 8) {
int v[n + 1];
for (int i = 0; i <= n; i++)
v[i] = n;
sum += b % (c | 1); /* always 0; the division adds a branch */
sum += v[n];
}
printf("%ld\n", sum);
return 0;
}
```
**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 repro.c -o o0
$ ./o0
131048
$ clang -O3 repro.c -o o3
$ ./o3
131056
```
Expected (as `-O0`): `131048`. `-O3` prints `131056`.
**Why the expected output is right**
`f = (unsigned short)(0-16) = 65520` (defined conversion); 2 iterations; VLA size `f+1 > 0`; `g` is fully written before `g[f]` is read. UBSan/ASan/MSan at -O0 are clean.
**Potential Root cause**
`llvm/lib/CodeGen/MachineSink.cpp`: `SinkInstruction` asks `hasStoreBetween` for loads over a critical edge. `hasStoreBetween` treats only `isCall()` / `hasOrderedMemoryRef()` as barriers and asks `mayAlias` for other stores; AA says NoAlias for two distinct IR allocas. The `$rsp = COPY` that ends the dynamic alloca is not a store, so neither `hasStoreBetween` nor the in-block `SawStore` scan sees it. Two dynamic allocas can share memory once a stackrestore is between them.
**Possible Proposed fix**
Treat an instruction that writes the stack pointer as a store barrier for loads:
- `hasStoreBetween`: `if (I.isCall() || I.hasOrderedMemoryRef() || I.modifiesRegister(SPReg, TRI)) return true;` (`SPReg = TLI->getStackPointerRegisterToSaveRestore()`).
- In-block scan: set `SawStore = true` when a later instruction defines SPReg.
(Optionally only when `MFI.hasVarSizedObjects()`.) `-mllvm -machine-sink-load-blocks-threshold=0` and `-mllvm -disable-machine-sink` give the right output.
Related: #47943 and #39465 (MemCpyOpt moves an access to a dead VLA past stackrestore) and #39711 (InstCombine). Those are IR passes; this one is the MIR pass MachineSink, which needs its own fix.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs