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

    <tr>
        <th>Summary</th>
        <td>
            [MLIR] OneShotBufferizer trying to make incompatible cast with SCF
        </td>
    </tr>

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

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

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

<pre>
    So I have an implementation of grouped convolution that is using multiple `linalg::Conv2DNchwFchwOp` operations, each operating on a different slice of a tensor. So for example, I would have the output tensor (containing the bias already) splitted into 4 tensors, using `tensor::ExtractSliceOp`, then apply conv2d operations on each one of those, and finally inserting the result tensors back into the output tensor using `tensor::InsertSliceOp`. After lowering the `linalg` operations into `scf`, the `OneShotBufferize` pass fails as it tries to introduce a `memref::CastOp` with incompatible operands.

Complete IR before bufferization [here](https://pastebin.com/R43C5GCi).

Complete IR after Bufferization [here](https://pastebin.com/SQZQmfgU). Note that the cast operation is only introduced if it's valid normally, but I disabled that check to get this IR

One of the part that's causing the issue is

```
%97 = "memref.alloc"() {operand_segment_sizes = dense<0> : vector<2xi32>} : () -> memref<1x1x3x3x2049xi64>
"memref.copy"(%95, %97) : (memref<1x1x3x3x2049xi64, #map10>, memref<1x1x3x3x2049xi64>) -> ()
%98 = "memref.cast"(%97) : (memref<1x1x3x3x2049xi64>) -> memref<1x1x3x3x2049xi64, #map10>
"scf.yield"(%98) : (memref<1x1x3x3x2049xi64, #map10>) -> ()
```

what is supposed to be yielded here is a `memref<1x1x3x3x2049xi64, #map10>`, however, another memref is being allocated (that is not a subview as is the expected type), and the content is being copied there to be yielded. Now the cast operation needs to be applied to the allocated buffer, to the yielded type, and that's where they aren't compatible.

AFAICT I think it's the pass not handling such case properly
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJydVU1v4zYQ_TXyhVhDliU7PvjgOJvCQL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