[GlobalOptimization] Expand dynamic tensor shapes through scf.for (#25366)

A dynamically shaped `scf.for` iter_arg fails in Flow with `'tensor.dim'
op unexpected during shape cleanup`, because `ExpandTensorShapes`
handles `scf.while` and `scf.if` but not `scf.for`. ONNX
NonMaxSuppression hits this since llvm/torch-mlir#4933. Part of #19474.

This expands `scf.for` like `scf.while`, with the dynamic dims as extra
iter_args. `scf.while` gets the same example comment.

Assisted-by: Claude Code

---------

Signed-off-by: Roberto Laudani <laudani@roofline.ai>
diff --git a/compiler/src/iree/compiler/GlobalOptimization/ExpandTensorShapes.cpp b/compiler/src/iree/compiler/GlobalOptimization/ExpandTensorShapes.cpp
index e2b900a..1978523 100644
--- a/compiler/src/iree/compiler/GlobalOptimization/ExpandTensorShapes.cpp
+++ b/compiler/src/iree/compiler/GlobalOptimization/ExpandTensorShapes.cpp
@@ -529,6 +529,23 @@
   op.erase();
 }
 
+// Moves dynamic dims across scf.while operands, regions and results.
+//
+// Example:
+//    %1 = flow.tensor.tie_shape %0 : tensor<?xf32>{%d}
+//    %r = scf.while (%t = %1) : (tensor<?xf32>) -> tensor<?xf32> {
+//      scf.condition(%c) %t : tensor<?xf32>
+//    } do {
+//    ^bb0(%u: tensor<?xf32>):
+//  ->
+//    %r:2 = scf.while (%t = %0, %td = %d)
+//        : (tensor<?xf32>, index) -> (tensor<?xf32>, index) {
+//      %2 = flow.tensor.tie_shape %t : tensor<?xf32>{%td}
+//      scf.condition(%c) %t, %td : tensor<?xf32>, index
+//    } do {
+//    ^bb0(%u: tensor<?xf32>, %ud: index):
+//      %3 = flow.tensor.tie_shape %u : tensor<?xf32>{%ud}
+//    %4 = flow.tensor.tie_shape %r#0 : tensor<?xf32>{%r#1}
 static void expandWhileOp(mlir::scf::WhileOp op, SymbolTable &symbolTable,
                           ExpandedGlobalMap &globalMap, IndexSet &indexSet,
                           TensorDimMap &tensorDimMap) {
@@ -552,6 +569,32 @@
   op.erase();
 }
 
