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

    <tr>
        <th>Summary</th>
        <td>
            [mlir][arith] canonicalization pattern causes miscompilation on `arith.index_cast`
        </td>
    </tr>

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

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

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

<pre>
    similar issue to: https://github.com/llvm/llvm-project/issues/90238

The following code:
```mlir
module {
    func.func @main() {
 %3 = call @gt_i8_max() : () -> index
        %4 = arith.index_cast %3 : index to i8
        %5 = arith.index_cast %4 : i8 to index
 vector.print str "%3="
        vector.print %3 : index
 vector.print str "%4="
        vector.print %4 : i8
 vector.print str "%5="
        vector.print %5 : index // Bug: expect "%5=0". 
        return
    }
    func.func @gt_i8_max() -> index {
        %max = arith.constant 256 : index
        return %max : index
    }
}
```
incorrectly prints out `%5=256` (correct result should be `%5=0`) when compiled and executed with:
`mlir-opt --canonicalize --arith-expand --convert-arith-to-llvm --convert-scf-to-cf --convert-cf-to-llvm --convert-vector-to-llvm --convert-func-to-llvm --reconcile-unrealized-casts | mlir-cpu-runner -e main --shared-libs ~/lib/mlir/libmlir_c_runner_utils.so --entry-point-result void`

This appears to be caused by the canonicalization for `arith.index_cast` folding the sequence:
```mlir
%3 = call @gt_i8_max() : () -> index
%4 = arith.index_cast %3 : index to i8
%5 = arith.index_cast %4 : i8 to index
```
into:
```mlir
%3 = call @gt_i8_max() : () -> index
%4 = arith.index_cast %3 : index to i8
// effectively: %5 = %3
```

Reproduction here: https://godbolt.org/z/oW318xzE5
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzMVslu4zgTfhr6UqAhU4vlgw_J7_YD_BhgjgZFli0OKFLDJbFzmGcfkIpjORsa3ZcJApos1sZavhL3Xp0M4pbUj6TeL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