Issue 238904
Summary [mlir][Shape] `shape.div` constant fold does not round toward negative infinity when the true quotient lies in (-1, 0)
Labels mlir
Assignees
Reporter lin334141-cell
    # [mlir][Shape] `shape.div` constant fold does not round toward negative infinity when the true quotient lies in (-1, 0)

## Versions

- **Executed (canonicalize fold) on LLVM `24.0.0git` at `67005b724c917e1bdca50c82ecaa1b21a69244ed`** (same-source rebuild, Release + assertions, macOS arm64; `mlir-opt` SHA-256 `4c65172e1a97c14b4ddb8c29a042a374398c2205ad2401470f421b77e2535c63`).
- **Executed on LLVM `main` at `61817b48e757f9a07f2a84e36326542052c12c22`** (local build dated 2026-10-29, macOS arm64; `mlir-opt` SHA-256 `6c2198e173ad511f667cab34ba3cd8e97938691609f9ea830002db5cb0366bf6`).
- **Source-level check of `main` at commit `ca566d552f7a9e507388cdba9539dd6e36c94bef`** (commit dated 2026-11-04; check performed 2026-11-05): `DivOp::fold` in `mlir/lib/Dialect/Shape/IR/Shape.cpp` (function starting at line 1135) is byte-identical to the `67005b72` revision — the defective fold is still present at that commit. This commit was **not** built or executed; the check is source-level only, and no newer revision was checked.
- The two executed builds above are the only executed revisions; all three are distinguished explicitly here. Output of both executed builds is byte-identical.

## Summary

`mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td` defines `shape.div` for `index` operands as follows (in-tree documentation, lines 159–162 at the checked revisions): the operands may be negative, and **"The result is rounded toward negative infinity, i.e. floor(lhs / rhs)"**, such that `div(lhs, rhs) * rhs + mod(lhs, rhs) = lhs` always holds.

`DivOp::fold` in `mlir/lib/Dialect/Shape/IR/Shape.cpp` implements the constant fold as:

```cpp
APInt::sdivrem(lhs.getValue(), rhs.getValue(), quotient, remainder);
if (quotient.isNegative() && !remainder.isZero()) {
  quotient -= 1;
}
```

`APInt::sdivrem` truncates toward zero. The correction guard `quotient.isNegative()` misses the case where the mathematical quotient lies in `(-1, 0)`: `sdivrem` then yields `quotient == 0`, which is not negative, so the floor correction is skipped and the fold returns `0` where the specification requires `-1`. This is **not** a Native-backend division-precision problem — the wrong constant is produced by the Shape-op constant folder itself during `canonicalize`.

The wrong domain is exactly: **opposite signs, non-zero remainder, and `|lhs| < |rhs|`**.

(First-error location: the `quotient.isNegative()` guard in `DivOp::fold`, `mlir/lib/Dialect/Shape/IR/Shape.cpp`; lines 1146–1148 at `67005b72`, identical body at the checked `ca566d552f7a9e507388cdba9539dd6e36c94bef` — source-level only.)

## Minimal reproducer (`min.mlir`)

```mlir
module{func.func @f()->index{
%c2=arith.constant 2:index %cm7=arith.constant -7:index
%r="shape.div"(%c2,%cm7):(index,index)->index
func.return %r:index
}}
```

## Commands (verified as shown, clean directory)

```bash
mlir-opt min.mlir --mlir-disable-threading --canonicalize -o folded.mlir
cat folded.mlir
```

No custom pipeline is required — the default `canonicalize` pass invokes `DivOp::fold` on the constant operands.

## Expected behavior

`floor(2 / (-7)) = floor(-0.2857…) = -1`. The fold should replace `shape.div` with `arith.constant -1 : index` (this is what the un-folded op computes through the Shape-to-Arith lowering, and what the specification requires).

## Actual behavior (executed on both revisions above, byte-identical output)

```mlir
module {
  func.func @f() -> index {
    %c0 = arith.constant 0 : index
    return %c0 : index
  }
}
```

## Boundary sweep

