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

    <tr>
        <th>Summary</th>
        <td>
            [mlir] Inconsistent output when executing MLIR program with `--affine-data-copy-generate="generate-dma=false fast-mem-space=0 skip-non-unit-stride-loops"`
        </td>
    </tr>

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

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

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

<pre>
    git version: d6c0839c9c823

system: `Ubuntu 18.04.6 LTS`

## Description:
I am experiencing an inconsistent result when executing the same MLIR program with and without `--affine-data-copy-generate="generate-dma=false fast-mem-space=0 skip-non-unit-stride-loops"`. 


## Steps to Reproduce:

### 1. **MLIR Program (a.mlir)**:
a.mlir: 
``` 
module {
 func.func private @printMemrefI32(tensor<*xi32>)
  func.func private @printMemrefF32(tensor<*xf32>)
  func.func @entry(%arg0: index) -> ( tensor<1x3x5xi32>) {
    %37 = "tosa.const"() <{value = dense<0> : tensor<1x3x5xi32>}> : () -> tensor<1x3x5xi32>
    %38 = tosa.while_loop (%arg1 = %37) : (tensor<1x3x5xi32>) -> tensor<1x3x5xi32> {
      %96 = "tosa.const"() <{value = dense<3> : tensor<1x3x5xi32>}> : () -> tensor<1x3x5xi32>
      %97 = tosa.greater %96, %arg1 : (tensor<1x3x5xi32>, tensor<1x3x5xi32>) -> tensor<1x3x5xi1>
      %extracted_8 = tensor.extract %97[%arg0, %arg0, %arg0] : tensor<1x3x5xi1>
      %from_elements_9 = tensor.from_elements %extracted_8 : tensor<i1>
      tosa.yield %from_elements_9 : tensor<i1>
    } do {
    ^bb0(%arg1: tensor<1x3x5xi32>):
      %101 = "tosa.const"() <{value = dense<1> : tensor<1x3x5xi32>}> : () -> tensor<1x3x5xi32>
      %102 = tosa.add %arg1, %101 : (tensor<1x3x5xi32>, tensor<1x3x5xi32>) -> tensor<1x3x5xi32>
 tosa.yield %102 : tensor<1x3x5xi32>
    }
    return  %38 : tensor<1x3x5xi32>
  }
  func.func @main() {
    %idx0 = index.constant 0
 %0 = call @entry(%idx0) : (index) -> ( tensor<1x3x5xi32>)
    %cast_0 = tensor.cast %0 : tensor<1x3x5xi32> to tensor<*xi32>
    call @printMemrefI32(%cast_0) : (tensor<*xi32>) -> ()
    return
  }
}


``` 

 ### 2. **Command to Run without  `--affine-data-copy-generate` :**

``` 
/data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-opt /data/szy/workspace/mlir-inconsistent/a.mlir   -tosa-to-scf  \
| /data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-opt -pass-pipeline="builtin.module(func.func(tosa-to-linalg))"  \
| /data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-opt -tosa-to-arith -tosa-to-tensor   -convert-scf-to-cf   --test-math-to-vcix \
-one-shot-bufferize="bufferize-function-boundaries" --expand-strided-metadata  -convert-linalg-to-affine-loops    -lower-affine \
-convert-scf-to-cf   -finalize-memref-to-llvm  -convert-arith-to-llvm -convert-func-to-llvm -convert-cf-to-llvm  -convert-index-to-llvm \
-reconcile-unrealized-casts | timeout 100 /data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-cpu-runner -e main \
-entry-point-result=void --shared-libs=/data/szy/MLIR/llvm-release/llvm-project/build/lib/libmlir_c_runner_utils.so \
--shared-libs=/data/szy/MLIR/llvm-release/llvm-project/build/lib/libmlir_runner_utils.so \
--shared-libs=/data/szy/MLIR/llvm-release/llvm-project/build/lib/libmlir_async_runtime.so
``` 

### 3. **Output  without   `--affine-data-copy-generate` :**:

``` 
[[[3],
  [3]]]
``` 

### 4. **Command to Run with `--affine-data-copy-generate`  :**


