[mlir][Math] Add constant folder for Log10Op.
authorjacquesguan <Jianjian.Guan@streamcomputing.com>
Thu, 14 Jul 2022 07:43:16 +0000 (15:43 +0800)
committerjacquesguan <Jianjian.Guan@streamcomputing.com>
Mon, 18 Jul 2022 02:19:25 +0000 (10:19 +0800)
This patch adds constant folder for Log10Op which only support single and double precision floating-point.

Reviewed By: Mogball

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

mlir/include/mlir/Dialect/Math/IR/MathOps.td
mlir/lib/Dialect/Math/IR/MathOps.cpp
mlir/test/Dialect/Math/canonicalize.mlir

index 94103ff..163e687 100644 (file)
@@ -517,6 +517,7 @@ def Math_Log10Op : Math_FloatUnaryOp<"log10"> {
     %y = math.log10 %x : f64
     ```
   }];
+  let hasFolder = 1;
 }
 
 //===----------------------------------------------------------------------===//
index ac6b1ae..b389f43 100644 (file)
@@ -108,6 +108,27 @@ OpFoldResult math::Log2Op::fold(ArrayRef<Attribute> operands) {
 }
 
 //===----------------------------------------------------------------------===//
+// Log10Op folder
+//===----------------------------------------------------------------------===//
+
+OpFoldResult math::Log10Op::fold(ArrayRef<Attribute> operands) {
+  return constFoldUnaryOpConditional<FloatAttr>(
+      operands, [](const APFloat &a) -> Optional<APFloat> {
+        if (a.isNegative())
+          return {};
+
+        switch (a.getSizeInBits(a.getSemantics())) {
+        case 64:
+          return APFloat(log10(a.convertToDouble()));
+        case 32:
+          return APFloat(log10f(a.convertToFloat()));
+        default:
+          return {};
+        }
+      });
+}
+
+//===----------------------------------------------------------------------===//
 // PowFOp folder
 //===----------------------------------------------------------------------===//
 
index b78e3ad..0aabd62 100644 (file)
@@ -174,3 +174,21 @@ func.func @ctpop_fold() -> i32 {
   %r = math.ctpop %c : i32
   return %r : i32
 }
+
+// CHECK-LABEL: @log10_fold
+// CHECK: %[[cst:.+]] = arith.constant 2.000000e+00 : f32
+  // CHECK: return %[[cst]]
+func.func @log10_fold() -> f32 {
+  %c = arith.constant 100.0 : f32
+  %r = math.log10 %c : f32
+  return %r : f32
+}
+
+// CHECK-LABEL: @log10_fold_vec
+// CHECK: %[[cst:.+]] = arith.constant dense<[0.000000e+00, 1.000000e+00, 2.000000e+00, 2.301030e+00]> : vector<4xf32>
+// CHECK: return %[[cst]]
+func.func @log10_fold_vec() -> (vector<4xf32>) {
+  %v1 = arith.constant dense<[1.0, 10.0, 100.0, 200.0]> : vector<4xf32>
+  %0 = math.log10 %v1 : vector<4xf32>
+  return %0 : vector<4xf32>
+}