[mlir][Math] Add constant folder for ExpM1Op.

This patch adds constant folder for ExpM1Op which only supports single and double precision floating-point.

Differential Revision: https://reviews.llvm.org/D130567
This commit is contained in:
jacquesguan 2022-07-26 21:56:43 +08:00
parent b2559f2f5c
commit 16cb6ce554
3 changed files with 37 additions and 0 deletions

View File

@ -420,6 +420,7 @@ def Math_ExpM1Op : Math_FloatUnaryOp<"expm1"> {
%a = math.expm1 %b : f64
```
}];
let hasFolder = 1;
}
//===----------------------------------------------------------------------===//

View File

@ -246,6 +246,24 @@ OpFoldResult math::Exp2Op::fold(ArrayRef<Attribute> operands) {
});
}
//===----------------------------------------------------------------------===//
// ExpM1Op folder
//===----------------------------------------------------------------------===//
OpFoldResult math::ExpM1Op::fold(ArrayRef<Attribute> operands) {
return constFoldUnaryOpConditional<FloatAttr>(
operands, [](const APFloat &a) -> Optional<APFloat> {
switch (a.getSizeInBits(a.getSemantics())) {
case 64:
return APFloat(expm1(a.convertToDouble()));
case 32:
return APFloat(expm1f(a.convertToFloat()));
default:
return {};
}
});
}
/// Materialize an integer or floating point constant.
Operation *math::MathDialect::materializeConstant(OpBuilder &builder,
Attribute value, Type type,

View File

@ -264,3 +264,21 @@ func.func @exp2_fold_vec() -> (vector<4xf32>) {
%0 = math.exp2 %v1 : vector<4xf32>
return %0 : vector<4xf32>
}
// CHECK-LABEL: @expm1_fold
// CHECK-NEXT: %[[cst:.+]] = arith.constant 6.3890562 : f32
// CHECK-NEXT: return %[[cst]]
func.func @expm1_fold() -> f32 {
%c = arith.constant 2.0 : f32
%r = math.expm1 %c : f32
return %r : f32
}
// CHECK-LABEL: @expm1_fold_vec
// CHECK-NEXT: %[[cst:.+]] = arith.constant dense<[0.000000e+00, 1.71828175, 0.000000e+00, 1.71828175]> : vector<4xf32>
// CHECK-NEXT: return %[[cst]]
func.func @expm1_fold_vec() -> (vector<4xf32>) {
%v1 = arith.constant dense<[0.0, 1.0, 0.0, 1.0]> : vector<4xf32>
%0 = math.expm1 %v1 : vector<4xf32>
return %0 : vector<4xf32>
}