<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/107508>107508</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [mlir] Semantic inconsistency in `ceildiv` optimization
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            mlir
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          Emilyaxe
      </td>
    </tr>
</table>

<pre>
    Git version: [c28b1a19aa](https://github.com/llvm/llvm-project/commit/c28b1a19aa)
System: Ubuntu 18.04.6 LTS

# Issue Description:
In the following MLIR:
a.mlir
```
func.func @semiaffine_composite_floor(%arg0: index, %arg1: index) -> index {
  %a = affine.apply affine_map<(d0)[s0] ->(((((s0 * 2) ceildiv 4) * 5) + s0 * 42) ceildiv s0)> (%arg0)[%arg1]
  return %a : index
}
```
After running `mlir-opt -canonicalize a.mlir`, the resulting optimized MLIR is:
```
module {
  func.func private @semiaffine_composite_floor(%arg0: index, %arg1: index) -> index {
 %c47 = arith.constant 47 : index
    return %c47 : index
 }
}
```
This leads to the result always being 47.

However, without applying the canonicalize optimization, the result of a.mlir varies depending on the input `%arg1` as follows:

- 44 if `%arg1` is less than 0
- Floating-point exception if `%arg1` is 0
- 47 if `%arg1` is 1
- 45 if `%arg1 `is greater than 1

This seems like a misoptimization in the handling of ceildiv. The canonicalize pass simplifies the expression to always return 47, but the expected behavior is input-dependent as shown above. Is this an unintended side effect of the ceildiv optimization?
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy0VU1zozgT_jXypcuUEGDMgUMyHr9vqmYvO9lzSkBjeldIlCSceH79lgRO7FT2sIetooQ-Wv3xPN1q6RydNGLNikdWHDZy9oOx9feR1EW-4aYx3aX-H3k4o3VkNMsegBWPrdg3qUwrKVlxYGI_eD85lj0wcWTieCI_zE3SmpGJo1Ln6287WfMntp6JY2vGkeLkQ5Oo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