Extend function expansion passes to support calls (#6982)

This also makes them module passes, which they have to be since they
mutate the function signature itself (this also manifested as the
verifier not properly running).

I also filed an upstream bug because it is too hard to do these sorts of
call graph rewrites:
https://bugs.llvm.org/show_bug.cgi?id=51740
diff --git a/iree/compiler/Dialect/Flow/Transforms/Passes.cpp b/iree/compiler/Dialect/Flow/Transforms/Passes.cpp
index 87affe9..975a41b 100644
--- a/iree/compiler/Dialect/Flow/Transforms/Passes.cpp
+++ b/iree/compiler/Dialect/Flow/Transforms/Passes.cpp
@@ -104,8 +104,7 @@
   // The generated ABI wrappers assume such an expansion and will generate code
   // to produce it from the original reflection metadata captured in the
   // previous pass.
-  passManager.addNestedPass<mlir::FuncOp>(
-      Shape::createExpandFunctionDynamicDimsPass());
+  passManager.addPass(Shape::createExpandFunctionDynamicDimsPass());
 
   // Special case peephole optimizations.
   {
diff --git a/iree/compiler/Dialect/HAL/Transforms/Passes.cpp b/iree/compiler/Dialect/HAL/Transforms/Passes.cpp
index 3b3df2c..fc00b5d 100644
--- a/iree/compiler/Dialect/HAL/Transforms/Passes.cpp
+++ b/iree/compiler/Dialect/HAL/Transforms/Passes.cpp
@@ -96,8 +96,7 @@
   // on explicit shape types (such as ranked_shape). After this pass, these
   // composite types will be expanded to primitives (i.e. one 'index' for each
   // dynamic dim in the case of ranked_shape).
-  passManager.addNestedPass<FuncOp>(
-      Shape::createExpandFunctionRankedShapeDimsPass());
+  passManager.addPass(Shape::createExpandFunctionRankedShapeDimsPass());
 
   passManager.addNestedPass<FuncOp>(createCanonicalizerPass());
   passManager.addNestedPass<FuncOp>(createCSEPass());
diff --git a/iree/compiler/Dialect/Shape/Transforms/FunctionSignatureExpansionPass.cpp b/iree/compiler/Dialect/Shape/Transforms/FunctionSignatureExpansionPass.cpp
index 316cd72..edd0814 100644
--- a/iree/compiler/Dialect/Shape/Transforms/FunctionSignatureExpansionPass.cpp
+++ b/iree/compiler/Dialect/Shape/Transforms/FunctionSignatureExpansionPass.cpp
@@ -21,10 +21,95 @@
 namespace mlir {
 namespace iree_compiler {
 namespace Shape {
+
+static LogicalResult expandCallGraphTypesForCall(
+    CallOp callOp, const TypeExpander &typeExpander) {
+  Location loc = callOp.getLoc();
+
+  OpBuilder builder(callOp);
+  // Create the operands list of the new `CallOp`.
+  SmallVector<Value> newOperands;
+  if (failed(typeExpander.expandSourceValuesToTarget(
+          loc, llvm::to_vector<6>(callOp.getOperands()), newOperands,
+          builder))) {
+    return failure();
+  }
+
+  // Create the new result types for the new `CallOp` and track the indices
+  // in the new call op's results that correspond to the old call op's
+  // results.
+  //
+  // expandedResultIndices[i] = "list of new result indices that old result
+  // i expanded to".
+  SmallVector<Type> newResultTypes;
+  SmallVector<SmallVector<unsigned>> expandedResultIndices;
+  for (Type resultType : callOp.getResultTypes()) {
+    unsigned oldSize = newResultTypes.size();
+    if (failed(typeExpander.convertType(resultType, newResultTypes))) {
+      return failure();
+    }
+    auto &resultMapping = expandedResultIndices.emplace_back();
+    for (unsigned i = oldSize, e = newResultTypes.size(); i < e; i++)
+      resultMapping.push_back(i);
+  }
+
+  CallOp newCallOp = builder.create<CallOp>(loc, callOp.getCallee(),
+                                            newResultTypes, newOperands);
+
+  // Build a replacement value for each result to replace its uses. If a
+  // result has multiple mapping values, it needs to be materialized as a
+  // single value.
+  SmallVector<Value, 2> replacedValues;
+  replacedValues.reserve(callOp.getNumResults());
+  for (unsigned i = 0, e = callOp.getNumResults(); i < e; ++i) {
+    auto decomposedValues = llvm::to_vector<6>(
+        llvm::map_range(expandedResultIndices[i],
+                        [&](unsigned i) { return newCallOp.getResult(i); }));
+    if (decomposedValues.empty()) {
+      // No replacement is required.
+      replacedValues.push_back(nullptr);
+    } else if (decomposedValues.size() == 1) {
+      replacedValues.push_back(decomposedValues.front());
+    } else {
+      Value materialized = typeExpander.castToSource(loc, callOp.getType(i),
+                                                     decomposedValues, builder);
+      replacedValues.push_back(materialized);
+    }
+  }
+  callOp.replaceAllUsesWith(replacedValues);
+  return success();
+}
+
+static LogicalResult expandCallGraphTypes(ModuleOp module,
+                                          const TypeExpander &typeExpander) {
+  for (auto funcOp : module.getOps<FuncOp>()) {
+    OpBuilder builder(funcOp);
+    if (failed(typeExpander.expandFunctionSignature(funcOp, builder)) ||
+        failed(typeExpander.expandAllReturnLikeTerminators<mlir::ReturnOp>(
+            funcOp, builder))) {
+      return funcOp.emitError()
+             << "couldn't expand function signature or return";
+    }
+    bool hadError = false;
+    SmallVector<Operation *> toErase;
+    funcOp.walk([&](CallOp callOp) {
+      if (failed(expandCallGraphTypesForCall(callOp, typeExpander))) {
+        hadError = true;
+        return;
+      }
+      toErase.push_back(callOp);
+    });
+    if (hadError) return failure();
+    for (Operation *op : toErase) op->erase();
+  }
+  return success();
+}
+
 namespace {
 
 class ExpandFunctionDynamicDimsPass
-    : public PassWrapper<ExpandFunctionDynamicDimsPass, FunctionPass> {
+    : public PassWrapper<ExpandFunctionDynamicDimsPass,
+                         OperationPass<ModuleOp>> {
   void getDependentDialects(DialectRegistry &registry) const override {
     registry.insert<ShapeDialect>();
   }
@@ -37,20 +122,16 @@
     return "Expands dynamic dimensions in function signatures.";
   }
 
-  void runOnFunction() override {
-    auto funcOp = getFunction();
+  void runOnOperation() override {
     auto &typeExpander = getDynamicShapeTypeExpander();
-    OpBuilder builder(funcOp);
-    if (failed(typeExpander.expandFunctionSignature(funcOp, builder)) ||
-        failed(typeExpander.expandAllReturnLikeTerminators<mlir::ReturnOp>(
-            funcOp, builder))) {
-      return signalPassFailure();
-    }
+    if (failed(expandCallGraphTypes(getOperation(), typeExpander)))
+      signalPassFailure();
   }
 };
 
 class ExpandFunctionRankedShapeDimsPass
-    : public PassWrapper<ExpandFunctionRankedShapeDimsPass, FunctionPass> {
+    : public PassWrapper<ExpandFunctionRankedShapeDimsPass,
+                         OperationPass<ModuleOp>> {
   void getDependentDialects(DialectRegistry &registry) const override {
     registry.insert<ShapeDialect>();
   }
@@ -63,15 +144,10 @@
     return "Expands ranked_shape types at function boundaries to loose dims.";
   }
 
-  void runOnFunction() override {
-    auto funcOp = getFunction();
+  void runOnOperation() override {
     auto &typeExpander = getShapeToPrimitiveTypeExpander();
-    OpBuilder builder(funcOp);
-    if (failed(typeExpander.expandFunctionSignature(funcOp, builder)) ||
-        failed(typeExpander.expandAllReturnLikeTerminators<mlir::ReturnOp>(
-            funcOp, builder))) {
-      return signalPassFailure();
-    }
+    if (failed(expandCallGraphTypes(getOperation(), typeExpander)))
+      signalPassFailure();
   }
 };
 
@@ -79,14 +155,14 @@
 
 // For any function which contains dynamic dims in its inputs or results,
 // rewrites it so that the dynamic dims are passed in/out.
-std::unique_ptr<OperationPass<FuncOp>> createExpandFunctionDynamicDimsPass() {
+std::unique_ptr<OperationPass<ModuleOp>> createExpandFunctionDynamicDimsPass() {
   return std::make_unique<Shape::ExpandFunctionDynamicDimsPass>();
 }
 
 // For any function which contains ranked_shape argument/result types,
 // expands them to individual dynamic dimensions, inserting appropriate casts
 // within the function.
-std::unique_ptr<OperationPass<FuncOp>>
+std::unique_ptr<OperationPass<ModuleOp>>
 createExpandFunctionRankedShapeDimsPass() {
   return std::make_unique<Shape::ExpandFunctionRankedShapeDimsPass>();
 }
diff --git a/iree/compiler/Dialect/Shape/Transforms/Passes.h b/iree/compiler/Dialect/Shape/Transforms/Passes.h
index ab1544a..3cc2889 100644
--- a/iree/compiler/Dialect/Shape/Transforms/Passes.h
+++ b/iree/compiler/Dialect/Shape/Transforms/Passes.h
@@ -18,12 +18,12 @@
 
 // For any function which contains dynamic dims in its inputs or results,
 // rewrites it so that the dynamic dims are passed in/out.
-std::unique_ptr<OperationPass<FuncOp>> createExpandFunctionDynamicDimsPass();
+std::unique_ptr<OperationPass<ModuleOp>> createExpandFunctionDynamicDimsPass();
 
 // For any function which contains ranked_shape argument/result types,
 // expands them to individual dynamic dimensions, inserting appropriate casts
 // within the function.
-std::unique_ptr<OperationPass<FuncOp>>
+std::unique_ptr<OperationPass<ModuleOp>>
 createExpandFunctionRankedShapeDimsPass();
 
 // Folds tensor.dim/memref.dim ops taking shape carrying ops as operands.
diff --git a/iree/compiler/Dialect/Shape/Transforms/test/expand_function_dynamic_dims.mlir b/iree/compiler/Dialect/Shape/Transforms/test/expand_function_dynamic_dims.mlir
index d0dfe66..be98e44 100644
--- a/iree/compiler/Dialect/Shape/Transforms/test/expand_function_dynamic_dims.mlir
+++ b/iree/compiler/Dialect/Shape/Transforms/test/expand_function_dynamic_dims.mlir
@@ -36,3 +36,18 @@
   // CHECK: return %[[RESULT]], %[[SHAPE]] : tensor<?x3xf32>, !shapex.ranked_shape<[?,3]>
   return %1 : tensor<?x3xf32>
 }
+
+// -----
+// CHECK-LABEL:   func @calls(
+// CHECK-SAME:                %[[ARG:.*]]: tensor<1x?x2x?xf32>,
+// CHECK-SAME:                %[[ARG_SHAPE:.*]]: !shapex.ranked_shape<[1,?,2,?]>) -> (tensor<1x?x2x?xf32>, !shapex.ranked_shape<[1,?,2,?]>) {
+func @calls(%arg0 : tensor<1x?x2x?xf32>) -> tensor<1x?x2x?xf32> {
+  // CHECK:           %[[ARG_TIED:.*]] = shapex.tie_shape %[[ARG]], %[[ARG_SHAPE]] : tensor<1x?x2x?xf32>, !shapex.ranked_shape<[1,?,2,?]>
+  // CHECK:           %[[ARG_TIED_SHAPE:.*]] = shapex.get_ranked_shape %[[ARG_TIED]] : tensor<1x?x2x?xf32> -> !shapex.ranked_shape<[1,?,2,?]>
+  // CHECK:           %[[CALL_RESULT:.*]]:2 = call @calls(%[[ARG_TIED]], %[[ARG_TIED_SHAPE]]) : (tensor<1x?x2x?xf32>, !shapex.ranked_shape<[1,?,2,?]>) -> (tensor<1x?x2x?xf32>, !shapex.ranked_shape<[1,?,2,?]>)
+  %0 = std.call @calls(%arg0) : (tensor<1x?x2x?xf32>) -> tensor<1x?x2x?xf32>
+  // CHECK:           %[[CALL_RESULT_TIED:.*]] = shapex.tie_shape %[[CALL_RESULT]]#0, %[[CALL_RESULT]]#1 : tensor<1x?x2x?xf32>, !shapex.ranked_shape<[1,?,2,?]>
+  // CHECK:           %[[CALL_RESULT_SHAPE:.*]] = shapex.get_ranked_shape %[[CALL_RESULT_TIED]] : tensor<1x?x2x?xf32> -> !shapex.ranked_shape<[1,?,2,?]>
+  // CHECK:           return %[[CALL_RESULT_TIED]], %[[CALL_RESULT_SHAPE]] : tensor<1x?x2x?xf32>, !shapex.ranked_shape<[1,?,2,?]>
+  return %0 : tensor<1x?x2x?xf32>
+}
diff --git a/iree/compiler/Dialect/Shape/Transforms/test/expand_function_ranked_shape_dims.mlir b/iree/compiler/Dialect/Shape/Transforms/test/expand_function_ranked_shape_dims.mlir
index 60e0cc4..9ad16d5 100644
--- a/iree/compiler/Dialect/Shape/Transforms/test/expand_function_ranked_shape_dims.mlir
+++ b/iree/compiler/Dialect/Shape/Transforms/test/expand_function_ranked_shape_dims.mlir
@@ -34,3 +34,12 @@
   // CHECK: return %[[CAST_IDX0]], %[[CAST_IDX1]]
   return %rs : !shapex.ranked_shape<[?,?]>
 }
+
+// -----
+// CHECK-LABEL: @calls
+// CHECK-SAME: (%arg0: index, %arg1: index) -> (index, index)
+func @calls(%arg0 :!shapex.ranked_shape<[?,?]>) -> !shapex.ranked_shape<[?,?]> {
+  // CHECK: call @calls(%{{.*}}, %{{.*}}) : (index, index) -> (index, index)
+  %0 = std.call @calls(%arg0) : (!shapex.ranked_shape<[?,?]>) -> !shapex.ranked_shape<[?,?]>
+  return %0 : !shapex.ranked_shape<[?,?]>
+}