+// Moves dynamic dims across scf.for iter_args, yields and results.
+//
+// Example:
+//    %1 = flow.tensor.tie_shape %0 : tensor<?xf32>{%d}
+//    %r = scf.for %i = %lb to %ub step %s iter_args(%t = %1) -> tensor<?xf32>
+//  ->
+//    %r:2 = scf.for %i = %lb to %ub step %s iter_args(%t = %0, %td = %d)
+//        -> (tensor<?xf32>, index) {
+//      %2 = flow.tensor.tie_shape %t : tensor<?xf32>{%td}
+//    %3 = flow.tensor.tie_shape %r#0 : tensor<?xf32>{%r#1}
+static void expandForOp(mlir::scf::ForOp op, SymbolTable &symbolTable,
+                        ExpandedGlobalMap &globalMap, IndexSet &indexSet,
+                        TensorDimMap &tensorDimMap) {
+  OpBuilder builder(op);
+  auto initArgs = expandOperands(op.getLoc(), op.getInitArgs(), tensorDimMap,
+                                 indexSet, builder);
+  auto newOp = scf::ForOp::create(builder, op.getLoc(), op.getLowerBound(),
+                                  op.getUpperBound(), op.getStep(), initArgs);
+  newOp.setUnsignedCmp(op.getUnsignedCmp());
+  newOp.getRegion().takeBody(op.getRegion());
+  expandRegion(newOp.getRegion(), symbolTable, globalMap, indexSet,
+               tensorDimMap);
+  retieResults(op, newOp, tensorDimMap);
+  op.erase();
+}
+
 static void expandIfOp(mlir::scf::IfOp op, SymbolTable &symbolTable,
                        ExpandedGlobalMap &globalMap, IndexSet &indexSet,
                        TensorDimMap &tensorDimMap) {
@@ -616,6 +659,8 @@
     expandCondBranchOp(condBranchOp, indexSet, tensorDimMap);
   } else if (auto selectOp = dyn_cast<mlir::arith::SelectOp>(op)) {
     expandSelectOp(selectOp, indexSet, tensorDimMap);
+  } else if (auto forOp = dyn_cast<mlir::scf::ForOp>(op)) {
+    expandForOp(forOp, symbolTable, globalMap, indexSet, tensorDimMap);
   } else if (auto whileOp = dyn_cast<mlir::scf::WhileOp>(op)) {
     expandWhileOp(whileOp, symbolTable, globalMap, indexSet, tensorDimMap);
   } else if (auto ifOp = dyn_cast<mlir::scf::IfOp>(op)) {
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/expand_tensor_shapes.mlir b/compiler/src/iree/compiler/GlobalOptimization/test/expand_tensor_shapes.mlir
index de519db..8a4b406 100644
--- a/compiler/src/iree/compiler/GlobalOptimization/test/expand_tensor_shapes.mlir
+++ b/compiler/src/iree/compiler/GlobalOptimization/test/expand_tensor_shapes.mlir
@@ -238,6 +238,32 @@
 
 // -----
 
+// CHECK-LABEL: @scf_for
+// CHECK-SAME: %[[ARG0:.+]]: tensor<?xf32>, %[[ARG1:.+]]: index, %[[ARG2:.+]]: index
+util.func private @scf_for(%arg0 : tensor<?xf32>, %arg1 : index) {
+  %c0 = arith.constant 0 : index
+  %c1 = arith.constant 1 : index
+  %zero = arith.constant 0 : i32
+  // CHECK:  %[[ZERO:.+]] = arith.constant 0 : i32
+  // CHECK:  %[[FOR:.+]]:3 = scf.for unsigned %{{.+}} = %{{.+}} to %[[ARG2]] step %{{.+}} iter_args(%[[ARG3:.+]] = %[[ARG0]], %[[ARG4:.+]] = %[[ARG1]], %[[ARG5:.+]] = %[[ZERO]]) -> (tensor<?xf32>, index, i32)
+  %0:2 = scf.for unsigned %iv = %c0 to %arg1 step %c1 iter_args(%arg2 = %arg0, %arg3 = %zero) -> (tensor<?xf32>, i32) {
+    // CHECK:    %[[TIE:.+]] = flow.tensor.tie_shape %[[ARG3]] : tensor<?xf32>{%[[ARG4]]}
+    // CHECK:    %[[ADD:.+]] = arith.addf %[[TIE]], %[[TIE]]
+    // CHECK:    %[[C0:.+]] = arith.constant 0 : index
+    // CHECK:    %[[DIM:.+]] = tensor.dim %[[ADD]], %[[C0]]
+    // CHECK:    scf.yield %[[ADD]], %[[DIM]], %[[ARG5]] : tensor<?xf32>, index, i32
+    %1 = arith.addf %arg2, %arg2 : tensor<?xf32>
+    scf.yield %1, %arg3 : tensor<?xf32>, i32
+  }
+
+  // CHECK:  %[[TIE:.+]] = flow.tensor.tie_shape %[[FOR]]#0 : tensor<?xf32>{%[[FOR]]#1}
+  // CHECK:  %[[BARRIER:.+]] = util.optimization_barrier %[[TIE]]
+  util.optimization_barrier %0#0 : tensor<?xf32>
+  util.return
+}
+
+// -----
+
 // CHECK-LABEL: @scf_if
 // CHECK-SAME: %[[ARG0:.+]]: tensor<?xf32>, %[[ARG1:.+]]: index, %[[ARG2:.+]]: i1
 util.func private @scf_if(%arg0 : tensor<?xf32>, %arg1 : i1) {