Issue 233447
Summary [GlobalOpt] Heap-to-global promotion gives two live allocations from repeated calls the same storage
Labels miscompilation, ipo, llvm:optimizations, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/dWbj3va8s

```llvm
@G = internal global ptr null
@fmt = constant [4 x i8] c"%d\0A\00"

declare ptr @malloc(i64) allockind("alloc,uninitialized") allocsize(0)
declare i32 @printf(ptr, ...)

define void @init() {
  %p = call ptr @malloc(i64 4)
  store ptr %p, ptr @G, align 8
  ret void
}

define i32 @main() {
  call void @init()
  %p = load ptr, ptr @G, align 8
  store i32 1, ptr %p, align 4
 call void @init()
  %q = load ptr, ptr @G, align 8
  store i32 2, ptr %q, align 4
  %v = load i32, ptr %p, align 4
  call i32 (ptr, ...) @printf(ptr @fmt, i32 %v)
  ret i32 0
}
```

```console
$ opt -S -passes=globalopt repro.ll
@G.body.0 = internal unnamed_addr global i32 undef, align 4
...
define i32 @main() local_unnamed_addr {
  call void @init()
  store i32 1, ptr @G.body.0, align 4
  call void @init()
  store i32 2, ptr @G.body.0, align 4
  %v = load i32, ptr @G.body.0, align 4
  %1 = call i32 (ptr, ...) @printf(ptr @fmt, i32 %v)
  ret i32 0
}

$ llubi repro.ll
1
$ opt -S -passes=globalopt repro.ll | llubi -
2
```

### suggested fix
The promotion (`optimizeOnceStoredGlobal` -> `tryToOptimizeStoreOfAllocationToGlobal`, GlobalOpt.cpp) requires that the allocation is the only value ever stored to `@G` (`GlobalStatus::StoredOnce`), but not that the allocation executes at most once; `OptimizeGlobalAddressOfAllocation` already notes it "may need to re-init the storage multiple times", yet maps every execution to one `.body` global.
Bail out unless the allocation runs at most once (e.g. not in a loop and its function is only reached once), or no value loaded from `@G` is used after a later store to it.

> Disclaimer: This test case was generated by a fuzzer, and the report was written with LLM assistance.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to