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

[MLIR] CSE fails to eliminate redundant `memref.load` across `scf.if` region

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

MLIR CSE misses a redundant memref.load inside an scf.if region. A load before the scf.if dominates the same load in the then branch, and there is no intervening store or side effect that could modify the loaded element.

The load in the then branch %1 = memref.load %A[%i] : memref<?xi32> should be replaced by the dominating load %0 = memref.load %A[%i] : memref<?xi32>. After that, both branches yield %0, so the scf.if result can also be simplified.

Minimized Program

test.mlir

func.func @load_region(%cond: i1, %A: memref<?xi32>, %i: index) -> (i32, i32) {
  %0 = memref.load %A[%i] : memref<?xi32>
  %r = scf.if %cond -> (i32) {
    %1 = memref.load %A[%i] : memref<?xi32>
    scf.yield %1 : i32
  } else {
    scf.yield %0 : i32
  }
  return %0, %r : i32, i32
}

Command

mlir-opt test.mlir --cse

Version: ef88536bbf62469eb2396d719d237b3191cf4843

MonSec-2077 avatar Aug 19 '26 12:08 MonSec-2077

@llvm/issue-subscribers-mlir

Author: MonSec-2077

MLIR CSE misses a redundant `memref.load` inside an `scf.if` region. A load before the `scf.if` dominates the same load in the then branch, and there is no intervening store or side effect that could modify the loaded element.

The load in the then branch %1 = memref.load %A[%i] : memref&lt;?xi32&gt; should be replaced by the dominating load %0 = memref.load %A[%i] : memref&lt;?xi32&gt;. After that, both branches yield %0, so the scf.if result can also be simplified.

Minimized Program

test.mlir

func.func @<!-- -->load_region(%cond: i1, %A: memref&lt;?xi32&gt;, %i: index) -&gt; (i32, i32) {
  %0 = memref.load %A[%i] : memref&lt;?xi32&gt;
  %r = scf.if %cond -&gt; (i32) {
    %1 = memref.load %A[%i] : memref&lt;?xi32&gt;
    scf.yield %1 : i32
  } else {
    scf.yield %0 : i32
  }
  return %0, %r : i32, i32
}

Command

mlir-opt test.mlir --cse

Version: ef88536bbf62469eb2396d719d237b3191cf4843

This is not a bug; CSE is intentionally implemented this way. CSE is triggered only when there are two identical reads (within the same block) with no intervening write.

linuxlonelyeagle avatar Aug 19 '26 12:08 linuxlonelyeagle

Yes, I presume the complex control flow scenario is not implemented because it's too complicated and bug prone. If you need this in downstream, I recommend you to write your own strict memref only CSE like opt, you can try to use the OperationEquivalence API to check the equivalence of operation. Can try to check mem2reg..

Because memref has MemoryEffects, you might want to properly check the dependency like DominanceInfo::properlyDominates(a, b) and do some alias analysis for view like ops.

hockyy avatar Aug 21 '26 06:08 hockyy