[mlir][Linalg] Add folding of linalg.copy that are in fact identities.
authorNicolas Vasilache <nicolas.vasilache@gmail.com>
Thu, 4 Mar 2021 13:08:21 +0000 (13:08 +0000)
committerNicolas Vasilache <nicolas.vasilache@gmail.com>
Thu, 4 Mar 2021 13:37:26 +0000 (13:37 +0000)
Differential Revision: https://reviews.llvm.org/D97939

mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp
mlir/test/Dialect/Linalg/canonicalize.mlir

index 4a2999a..1f686b9 100644 (file)
@@ -2595,6 +2595,15 @@ struct RemoveIdentityLinalgOps : public RewritePattern {
 
   LogicalResult matchAndRewrite(Operation *op,
                                 PatternRewriter &rewriter) const override {
+    if (auto copyOp = dyn_cast<CopyOp>(op)) {
+      assert(copyOp.hasBufferSemantics());
+      if (copyOp.input() == copyOp.output() &&
+          copyOp.inputPermutation() == copyOp.outputPermutation()) {
+        rewriter.eraseOp(op);
+        return success();
+      }
+    }
+
     if (!isa<GenericOp, IndexedGenericOp>(op))
       return failure();
     LinalgOp genericOp = cast<LinalgOp>(op);
index f2f3a44..1ab790a 100644 (file)
@@ -789,3 +789,15 @@ func @propogate_casts(%arg0 : tensor<?x?xf32>, %arg1 : f32, %arg2 : index,
 //       CHECK:   %[[INSERTED:.+]] = subtensor_insert %{{.+}} into %[[FILL]]
 //       CHECK:   %[[RESULT:.+]] = tensor.cast %[[INSERTED]]
 //       CHECK:   return %[[RESULT]]
+
+// -----
+
+// CHECK-LABEL: @self_copy
+func @self_copy(%arg0 : memref<2x3x?x4xf32>) {
+
+//   CHECK-NOT: linalg.copy
+  linalg.copy(%arg0, %arg0): memref<2x3x?x4xf32>, memref<2x3x?x4xf32>
+
+//   CHECK: return
+  return
+}