| Issue |
241244
|
| Summary |
[SCCP] invalidate() resets calls that only pass the function address; result becomes undef (miscompile at -O3)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
jeffchen006
|
After function specialization, IPSCCP folds the result of `g(k)` to undef (`k` is only a data argument). Prints 0, not 3.
**Reproducer** (`repro.c`)
```c
/* g ignores its argument and returns 3, so the correct output is 3
(clang -O0, gcc). clang -O3 prints 0. k is never called. k has 128 copies
of S only so that it is large enough (>= 500 IR instructions) for the
function specializer, which clones k for the constant argument h. */
int printf(const char *, ...);
typedef unsigned (*fp_t)(unsigned);
unsigned w;
unsigned h(unsigned x) { return x * 3 + 1; }
#define S w = fp(w) ^ (w >> 3);
#define S8 S S S S S S S S
#define S64 S8 S8 S8 S8 S8 S8 S8 S8
unsigned k(fp_t fp) {
S64 S64
return k(h);
}
long g(unsigned (*p)(fp_t)) { return 3; }
int main(void) {
short f = (short)g(k);
printf("%d\n", f);
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
3
$ clang -O3 repro.c -o ./o3
$ ./o3
0
$ clang -O3 -mllvm -print-after=ipsccp -mllvm -filter-print-funcs=main repro.c -o ./x 2>&1 | grep trunc
%2 = trunc i64 undef to i16
```
Expected (as `-O0`, gcc -O0/-O2): `3`. `-O3` prints `0`. The last command shows the result of `g(k)` after IPSCCP.
**Why the expected output is right**
`k` is never called; `g` ignores its argument and returns 3, and `(short)3` is exact. The 128 copies of `S` in `k` only make `k` large enough for the function specializer. UBSan/ASan/MSan at -O0 are clean.
**Potential Root cause**
`llvm/lib/Transforms/Utils/SCCPSolver.cpp`, `SCCPInstVisitor::invalidate` (via `resetLatticeValueFor` from `FunctionSpecializer::run`): after it resets `TrackedRetVals[k]` it pushes every user of `k`, also `call @g(ptr @k)`. Nothing re-solves that call, so IPSCCP treats it as undef (`trunc i64 undef to i16`).
**Potential Proposed fix**
In `invalidate`, when `V` is a Function, follow only call sites that call it:
```diff
for (User *U : V->users())
- if (auto *UI = dyn_cast<Instruction>(U))
- ToInvalidate.push_back(UI);
+ if (auto *UI = dyn_cast<Instruction>(U)) {
+ if (isa<Function>(V)) {
+ auto *CB = dyn_cast<CallBase>(UI);
+ if (!CB || CB->getCalledOperand() != V)
+ continue;
+ }
+ ToInvalidate.push_back(UI);
+ }
```
declare i32 @printf(ptr, ...)
```
`opt -passes=ipsccp -force-specialization repro.ll` gives `%2 = trunc i64 undef to i16` in `@main`.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs