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

[MLIR] Unused `scf.if` results are not removed by `--remove-dead-values`

Open dev-816 opened this issue 3 months ago • 1 comments

The compiler optimization --remove-dead-values does not remove an unused result of scf.if (%r at line 3) when the branches contain side-effecting operations, even though only the result is dead and the scf.if itself must be preserved, leading to a missed optimization bug.

Input Program

input.mlir

module {
  func.func @func_t13(%cond: i1, %m: memref<i32>) {
    %r = scf.if %cond -> (i32) {
      %c1 = arith.constant 1 : i32
      memref.store %c1, %m[] : memref<i32>
      scf.yield %c1 : i32
    } else {
      %c2 = arith.constant 2 : i32
      memref.store %c2, %m[] : memref<i32>
      scf.yield %c2 : i32
    }
    return
  }
}

Ideally, it should optimized into the following form:

module {
  func.func @func_t13(%cond: i1, %m: memref<i32>) {
    scf.if %cond {
      %c1 = arith.constant 1 : i32
      memref.store %c1, %m[] : memref<i32>
    } else {
      %c2 = arith.constant 2 : i32
      memref.store %c2, %m[] : memref<i32>
    }
    return
  }
}

Command

mlir-opt --remove-dead-values input.mlir

Version: ef88536bbf62469eb2396d719d237b3191cf4843

dev-816 avatar Aug 17 '26 06:08 dev-816

@llvm/issue-subscribers-mlir

Author: CC_Fans (dev-816)

The compiler optimization `--remove-dead-values` does not remove an unused result of `scf.if` (`%r` at line 3) when the branches contain side-effecting operations, even though only the result is dead and the `scf.if` itself must be preserved, leading to a missed optimization bug.

Input Program

input.mlir

module {
  func.func @<!-- -->func_t13(%cond: i1, %m: memref&lt;i32&gt;) {
    %r = scf.if %cond -&gt; (i32) {
      %c1 = arith.constant 1 : i32
      memref.store %c1, %m[] : memref&lt;i32&gt;
      scf.yield %c1 : i32
    } else {
      %c2 = arith.constant 2 : i32
      memref.store %c2, %m[] : memref&lt;i32&gt;
      scf.yield %c2 : i32
    }
    return
  }
}

Ideally, it should optimized into the following form:

module {
  func.func @<!-- -->func_t13(%cond: i1, %m: memref&lt;i32&gt;) {
    scf.if %cond {
      %c1 = arith.constant 1 : i32
      memref.store %c1, %m[] : memref&lt;i32&gt;
    } else {
      %c2 = arith.constant 2 : i32
      memref.store %c2, %m[] : memref&lt;i32&gt;
    }
    return
  }
}

Command

mlir-opt --remove-dead-values input.mlir

Version: ef88536bbf62469eb2396d719d237b3191cf4843