[MLIR] CSE fails to eliminate redundant `memref.load` across `scf.if` region
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
@llvm/issue-subscribers-mlir
Author: MonSec-2077
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
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.
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.