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 @@ -363,6 +363,7 @@ %a = math.exp %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 @@ -210,6 +210,24 @@ }); } +//===----------------------------------------------------------------------===// +// ExpOp folder +//===----------------------------------------------------------------------===// + +OpFoldResult math::ExpOp::fold(ArrayRef operands) { + return constFoldUnaryOpConditional( + operands, [](const APFloat &a) -> Optional { + switch (a.getSizeInBits(a.getSemantics())) { + case 64: + return APFloat(exp(a.convertToDouble())); + case 32: + return APFloat(expf(a.convertToFloat())); + default: + return {}; + } + }); +} + /// Materialize an integer or floating point constant. Operation *math::MathDialect::materializeConstant(OpBuilder &builder, Attribute value, Type type, 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 @@ -228,3 +228,21 @@ %0 = math.log %v1 : vector<4xf32> return %0 : vector<4xf32> } + +// CHECK-LABEL: @exp_fold +// CHECK: %[[cst:.+]] = arith.constant 7.3890562 : f32 + // CHECK: return %[[cst]] +func.func @exp_fold() -> f32 { + %c = arith.constant 2.0 : f32 + %r = math.exp %c : f32 + return %r : f32 +} + +// CHECK-LABEL: @exp_fold_vec +// CHECK: %[[cst:.+]] = arith.constant dense<[2.71828175, 7.3890562, 20.085537, 54.5981483]> : vector<4xf32> +// CHECK: return %[[cst]] +func.func @exp_fold_vec() -> (vector<4xf32>) { + %v1 = arith.constant dense<[1.0, 2.0, 3.0, 4.0]> : vector<4xf32> + %0 = math.exp %v1 : vector<4xf32> + return %0 : vector<4xf32> +}