Issue 240162
Summary [mlir][bug][fuzzer-found] --affine-loop-fusion intermittently segfaults in getStoreOpCount on a freed affine.prefetch
Labels mlir
Assignees
Reporter Kiritobl
    

#### Version

git commit hash: 0fdfbb6f057f1a01a9bc6fc025c502471f106f23

LLVM/MLIR 24.0.0git, optimized build with assertions.

#### Bug Description

`--affine-loop-fusion` intermittently segfaults in `MemRefDependenceGraph::Node::getStoreOpCount` during sibling fusion. This is not a missing assertion: Valgrind reports a use-after-free. The `Operation` being read is an `affine.prefetch` that `replaceAllMemRefUsesWith` erased while `createPrivateMemRef` was privatizing its memref. A dangling pointer to that operation remains in the dependence-graph node's `memrefStores` list, because `clearNodeLoadAndStores` clears only `loads` and `stores`. `getStoreOpCount` later walks `concat(stores, memrefStores)` and calls `dyn_cast<AffineWriteOpInterface>` on every entry, including the stale one.

The trigger is unstable and depends on heap reuse, not on the input. Repeated 30-run samples of the two archived fuzzer inputs are not consistent: one sample produced 27/30 and 10/30 SIGSEGV, a later sample produced 29/30 and 12/30, and the remaining runs exited 0. One copy of the minimized function below exited 0 in 10/10 native runs, yet Valgrind reported the invalid read in every run. Repeating the same function five times raised the native SIGSEGV rate to 10/10. The use-after-free is present with a single copy; the extra copies only make it more likely that the freed block is reused before `getStoreOpCount` reads it.

The minimized input below parses and verifies successfully without the pass. It was reduced by hand to three top-level loops, one `affine.prefetch`, and two memrefs. Removing the `affine.prefetch` makes Valgrind clean. Because the process does not reliably fault, the reproducer section gives both a single-function Valgrind reproducer and a five-copy native reproducer.

The pass should not read operations that it has already erased. The input is verifier-accepted and should either be fused without crashing or be rejected conservatively.

#### Crash Chain & Root Cause

Crash chain:

```text
--affine-loop-fusion (greedy)
  → GreedyFusion::fuseProducerConsumerNodes → performFusionsIntoDest
  → createPrivateMemRef
  → replaceAllMemRefUsesWith(...)           // erases the old affine.prefetch
  ...
  → GreedyFusion::fuseSiblingNodes
  → GreedyFusion::fuseWithSiblingNodes
  → MemRefDependenceGraph::forEachMemRefInputEdge
  → findSiblingNodeToFuse(...)::{lambda(Edge)#3}
  → MemRefDependenceGraph::Node::getStoreOpCount   // reads the freed Operation
  → SIGSEGV
```

`LoopNestStateCollector::collect` (`Analysis/Utils.cpp:44-77`) records `affine.prefetch` in both `memrefLoads` and `memrefStores`: it implements `AffineMapAccessInterface` but not `MemoryEffectOpInterface`, so it takes the conservative branch at `:52-65`. `replaceAllMemRefUsesWith` (`Utils.cpp:1116-1310`) treats it as dereferencing and erases it at `:1306-1307`. After fusion, `performFusionsIntoDest` (`LoopFusion.cpp:1145-1150`) calls `clearNodeLoadAndStores` (`Analysis/Utils.cpp:808-812`), which clears only `loads` and `stores`, while `addToNode` (`:795-806`) appends all five lists. The erased prefetch therefore stays in `memrefStores`. Sibling fusion's `findSiblingNodeToFuse` (`LoopFusion.cpp:1437-1445`) then calls `getStoreOpCount` (`Analysis/Utils.cpp:94-107`), which dereferences every entry of `concat(stores, memrefStores)` and reads the freed `Operation`.

The freed block is 176 or 208 bytes and was allocated by the parser. Whether the read faults depends on whether the block has been reused or unmapped, which is why the same input sometimes exits 0. I could not find an existing report for a dangling non-affine operation list in the dependence graph.

#### Steps to Reproduce

```bash
mlir-opt reproducer.mlir --mlir-disable-threading \
  --pass-pipeline='builtin.module(func.func(affine-loop-fusion))' -o /dev/null
```

