[MLIR] LICM fails to hoist loop-invariant `arith.addi` in a reachable loop
Hi, I found a missed optimization bug in MLIR LICM. In the following example, %2 = arith.addi %arg0, %arg0 : index is loop-invariant in a reachable loop and should be hoisted outside the loop. However, MLIR fails to do so, resulting in a missed opt bug.
Input Program
input.mlir
module {
func.func @valid_symbol_affine_scope(%arg0: index, %arg1: memref<?xf32>) {
test.affine_scope {
%c1 = arith.constant 1 : index
%0 = arith.subi %arg0, %c1 : index
affine.for %arg2 = %0 to %arg0 {
%1 = arith.subi %0, %arg2 : index
test.affine_scope {
affine.for %arg3 = %1 to %arg0 {
%3 = affine.load %arg1[%arg0 - 1] : memref<?xf32>
affine.store %3, %arg1[%arg0 - 1] : memref<?xf32>
}
%2 = arith.addi %arg0, %arg0 : index
%c0 = arith.constant 0 : index
%alloca = memref.alloca() : memref<1xindex>
memref.store %2, %alloca[%c0] : memref<1xindex>
"terminate"() : () -> ()
}
}
"terminate"() : () -> ()
}
return
}
}
Command
mlir-opt --allow-unregistered-dialect --loop-invariant-code-motion input.mlir
Version: 9d3a3fa57c47fd06efea20f100ec747f5e5fbfdd
@llvm/issue-subscribers-mlir
Author: RJerrica
Input Program
input.mlir
module {
func.func @<!-- -->valid_symbol_affine_scope(%arg0: index, %arg1: memref<?xf32>) {
test.affine_scope {
%c1 = arith.constant 1 : index
%0 = arith.subi %arg0, %c1 : index
affine.for %arg2 = %0 to %arg0 {
%1 = arith.subi %0, %arg2 : index
test.affine_scope {
affine.for %arg3 = %1 to %arg0 {
%3 = affine.load %arg1[%arg0 - 1] : memref<?xf32>
affine.store %3, %arg1[%arg0 - 1] : memref<?xf32>
}
%2 = arith.addi %arg0, %arg0 : index
%c0 = arith.constant 0 : index
%alloca = memref.alloca() : memref<1xindex>
memref.store %2, %alloca[%c0] : memref<1xindex>
"terminate"() : () -> ()
}
}
"terminate"() : () -> ()
}
return
}
}
Command
mlir-opt --allow-unregistered-dialect --loop-invariant-code-motion input.mlir
Version: 9d3a3fa57c47fd06efea20f100ec747f5e5fbfdd
I would like to take this issue. I'm new to the MLIR part of the codebase. So will take some time and raise a PR soon.
Can I be assigned?
Thank you for your interest, @VachanVY! Please submit a PR once you are ready. Assigning is no needed.
I don't think this is a missed optimization. The LICM hoisting operates at the top op level as per here. And so it does not recursively check the test.affine_scope for hoistable instructions since it is not LoopLike.
However notice that if you had put the %2 = arith.addi %arg0, %arg0 : index (and its successors) inside the for loop at line 9. It will get hoisted, but remains inside the test.affine_scope.
cc: @Men-cotton