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

    <tr>
        <th>Summary</th>
        <td>
            [MLIR][Arith] Invalid SelectOp folding
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            bug,
            mlir:arith
      </td>
    </tr>

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

    <tr>
      <th>Reporter</th>
      <td>
          7FM
      </td>
    </tr>
</table>

<pre>
    In CIRCT, we have a dialect named `hwarith` to represent arithmetics that persist signedness information and prevent unintentional under- and overflows.
Using this dialect in combination with `arith.select` revealed an issue. Take the following example code:
```
func.func @test(%sel : i1) -> ui1 {
  %trueVal = hwarith.constant 1 : ui1
  %falseVal = hwarith.constant 0 : ui1
  %res = arith.select %sel, %trueVal, %falseVal : ui1
  func.return %res : ui1
}
```
The SelectOp's folder tries to replace the SelectOp directly with `%sel`. However, `%sel` is of type `i1` whereas the true- and falseVal values are of type `ui1`. Consequently, the following crash is caused: `error: 'arith.select' op folder produced a value of incorrect type: 'i1', expected: 'ui1'`.

The corresponding pattern matching code has a bit-width check for the return type but lacks a signedness check and thus implicitly assumes that the return type is signless (i1):
https://github.com/llvm/llvm-project/blob/612f8ec7ac5dcddd16fb027aad64e2e353faa528/mlir/lib/Dialect/Arith/IR/ArithOps.cpp#L2317-L2319
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVE1v4zYQ_TX0ZRBBpCzJPujgxDUaYBcLpGnvFDmy2FCkyg978-8LUnLiDdBDAUOWyJk3780X916dDWJH6kdSHzc8htG6rj193_RWvnfPBp6eX55eCXuCK8LILwgcpOIaRQDDJ5RAmnK8cqfCSJoSggWHs0OPJkA-nTAo4SGMPMCMzisfIEeVBr0HZQbrJh6UNcCNhNnhJflGo0xAk865hmgkuodsYC_oBm2vviDl4U-vzBnCqPwHK2VA2KlXZsG8qjAmjplL4THZJKIpDNcogRtQ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