With the single-function reproducer below, native runs exited 0 in 10/10 runs on this build, so this command alone is not a reliable crash. The use-after-free is visible in every run under Valgrind:

```bash
valgrind --error-exitcode=99 -q --leak-check=no \
  mlir-opt reproducer.mlir --mlir-disable-threading \
  --pass-pipeline='builtin.module(func.func(affine-loop-fusion))' -o /dev/null
# Invalid read of size 8 in getStoreOpCount
```

Valgrind reports four invalid reads in one process run. To obtain a native crash, `reproducer_native.mlir` repeats the same function five times with different names; the extra copies make the freed block more likely to be reused:

```bash
mlir-opt reproducer_native.mlir --mlir-disable-threading \
  --pass-pipeline='builtin.module(func.func(affine-loop-fusion))' -o /dev/null
# SIGSEGV (shell exit status 139)
```

The process terminated with SIGSEGV in 10/10 runs with the five-copy input. The two archived fuzzer inputs behind this report show the same instability: in two separate 30-run samples they produced 27/30 and 10/30, then 29/30 and 12/30 SIGSEGV, exiting 0 in the remaining runs. A native run of an archived input also occasionally hangs instead of faulting, which is consistent with heap corruption rather than a deterministic bad path.

#### Reproducer (`reproducer.mlir`)

```mlir
func.func @f(%v: f32) {
  %a = memref.alloc() : memref<2xf32>
  %b = memref.alloc() : memref<1x2xf32>
  affine.for %i = 0 to 2 {
    affine.store %v, %a[%i] : memref<2xf32>
  }
  affine.for %j = 0 to 2 {
    affine.prefetch %a[%j], write, locality<0>, data : memref<2xf32>
    %x = affine.load %a[%j] : memref<2xf32>
    affine.store %x, %b[0, %j] : memref<1x2xf32>
  }
  affine.for %k = 0 to 2 {
    affine.for %l = 0 to 2 {
      %y = affine.load %b[0, %l] : memref<1x2xf32>
    }
  }
  return
}
```

The first loop writes `%a`; the second consumes and prefetches `%a` and writes `%b`; the third reads `%b`. Producer-consumer fusion privatizes `%a`, erasing the prefetch, and the third loop remains a sibling node whose input edge queries the fused node with `getStoreOpCount`. No `affine.parallel`, `scf`, or vector ops are needed, and a `read` prefetch also triggers it.

<details>
<summary>Native reproducer (`reproducer_native.mlir`, five copies)</summary>

