diff --git a/mlir/include/mlir/Dialect/Math/IR/MathOps.td b/mlir/include/mlir/Dialect/Math/IR/MathOps.td --- a/mlir/include/mlir/Dialect/Math/IR/MathOps.td +++ b/mlir/include/mlir/Dialect/Math/IR/MathOps.td @@ -285,6 +285,7 @@ %a = math.sin %b : f64 ``` }]; + let hasFolder = 1; } //===----------------------------------------------------------------------===// diff --git a/mlir/lib/Dialect/Math/IR/MathOps.cpp b/mlir/lib/Dialect/Math/IR/MathOps.cpp --- a/mlir/lib/Dialect/Math/IR/MathOps.cpp +++ b/mlir/lib/Dialect/Math/IR/MathOps.cpp @@ -122,6 +122,24 @@ }); } +//===----------------------------------------------------------------------===// +// SinOp folder +//===----------------------------------------------------------------------===// + +OpFoldResult math::SinOp::fold(ArrayRef operands) { + return constFoldUnaryOpConditional( + operands, [](const APFloat &a) -> Optional { + switch (a.getSizeInBits(a.getSemantics())) { + case 64: + return APFloat(sin(a.convertToDouble())); + case 32: + return APFloat(sinf(a.convertToFloat())); + default: + return {}; + } + }); +} + //===----------------------------------------------------------------------===// // CountLeadingZerosOp folder //===----------------------------------------------------------------------===// diff --git a/mlir/test/Dialect/Math/canonicalize.mlir b/mlir/test/Dialect/Math/canonicalize.mlir --- a/mlir/test/Dialect/Math/canonicalize.mlir +++ b/mlir/test/Dialect/Math/canonicalize.mlir @@ -447,3 +447,21 @@ %0 = math.trunc %v : vector<4xf32> return %0 : vector<4xf32> } + +// CHECK-LABEL: @sin_fold +// CHECK-NEXT: %[[cst:.+]] = arith.constant 0.84{{[0-9]+}} : f32 +// CHECK-NEXT: return %[[cst]] +func.func @sin_fold() -> f32 { + %c = arith.constant 1.0 : f32 + %r = math.sin %c : f32 + return %r : f32 +} + +// CHECK-LABEL: @sin_fold_vec +// CHECK-NEXT: %[[cst:.+]] = arith.constant dense<[0.000000e+00, 0.84{{[0-9]+}}, 0.000000e+00, 0.84{{[0-9]+}}]> : vector<4xf32> +// CHECK-NEXT: return %[[cst]] +func.func @sin_fold_vec() -> (vector<4xf32>) { + %v1 = arith.constant dense<[0.0, 1.0, 0.0, 1.0]> : vector<4xf32> + %0 = math.sin %v1 : vector<4xf32> + return %0 : vector<4xf32> +}