Nine `index` input pairs covering the sign combinations, exact vs. non-exact division, and the `|q| < 1` corner. The results come from **two independent reproducer files** — `signs.mlir` (seven rows) and the minimal `min.mlir` above (the `2 / −7` row) — each folded with the **same** `canonicalize` command shown above on both builds:

| lhs / rhs | signs | exact quotient | spec (floor) | folded result | evidence file |
|---|---|---|---|---|---|
| 8 / 2 | +,+ | 4 (exact) | 4 | 4 ✓ | signs.mlir |
| 7 / 2 | +,+ | 3.5 | 3 | 3 ✓ | signs.mlir |
| 7 / −2 | +,− | −3.5 | −4 | −4 ✓ | signs.mlir |
| −7 / 3 | −,+ | −2.33 | −3 | −3 ✓ | signs.mlir |
| −7 / −2 | −,− | 3.5 | 3 | 3 ✓ | signs.mlir |
| −7 / −1 | −,− | 7 (exact) | 7 | 7 ✓ | signs.mlir |
| 2 / −2 | +,− | −1 (exact) | −1 | −1 ✓ | signs.mlir |
| **−1 / 2** | −,+ | **−0.5** | **−1** | **0 ✗** | signs.mlir |
| **2 / −7** | +,− | **−0.2857** | **−1** | **0 ✗** | min.mlir (this reproducer) |

(`2 / −7` does not appear in the nine-slot `signs.mlir` file; its evidence is this reproducer itself, executed separately on both builds. The rows above were not all produced by a single file run and are labeled accordingly.)

`INT64_MIN / -1` was also tested: the mathematical quotient 2^63 is not representable in `index` (i64). `APInt::sdivrem` yields `q = INT64_MIN, r = 0`, which the fold returns unchanged. The in-tree description does not define the overflow domain for `index`, so this input is reported for completeness only and is **not** claimed as part of the defect.

## Provenance and scope of the evidence

- The reproducer above is a pure `mlir-opt --canonicalize` observation: a well-defined, verifier-accepted program is folded into a constant that contradicts the operation's own specification. This is compiler-side evidence; no end-to-end native execution is required to demonstrate it.
- Independently, a broader program containing four `shape.div` operations on `index` constants was observed to disagree between an unoptimized path (correct values `[−1, −1, −3, 7]`) and a canonicalized path (`[0, 0, −3, 7]`) in an end-to-end native harness. That observation was produced by an external compiler-testing pipeline whose harness routes `shape.div` through a Shape-to-Arith adapter before lowering; it is consistent with, but not required by, the minimal fold reproducer above and is mentioned only as corroborating context.

## Upstream dedup (checked 2026-11-05)

Searches over "shape.div constant folding", "Shape DivOp fold", "negative quotient floor division", and "APInt::sdivrem rounding" (issues and PRs) found no existing report of this mechanism.

## Suggested fix direction

The floor correction should trigger on the sign difference of the operands plus a non-zero remainder, rather than on the sign of the (truncated) quotient, e.g.:

```cpp
if (!remainder.isZero() &&
    lhs.getValue().isNegative() != rhs.getValue().isNegative())
  quotient -= 1;
```

This also covers the truncated-quotient-zero case (`0 - 1 = -1`). The sketch has only been checked against the witnesses shown; it has not been exhaustively tested, and we make no claim about signed-overflow domains (`INT64_MIN / -1`) or index widths other than the ones observable here. Happy to test a patch.

## Request for Maintainer Feedback

I would appreciate the maintainers' feedback on whether this issue should be classified as a *silent miscompilation*, since canonicalization completes successfully but changes the semantics of a well-defined MLIR program without reporting an error.

I have also recently submitted several other MLIR semantic-correctness reports (#238834, #238835, and #238836), including cases where lowering introduces LLVM poison. I would be grateful for any guidance on whether these issues are appropriately described as silent miscompilations or whether a different classification would be more accurate.

There is no urgency. My goal is to describe these findings accurately in our compiler-testing research. Thank you for your time and consideration.

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

Reply via email to