```mlir
module {
  func.func @f0(%v: f32) {
    %a = memref.alloc() : memref<2xf32>
    %b = memref.alloc() : memref<1x2xf32>
    affine.for %i = 0 to 2 { affine.store %v, %a[%i] : memref<2xf32> }
    affine.for %j = 0 to 2 {
      affine.prefetch %a[%j], write, locality<0>, data : memref<2xf32>
      %x = affine.load %a[%j] : memref<2xf32>
      affine.store %x, %b[0, %j] : memref<1x2xf32>
    }
    affine.for %k = 0 to 2 { affine.for %l = 0 to 2 { %y = affine.load %b[0, %l] : memref<1x2xf32> } }
    return
  }
  func.func @f1(%v: f32) {
    %a = memref.alloc() : memref<2xf32>
    %b = memref.alloc() : memref<1x2xf32>
    affine.for %i = 0 to 2 { affine.store %v, %a[%i] : memref<2xf32> }
    affine.for %j = 0 to 2 {
      affine.prefetch %a[%j], write, locality<0>, data : memref<2xf32>
      %x = affine.load %a[%j] : memref<2xf32>
      affine.store %x, %b[0, %j] : memref<1x2xf32>
    }
    affine.for %k = 0 to 2 { affine.for %l = 0 to 2 { %y = affine.load %b[0, %l] : memref<1x2xf32> } }
    return
  }
  func.func @f2(%v: f32) {
    %a = memref.alloc() : memref<2xf32>
    %b = memref.alloc() : memref<1x2xf32>
    affine.for %i = 0 to 2 { affine.store %v, %a[%i] : memref<2xf32> }
    affine.for %j = 0 to 2 {
      affine.prefetch %a[%j], write, locality<0>, data : memref<2xf32>
      %x = affine.load %a[%j] : memref<2xf32>
      affine.store %x, %b[0, %j] : memref<1x2xf32>
    }
    affine.for %k = 0 to 2 { affine.for %l = 0 to 2 { %y = affine.load %b[0, %l] : memref<1x2xf32> } }
    return
  }
  func.func @f3(%v: f32) {
    %a = memref.alloc() : memref<2xf32>
    %b = memref.alloc() : memref<1x2xf32>
    affine.for %i = 0 to 2 { affine.store %v, %a[%i] : memref<2xf32> }
    affine.for %j = 0 to 2 {
      affine.prefetch %a[%j], write, locality<0>, data : memref<2xf32>
      %x = affine.load %a[%j] : memref<2xf32>
      affine.store %x, %b[0, %j] : memref<1x2xf32>
    }
    affine.for %k = 0 to 2 { affine.for %l = 0 to 2 { %y = affine.load %b[0, %l] : memref<1x2xf32> } }
    return
  }
  func.func @f4(%v: f32) {
    %a = memref.alloc() : memref<2xf32>
    %b = memref.alloc() : memref<1x2xf32>
    affine.for %i = 0 to 2 { affine.store %v, %a[%i] : memref<2xf32> }
    affine.for %j = 0 to 2 {
      affine.prefetch %a[%j], write, locality<0>, data : memref<2xf32>
      %x = affine.load %a[%j] : memref<2xf32>
      affine.store %x, %b[0, %j] : memref<1x2xf32>
    }
    affine.for %k = 0 to 2 { affine.for %l = 0 to 2 { %y = affine.load %b[0, %l] : memref<1x2xf32> } }
    return
  }
}
```

</details>

Copy count only affects the native crash probability: in a 10-run sample, 3 copies crashed 3/10, 4 copies 9/10, and 5 copies 10/10. The use-after-free itself already exists with one copy and is detected by Valgrind in every run.

#### Stack Dump

The following block is the unmodified stderr from running `reproducer_native.mlir` above with this build:

