| Issue |
242621
|
| Summary |
[MLIR][Affine] LICM hoists integer division across a preceding non-returning call or assertion
|
| Labels |
mlir
|
| Assignees |
|
| Reporter |
Cerulime
|
## Summary
`--affine-loop-invariant-code-motion` can introduce division-by-zero undefined behavior by moving an `arith.divsi` out of a statically positive-trip loop, across an earlier operation that terminates execution.
In the reproducer below, the first operation in the loop calls `exit(0)`. The original program terminates successfully without executing the division. Affine LICM moves the division before the loop, so the transformed program instead raises `SIGFPE`. A second reproducer places `cf.assert` before the division: the original program aborts at the assertion, whereas the transformed program divides by zero before reaching it.
The generic `--loop-invariant-code-motion` pass leaves the division in the loop and preserves the behavior in both cases. A positive static trip count proves that the loop body is entered; it does not prove that every operation in the body is reached.
## Environment
Reproduced with a rebuilt upstream `llvm-project` toolchain:
- Build revision: `57806b9ff51d362d2c5d139ccf5d7163bfec3998`, recorded in the build's generated `llvm/Support/VCSRevision.h`.
- `mlir-opt --version`: LLVM 24.0.0git, optimized build with assertions.
- Host/default target: `x86_64-unknown-linux-gnu`; execution tested on Linux x86-64.
- Runtime verification uses the matching `mlir-runner` at `-O0` and `libmlir_c_runner_utils.so` from the same build.
The reproducer uses only standard MLIR dialects, libc `exit`, and the runner utility `printI64`. It contains no affine loads or stores and requires no sanitizer or custom dialect.
## Reproducer
Save as `repro.mlir`:
```mlir
module {
func.func private @exit(i32)
func.func private @printI64(i64)
func.func @probe(%num: i64, %denom: i64, %status: i32) {
affine.for %i = 0 to 4 {
func.call @exit(%status) : (i32) -> ()
%q = arith.divsi %num, %denom : i64
func.call @printI64(%q) : (i64) -> ()
}
return
}
func.func @main() {
%num = arith.constant 42 : i64
%denom = arith.constant 0 : i64
%status = arith.constant 0 : i32
func.call @probe(%num, %denom, %status) : (i64, i64, i32) -> ()
return
}
}
```
The input is well-defined for this invocation: `exit(0)` terminates execution before the division is reached. There is no division-by-zero UB in the original execution.
Run:
```bash
LLVM_BUILD=/path/to/llvm-project/build
"$LLVM_BUILD/bin/mlir-opt" repro.mlir -o original.mlir
"$LLVM_BUILD/bin/mlir-opt" repro.mlir \
--loop-invariant-code-motion -o generic.mlir
"$LLVM_BUILD/bin/mlir-opt" repro.mlir \
--affine-loop-invariant-code-motion -o affine.mlir
```
### Actual IR output
Affine LICM produces the following `@probe`:
```mlir
func.func @probe(%arg0: i64, %arg1: i64, %arg2: i32) {
%0 = arith.divsi %arg0, %arg1 : i64
affine.for %arg3 = 0 to 4 {
func.call @exit(%arg2) : (i32) -> ()
func.call @printI64(%0) : (i64) -> ()
}
return
}
```
The division now executes before `exit`, even though it was unreachable in the original execution. The generic LICM output keeps the division after the call inside the loop.
### Runtime verification
Lower and execute all three variants with the same pipeline and runner options:
```bash
ulimit -c 0
for variant in original generic affine; do
"$LLVM_BUILD/bin/mlir-opt" "$variant.mlir" \
--lower-affine --convert-scf-to-cf --convert-to-llvm \
--reconcile-unrealized-casts -o "$variant.llvm.mlir"
"$LLVM_BUILD/bin/mlir-runner" "$variant.llvm.mlir" \
-e main --entry-point-result=void -O0 \
--shared-libs="$LLVM_BUILD/lib/libmlir_c_runner_utils.so"
printf '%s: exit status %s\n' "$variant" "$?"
done
```
Observed results:
| Variant | Result |
| --- | --- |
| Original | Normal termination, exit status 0 |
| Generic LICM | Normal termination, exit status 0 |
| Affine LICM | `SIGFPE` from integer division by zero |
All transformation and lowering commands succeed. The failure occurs when executing the generated code. The incorrect reordering is already visible immediately after Affine LICM, before LLVM lowering or JIT optimization.
## Assertion variant
The issue also occurs with an explicit MLIR assertion instead of the external terminating call. Save this as `repro.mlir` and repeat the commands above:
```mlir
module {
func.func private @printI64(i64)
func.func @probe(%num: i64, %denom: i64) {
%zero = arith.constant 0 : i64
%valid = arith.cmpi ne, %denom, %zero : i64
affine.for %i = 0 to 4 {
cf.assert %valid, "denominator must be nonzero"
%q = arith.divsi %num, %denom : i64
func.call @printI64(%q) : (i64) -> ()
}
return
}
func.func @main() {
%num = arith.constant 42 : i64
%denom = arith.constant 0 : i64
func.call @probe(%num, %denom) : (i64, i64) -> ()
return
}
}
```
`cf.assert` specifies that execution aborts when its condition is false. In the original execution the assertion fails before the division is reached. Affine LICM produces:
```mlir
func.func @probe(%arg0: i64, %arg1: i64) {
%c0_i64 = arith.constant 0 : i64
%0 = arith.cmpi ne, %arg1, %c0_i64 : i64
%1 = arith.divsi %arg0, %arg1 : i64
affine.for %arg2 = 0 to 4 {
cf.assert %0, "denominator must be nonzero"
func.call @printI64(%1) : (i64) -> ()
}
return
}
```
| Variant | Result |
| --- | --- |
| Original | `SIGABRT` from the failed assertion |
| Generic LICM | `SIGABRT` from the failed assertion |
| Affine LICM | `SIGFPE` before reaching the assertion |
## Expected behavior
Affine LICM should preserve the original execution condition of a potentially undefined operation. It must not move the division before an earlier operation that may terminate execution unless it can prove the motion is safe.
Keeping these divisions in the loop preserves the behavior, as the generic LICM pass demonstrates. The report does not require all division hoisting to be disabled: a nonzero-trip proof alone is insufficient for these cases.
## Root cause
In `mlir/lib/Dialect/Affine/Transforms/AffineLoopInvariantCodeMotion.cpp`, `runOnAffineForOp` computes:
```cpp
auto tripCount = forOp.getStaticTripCount();
bool guaranteedToExecute =
tripCount.has_value() && tripCount->getZExtValue() > 0;
```
It then gates each candidate with:
```cpp
if (!guaranteedToExecute && !isPure(&op))
continue;
if (isOpLoopInvariant(op, forOp, opsWithUsers, opsToHoist)) {
opsToMove.push_back(&op);
}
```
For the positive-trip loop, the `isPure` requirement is bypassed. `isOpLoopInvariant` accepts a memory-effect-free operation with loop-invariant operands without requiring speculatability. The preceding call or assertion is rejected for motion, but it does not prevent a later division from being selected and moved before the loop.
`arith.divsi` has `NoMemoryEffect`, but its `getSpeculatability()` implementation in `mlir/lib/Dialect/Arith/IR/ArithOps.cpp` returns `NotSpeculatable` for an unconstrained divisor. `NoMemoryEffect` does not imply that executing an operation on an additional path is safe.
By comparison, `moveLoopInvariantCode(LoopLikeOpInterface)` in `mlir/lib/Transforms/Utils/LoopInvariantCodeMotionUtils.cpp` requires `isPure(op)`, which includes speculatability, and does not perform this reordering.
## Possible fix and regression coverage
For memory-effect-free candidates, require speculatability unless there is an operation-level proof that the candidate will be reached and can safely move across all preceding operations. A positive loop trip count alone does not provide that proof.
Regression coverage should check that an unknown-divisor `arith.divsi` remains after a preceding potentially non-returning call or `cf.assert` in a positive-trip affine loop. Existing dynamic-trip and zero-trip behavior should remain protected, while provably safe divisions can still be hoisted.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs