[mlir] Add folder for complex.ReOp and complex.ImOp.
authorAdrian Kuegel <akuegel@google.com>
Mon, 17 May 2021 11:21:24 +0000 (13:21 +0200)
committerAdrian Kuegel <akuegel@google.com>
Mon, 17 May 2021 11:35:51 +0000 (13:35 +0200)
Now that complex constants are supported, we can also fold.

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

mlir/include/mlir/Dialect/Complex/IR/ComplexOps.td
mlir/lib/Dialect/Complex/IR/ComplexOps.cpp
mlir/test/Dialect/Complex/canonicalize.mlir [new file with mode: 0644]

index 5e4648d..efea0b2 100644 (file)
@@ -144,6 +144,7 @@ def ImOp : Complex_Op<"im",
   let results = (outs AnyFloat:$imaginary);
 
   let assemblyFormat = "$complex attr-dict `:` type($complex)";
+  let hasFolder = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -185,6 +186,7 @@ def ReOp : Complex_Op<"re",
   let results = (outs AnyFloat:$real);
 
   let assemblyFormat = "$complex attr-dict `:` type($complex)";
+  let hasFolder = 1;
 }
 
 
index 6b4855d..37fae63 100644 (file)
@@ -17,3 +17,13 @@ using namespace mlir::complex;
 
 #define GET_OP_CLASSES
 #include "mlir/Dialect/Complex/IR/ComplexOps.cpp.inc"
+
+OpFoldResult ReOp::fold(ArrayRef<Attribute> operands) {
+  ArrayAttr arrayAttr = operands[0].dyn_cast<ArrayAttr>();
+  return arrayAttr[0];
+}
+
+OpFoldResult ImOp::fold(ArrayRef<Attribute> operands) {
+  ArrayAttr arrayAttr = operands[0].dyn_cast<ArrayAttr>();
+  return arrayAttr[1];
+}
diff --git a/mlir/test/Dialect/Complex/canonicalize.mlir b/mlir/test/Dialect/Complex/canonicalize.mlir
new file mode 100644 (file)
index 0000000..3ad66f9
--- /dev/null
@@ -0,0 +1,19 @@
+// RUN: mlir-opt %s -canonicalize | FileCheck %s
+
+// CHECK-LABEL: func @real_of_const(
+func @real_of_const() -> f32 {
+  // CHECK: %[[CST:.*]] = constant 1.000000e+00 : f32
+  // CHECK-NEXT: return %[[CST]] : f32
+  %complex = constant [1.0 : f32, 0.0 : f32] : complex<f32>
+  %1 = complex.re %complex : complex<f32>
+  return %1 : f32
+}
+
+// CHECK-LABEL: func @imag_of_const(
+func @imag_of_const() -> f32 {
+  // CHECK: %[[CST:.*]] = constant 0.000000e+00 : f32
+  // CHECK-NEXT: return %[[CST]] : f32
+  %complex = constant [1.0 : f32, 0.0 : f32] : complex<f32>
+  %1 = complex.im %complex : complex<f32>
+  return %1 : f32
+}