```text
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace and instructions to reproduce the bug.
Stack dump:
0.	Program arguments: /12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt reproducer_native.mlir --mlir-disable-threading --pass-pipeline=builtin.module(func.func(affine-loop-fusion)) -o /dev/null
 #0 0x000055d0146a4a29 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0x1fb9a29)
 #1 0x000055d0146a122c llvm::sys::RunSignalHandlers() (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0x1fb622c)
 #2 0x000055d0146a1396 SignalHandler(int, siginfo_t*, void*) Signals.cpp:0:0
 #3 0x00007f72af7d7520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x000055d01b5fbc65 mlir::affine::MemRefDependenceGraph::Node::getStoreOpCount(mlir::Value) const (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0x8f10c65)
 #5 0x000055d01b50bd14 std::_Function_handler<void (mlir::affine::MemRefDependenceGraph::Edge), (anonymous namespace)::GreedyFusion::findSiblingNodeToFuse(mlir::affine::MemRefDependenceGraph::Node*, llvm::DenseSet<unsigned int, llvm::DenseMapInfo<unsigned int, void>>*, std::pair<unsigned int, mlir::Value>*)::'lambda1'(mlir::affine::MemRefDependenceGraph::Edge)>::_M_invoke(std::_Any_data const&, mlir::affine::MemRefDependenceGraph::Edge&&) LoopFusion.cpp:0:0
 #6 0x000055d01b5f52b6 mlir::affine::MemRefDependenceGraph::forEachMemRefEdge(llvm::ArrayRef<mlir::affine::MemRefDependenceGraph::Edge>, std::function<void (mlir::affine::MemRefDependenceGraph::Edge)> const&) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0x8f0a2b6)
 #7 0x000055d01b5f9dc4 mlir::affine::MemRefDependenceGraph::forEachMemRefInputEdge(unsigned int, std::function<void (mlir::affine::MemRefDependenceGraph::Edge)> const&) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0x8f0edc4)
 #8 0x000055d01b515afb (anonymous namespace)::GreedyFusion::fuseWithSiblingNodes(mlir::affine::MemRefDependenceGraph::Node*) LoopFusion.cpp:0:0
 #9 0x000055d01b517111 (anonymous namespace)::GreedyFusion::fuseSiblingNodes() LoopFusion.cpp:0:0
#10 0x000055d01b5173ce (anonymous namespace)::LoopFusion::runOnBlock(mlir::Block*) LoopFusion.cpp:0:0
#11 0x000055d01b517b67 void mlir::detail::walk<mlir::ForwardIterator>(mlir::Operation*, llvm::function_ref<void (mlir::Operation*)>, mlir::WalkOrder) (.constprop.0) LoopFusion.cpp:0:0
#12 0x000055d01b517c1c (anonymous namespace)::LoopFusion::runOnOperation() LoopFusion.cpp:0:0
#13 0x000055d01cd016d9 mlir::detail::OpToOpPassAdaptor::run(mlir::Pass*, mlir::Operation*, mlir::AnalysisManager, bool, unsigned int) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa6166d9)
#14 0x000055d01cd019b4 mlir::detail::OpToOpPassAdaptor::runPipeline(mlir::OpPassManager&, mlir::Operation*, mlir::AnalysisManager, bool, unsigned int, mlir::PassInstrumentor*, mlir::PassInstrumentation::PipelineParentInfo const*) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa6169b4)
#15 0x000055d01cd028b4 mlir::detail::OpToOpPassAdaptor::runOnOperationImpl(bool) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa6178b4)
#16 0x000055d01cd015b1 mlir::detail::OpToOpPassAdaptor::run(mlir::Pass*, mlir::Operation*, mlir::AnalysisManager, bool, unsigned int) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa6165b1)
#17 0x000055d01cd019b4 mlir::detail::OpToOpPassAdaptor::runPipeline(mlir::OpPassManager&, mlir::Operation*, mlir::AnalysisManager, bool, unsigned int, mlir::PassInstrumentor*, mlir::PassInstrumentation::PipelineParentInfo const*) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa6169b4)
#18 0x000055d01cd03602 mlir::PassManager::runPasses(mlir::Operation*, mlir::AnalysisManager) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa618602)
#19 0x000055d01cd045d9 mlir::PassManager::run(mlir::Operation*) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa6195d9)
#20 0x000055d01476f0e6 performActions(llvm::raw_ostream&, std::shared_ptr<llvm::SourceMgr> const&, mlir::MLIRContext*, mlir::MlirOptMainConfig const&) MlirOptMain.cpp:0:0
#21 0x000055d01477069e processBuffer(llvm::raw_ostream&, std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, llvm::MemoryBufferRef, mlir::MlirOptMainConfig const&, mlir::DialectRegistry&, mlir::SourceMgrDiagnosticVerifierHandler*, llvm::ThreadPoolInterface*) MlirOptMain.cpp:0:0
#22 0x000055d0147708e1 llvm::LogicalResult llvm::function_ref<llvm::LogicalResult (std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, llvm::MemoryBufferRef const&, llvm::raw_ostream&)>::callback_fn<mlir::MlirOptMain(llvm::raw_ostream&, std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, mlir::DialectRegistry&, mlir::MlirOptMainConfig const&)::'lambda'(std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, llvm::MemoryBufferRef, llvm::raw_ostream&)>(long, std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, llvm::MemoryBufferRef const&, llvm::raw_ostream&) MlirOptMain.cpp:0:0
#23 0x000055d01d03f30d mlir::splitAndProcessBuffer(std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, llvm::function_ref<llvm::LogicalResult (std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, llvm::MemoryBufferRef const&, llvm::raw_ostream&)>, llvm::raw_ostream&, llvm::StringRef, llvm::StringRef) (/12T/qin/Fuzzing/MLIR_latest_20261104/llvm-project/build/bin/mlir-opt+0xa95430d)
#24 0x000055d01476a5da mlir::MlirOptMain(llvm::raw_ostream&, std::unique_ptr<llvm::MemoryBuffer, std::default_delete<llvm::MemoryBuffer>>, mlir::DialectRegistry&, mlir::MlirOptMainConfig const&) (.<truncated>Please see the issue for the entire body.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to