[mlir][complex] Canonicalization for consecutive complex.neg
authorlewuathe <lewuathe@me.com>
Wed, 29 Jun 2022 08:32:23 +0000 (10:32 +0200)
committerAlexander Belyaev <pifon@google.com>
Wed, 29 Jun 2022 09:11:40 +0000 (11:11 +0200)
Consecutive complex.neg are redundant so that we can canonicalize them to the original operands.

Reviewed By: pifon2a

Differential Revision: https://reviews.llvm.org/D128781

mlir/include/mlir/Dialect/Complex/IR/ComplexOps.td
mlir/lib/Dialect/Complex/IR/ComplexOps.cpp
mlir/test/Dialect/Complex/canonicalize.mlir

index 5ca24398843cbb2d4ca918905ced8d69f393c118..b76276c726ee5d1ed64f5dfc82c043ec26ee1ebc 100644 (file)
@@ -365,6 +365,8 @@ def NegOp : ComplexUnaryOp<"neg", [SameOperandsAndResultType]> {
   }];
 
   let results = (outs Complex<AnyFloat>:$result);
+
+  let hasFolder = 1;
 }
 
 //===----------------------------------------------------------------------===//
index 0390a00cf68447eb14caf99b3b65275bf0d16ba0..00dbb564481ee9dacfbc5356e4def35eb6809177 100644 (file)
@@ -124,6 +124,20 @@ OpFoldResult AddOp::fold(ArrayRef<Attribute> operands) {
   return {};
 }
 
+//===----------------------------------------------------------------------===//
+// NegOp
+//===----------------------------------------------------------------------===//
+
+OpFoldResult NegOp::fold(ArrayRef<Attribute> operands) {
+  assert(operands.size() == 1 && "unary op takes 1 operand");
+
+  // complex.neg(complex.neg(a)) -> a
+  if (auto negOp = getOperand().getDefiningOp<NegOp>())
+    return negOp.getOperand();
+
+  return {};
+}
+
 //===----------------------------------------------------------------------===//
 // TableGen'd op method definitions
 //===----------------------------------------------------------------------===//
index 8bca3232774a1bda437458be8fad5084b715c33b..093e92f6a0308c84dd4525407cdc11f06e276149 100644 (file)
@@ -83,4 +83,14 @@ func.func @complex_add_sub_rhs() -> complex<f32> {
   %sub = complex.sub %complex1, %complex2 : complex<f32>
   %add = complex.add %complex2, %sub : complex<f32>
   return %add : complex<f32>
+}
+
+// CHECK-LABEL: func @complex_neg_neg
+func.func @complex_neg_neg() -> complex<f32> {
+  %complex1 = complex.constant [1.0 : f32, 0.0 : f32] : complex<f32>
+  // CHECK: %[[CPLX:.*]] = complex.constant [1.000000e+00 : f32, 0.000000e+00 : f32] : complex<f32>
+  // CHECK-NEXT: return %[[CPLX:.*]] : complex<f32>
+  %neg1 = complex.neg %complex1 : complex<f32>
+  %neg2 = complex.neg %neg1 : complex<f32>
+  return %neg2 : complex<f32>
 }
\ No newline at end of file