llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[MLIR] Missed Optimization: Partial ownership simplification leaves redundant deallocation candidates

Open MonSec-2077 opened this issue 2 months ago • 2 comments

The constant-true rule replaces the first two ownership results with true, but keeps %a and %b because the result for %fresh is not also known to be true. Neither candidate can alias %fresh, so both can be removed from the candidate list while preserving %selected and all retained operands.

Code Example

example.mlir

func.func @partial_ownership(%a: memref<4xi32>, %b: memref<4xi32>, %pick: i1, %owned: i1) -> (memref<4xi32>, i1, i1, i1) {
  %true = arith.constant true
  %fresh = memref.alloc() : memref<4xi32>
  %selected = scf.if %pick -> (memref<4xi32>) {
    scf.yield %fresh : memref<4xi32>
  } else {
    scf.yield %a : memref<4xi32>
  }
  %r:3 = bufferization.dealloc(%a, %b, %selected : memref<4xi32>, memref<4xi32>, memref<4xi32>)
      if (%true, %true, %owned)
      retain (%a, %b, %fresh : memref<4xi32>, memref<4xi32>, memref<4xi32>)
  return %fresh, %r#0, %r#1, %r#2 : memref<4xi32>, i1, i1, i1
}

Command

mlir-opt example.mlir --buffer-deallocation-simplification

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

MonSec-2077 avatar Oct 01 '26 08:10 MonSec-2077

@llvm/issue-subscribers-mlir

Author: MonSec-2077

The constant-true rule replaces the first two ownership results with `true`, but keeps `%a` and `%b` because the result for `%fresh` is not also known to be `true`. Neither candidate can alias `%fresh`, so both can be removed from the candidate list while preserving `%selected` and all retained operands.

Code Example

example.mlir

func.func @<!-- -->partial_ownership(%a: memref&lt;4xi32&gt;, %b: memref&lt;4xi32&gt;, %pick: i1, %owned: i1) -&gt; (memref&lt;4xi32&gt;, i1, i1, i1) {
  %true = arith.constant true
  %fresh = memref.alloc() : memref&lt;4xi32&gt;
  %selected = scf.if %pick -&gt; (memref&lt;4xi32&gt;) {
    scf.yield %fresh : memref&lt;4xi32&gt;
  } else {
    scf.yield %a : memref&lt;4xi32&gt;
  }
  %r:3 = bufferization.dealloc(%a, %b, %selected : memref&lt;4xi32&gt;, memref&lt;4xi32&gt;, memref&lt;4xi32&gt;)
      if (%true, %true, %owned)
      retain (%a, %b, %fresh : memref&lt;4xi32&gt;, memref&lt;4xi32&gt;, memref&lt;4xi32&gt;)
  return %fresh, %r#<!-- -->0, %r#<!-- -->1, %r#<!-- -->2 : memref&lt;4xi32&gt;, i1, i1, i1
}

Command

mlir-opt example.mlir --buffer-deallocation-simplification

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

I'm working on this and plan to open a PR soon. If anyone else is also working on it, please let me know.

heturing avatar Oct 01 '26 10:10 heturing