``` 
/data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-opt /data/szy/workspace/mlir-inconsistent/a.mlir   -tosa-to-scf  \
| /data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-opt -pass-pipeline="builtin.module(func.func(tosa-to-linalg))"  \
| /data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-opt -tosa-to-arith -tosa-to-tensor   -convert-scf-to-cf   --test-math-to-vcix \
-one-shot-bufferize="bufferize-function-boundaries" --expand-strided-metadata  -convert-linalg-to-affine-loops \
--affine-data-copy-generate="generate-dma=false fast-mem-space=0 skip-non-unit-stride-loops"  -lower-affine  -convert-scf-to-cf \
-finalize-memref-to-llvm  -convert-arith-to-llvm   -convert-func-to-llvm -convert-cf-to-llvm  -convert-index-to-llvm  \
-reconcile-unrealized-casts | timeout 100 /data/szy/MLIR/llvm-release/llvm-project/build/bin/mlir-cpu-runner -e main \
-entry-point-result=void --shared-libs=/data/szy/MLIR/llvm-release/llvm-project/build/lib/libmlir_c_runner_utils.so \
--shared-libs=/data/szy/MLIR/llvm-release/llvm-project/build/lib/libmlir_runner_utils.so \
--shared-libs=/data/szy/MLIR/llvm-release/llvm-project/build/lib/libmlir_async_runtime.so
``` 

### 5. **Output with  `--affine-data-copy-generate` :**

``` 
[[[109110929],
  [21903]]]
``` 

### 6. **Analysis for this case :**

This MLIR program is expected to correctly output` [[3],[3]]` because the loop terminates when the condition greater than 3 is no longer met. The loop variable `%arg1` is initialized to 0 and incremented by 1 in each iteration, ensuring that it reaches 3 before exiting. However, after applying ` --affine-data-copy-generate`, the program incorrectly outputs a random value instead. 

I debug this issue and find the faulty pass is `--affine-data-copy-generate `pass
**The input IR** (ir before running the` --affine-data-copy-generate` pass) can be found in [input.txt](https://github.com/user-attachments/files/19122238/input.txt)
**The output IR** (ir after running the --affine-data-copy-generate pass) can be found in [output.txt](https://github.com/user-attachments/files/19122240/output.txt)
Please change file from .txt to .mlir

As shown in the first image, the loop variable %1 is incremented by 1 in line 32-33. However, after running `--affine-data-copy-generate`, as shown in the second image, it mistakenly load %alloc_16 (in line 60) that has been deallocated in line 53, leading to a random value result.
`%alloc_16` should be %1.

![Image](https://github.com/user-attachments/assets/5f277357-bcba-44ba-bd98-ea7d321204b3)

![Image](https://github.com/user-attachments/assets/0406fa4e-847f-4090-a3b5-b4f8cd8ac42c)
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzsWU9v27gS_zTMZUBDoiTbOuTgxjVegF28xW7fOaCkkc1XiRRIKrH30y-GkmzHcdJum_ZUQEgskZz5zR_OjxpJ59RWI96y7APL1jey9ztjbz-2qjnIPd4UpjrcbpWHR7ROGc2SFVTzMlomeZmXS5GwaMWilTs4jy0Nsnn0v6LXvod4OYvS2Rx--_QXm0fDPCYSJhJYoyut6vwgkEWre5At4L5Dq1CXSm9BalC6NNop51F7sOj6xsPTDjXgHsve0yy_Q3CyRfj9t_s_obNma2ULT8rvQOoq_DC9J1Ccy7pWGnklveSl6Q58ixqt9MiSNRNiuuNVK1myrmXjEGrpPG-x5a6TJU2MwH1WHddG814rz523qkLeGNM5JgSbRzMYTT1a-5fHzoE38Cd21lQ9CXo2gybFM2BixcQqWPLHaAkTSzlrG2WZyIfhYen4kPwdrci74aKb1lR9g8AWH1i0grrX5Yz-QGfVo_QILI06q7T_HVuL9X0imFh61M5YltwxsdqrRLDkI-mLVvBFAZuXAupXBLA0Qu3tgYklE5m024jwK13hnokcOEs-kr1wFBbvk312wjPZBABMZMkCWLIGJoQ3Ts4oUzwFgITnQFAWHx5l02OYVqF2yJK7KChJVq8oWayn8VFOAHV97gnJMqgIMJ52qsEHygY4mhmPQLNkMUAL0l-18nWVZw4IivP5t7ggeW8XDFgWJydsLUqPdoDIxB2c_PCW6XevR_4qhvgCAu69laXH6mEMSJg_Gx8PIKnKjbl3xPXsZ7a-6ptLXbU17QM22KL27iE_1_ds6CWuM9nPpQbXHRQ21XUFryxkizVU5nxvZB-LIjpl3-uhFvlQTI5WxVH8LRkV_5CMiiNxSilZVVMWjdEasL5nPh0RPI_EgOM1445BGH9Z9L3Vp7rw1rpp1bMS2UqlJ3-f1ztV7aPgj1Awh9BI7YGIlcaHwVI2zUWhpYVndefr6-1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